blade-code 0.9.0 → 0.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -5
- package/dist/blade.js +4 -4
- package/dist/{chunk-1v2n922p.js → chunk-0h81hxkw.js} +1 -1
- package/dist/chunk-11qty4fd.js +13 -0
- package/dist/chunk-29r7z43j.js +2 -0
- package/dist/chunk-2beq0syt.js +2 -0
- package/dist/chunk-3nx2579c.js +44 -0
- package/dist/chunk-44wkjs2j.js +114 -0
- package/dist/chunk-49sytjma.js +22 -0
- package/dist/chunk-4vaywb2r.js +2 -0
- package/dist/chunk-51wa5fct.js +25 -0
- package/dist/{chunk-d7y2mf7c.js → chunk-5pvxw7sd.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-793k86j6.js +1485 -0
- package/dist/chunk-859m18ra.js +160 -0
- package/dist/chunk-88vy9hh0.js +4 -0
- package/dist/{chunk-gdm1xzvp.js → chunk-8nm1hqr1.js} +2 -2
- package/dist/chunk-a7nbn5kf.js +3 -0
- package/dist/chunk-a8y9xbxw.js +99 -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-ax7bx0j8.js → chunk-d3236505.js} +1 -1
- package/dist/chunk-d9ddpapp.js +18 -0
- package/dist/chunk-dnhb7k9g.js +4 -0
- package/dist/chunk-f19yx9an.js +1 -0
- package/dist/chunk-fjw32ex5.js +2 -0
- package/dist/chunk-g0jb7v73.js +1 -0
- package/dist/chunk-g2972yzq.js +1 -0
- package/dist/chunk-gafbzeyk.js +1 -0
- package/dist/chunk-gv8gfnz8.js +1 -0
- package/dist/chunk-h7kj4gvj.js +2 -0
- package/dist/chunk-hefv4415.js +45 -0
- package/dist/{chunk-rmfk5f9m.js → chunk-j457sh1b.js} +2 -2
- package/dist/chunk-j51fwecz.js +636 -0
- package/dist/chunk-jv4nkkb5.js +1 -0
- package/dist/{chunk-2fbwmdvg.js → chunk-jxv6r0c7.js} +2 -2
- package/dist/chunk-jzrqjzjm.js +174 -0
- package/dist/chunk-k6qwdjyy.js +25 -0
- package/dist/{chunk-x40fkg4z.js → chunk-km7m66vw.js} +2 -2
- package/dist/{chunk-aq7wf2zt.js → chunk-kq5my0yy.js} +2 -2
- package/dist/chunk-m3g8hz67.js +1 -0
- package/dist/chunk-m3tx1k0s.js +1 -0
- package/dist/chunk-m78ceafk.js +1 -0
- package/dist/{chunk-ppyg431d.js → chunk-mjp61rqd.js} +1 -1
- package/dist/chunk-mrpvdvn4.js +3 -0
- package/dist/chunk-mz1jrcgc.js +6 -0
- package/dist/chunk-nah0cbnp.js +2 -0
- package/dist/chunk-p6yed31x.js +1 -0
- package/dist/chunk-pms05z02.js +2 -0
- package/dist/chunk-px5ck9pf.js +2 -0
- package/dist/chunk-qev36qrb.js +2 -0
- package/dist/chunk-qk0akpsg.js +1 -0
- package/dist/chunk-rppak8ep.js +6 -0
- package/dist/{chunk-z0qxaky4.js → chunk-sndbq5xt.js} +1 -1
- package/dist/chunk-t7ej11xd.js +9 -0
- package/dist/chunk-t8q9ks7e.js +3 -0
- package/dist/{chunk-mns8e65q.js → chunk-th7sxjtk.js} +2 -2
- package/dist/chunk-tkd04sjm.js +1 -0
- package/dist/chunk-tkr4d9ej.js +1 -0
- package/dist/{chunk-w3me85va.js → chunk-vjpd3nee.js} +2 -2
- package/dist/chunk-vvy506b3.js +3 -0
- package/dist/chunk-w1wp1t52.js +10 -0
- package/dist/{chunk-bc6wbcrs.js → chunk-wvj9h7mb.js} +1 -1
- package/dist/{chunk-j8en7x02.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 +36 -34
- package/dist/chunk-0abtfzm6.js +0 -1
- package/dist/chunk-0zkhjsbv.js +0 -1
- package/dist/chunk-119fhp5q.js +0 -9
- package/dist/chunk-1rpgvk3r.js +0 -10
- package/dist/chunk-3qgj2y5r.js +0 -1
- package/dist/chunk-45bme7n9.js +0 -2
- package/dist/chunk-5jq01mg6.js +0 -4
- package/dist/chunk-5nye3k5w.js +0 -1
- package/dist/chunk-7pevqbfd.js +0 -2
- package/dist/chunk-8dqvnx7n.js +0 -2
- package/dist/chunk-8edsvxf3.js +0 -1
- package/dist/chunk-8vemqfe4.js +0 -2
- package/dist/chunk-8vtznxpq.js +0 -5
- package/dist/chunk-936ft6kq.js +0 -2
- package/dist/chunk-9ax02vtg.js +0 -22
- package/dist/chunk-9qknesxs.js +0 -6
- package/dist/chunk-acegy4td.js +0 -3
- package/dist/chunk-aewrn5xp.js +0 -1
- package/dist/chunk-b10vr4xj.js +0 -2
- package/dist/chunk-bfgm5k3e.js +0 -1566
- package/dist/chunk-cf3fhs7j.js +0 -1
- package/dist/chunk-e1586s4t.js +0 -1
- package/dist/chunk-enk621t7.js +0 -98
- package/dist/chunk-fpr6d8zc.js +0 -2
- package/dist/chunk-gagt42k2.js +0 -13
- package/dist/chunk-gm62cfjw.js +0 -1
- package/dist/chunk-h3bjmkvz.js +0 -1
- package/dist/chunk-jyr9417h.js +0 -34
- package/dist/chunk-mcnfbhpr.js +0 -6
- package/dist/chunk-mpkr3s6b.js +0 -3
- package/dist/chunk-n9tgxfvw.js +0 -615
- package/dist/chunk-qxhrzws6.js +0 -1
- package/dist/chunk-r6h7eja3.js +0 -151
- package/dist/chunk-r8pjwjt6.js +0 -1
- package/dist/chunk-rrg9bw8r.js +0 -25
- package/dist/chunk-wtxwny0p.js +0 -41
- package/dist/chunk-x548f12z.js +0 -2
- package/dist/chunk-xtfzjb72.js +0 -6
- package/dist/web/assets/CodeBlockHighlighter-D8_cOYpG.js +0 -1
- package/dist/web/assets/FilePreview-DpovIbME.js +0 -7
- package/dist/web/assets/MarkdownRenderer-73wC_SGk.js +0 -1
- package/dist/web/assets/McpModal-CIpxuyTG.js +0 -5
- package/dist/web/assets/SettingsModal-BBa1libe.js +0 -1
- package/dist/web/assets/SettingsStore-C8YBWQPS.js +0 -1
- package/dist/web/assets/SkillsModal-DArZ-nCX.js +0 -1
- package/dist/web/assets/TerminalPanel-BX7C7qiD.js +0 -1
- package/dist/web/assets/index-Ch0eqSLM.css +0 -1
- package/dist/web/assets/index-DIWzaS2_.js +0 -16
- 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/README.md
CHANGED
|
@@ -68,13 +68,28 @@ blade serve --port 3000 # 无头服务器模式
|
|
|
68
68
|
|
|
69
69
|
```json
|
|
70
70
|
{
|
|
71
|
-
"
|
|
72
|
-
"
|
|
73
|
-
|
|
74
|
-
|
|
71
|
+
"currentModelId": "custom",
|
|
72
|
+
"modelProviders": {
|
|
73
|
+
"company-gateway": {
|
|
74
|
+
"name": "Company Gateway",
|
|
75
|
+
"baseUrl": "https://gateway.example.com/v1",
|
|
76
|
+
"wireApi": "openai-completions"
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
"models": [
|
|
80
|
+
{
|
|
81
|
+
"id": "custom",
|
|
82
|
+
"provider": "company-gateway",
|
|
83
|
+
"model": "gpt-4o-mini"
|
|
84
|
+
}
|
|
85
|
+
]
|
|
75
86
|
}
|
|
76
87
|
```
|
|
77
88
|
|
|
89
|
+
API key 以渠道 ID 为键存放在权限为 `0600` 的 `~/.blade/auth.json`,不会写入模型
|
|
90
|
+
或渠道配置。TUI 与 Web 均可创建 OpenAI Chat Completions 和 Anthropic Messages
|
|
91
|
+
兼容渠道。
|
|
92
|
+
|
|
78
93
|
---
|
|
79
94
|
|
|
80
95
|
## 🧰 命令速览
|
|
@@ -84,7 +99,7 @@ blade serve --port 3000 # 无头服务器模式
|
|
|
84
99
|
- `blade` 启动交互式 CLI 界面
|
|
85
100
|
- `blade web` 启动 Web UI(0.2.0 新增)
|
|
86
101
|
- `blade serve` 启动无头服务器(0.2.0 新增)
|
|
87
|
-
- `blade mcp` 管理 MCP
|
|
102
|
+
- `blade mcp` 管理 MCP 服务器;`blade mcp login/logout` 显式管理远程 OAuth
|
|
88
103
|
- `blade doctor` 环境自检
|
|
89
104
|
- `blade update` 检查更新
|
|
90
105
|
|
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
3
|
-
Stack trace:`),console.error(
|
|
4
|
-
Run with --debug to show the stack trace.`);process.exit(1)}if(
|
|
5
|
-
Hint: Did you mean:`),
|
|
2
|
+
import{Hb as W}from"./chunk-km7m66vw.js";import{Kb as F,Lb as M}from"./chunk-kq5my0yy.js";import"./chunk-k6qwdjyy.js";import"./chunk-gafbzeyk.js";import"./chunk-0h81hxkw.js";import"./chunk-hefv4415.js";import"./chunk-beqaxytd.js";import{cd as T}from"./chunk-jxv6r0c7.js";import"./chunk-3nx2579c.js";import"./chunk-4vaywb2r.js";import"./chunk-qev36qrb.js";import{ge as N,he as B}from"./chunk-vjpd3nee.js";import"./chunk-a7nbn5kf.js";import"./chunk-2beq0syt.js";import"./chunk-h7kj4gvj.js";import"./chunk-6hj2dk75.js";import"./chunk-6n5xdf2r.js";import"./chunk-8nm1hqr1.js";import{Le as K}from"./chunk-mjp61rqd.js";import C from"node:path";var E=process.argv.slice(2),I=p(E),v=I!==null;if(I!==null)T.setGlobalDebug(I);function p(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function u(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function c(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function m(){if(u(E)){let{getVersion:J}=await import("./chunk-f19yx9an.js");console.log(J());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=c(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:J}=await import("./chunk-tkr4d9ej.js");J(U.map((Z)=>C.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:J}=await import("./chunk-6g21dh3n.js");await J.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let J=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(J&&!Z)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(q(E,"--headless")){let{handleHeadlessMode:J}=await import("./chunk-rppak8ep.js");if(await J())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:J}=await import("./chunk-t7ej11xd.js");if(await J())return}if(E.includes("--acp")){let{runAcpIntegration:J}=await import("./chunk-49sytjma.js");await J();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{doctorCommands:S},{installCommands:k},{mcpCommands:O},{projectsCommands:y},{serveCommand:b},{updateCommands:V},{webCommand:P}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-g0jb7v73.js"),import("./chunk-p6yed31x.js"),import("./chunk-5pvxw7sd.js"),import("./chunk-d3236505.js"),import("./chunk-11qty4fd.js"),import("./chunk-vvy506b3.js"),import("./chunk-g2972yzq.js"),import("./chunk-zkbf8n6y.js"),import("./chunk-w1wp1t52.js")]),x=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(O).command(y).command(S).command(V).command(k).command(P).command(b).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((J,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),v&&Z.stack)console.error(`
|
|
3
|
+
Stack trace:`),console.error(Z.stack);else console.error(`
|
|
4
|
+
Run with --debug to show the stack trace.`);process.exit(1)}if(J)console.error("Error: Invalid arguments:"),console.error(J),console.error(`
|
|
5
|
+
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(J)=>{let Z=J._.slice(1),L=Z.length>0?Z.join(" "):void 0,h=import("./chunk-m78ceafk.js").then(({checkVersionOnStartup:j})=>j()),[{render:A},{createElement:w},{AppWrapper:f}]=await Promise.all([import("ink"),import("react"),import("./chunk-859m18ra.js")]),H={...J,initialMessage:L,debug:J.debug,print:Boolean(J.print),versionCheckPromise:h};delete H._,delete H.$0,delete H.message,A(w(f,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await x.parse()}catch(J){console.error("Error: Parse error:",J),process.exit(1)}}if(K.main==K.module)m().catch(console.error);export{m as main};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{nanoid as q}from"nanoid";var u=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function B(j="session",m=21){if(!u.test(j))throw Error(`Invalid session ID prefix: ${j}`);return`${j}-${q(m)}`}
|
|
2
|
-
export{B as
|
|
2
|
+
export{B as mc};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import{ia as H}from"./chunk-51wa5fct.js";import"./chunk-88vy9hh0.js";import{ec as $,kc as T}from"./chunk-k6qwdjyy.js";import"./chunk-gafbzeyk.js";import"./chunk-0h81hxkw.js";import"./chunk-hefv4415.js";import"./chunk-beqaxytd.js";import"./chunk-jxv6r0c7.js";import"./chunk-3nx2579c.js";import"./chunk-4vaywb2r.js";import"./chunk-qev36qrb.js";import{he as k}from"./chunk-vjpd3nee.js";import"./chunk-a7nbn5kf.js";import"./chunk-2beq0syt.js";import"./chunk-h7kj4gvj.js";import"./chunk-6hj2dk75.js";import"./chunk-6n5xdf2r.js";import"./chunk-8nm1hqr1.js";import"./chunk-mjp61rqd.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
|
|
2
|
+
blade mcp
|
|
3
|
+
`),console.log(`管理 MCP 服务器
|
|
4
|
+
`),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
|
|
5
|
+
`),console.log("Options:"),console.log(` -h, --help 显示帮助信息 [boolean]
|
|
6
|
+
`),console.log("Examples:"),console.log(" blade mcp list"),console.log(" blade mcp add github npx -y @modelcontextprotocol/server-github"),console.log(" blade mcp add api --transport http http://localhost:3000"),console.log(` blade mcp remove github
|
|
7
|
+
`),console.log(`使用 blade mcp <command> --help 查看各子命令的详细帮助
|
|
8
|
+
`)}function I(z){return z.reduce((q,K)=>{let[F,...B]=K.split("=");return q[F]=B.join("="),q},{})}function R(z){return z.reduce((q,K)=>{let[F,...B]=K.split(":");return q[F.trim()]=B.join(":").trim(),q},{})}var M={command:"add <name> [commandOrUrl] [args...]",describe:"添加 MCP 服务器",builder:(z)=>{return z.positional("name",{type:"string",describe:"服务器名称",demandOption:!0}).positional("commandOrUrl",{type:"string",describe:"stdio: 命令 | http/sse: URL"}).positional("args",{type:"string",array:!0,describe:"stdio 命令参数",default:[]}).option("transport",{alias:"t",choices:["stdio","sse","http"],default:"stdio",describe:"传输类型"}).option("env",{alias:"e",type:"array",describe:"环境变量 (KEY=value)"}).option("header",{alias:"H",type:"array",describe:"HTTP 头 (Key: Value)"}).option("timeout",{type:"number",describe:"超时时间(毫秒)"}).option("global",{alias:"g",type:"boolean",default:!1,describe:"存储到全局配置(~/.blade/config.json)"}).example([["$0 mcp add github -- npx -y @modelcontextprotocol/server-github","Add stdio server (recommended)"],["$0 mcp add github npx @modelcontextprotocol/server-github -e GITHUB_TOKEN=xxx","Add stdio server with env"],['$0 mcp add api --transport http http://localhost:3000 -H "Auth: Bearer token"',"Add HTTP server"]])},handler:async(z)=>{try{let{name:q,commandOrUrl:K,args:F,transport:B,env:Q,header:V,timeout:Y}=z,W=z.global===!0,x=X(q),_=X(K),L=N(F)||[],w=N(Q),D=N(V),O=typeof Y==="number"?Y:void 0,P=B==="stdio"||B==="sse"||B==="http"?B:"stdio",E=z["--"];if(Array.isArray(E)&&E.length>0)_=String(E[0]),L=E.slice(1).map((G)=>String(G));if(!x||!_)console.error("Error: 缺少必需参数: name 和 commandOrUrl"),console.log(`
|
|
9
|
+
Tip: 用法:`),console.log(" blade mcp add <name> <command> [args...]"),console.log(" blade mcp add <name> -- <command> [args...]"),console.log(`
|
|
10
|
+
示例:`),console.log(" blade mcp add github npx -y @modelcontextprotocol/server-github"),console.log(" blade mcp add github -- npx -y @modelcontextprotocol/server-github"),process.exit(1);let Z={type:P};if(P==="stdio"){if(Z.command=_,Z.args=L,w)Z.env=I(w)}else if(Z.url=_,D)Z.headers=R(D);if(O!==void 0)Z.timeout=O;await T().addMcpServer(x,Z,{scope:W?"global":"project"});let j=W?J.join(U.homedir(),".blade","config.json"):J.join(k(),".blade","config.json");console.log(`MCP 服务器 "${x}" 已添加`),console.log(` 配置文件: ${j}`)}catch(q){console.error(`Error: 添加失败: ${q instanceof Error?q.message:"未知错误"}`),process.exit(1)}}},C={command:"remove <name>",describe:"删除 MCP 服务器",aliases:["rm"],builder:(z)=>{return z.positional("name",{type:"string",describe:"服务器名称",demandOption:!0}).option("global",{alias:"g",type:"boolean",default:!1,describe:"从全局配置删除(~/.blade/config.json)"}).example([["$0 mcp remove github","Remove the specified MCP server"]])},handler:async(z)=>{try{let q=$(),K=z.global===!0,F=X(z.name);if(!F)console.error("Error: 缺少必需参数: name"),process.exit(1);if(!q[F])console.error(`Error: 服务器 "${F}" 不存在`),process.exit(1);await T().removeMcpServer(F,{scope:K?"global":"project"}),console.log(`MCP 服务器 "${F}" 已删除`)}catch(q){console.error(`Error: 删除失败: ${q instanceof Error?q.message:"未知错误"}`),process.exit(1)}}},A={command:"list",describe:"列出所有 MCP 服务器并检查健康状态",aliases:["ls"],handler:async()=>{try{let z=$();if(console.log(""),Object.keys(z).length===0){console.log("暂无配置的 MCP 服务器");return}console.log(`检查 MCP 服务器健康状态...
|
|
11
|
+
`);let q=H.getInstance(),K=Object.entries(z).map(async([B,Q])=>{try{let V=q.getServerStatus(B);if(!V)await q.registerServer(B,Q),V=q.getServerStatus(B);else if(V.status==="disconnected")await q.connectServer(B);return{name:B,config:Q,serverInfo:V}}catch(V){return{name:B,config:Q,serverInfo:null,error:V}}}),F=await Promise.all(K);for(let{name:B,config:Q,serverInfo:V,error:Y}of F){let W=V?.status||"disconnected",x=W==="connected"?"[OK]":W==="reconnecting"?"[WAIT]":"[FAIL]",_=W==="connected"?"Connected":W==="reconnecting"?`Recovering ${V?.recovery?.attempt??0}/${V?.recovery?.maxAttempts??0}`:"Failed";if(console.log(`${B}: ${Q.type==="stdio"?Q.command:Q.url} - ${x} ${_}`),Y&&W!=="connected")console.log(` 错误: ${Y instanceof Error?Y.message:String(Y)}`)}console.log("");for(let{name:B}of F)try{await q.unregisterServer(B)}catch(Q){}process.exit(0)}catch(z){console.error(`Error: 列表获取失败: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}}},h={command:"get <name>",describe:"获取服务器详情",builder:(z)=>{return z.positional("name",{type:"string",describe:"服务器名称",demandOption:!0}).example([["$0 mcp get github","Get details of the specified server"]])},handler:async(z)=>{try{let q=$(),K=X(z.name);if(!K)console.error("Error: 缺少必需参数: name"),process.exit(1);let F=q[K];if(!F)console.error(`Error: 服务器 "${K}" 不存在`),process.exit(1);console.log(`
|
|
12
|
+
服务器: ${K}
|
|
13
|
+
`),console.log(JSON.stringify(F,null,2))}catch(q){console.error(`Error: 获取失败: ${q instanceof Error?q.message:"未知错误"}`),process.exit(1)}}},d={command:"login <name>",describe:"显式启动远程 MCP OAuth 登录",builder:(z)=>z.positional("name",{type:"string",describe:"服务器名称",demandOption:!0}),handler:async(z)=>{let q=X(z.name);if(!q){console.error("Error: 缺少必需参数: name"),process.exitCode=1;return}let K=$()[q];if(!K){console.error(`Error: 服务器 "${q}" 不存在`),process.exitCode=1;return}let F=H.getInstance();try{if(!F.getServerStatus(q))await F.registerServer(q,K,{connect:!1});let B=await F.beginOAuthLogin(q,{openBrowser:!0});console.log(`OAuth 授权已启动: ${B.authorizationUrl}`),console.log("等待浏览器授权完成..."),await B.completion,console.log(`MCP 服务器 "${q}" OAuth 登录成功`)}catch(B){console.error(`Error: OAuth 登录失败: ${B instanceof Error?B.message:"未知错误"}`),process.exitCode=1}finally{await F.unregisterServer(q)}}},l={command:"logout <name>",describe:"清除远程 MCP OAuth 凭证",builder:(z)=>z.positional("name",{type:"string",describe:"服务器名称",demandOption:!0}),handler:async(z)=>{let q=X(z.name);if(!q){console.error("Error: 缺少必需参数: name"),process.exitCode=1;return}let K=$()[q];if(!K){console.error(`Error: 服务器 "${q}" 不存在`),process.exitCode=1;return}let F=H.getInstance();try{if(!F.getServerStatus(q))await F.registerServer(q,K,{connect:!1});await F.logoutOAuth(q),console.log(`MCP 服务器 "${q}" OAuth 凭证已清除`)}catch(B){console.error(`Error: OAuth 登出失败: ${B instanceof Error?B.message:"未知错误"}`),process.exitCode=1}finally{await F.unregisterServer(q)}}},f={command:"add-json <name> <json>",describe:"从 JSON 字符串添加服务器",builder:(z)=>{return z.positional("name",{type:"string",describe:"服务器名称",demandOption:!0}).positional("json",{type:"string",describe:"JSON 配置字符串",demandOption:!0}).option("global",{alias:"g",type:"boolean",default:!1,describe:"存储到全局配置(~/.blade/config.json)"}).example([[`$0 mcp add-json my-server '{"type":"stdio","command":"npx","args":["-y","@example/server"]}'`,"Add server from JSON string"]])},handler:async(z)=>{try{let q=X(z.json),K=X(z.name);if(!q||!K)throw Error("缺少必需参数: name 或 json");let F=JSON.parse(q),B=z.global===!0;if(!F.type)throw Error('配置必须包含 "type" 字段');await T().addMcpServer(K,F,{scope:B?"global":"project"});let Q=B?J.join(U.homedir(),".blade","config.json"):J.join(k(),".blade","config.json");console.log(`MCP 服务器 "${K}" 已添加`),console.log(` 配置文件: ${Q}`)}catch(q){console.error(`Error: 添加失败: ${q instanceof Error?q.message:"未知错误"}`),process.exit(1)}}},m={command:"mcp",describe:"管理 MCP 服务器",builder:(z)=>{return z.command(M).command(C).command(A).command(h).command(d).command(l).command(f).demandCommand(0).help(!1).option("help",{alias:"h",type:"boolean",describe:"显示帮助信息"})},handler:(z)=>{let q=["add","remove","list","ls","get","login","logout","add-json"];if(!(Array.isArray(z._)?z._:[]).some((B)=>typeof B==="string"&&q.includes(B))||z.help)b(),process.exit(0)}};export{m as mcpCommands};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{Rd as F}from"./chunk-3nx2579c.js";import{le as D,me as E}from"./chunk-a7nbn5kf.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
|
|
2
|
+
export{H as xc,Q as yc,T as zc};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var t=["auto","low","medium","high"],s=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function n(e){return/(?:^|[/.:_-])gpt-5(?:$|[/.:_-])/i.test(e.id)}function f(e){return typeof e==="string"&&t.includes(e)}function p(e){if(e.api==="openai-codex-responses"||s.has(e.api)&&n(e))return["low","medium","high"];return[]}function u(e,r){let i=p(e);if(r!=="auto"&&!i.includes(r))throw Error(`Response verbosity ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};return{selection:r,effective:r,supported:i,providerValue:r}}var a=["auto","standard","fast","flex"],o=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function S(e){return typeof e==="string"&&a.includes(e)}function c(e){if(o.has(e.api))return["standard","fast","flex"];if(e.api==="anthropic-messages"&&/(?:^|-)claude-opus-4-6(?:-|$)/i.test(e.id))return["standard","fast"];return["standard"]}function l(e,r){let i=c(e);if(r!=="auto"&&!i.includes(r))throw Error(`Service tier ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};if(r==="standard")return{selection:r,effective:"standard",supported:i,...o.has(e.api)?{providerValue:"default"}:{}};if(r==="fast")return{selection:r,effective:"fast",supported:i,providerValue:e.api==="anthropic-messages"?"fast":"priority"};return{selection:r,effective:"flex",supported:i,providerValue:"flex"}}
|
|
2
|
+
export{f as ne,p as oe,u as pe,S as qe,c as re,l as se};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import{$d as Zn,Ud as rn,Vd as D,Wd as m,ae as Jn}from"./chunk-4vaywb2r.js";import{be as Nn,ce as pn}from"./chunk-qev36qrb.js";import{he as b}from"./chunk-vjpd3nee.js";import{je as Dn,me as H}from"./chunk-a7nbn5kf.js";import{ue as En,ve as fn}from"./chunk-h7kj4gvj.js";import{ze as P}from"./chunk-6hj2dk75.js";import{Je as un}from"./chunk-8nm1hqr1.js";var Qn=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Wn(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function I(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&Wn(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{I(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function q(n){let t=n.oauth;if(!t)return;let e=t;for(let o of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[o]!==void 0)throw Error(`MCP OAuth "${o}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(I(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((o)=>o.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let u=t.clientId?.trim();if(u&&u.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let _=t.scopes?.map((o)=>o.trim());if(_){if(_.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(_.some((o)=>!o||o.length>128||!Qn.test(o)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(_).size!==_.length)throw Error("MCP OAuth scopes must not contain duplicates")}let M=t.callbackPort;if(M!==void 0&&(!Number.isInteger(M)||M<1024||M>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...u?{clientId:u}:{},..._?.length?{scopes:_}:{},...M!==void 0?{callbackPort:M}:{}}}import{randomUUID as J}from"node:crypto";import it from"node:http";import{auth as on}from"@modelcontextprotocol/sdk/client/auth.js";import St from"open";import{createHash as jn,randomUUID as Fn}from"node:crypto";import{constants as O,promises as A}from"node:fs";import Y from"node:path";import{Mutex as vn}from"async-mutex";import nt from"write-file-atomic";var Mn=1,tt=1048576,et=5000,ut=50,rt=/^[a-f0-9]{64}$/,Mt=m.Object({client_id:m.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),_t=m.Object({access_token:m.String({minLength:1,maxLength:65536}),token_type:m.String({minLength:1,maxLength:64}),expires_in:m.Optional(m.Number({minimum:0})),refresh_token:m.Optional(m.String({minLength:1,maxLength:65536})),scope:m.Optional(m.String({maxLength:16384})),id_token:m.Optional(m.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),ot=m.Unsafe({type:"object",properties:{authorizationServerUrl:m.String({format:"uri"}),resourceMetadataUrl:m.Optional(m.String({format:"uri"})),resourceMetadata:m.Optional(m.Unknown()),authorizationServerMetadata:m.Optional(m.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),_n=m.Object({serverUrl:m.String({format:"uri"}),clientId:m.Optional(m.String({minLength:1,maxLength:4096})),clientInformation:m.Optional(Mt),tokens:m.Optional(_t),tokenExpiresAt:m.Optional(m.Number({minimum:0})),discoveryState:m.Optional(ot),updatedAt:m.String({format:"date-time"})},{additionalProperties:!1}),tn=m.Object({version:m.Literal(Mn),credentials:m.Record(m.String(),_n)},{additionalProperties:!1});function y(n,t){return n instanceof Error&&"code"in n&&n.code===t}function st(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return y(t,"EPERM")}}function V(n){return structuredClone(n)}function en(n){if(Object.keys(n.credentials).some((t)=>!rt.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function K(n){let t=new URL(n);return t.hash="",t.toString()}function Z(n,t,e=[]){return jn("sha256").update(JSON.stringify({serverUrl:K(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class x{static mutexes=new Map;stateRoot;tokenFilePath;mutex;constructor(n=un()){this.stateRoot=Y.join(n,"mcp"),this.tokenFilePath=Y.join(this.stateRoot,"oauth-credentials.json");let t=x.mutexes.get(this.tokenFilePath);if(!t)t=new vn,x.mutexes.set(this.tokenFilePath,t);this.mutex=t}async getCredential(n){return this.mutex.runExclusive(async()=>{let e=(await this.readStore()).credentials[n];return e?V(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let r=e.credentials[n],u=await t(r?V(r):null);if(u)e.credentials[n]=D(_n,u);else delete e.credentials[n];return u?V(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return this.mutex.runExclusive(async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return this.mutex.runExclusive(async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),r=await n(e);return await this.writeStore(e),r}finally{await t()}})}async ensureStateRoot(){await A.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await A.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await A.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>tt)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await A.readFile(this.tokenFilePath,"utf8")),e=rn(tn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return en(e.data),e.data}catch(n){if(y(n,"ENOENT"))return{version:Mn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=D(tn,n);en(t),await nt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
|
|
2
|
+
`,{mode:384,encoding:"utf8"}),await A.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=Y.join(this.stateRoot,".oauth-credentials.lock"),t=Fn(),e=Date.now()+et;while(Date.now()<e)try{let r=await A.open(n,O.O_CREAT|O.O_EXCL|O.O_WRONLY,384);return await r.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
|
|
3
|
+
`,"utf8"),await r.close(),async()=>{try{if(JSON.parse(await A.readFile(n,"utf8")).token===t)await A.unlink(n)}catch(u){if(!y(u,"ENOENT"))throw u}}}catch(r){if(!y(r,"EEXIST"))throw r;await this.removeDeadLock(n),await new Promise((u)=>setTimeout(u,ut))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await A.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let e=JSON.parse(await A.readFile(n,"utf8"));if(typeof e.pid!=="number"||!Number.isInteger(e.pid)||e.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!st(e.pid))await A.unlink(n)}}var sn="127.0.0.1",Sn=7777,mn="/oauth/callback",mt=300000;class Q extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class an extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function Et(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
|
|
4
|
+
<html lang="en">
|
|
5
|
+
<head>
|
|
6
|
+
<meta charset="utf-8">
|
|
7
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
8
|
+
<title>${t}</title>
|
|
9
|
+
</head>
|
|
10
|
+
<body>
|
|
11
|
+
<main>
|
|
12
|
+
<h1>${t}</h1>
|
|
13
|
+
<p>${n?"You can close this window and return to Blade.":"Return to Blade and retry the OAuth login."}</p>
|
|
14
|
+
</main>
|
|
15
|
+
</body>
|
|
16
|
+
</html>`}function X(n,t,e){n.writeHead(t,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Content-Security-Policy":"default-src 'none'; style-src 'unsafe-inline'","X-Content-Type-Options":"nosniff","Referrer-Policy":"no-referrer"}),n.end(Et(e))}class L{serverName;config;static activeFlowIdentity;tokenStorage;serverUrl;identity;callbackUrl;openAuthorizationUrl;codeVerifierValue;activeFlow;lastError;constructor(n,t,e,r={}){this.serverName=n;this.config=e;this.serverUrl=K(t),this.identity=Z(this.serverUrl,e.clientId,e.scopes),this.tokenStorage=r.tokenStorage??new x;let u=e.callbackPort??Sn;this.callbackUrl=`http://${sn}:${u}${mn}`,this.openAuthorizationUrl=r.openAuthorizationUrl??(async(_)=>{await St(_,{wait:!1})})}get redirectUrl(){return this.callbackUrl}get clientMetadata(){return{redirect_uris:[this.callbackUrl],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:`${fn()} ${En()}`,...this.config.scopes?.length?{scope:this.config.scopes.join(" ")}:{}}}async state(){return this.activeFlow?.state??J()}async clientInformation(){if(this.config.clientId)return{client_id:this.config.clientId};return(await this.readCredential())?.clientInformation}async saveClientInformation(n){await this.updateCredential((t)=>({...this.baseCredential(t),clientInformation:n}))}async tokens(){let n=await this.readCredential();if(!n?.tokens)return;if(n.tokenExpiresAt!==void 0&&n.tokenExpiresAt<=Date.now()&&!n.tokens.refresh_token)return;return structuredClone(n.tokens)}async saveTokens(n){let t=n.expires_in===void 0?void 0:Date.now()+n.expires_in*1000;await this.updateCredential((e)=>({...this.baseCredential(e),tokens:structuredClone(n),...t===void 0?{}:{tokenExpiresAt:t}})),this.lastError=void 0}async redirectToAuthorization(n){let t=this.activeFlow;if(!t)throw new Q(this.serverName);t.authorizationUrl=I(n,"MCP OAuth authorization URL").toString()}async saveCodeVerifier(n){this.codeVerifierValue=n}async codeVerifier(){if(!this.codeVerifierValue)throw Error("MCP OAuth PKCE verifier is unavailable");return this.codeVerifierValue}async saveDiscoveryState(n){await this.updateCredential((t)=>({...this.baseCredential(t),discoveryState:structuredClone(n)}))}async discoveryState(){let n=(await this.readCredential())?.discoveryState;return n?structuredClone(n):void 0}async invalidateCredentials(n){if(n==="verifier"){this.codeVerifierValue=void 0;return}if(n==="all"){await this.tokenStorage.deleteCredential(this.identity),this.codeVerifierValue=void 0;return}await this.updateCredential((t)=>{if(!t)return null;let e={...t};if(n==="client")delete e.clientInformation,delete e.tokens,delete e.tokenExpiresAt;else if(n==="tokens")delete e.tokens,delete e.tokenExpiresAt;else if(n==="discovery")delete e.discoveryState;return{...e,updatedAt:new Date().toISOString()}})}async getStatus(){if(this.activeFlow)return"authorizing";if(this.lastError)return"error";return await this.hasUsableCredentials()?"authenticated":"unauthenticated"}async hasUsableCredentials(){let n=await this.readCredential();if(!n?.tokens?.access_token)return!1;if(n.tokenExpiresAt===void 0||n.tokenExpiresAt>Date.now())return!0;return Boolean(n.tokens.refresh_token)}async beginAuthorization(){if(this.activeFlow)return this.toHandle(this.activeFlow);if(await this.hasUsableCredentials())throw Error(`MCP server "${this.serverName}" already has OAuth credentials`);if(L.activeFlowIdentity)throw Error("Another MCP OAuth authorization is already in progress");L.activeFlowIdentity=this.identity,this.lastError=void 0,this.codeVerifierValue=void 0;try{let n=await this.createFlow();if(this.activeFlow=n,await on(this,{serverUrl:this.serverUrl,fetchFn:B})!=="REDIRECT"||!n.authorizationUrl)throw Error("MCP OAuth server did not start an authorization redirect");return this.toHandle(n)}catch(n){let t=n instanceof Error?n:Error(String(n));throw await this.failActiveFlow(t),t}}async openAuthorization(){let n=await this.beginAuthorization();return await this.openAuthorizationUrl(n.authorizationUrl),n}async logout(){if(this.activeFlow)await this.failActiveFlow(Error("MCP OAuth authorization cancelled"));await this.tokenStorage.deleteCredential(this.identity),this.codeVerifierValue=void 0,this.lastError=void 0}async dispose(){if(this.activeFlow)await this.failActiveFlow(Error("MCP OAuth authorization cancelled"))}async createFlow(){let n,t,e=new Promise((M,o)=>{n=M,t=o});e.catch(()=>{return});let r=J(),u=it.createServer((M,o)=>{this.handleCallback(M,o)});u.on("clientError",(M,o)=>{o.end(`HTTP/1.1 400 Bad Request\r
|
|
17
|
+
Connection: close\r
|
|
18
|
+
\r
|
|
19
|
+
`)}),await new Promise((M,o)=>{let s=(S)=>o(S);u.once("error",s),u.listen(this.config.callbackPort??Sn,sn,()=>{u.off("error",s),M()})});let _={flowId:J(),state:r,callbackUrl:this.callbackUrl,server:u,timeout:setTimeout(()=>{this.failActiveFlow(Error("MCP OAuth authorization timed out"))},mt),completion:e,resolve:n,reject:t,settled:!1};return _.timeout.unref(),_}async handleCallback(n,t){let e=this.activeFlow;if(!e){X(t,410,!1);return}try{if(n.method!=="GET"){t.setHeader("Allow","GET"),X(t,405,!1);return}let r=new URL(n.url??"/",e.callbackUrl);if(r.pathname!==mn){X(t,404,!1);return}let u=r.searchParams.get("state"),_=r.searchParams.get("code");if(r.searchParams.get("error"))throw Error("MCP OAuth authorization was denied");if(!u||u!==e.state)throw Error("MCP OAuth state mismatch");if(!_)throw Error("MCP OAuth callback is missing the authorization code");if(await on(this,{serverUrl:this.serverUrl,authorizationCode:_,fetchFn:B})!=="AUTHORIZED")throw Error("MCP OAuth token exchange did not complete");X(t,200,!0),await this.completeActiveFlow()}catch(r){X(t,400,!1),await this.failActiveFlow(r instanceof Error?r:Error(String(r)))}}async completeActiveFlow(){let n=this.activeFlow;if(!n||n.settled)return;n.settled=!0,clearTimeout(n.timeout),await new Promise((t)=>n.server.close(()=>t())),this.activeFlow=void 0,L.activeFlowIdentity=void 0,this.codeVerifierValue=void 0,this.lastError=void 0,n.resolve()}async failActiveFlow(n){let t=this.activeFlow;if(this.lastError=n,this.codeVerifierValue=void 0,L.activeFlowIdentity=void 0,!t||t.settled){this.activeFlow=void 0;return}t.settled=!0,clearTimeout(t.timeout),await new Promise((e)=>t.server.close(()=>e())),this.activeFlow=void 0,t.reject(n)}toHandle(n){if(!n.authorizationUrl)throw Error("MCP OAuth authorization URL is unavailable");return{flowId:n.flowId,authorizationUrl:n.authorizationUrl,callbackUrl:n.callbackUrl,completion:n.completion}}readCredential(){return this.tokenStorage.getCredential(this.identity)}updateCredential(n){return this.tokenStorage.updateCredential(this.identity,n)}baseCredential(n){return{...n??{},serverUrl:this.serverUrl,...this.config.clientId?{clientId:this.config.clientId}:{},updatedAt:new Date().toISOString()}}}var E={currentModelId:"",models:[],modelProviders:{},temperature:0,maxOutputTokens:void 0,stream:!0,topP:0.9,topK:50,timeout:180000,theme:"dracula",uiTheme:"system",language:"zh-CN",fontSize:14,autoSaveSessions:!0,notifyBuild:!0,notifyErrors:!1,notifySounds:!1,privacyTelemetry:!1,privacyCrash:!0,debug:!1,mcpEnabled:!1,mcpServers:{},lspServers:{},permissions:{allow:["Bash(pwd)","Bash(which *)","Bash(whoami)","Bash(hostname)","Bash(uname *)","Bash(date)","Bash(echo *)","Bash(ls *)","Bash(tree *)","Bash(git status)","Bash(git status -*)","Bash(git log *)","Bash(git diff *)","Bash(git show *)","Bash(git branch -* *)","Bash(git branch)","Bash(git tag -l *)","Bash(git tag --list *)","Bash(git stash list *)","Bash(git stash show *)","Bash(git rev-parse *)","Bash(git describe *)","Bash(git blame *)","Bash(git ls-files *)","Bash(git config --get *)","Bash(git config --list *)","Bash(git shortlog *)","Bash(git merge-base *)","Bash(git cat-file *)","Bash(git for-each-ref *)","Bash(git grep *)","Bash(git worktree list *)","Bash(git reflog show *)","Bash(git reflog)","Bash(git rev-list *)","Bash(git ls-remote *)","Bash(git remote -v)","Bash(git remote --verbose)","Bash(git remote)","Bash(gh pr view *)","Bash(gh pr list *)","Bash(gh pr diff *)","Bash(gh pr checks *)","Bash(gh pr status *)","Bash(gh issue view *)","Bash(gh issue list *)","Bash(gh issue status *)","Bash(gh run list *)","Bash(gh run view *)","Bash(gh repo view *)","Bash(gh auth status)","Bash(npm list *)","Bash(bun pm ls *)","Bash(npm view *)","Bash(npm outdated *)","Bash(pnpm list *)","Bash(yarn list *)","Bash(pip list *)","Bash(pip show *)"],ask:["Bash(curl *)","Bash(wget *)","Bash(aria2c *)","Bash(axel *)","Bash(rm -rf *)","Bash(rm -r *)","Bash(rm --recursive *)","Bash(nc *)","Bash(netcat *)","Bash(telnet *)","Bash(ncat *)"],deny:["Read(./.env)","Read(./.env.*)","Bash(rm -rf /)","Bash(rm -rf /*)","Bash(sudo *)","Bash(chmod 777 *)","Bash(bash *)","Bash(sh *)","Bash(zsh *)","Bash(fish *)","Bash(dash *)","Bash(eval *)","Bash(source *)","Bash(mkfs *)","Bash(fdisk *)","Bash(dd *)","Bash(format *)","Bash(parted *)","Bash(open http*)","Bash(open https*)","Bash(xdg-open http*)","Bash(xdg-open https*)"]},permissionMode:"default",hooks:{enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionRequest:[],Elicitation:[],ElicitationResult:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]},enabledPlugins:{},pluginSourcePolicy:{restrictToAllowedSources:!1,requireGitCommitSha:!1,allowedGitHosts:[],allowedMarketplaces:[],allowedLocalRoots:[]},env:{},disableAllHooks:!1,maxTurns:-1,maxConcurrentTasks:3,maxQueuedTasks:100};import{promises as Vn}from"fs";import{merge as R}from"lodash-es";import a from"os";import i from"path";function Tn(n){let t=cn(n.timeout??300000,"MCP timeout"),e=cn(n.idleTimeout??Math.min(60000,t),"MCP idleTimeout");if(e>t)throw Error("MCP idleTimeout must not exceed timeout");return{totalTimeoutMs:t,idleTimeoutMs:e,maxProgressEvents:128}}function ie(n,t,e){if(t.count>=e.maxProgressEvents)return;if(!Number.isFinite(n.progress)||n.progress<0)return;if(n.total!==void 0&&(!Number.isFinite(n.total)||n.total<=0))return;if(t.lastProgress!==void 0&&n.progress<t.lastProgress)return;t.count++,t.lastProgress=n.progress;let r=n.message?.replace(/\0/g,"").trim().slice(0,1000);return{progress:n.progress,...n.total!==void 0?{total:n.total}:{},message:r||at(n.progress,n.total)}}function cn(n,t){if(!Number.isSafeInteger(n)||n<1000||n>1800000)throw Error(`${t} must be an integer between 1000 and 1800000 milliseconds`);return n}function at(n,t){if(t!==void 0)return`MCP progress ${Math.max(0,Math.min(100,n/t*100)).toFixed(0)}%`;return`MCP progress ${n}`}import{createHash as ct}from"node:crypto";var U=["debug","info","notice","warning","error","critical","alert","emergency"],Ee=64,fe=64,ae=256,Tt=8192,Pn=16384,At=256,bt=6,gt=128,An=64,bn=64,Pt=128,wt=/authorization|api[-_]?key|cookie|credential|password|secret|token/i;function wn(n){let t=n.logging;if(t!==void 0&&(t===null||typeof t!=="object"||Array.isArray(t)))throw Error("MCP logging configuration must be an object");let e=t?.enabled??!0;if(typeof e!=="boolean")throw Error("MCP logging enabled must be a boolean");let r=t?.level??"warning";if(!dt(r))throw Error(`MCP logging level must be one of: ${U.join(", ")}`);return{enabled:e,level:r}}function dt(n){return typeof n==="string"&&U.includes(n)}function ce(n,t){return U.indexOf(n)>=U.indexOf(t)}function xt(n,t={}){let e=Lt(n.data),r=typeof e.value==="string"?e.value:JSON.stringify(e.value),u=gn(r,Pn),_=u.value,M=Buffer.byteLength(_),o=ct("sha256").update(_).digest("hex"),s=t.exposeDetails!==!1,S=s?gn(_,Tt):{value:`[MCP log details omitted; sha256=${o}]`,truncated:!1},T=s&&n.logger?k(j(n.logger),At):void 0;return{level:n.level,...T?{logger:T}:{},message:S.value||"[empty MCP log message]",projectedBytes:M,dataSha256:o,truncated:e.truncated||u.truncated||S.truncated,detailsOmitted:!s,timestamp:t.now??Date.now()}}function Te(n,t={}){return{...xt({level:"warning",logger:"blade.mcp.logging",data:`MCP log rate exceeded; dropped at least ${Math.max(1,n)} message(s)`},t),synthetic:!0}}function Lt(n){let t={nodes:0,remainingStringBytes:Pn,truncated:!1,seen:new WeakSet};return{value:W(n,0,t),truncated:t.truncated}}function W(n,t,e){if(e.nodes++,e.nodes>gt)return e.truncated=!0,"[node limit reached]";if(n===null||typeof n==="boolean")return n;if(typeof n==="number")return Number.isFinite(n)?n:String(n);if(typeof n==="bigint")return n.toString();if(typeof n==="string"){let r=j(n),u=Math.max(0,e.remainingStringBytes),_=k(r,u),M=Buffer.byteLength(_);if(e.remainingStringBytes-=M,M<Buffer.byteLength(r))e.truncated=!0;return _}if(typeof n>"u")return"[undefined]";if(typeof n==="symbol"||typeof n==="function")return`[${typeof n}]`;if(t>=bt)return e.truncated=!0,"[depth limit reached]";if(e.seen.has(n))return e.truncated=!0,"[circular]";e.seen.add(n);try{if(Array.isArray(n)){if(n.length>An)e.truncated=!0;return n.slice(0,An).map((_)=>W(_,t+1,e))}let r=Object.create(null),u=Object.entries(n);if(u.length>bn)e.truncated=!0;for(let[_,M]of u.slice(0,bn)){let o=k(j(_),Pt)||"[empty-key]";if(_==="_meta"||wt.test(_))r[o]="[redacted]";else r[o]=W(M,t+1,e)}return r}finally{e.seen.delete(n)}}function j(n){return[...n.replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]")].filter((e)=>{let r=e.charCodeAt(0);return(r===9||r===10||r===13||r>=32)&&r!==127}).join("")}function k(n,t){if(t<=0)return"";if(Buffer.byteLength(n)<=t)return n;let e=Buffer.from(n).subarray(0,t).toString("utf8");while(Buffer.byteLength(e)>t)e=e.slice(0,-1);return e}function gn(n,t){if(Buffer.byteLength(n)<=t)return{value:n,truncated:!1};let e=`
|
|
20
|
+
...[MCP log truncated]`;return{value:k(n,t-Buffer.byteLength(e))+e,truncated:!0}}var dn=1024,ht=4096,xn=2,Ct=8,Ln=65536,$t=1048576,hn=50,Cn=16000,$n=4,It=100,In=1048576,Xt=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function Rn(n){if(!n)return{enabled:!1,maxTokens:dn,maxRequestsPerToolCall:xn,maxInputBytes:Ln};if(typeof n.enabled!=="boolean")throw Error("MCP sampling.enabled must be a boolean");return{enabled:n.enabled,maxTokens:z(n.maxTokens??dn,1,ht,"MCP sampling.maxTokens"),maxRequestsPerToolCall:z(n.maxRequestsPerToolCall??xn,1,Ct,"MCP sampling.maxRequestsPerToolCall"),maxInputBytes:z(n.maxInputBytes??Ln,1,$t,"MCP sampling.maxInputBytes")}}function ge(n,t){if(!t.enabled)throw Error("MCP sampling is disabled");if(n.task)throw Error("Task-based MCP sampling is not supported");if(n.tools?.length)throw Error("MCP sampling tools were not negotiated");if(n.includeContext&&n.includeContext!=="none")throw Error("MCP sampling server context was not negotiated");if(n.messages.length===0||n.messages.length>hn)throw Error(`MCP sampling messages must contain 1-${hn} entries`);if(n.systemPrompt!==void 0&&n.systemPrompt.length>Cn)throw Error(`MCP sampling system prompt exceeds ${Cn} characters`);if(n.temperature!==void 0&&(!Number.isFinite(n.temperature)||n.temperature<0||n.temperature>2))throw Error("MCP sampling temperature must be between 0 and 2");let e=n.stopSequences??[];if(e.length>$n||e.some((S)=>!S||S.length>It||S.includes("\x00")))throw Error(`MCP sampling stop sequences must contain at most ${$n} non-empty bounded values`);let r=[],u=0,_=0,M=0,o=[];if(n.systemPrompt)u+=Buffer.byteLength(n.systemPrompt,"utf8"),r.push({role:"system",content:n.systemPrompt}),o.push(`System: ${Xn(n.systemPrompt)}`);for(let S of n.messages){let T=Array.isArray(S.content)?S.content:[S.content],g=[],c=[];for(let f of T){if(f.type==="text"){u+=Buffer.byteLength(f.text,"utf8"),g.push({type:"text",text:f.text}),c.push(Xn(f.text));continue}if(f.type==="image"){if(S.role!=="user")throw Error("MCP sampling images are only supported in user messages");if(!Xt.has(f.mimeType))throw Error(`Unsupported MCP sampling image type: ${f.mimeType}`);let $=Nt(f.data);_+=$,M++,g.push({type:"image_url",image_url:{url:`data:${f.mimeType};base64,${f.data}`}}),c.push(`[${f.mimeType} image, ${$} bytes]`);continue}throw Error(`Unsupported MCP sampling content type: ${f.type}`)}if(g.length===0)throw Error("MCP sampling message has no supported content");r.push({role:S.role,content:g.length===1&&g[0]?.type==="text"?g[0].text:g}),o.push(`${S.role==="user"?"User":"Assistant"}: ${c.join(" ")}`)}if(u+_>t.maxInputBytes)throw Error(`MCP sampling input exceeds ${t.maxInputBytes} bytes`);if(M>Nn||_>pn)throw Error("MCP sampling image input exceeds the shared attachment budget");let s=z(n.maxTokens,1,Number.MAX_SAFE_INTEGER,"MCP sampling maxTokens");return{messages:r,maxTokens:Math.min(s,t.maxTokens),...n.temperature!==void 0?{temperature:n.temperature}:{},stopSequences:[...e],preview:o.join(`
|
|
21
|
+
`).slice(0,8000)}}function Pe(n,t,e){if(n.toolCalls?.length)throw Error("Model returned tools for basic MCP sampling");let r=n.content,u=n.finishReason==="length"||n.finishReason==="max_tokens"?"maxTokens":"endTurn",_=-1;for(let M of e.stopSequences){let o=r.indexOf(M);if(o>=0&&(_===-1||o<_))_=o}if(_>=0)r=r.slice(0,_),u="stopSequence";if(Buffer.byteLength(r,"utf8")>In)throw Error(`MCP sampling response exceeds ${In} bytes`);return{model:t,role:"assistant",content:{type:"text",text:r},stopReason:u}}function z(n,t,e,r){if(!Number.isSafeInteger(n)||n<t||n>e)throw Error(`${r} must be an integer between ${t} and ${e}`);return n}function Nt(n){if(!n||n.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(n))throw Error("MCP sampling image contains invalid base64 data");return Buffer.from(n,"base64").byteLength}function Xn(n){return n.replace(/\s+/g," ").trim().slice(0,1000)}var de=256,xe=1e4,Le=86400000;var pt=/[\p{Cf}\p{Co}\p{Cn}]/u;function yn(n){if(!n)return{enabled:!1,defaultTtlMs:600000,pollIntervalMs:500,maxTasksPerSession:32,maxLifetimeMs:1800000};if(typeof n.enabled!=="boolean")throw Error("MCP tasks.enabled must be a boolean");let t=d(n.defaultTtlMs??600000,1e4,86400000,"MCP tasks.defaultTtlMs"),e=d(n.maxLifetimeMs??1800000,1e4,86400000,"MCP tasks.maxLifetimeMs");if(t>e)throw Error("MCP tasks.defaultTtlMs must not exceed tasks.maxLifetimeMs");return{enabled:n.enabled,defaultTtlMs:t,pollIntervalMs:d(n.pollIntervalMs??500,100,1e4,"MCP tasks.pollIntervalMs"),maxTasksPerSession:d(n.maxTasksPerSession??32,1,32,"MCP tasks.maxTasksPerSession"),maxLifetimeMs:e}}function he(n,t){return d(n??t.defaultTtlMs,1e4,Math.min(86400000,t.maxLifetimeMs),"MCP task ttl")}function Ce(n,t,e){let r=Bt(n.taskId,"task ID",512),u=Bn(n.createdAt,"createdAt"),_=Bn(n.lastUpdatedAt,"lastUpdatedAt");if(Date.parse(_)<Date.parse(u))throw Error("MCP task lastUpdatedAt precedes createdAt");if(e&&(r!==e.taskId||u!==e.createdAt))throw Error("MCP task identity changed across connection generation");let M=n.ttl===null?null:d(n.ttl,0,86400000,"MCP task ttl"),o=n.pollInterval===void 0?t.pollIntervalMs:d(n.pollInterval,0,Number.MAX_SAFE_INTEGER,"MCP task pollInterval"),s=Math.min(1e4,Math.max(100,o)),S=n.statusMessage?Rt(n.statusMessage,r):void 0;return{taskId:r,status:n.status,createdAt:u,lastUpdatedAt:_,ttl:M,pollIntervalMs:s,...S?{statusMessage:S}:{}}}function $e(n){return["completed","failed","cancelled"].includes(n)}function Ie(n){let t=n instanceof Error?n.message:String(n);return Kn(F(t.replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]")),1024)}function Rt(n,t){return Kn(F(n.replaceAll(t,"[redacted-task-id]")),1024)}function F(n){return[...n.normalize("NFKC")].filter((t)=>{let e=t.codePointAt(0)??0;if(e===0||e>=1&&e<=8||e===11||e===12||e>=14&&e<=31||e===127)return!1;return!pt.test(t)}).join("").trim()}function Bn(n,t){let e=Date.parse(n);if(!Number.isFinite(e))throw Error(`MCP task ${t} is invalid`);return new Date(e).toISOString()}function Bt(n,t,e){if(!n||Buffer.byteLength(n)>e||F(n)!==n)throw Error(`MCP ${t} is invalid`);return n}function d(n,t,e,r){if(!Number.isSafeInteger(n)||n<t||n>e)throw Error(`${r} must be an integer between ${t} and ${e}`);return n}function Kn(n,t){let e=Buffer.from(n);if(e.length<=t)return n;let r=e.subarray(0,t).toString("utf8");while(Buffer.byteLength(r)>t)r=r.slice(0,-1);return r}var yt={sonnet:"claude-sonnet-4-20250514",opus:"claude-opus-4-20250514",haiku:"claude-3-5-haiku-20241022",claude:"claude-sonnet-4-20250514",gpt4o:"gpt-4o",gpt4:"gpt-4o",o1:"o1",o3:"o3","o4-mini":"o4-mini",deepseek:"deepseek-chat","deepseek-v3":"deepseek-chat","deepseek-r1":"deepseek-reasoner","deepseek-v4":"deepseek-v4-0324",gemini:"gemini-2.5-pro",flash:"gemini-2.5-flash",qwen:"qwen3-235b-a22b","qwen-max":"qwen-max","qwen-plus":"qwen-plus"};function v(n){let t=n.toLowerCase().trim();return yt[t]??n}var Kt=/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/,Ut=/^\.[A-Za-z0-9_+-]{1,32}$/;function l(n){return n!==null&&typeof n==="object"&&!Array.isArray(n)}function h(n,t,e,r,u){if(n===void 0)return u;if(!Number.isInteger(n)||Number(n)<e||Number(n)>r)throw Error(`${t} must be an integer between ${e} and ${r}`);return Number(n)}function Un(n,t){if(n===void 0)return;let e;try{e=JSON.stringify(n)}catch{throw Error(`${t} must be JSON serializable`)}if(e===void 0||Buffer.byteLength(e)>262144)throw Error(`${t} exceeds the 256 KiB limit`);return structuredClone(n)}function kt(n,t){if(n===void 0)return{};if(!l(n))throw Error(`${t} must be an object`);let e={};for(let[r,u]of Object.entries(n)){if(!r||typeof u!=="string"||u.includes("\x00"))throw Error(`${t} must contain non-empty string values`);e[r]=u}return e}function w(n){if(n===void 0)return{};if(!l(n))throw Error("lspServers must be an object");let t=Object.entries(n);if(t.length>32)throw Error("lspServers exceeds the 32-server limit");let e={};for(let[r,u]of t){if(!Kt.test(r))throw Error(`Invalid LSP server name: ${r}`);if(!l(u))throw Error(`lspServers.${r} must be an object`);let _=new Set(["command","args","extensionToLanguage","env","initializationOptions","settings","enabled","priority","startupTimeout","shutdownTimeout","requestTimeout","diagnosticWaitTimeout","maxRestarts"]),M=Object.keys(u).filter((c)=>!_.has(c));if(M.length>0)throw Error(`Unknown LSP server field: ${r}.${M[0]}`);if(typeof u.command!=="string"||!u.command.trim()||u.command.includes("\x00")||u.command.includes(`
|
|
22
|
+
`))throw Error(`lspServers.${r}.command must be a non-empty command`);if(u.args!==void 0&&!Array.isArray(u.args))throw Error(`lspServers.${r}.args must be an array`);let o=(u.args??[]).map((c,f)=>{if(typeof c!=="string"||c.includes("\x00"))throw Error(`lspServers.${r}.args.${f} must be a string`);return c});if(o.length>128)throw Error(`lspServers.${r}.args exceeds the 128-item limit`);if(!l(u.extensionToLanguage))throw Error(`lspServers.${r}.extensionToLanguage must be an object`);let s=Object.entries(u.extensionToLanguage);if(s.length===0||s.length>64)throw Error(`lspServers.${r}.extensionToLanguage must contain 1-64 entries`);let S={};for(let[c,f]of s){let $=c.startsWith(".")?c.toLowerCase():`.${c.toLowerCase()}`;if(!Ut.test($)||typeof f!=="string"||!f.trim())throw Error(`Invalid lspServers.${r}.extensionToLanguage entry: ${c}`);S[$]=f.trim()}if(u.enabled!==void 0&&typeof u.enabled!=="boolean")throw Error(`lspServers.${r}.enabled must be a boolean`);let T=Un(u.initializationOptions,`lspServers.${r}.initializationOptions`),g=Un(u.settings,`lspServers.${r}.settings`);e[r]={command:u.command.trim(),...o.length>0?{args:o}:{},extensionToLanguage:S,...u.env!==void 0?{env:kt(u.env,`lspServers.${r}.env`)}:{},...T!==void 0?{initializationOptions:T}:{},...g!==void 0?{settings:g}:{},...u.enabled!==void 0?{enabled:u.enabled}:{},priority:h(u.priority,`lspServers.${r}.priority`,-1000,1000,0),startupTimeout:h(u.startupTimeout,`lspServers.${r}.startupTimeout`,100,60000,1e4),shutdownTimeout:h(u.shutdownTimeout,`lspServers.${r}.shutdownTimeout`,100,1e4,2000),requestTimeout:h(u.requestTimeout,`lspServers.${r}.requestTimeout`,100,60000,1e4),diagnosticWaitTimeout:h(u.diagnosticWaitTimeout,`lspServers.${r}.diagnosticWaitTimeout`,0,5000,750),maxRestarts:h(u.maxRestarts,`lspServers.${r}.maxRestarts`,0,10,3)}}return e}import kn from"node:path";var zn=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,zt=/^(?:\*\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;function N(n){let t=[];for(let[e,r]of Object.entries(n)){if(!zn.test(e))throw Error(`Invalid plugin name in enabledPlugins: ${e}`);if(typeof r!=="boolean")throw Error(`Invalid enabledPlugins value for ${e}`);t.push([e,r])}return Object.fromEntries(t)}function nn(n,t,e){if(!Array.isArray(n))throw Error(`${t} must be an array`);return[...new Set(n.map((r,u)=>{if(typeof r!=="string"||!r.trim())throw Error(`${t}[${u}] must be a non-empty string`);return e(r.trim())}))].sort()}function p(n){let t=new Set(["restrictToAllowedSources","requireGitCommitSha","allowedGitHosts","allowedMarketplaces","allowedLocalRoots"]),e=Object.keys(n).filter((u)=>!t.has(u));if(e.length>0)throw Error(`Unknown pluginSourcePolicy fields: ${e.join(", ")}`);let r={};for(let u of["restrictToAllowedSources","requireGitCommitSha"]){if(n[u]===void 0)continue;if(typeof n[u]!=="boolean")throw Error(`pluginSourcePolicy.${u} must be boolean`);r[u]=n[u]}if(n.allowedGitHosts!==void 0)r.allowedGitHosts=nn(n.allowedGitHosts,"pluginSourcePolicy.allowedGitHosts",(u)=>{let _=u.toLowerCase();if(!zt.test(_))throw Error(`Invalid plugin Git host pattern: ${u}`);return _});if(n.allowedMarketplaces!==void 0)r.allowedMarketplaces=nn(n.allowedMarketplaces,"pluginSourcePolicy.allowedMarketplaces",(u)=>{if(!zn.test(u))throw Error(`Invalid allowed Marketplace name: ${u}`);return u});if(n.allowedLocalRoots!==void 0)r.allowedLocalRoots=nn(n.allowedLocalRoots,"pluginSourcePolicy.allowedLocalRoots",(u)=>{if(!kn.isAbsolute(u))throw Error(`Plugin local allowlist root must be absolute: ${u}`);return kn.resolve(u)});return r}function G(n){let t=[];for(let[e,r]of Object.entries(n)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw Error(`Invalid environment variable name: ${e}`);if(typeof r!=="string"||r.includes("\x00"))throw Error(`Invalid environment variable value: ${e}`);t.push([e,r])}return Object.fromEntries(t)}var ln=1,Gn=64,Hn=1,qn=1e4;function On(n){return Number.isInteger(n)&&n>=1&&n<=64}function Yn(n){return Number.isInteger(n)&&n>=1&&n<=1e4}class C{static instance=null;runtimePermissionOverrides;lastAdditionalSettings;constructor(){}static getInstance(){if(!C.instance)C.instance=new C;return C.instance}static resetInstance(){C.instance=null}async initialize(n){try{this.lastAdditionalSettings=n,this.runtimePermissionOverrides=n?.permissions;let e=(await P.getInstance().getStatus(b())).state==="trusted",r=await this.loadConfigFiles(e),u=await this.loadSettingsFiles(e),_={...r,...u,enabledPlugins:{...r.enabledPlugins||{},...u.enabledPlugins||{}}};if(n)_=this.mergeSettings(_,n);let M=this.normalizeConfig(_),o={...E,...M};if(o.enabledPlugins=N(o.enabledPlugins),o.lspServers=w(o.lspServers),o.pluginSourcePolicy={...E.pluginSourcePolicy,...p(o.pluginSourcePolicy)},this.resolveEnvInterpolation(o),process.env.BLADE_MODEL&&o.models?.length>0){let s=v(process.env.BLADE_MODEL),S=o.models.find((T)=>T.id===s||T.model===s||T.id===process.env.BLADE_MODEL||T.model===process.env.BLADE_MODEL);if(S)o.currentModelId=S.id}if(process.env.BLADE_DEBUG)o.debug=process.env.BLADE_DEBUG==="1"||process.env.BLADE_DEBUG==="true"||process.env.BLADE_DEBUG;if(H().configureModelProviders(o.modelProviders,o.models),o.models.length>0)this.validateConfig(o);if(o.debug)console.log("[ConfigManager] Configuration loaded successfully");return o}catch(t){return console.error("[ConfigManager] Failed to initialize:",t),H().configureModelProviders({},[]),E}}async reload(){return this.initialize(this.lastAdditionalSettings)}async loadConfigFiles(n){let t=i.join(a.homedir(),".blade","config.json"),e=i.join(b(),".blade","config.json"),r={},u=await this.loadJsonFile(t);if(u)r={...r,...u};let _=await this.loadJsonFile(e);if(_&&n){let M={...r.mcpServers||{},..._.mcpServers||{}},o={...r.lspServers||{},..._.lspServers||{}},s={...r.modelProviders||{},..._.modelProviders||{}},S={...r.enabledPlugins||{},..._.enabledPlugins||{}};if(r={...r,..._},Object.keys(M).length>0)r.mcpServers=M;if(Object.keys(o).length>0)r.lspServers=w(o);if(Object.keys(s).length>0)r.modelProviders=s;if(Object.keys(S).length>0)r.enabledPlugins=N(S)}else if(_?.hooks)r.hooks=_.hooks;return r}async loadSettingsFiles(n){let t=i.join(a.homedir(),".blade","settings.json"),e=i.join(b(),".blade","settings.json"),r=i.join(b(),".blade","settings.local.json"),u={},_=await this.loadJsonFile(t);if(_)u=this.mergeSettings(u,_);let M=await this.loadJsonFile(e);if(M&&n)u=this.mergeSettings(u,M);else if(M?.hooks)u=this.mergeSettings(u,{hooks:M.hooks});let o=await this.loadJsonFile(r);if(o&&n)u=this.mergeSettings(u,o);else if(o?.hooks)u=this.mergeSettings(u,{hooks:o.hooks});return u}async loadWorkspacePermissions(n,t){let e={allow:[...t.allow],ask:[...t.ask],deny:[...t.deny]};if(i.resolve(n)!==i.resolve(b())){let u=await this.loadWorkspacePermissionOverrides(b(),{includeUntrusted:!0}),_=await this.loadJsonFile(i.join(a.homedir(),".blade","settings.json")),M={allow:Array.from(new Set([...E.permissions.allow,..._?.permissions?.allow||[],...this.runtimePermissionOverrides?.allow||[]])),ask:Array.from(new Set([...E.permissions.ask,..._?.permissions?.ask||[],...this.runtimePermissionOverrides?.ask||[]])),deny:Array.from(new Set([...E.permissions.deny,..._?.permissions?.deny||[],...this.runtimePermissionOverrides?.deny||[]]))};for(let o of["allow","ask","deny"]){let s=new Set(u[o].filter((S)=>!M[o].includes(S)));e[o]=e[o].filter((S)=>!s.has(S))}}let r=await this.loadWorkspacePermissionOverrides(n);for(let u of["allow","ask","deny"])e[u]=Array.from(new Set([...e[u],...r[u]]));return e}async loadWorkspaceMcpServers(n,t){if(i.resolve(n)===i.resolve(b()))return{...t};let e=await P.getInstance().getStatus(n),r=e.state==="trusted",u=e.projectPath,_={},M=async(s)=>{let S=await this.loadJsonFile(s);if(S?.mcpServers)_={..._,...S.mcpServers}};if(await M(i.join(a.homedir(),".blade","config.json")),await M(i.join(a.homedir(),".blade","settings.json")),r)await M(i.join(u,".blade","config.json")),await M(i.join(u,".blade","settings.json")),await M(i.join(u,".blade","settings.local.json"));if(this.lastAdditionalSettings?.mcpServers)_={..._,...this.lastAdditionalSettings.mcpServers};let o={mcpServers:_};return this.resolveEnvInterpolation(o),o.mcpServers}async loadWorkspaceLspServers(n,t){if(i.resolve(n)===i.resolve(b()))return w(t);let e=await P.getInstance().getStatus(n),r={},u=async(M)=>{let o=await this.loadJsonFile(M);if(o?.lspServers)r={...r,...w(o.lspServers)}};if(await u(i.join(a.homedir(),".blade","config.json")),await u(i.join(a.homedir(),".blade","settings.json")),e.state==="trusted")for(let M of["config.json","settings.json","settings.local.json"])await u(i.join(e.projectPath,".blade",M));if(this.lastAdditionalSettings?.lspServers)r={...r,...w(this.lastAdditionalSettings.lspServers)};let _={lspServers:r};return this.resolveEnvInterpolation(_),w(_.lspServers)}async loadWorkspaceModelConfig(n,t){if(i.resolve(n)===i.resolve(b()))return{currentModelId:t.currentModelId,models:t.models.map((M)=>structuredClone(M)),modelProviders:structuredClone(t.modelProviders),temperature:t.temperature,...t.maxOutputTokens!==void 0?{maxOutputTokens:t.maxOutputTokens}:{},timeout:t.timeout};let e=await P.getInstance().getStatus(n),r=e.projectPath,u={currentModelId:E.currentModelId,models:E.models.map((M)=>structuredClone(M)),modelProviders:structuredClone(E.modelProviders),temperature:E.temperature,...E.maxOutputTokens!==void 0?{maxOutputTokens:E.maxOutputTokens}:{},timeout:E.timeout},_=(M)=>{if(!M)return;if(M.modelProviders)u.modelProviders={...u.modelProviders,...structuredClone(M.modelProviders)};if(M.models)u.models=M.models.map((o)=>structuredClone(o));if(M.currentModelId!==void 0)u.currentModelId=M.currentModelId;if(M.temperature!==void 0)u.temperature=M.temperature;if(M.maxOutputTokens!==void 0)u.maxOutputTokens=M.maxOutputTokens;if(M.timeout!==void 0)u.timeout=M.timeout};if(_(await this.loadJsonFile(i.join(a.homedir(),".blade","config.json"))),_(await this.loadJsonFile(i.join(a.homedir(),".blade","settings.json"))),e.state==="trusted")_(await this.loadJsonFile(i.join(r,".blade","config.json"))),_(await this.loadJsonFile(i.join(r,".blade","settings.json"))),_(await this.loadJsonFile(i.join(r,".blade","settings.local.json")));if(_(this.lastAdditionalSettings),u=this.normalizeConfig(u),this.resolveEnvInterpolation(u),process.env.BLADE_MODEL&&u.models.length>0){let M=process.env.BLADE_MODEL,o=v(M),s=u.models.find((S)=>S.id===o||S.model===o||S.id===M||S.model===M);if(s)u.currentModelId=s.id}if(!u.models.some((M)=>M.id===u.currentModelId))u.currentModelId=u.models[0]?.id??"";return u}async loadWorkspaceRuntimeSettings(n,t){if(i.resolve(n)===i.resolve(b()))return{env:G(t.env),disableAllHooks:t.disableAllHooks,maxTurns:t.maxTurns,permissionMode:t.permissionMode};let e=await P.getInstance().getStatus(n),r=e.projectPath,u={env:{},disableAllHooks:E.disableAllHooks,maxTurns:E.maxTurns,permissionMode:E.permissionMode},_=(s,S)=>{if(!s)return;if(S.allowExecutionSettings){if(s.env)u.env={...u.env,...G(s.env)};if(s.maxTurns!==void 0)u.maxTurns=s.maxTurns;if(s.permissionMode!==void 0)u.permissionMode=s.permissionMode;if(s.disableAllHooks!==void 0)u.disableAllHooks=s.disableAllHooks}else if(s.disableAllHooks===!0)u.disableAllHooks=!0};_(await this.loadJsonFile(i.join(a.homedir(),".blade","config.json")),{allowExecutionSettings:!0}),_(await this.loadJsonFile(i.join(a.homedir(),".blade","settings.json")),{allowExecutionSettings:!0});let M=await Promise.all([this.loadJsonFile(i.join(r,".blade","config.json")),this.loadJsonFile(i.join(r,".blade","settings.json")),this.loadJsonFile(i.join(r,".blade","settings.local.json"))]);for(let s of M)_(s,{allowExecutionSettings:e.state==="trusted"});_(this.lastAdditionalSettings,{allowExecutionSettings:!0});let o={env:u.env};return this.resolveEnvInterpolation(o),u.env=G(o.env),u}async loadWorkspacePluginSettings(n){let t=await P.getInstance().getStatus(n),e={},r=(u,_)=>{if(!u?.enabledPlugins)return;let M=N(u.enabledPlugins);for(let[o,s]of Object.entries(M))if(_||s===!1)e[o]=s};r(await this.loadJsonFile(i.join(a.homedir(),".blade","config.json")),!0),r(await this.loadJsonFile(i.join(a.homedir(),".blade","settings.json")),!0);for(let u of["config.json","settings.json","settings.local.json"])r(await this.loadJsonFile(i.join(t.projectPath,".blade",u)),t.state==="trusted");return r(this.lastAdditionalSettings,!0),e}async loadWorkspacePluginSourcePolicy(n){let t=await P.getInstance().getStatus(n),e={...E.pluginSourcePolicy,allowedGitHosts:[...E.pluginSourcePolicy.allowedGitHosts],allowedMarketplaces:[...E.pluginSourcePolicy.allowedMarketplaces],allowedLocalRoots:[...E.pluginSourcePolicy.allowedLocalRoots]},r=(M)=>{if(!M?.pluginSourcePolicy)return;Object.assign(e,p(M.pluginSourcePolicy))},u=(M,o)=>{if(!o)return M;if(M.length===0&&!e.restrictToAllowedSources)return o;let s=new Set(o);return M.filter((S)=>s.has(S))},_=(M)=>{if(!M?.pluginSourcePolicy)return;let o=p(M.pluginSourcePolicy);e.allowedGitHosts=u(e.allowedGitHosts,o.allowedGitHosts),e.allowedMarketplaces=u(e.allowedMarketplaces,o.allowedMarketplaces),e.allowedLocalRoots=u(e.allowedLocalRoots,o.allowedLocalRoots),e.restrictToAllowedSources=e.restrictToAllowedSources||o.restrictToAllowedSources===!0,e.requireGitCommitSha=e.requireGitCommitSha||o.requireGitCommitSha===!0};r(await this.loadJsonFile(i.join(a.homedir(),".blade","config.json"))),r(await this.loadJsonFile(i.join(a.homedir(),".blade","settings.json")));for(let M of["config.json","settings.json","settings.local.json"])_(await this.loadJsonFile(i.join(t.projectPath,".blade",M)));if(_(this.lastAdditionalSettings),process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true")e.requireGitCommitSha=!0;return e}async loadWorkspaceHooks(n,t,e={}){if(i.resolve(n)===i.resolve(b())&&e.includeBaseForCurrentWorkspace!==!1)return R({},t);let r=R({},E.hooks),u=[i.join(a.homedir(),".blade","settings.json"),i.join(n,".blade","settings.json"),i.join(n,".blade","settings.local.json")];for(let _ of u){let M=await this.loadJsonFile(_);if(M?.hooks)r=R({},r,M.hooks)}return r}async loadWorkspacePermissionOverrides(n,t={}){let e={allow:[],ask:[],deny:[]},r=(await P.getInstance().getStatus(n)).state==="trusted",u=[...r||t.includeUntrusted?[i.join(n,".blade","settings.json")]:[],...r||t.includeUntrusted?[i.join(n,".blade","settings.local.json")]:[]];for(let _ of u){let M=await this.loadJsonFile(_);if(!M?.permissions)continue;for(let o of["allow","ask","deny"])e[o]=Array.from(new Set([...e[o],...M.permissions[o]||[]]))}return e}mergeSettings(n,t){let e={...JSON.parse(JSON.stringify(n)),...JSON.parse(JSON.stringify(t))};if(t.permissions)e.permissions={allow:Array.from(new Set([...n.permissions?.allow||[],...t.permissions.allow||[]])),ask:Array.from(new Set([...n.permissions?.ask||[],...t.permissions.ask||[]])),deny:Array.from(new Set([...n.permissions?.deny||[],...t.permissions.deny||[]]))};if(t.hooks)e.hooks=R({},e.hooks,t.hooks);if(t.enabledPlugins)e.enabledPlugins={...n.enabledPlugins||{},...N(t.enabledPlugins)};if(t.pluginSourcePolicy)e.pluginSourcePolicy={...n.pluginSourcePolicy??E.pluginSourcePolicy,...p(t.pluginSourcePolicy)};if(t.env)e.env=R({},e.env,t.env);if(t.mcpServers)e.mcpServers={...e.mcpServers||{},...t.mcpServers};if(t.lspServers)e.lspServers={...e.lspServers||{},...w(t.lspServers)};if(t.disableAllHooks!==void 0)e.disableAllHooks=t.disableAllHooks;if(t.permissionMode!==void 0)e.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)e.maxTurns=t.maxTurns;return e}resolveEnvInterpolation(n){let t=/\$\{?([A-Z_][A-Z0-9_]*)(:-([^}]+))?\}?/g,e=(u)=>{if(typeof u==="string")return u.replace(t,(_,M,o,s)=>{return process.env[M]||s||_});if(Array.isArray(u))return u.map(e);if(typeof u==="object"&&u!==null){let _=u;for(let[M,o]of Object.entries(_))_[M]=e(o);return _}return u},r=n;for(let[u,_]of Object.entries(r))r[u]=e(_)}async loadJsonFile(n){try{if(await this.fileExists(n)){let t=await Vn.readFile(n,"utf-8");return JSON.parse(t)}}catch(t){console.warn(`[ConfigManager] Failed to load ${n}:`,t)}return null}async fileExists(n){try{return await Vn.access(n),!0}catch{return!1}}normalizeConfig(n){let t=JSON.parse(JSON.stringify(n)),e=(u)=>u.trim().replace(/^`|`$/g,""),r=(u)=>{for(let[_,M]of Object.entries(u))if(typeof M==="string")u[_]=e(M);else if(Array.isArray(M))M.forEach((o,s)=>{if(typeof o==="string")M[s]=e(o);else if(typeof o==="object"&&o!==null)r(o)});else if(typeof M==="object"&&M!==null)r(M)};return r(t),t}validateConfig(n,t=H()){let e=[];try{n.lspServers=w(n.lspServers)}catch(r){e.push(r instanceof Error?r.message:"Invalid LSP server configuration")}for(let[r,u]of Object.entries(n.mcpServers||{}))try{Tn(u),u.oauth=q(u);let _=wn(u);if(u.logging!==void 0)u.logging=_;if(u.sampling)u.sampling=Rn(u.sampling);if(u.tasks)u.tasks=yn(u.tasks)}catch(_){e.push(`MCP server "${r}": ${_ instanceof Error?_.message:"invalid sampling policy"}`)}for(let[r,u]of Object.entries(n.modelProviders||{}))if(e.push(...Dn(r,u)),t.isReservedProviderId(r))e.push(`modelProviders.${r}: built-in provider ids cannot be overridden`);if(e.length===0)try{t.configureModelProviders(n.modelProviders||{},n.models)}catch(r){e.push(r instanceof Error?r.message:"Failed to configure custom model providers")}if(!n.models||n.models.length===0)e.push("没有可用的模型配置");if(!Zn(n.maxTurns))e.push(`maxTurns 必须是 ${Jn()}`);if(!On(n.maxConcurrentTasks))e.push(`maxConcurrentTasks 必须是 ${ln}-${Gn} 之间的整数`);if(!Yn(n.maxQueuedTasks))e.push(`maxQueuedTasks 必须是 ${Hn}-${qn} 之间的整数`);if(n.models&&n.models.length>0){if(!n.currentModelId)e.push("未设置当前模型 ID");else if(!n.models.find((u)=>u.id===n.currentModelId))e.push(`当前模型 ID "${n.currentModelId}" 在 models 列表中不存在`);for(let r of n.models){let u=`模型 "${r.displayName||r.id}"`,_=["name","apiKey","baseUrl","maxContextTokens","maxOutputTokens","supportsThinking","thinkingBudget","thinkingMode"].filter((o)=>(o in r));if(_.length>0)e.push(`${u}: 不再支持旧字段 ${_.join(", ")};请重新配置模型`);if(!r.model)e.push(`${u}: model 字段必填`);if(!r.provider)e.push(`${u}: provider 字段必填`);if(r.overrides?.baseUrl&&!r.overrides.baseUrl.startsWith("http"))e.push(`${u}: overrides.baseUrl "${r.overrides.baseUrl}" 不是有效的 HTTP URL`);let M=r.overrides?.streamIdleTimeout;if(M!==void 0&&(!Number.isFinite(M)||M<1000))e.push(`${u}: overrides.streamIdleTimeout 必须至少为 1000ms`);try{t.getModel(r.provider,r.model)}catch{e.push(`${u}: 内置 catalog 中不存在 ${r.provider}/${r.model}`)}}}if(e.length>0)throw Error(`配置验证失败:
|
|
23
|
+
${e.map((r)=>` - ${r}`).join(`
|
|
24
|
+
`)}
|
|
25
|
+
|
|
26
|
+
`+`请通过以下方式之一提供配置:
|
|
27
|
+
`+` 1. 首次启动: 运行 blade,系统会自动引导配置
|
|
28
|
+
`+` 2. 添加模型: blade 后输入 /model add
|
|
29
|
+
`+` 3. 初始化向导: 输入 /init
|
|
30
|
+
|
|
31
|
+
`+`配置文件示例 (~/.blade/config.json):
|
|
32
|
+
`+`{
|
|
33
|
+
"currentModelId": "model-id-123",
|
|
34
|
+
"models": [
|
|
35
|
+
{
|
|
36
|
+
"id": "model-id-123",
|
|
37
|
+
`+` "displayName": "默认模型",
|
|
38
|
+
`+` "provider": "deepseek",
|
|
39
|
+
"model": "deepseek-v4-pro"
|
|
40
|
+
}
|
|
41
|
+
]
|
|
42
|
+
}
|
|
43
|
+
`)}}function Mu(n,t={}){let e={...n};if(t.debug!==void 0)e.debug=t.debug===""?!0:t.debug;if(t.model){if(!n.models.some((u)=>u.id===t.model))throw Error(`模型配置未找到: ${t.model}`);e.currentModelId=t.model}if(t.yolo===!0)e.permissionMode="yolo";else if(t.permissionMode!==void 0)e.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)e.maxTurns=t.maxTurns;if(t.maxConcurrentTasks!==void 0)e.maxConcurrentTasks=t.maxConcurrentTasks;if(t.maxQueuedTasks!==void 0)e.maxQueuedTasks=t.maxQueuedTasks;return e.systemPrompt=t.systemPrompt,e.appendSystemPrompt=t.appendSystemPrompt,e.model=t.model,e.resumeSessionId=t.sessionId,e.forkSession=t.forkSession,e.allowedTools=t.allowedTools,e.disallowedTools=t.disallowedTools,e.mcpConfigPaths=t.mcpConfig,e.strictMcpConfig=t.strictMcpConfig,e.addDirs=t.addDir,e.outputFormat=t.outputFormat,e.inputFormat=t.inputFormat,e.print=t.print,e.includePartialMessages=t.includePartialMessages,e.replayUserMessages=t.replayUserMessages,e.agentsConfig=t.agents,e.settingSources=t.settingSources,e}
|
|
44
|
+
export{B as fd,q as gd,x as hd,Q as id,an as jd,L as kd,Tn as ld,ie as md,U as nd,Ee as od,fe as pd,ae as qd,wn as rd,dt as sd,ce as td,xt as ud,Te as vd,Rn as wd,ge as xd,Pe as yd,de as zd,xe as Ad,Le as Bd,yn as Cd,he as Dd,Ce as Ed,$e as Fd,Ie as Gd,E as Hd,w as Id,p as Jd,G as Kd,ln as Ld,Gn as Md,Hn as Nd,qn as Od,On as Pd,Yn as Qd,C as Rd,Mu as Sd};
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import{dd as o}from"./chunk-jxv6r0c7.js";import{Be as l,De as C,Fe as u,Je as y,Ke as n}from"./chunk-8nm1hqr1.js";import{Le as J}from"./chunk-mjp61rqd.js";import{stat as i}from"node:fs/promises";import A from"node:path";import*as M from"node:path";var a=50,s=100,t=/^[A-Za-z0-9_-]+$/,e=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function EE(_){return typeof _==="string"&&e.test(_)&&Number.isFinite(Date.parse(_))}function P(_){return typeof _==="string"&&M.isAbsolute(_)}function _E(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function RE(_){try{if(!t.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||P(R.cwd))||!EE(R.lastMessageTime)||!P(R.projectPath)||!C(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:M.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:M.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function q(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function WE(_){if(!_.cursor)return;let E=RE(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function wE(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:k=!1}=_;if(E!==void 0&&!M.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let H=W===void 0?a:W;if(!Number.isInteger(H)||H<1||H>s)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:M.resolve(E),cursor:R??void 0,limit:H,includeSubagents:$,archived:k}}function $E(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function xE(_,E){let R=[..._],W=WE(E);if(W)R=R.filter((H)=>$E(H,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let k=$[$.length-1];return{sessions:$,nextCursor:_E({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:k.lastMessageTime,projectPath:k.projectPath,sessionId:k.sessionId})}}function kE(_){return _.type==="message_created"||_.type==="part_created"||_.type==="part_updated"}function O(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function N(_,E){let R=_.find((W)=>O(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:p(_,E),createdAt:R.data.createdAt}}function p(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function S(_,E){N(_,E);let R=_.findIndex((W)=>W.type==="message_created"&&W.data.messageId===E);return _.filter((W,$)=>$<R||!kE(W))}function z(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(N(E,R.data.targetMessageId),R.data.mode!=="code")E=S(E,R.data.targetMessageId)}return E}function fE(_){let E=z(_);return E.filter(O).map((R)=>({messageId:R.data.messageId,preview:p(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function qE(_,E){let R=z(_),W=N(R,E),$=R.findIndex((H)=>H.type==="message_created"&&H.data.messageId===E),k=R.slice($);return{checkpoint:W,projectedEntries:S(R,E),removedTurns:k.filter(O).length,snapshotMessageIds:k.flatMap((H)=>H.type==="part_created"&&H.data.partType==="tool_call"?[H.data.partId]:[])}}import*as x from"node:fs";import{createReadStream as HE}from"node:fs";import*as Y from"node:fs/promises";import*as I from"node:path";import{createInterface as QE}from"node:readline";var c=65536;function VE(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function w(_,E="session transcript"){let R=_.split(`
|
|
2
|
+
`),W=!_.endsWith(`
|
|
3
|
+
`),$=[];for(let[k,H]of R.entries())try{let Q=VE(H,k+1,E);if(Q){if(typeof Q.seq!=="number")Q.seq=$.length+1;$.push(Q)}}catch(Q){if(W&&k===R.length-1)break;throw Q}return $}class Z{static appendQueues=new Map;filePath;constructor(_){this.filePath=_}static maxSeq(_){let E=0;for(let R of _)if(typeof R.seq==="number"&&R.seq>E)E=R.seq;return E}static stampSeqFrom(_,E){let R=E;return _.map((W)=>{if(typeof W.seq==="number"){if(W.seq>R)R=W.seq;return W}return R+=1,{...W,seq:R}})}static stampSeq(_,E){return Z.stampSeqFrom(_,Z.maxSeq(E))}async append(_){try{let[E]=await this.appendEntries([_]);return E}catch(E){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,E),E}}async appendBatch(_){try{return await this.appendEntries(_)}catch(E){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,E),E}}async appendEntries(_){if(_.length===0)return[];return this.enqueue(async()=>{await Y.mkdir(I.dirname(this.filePath),{recursive:!0,mode:493});let E=await Y.open(this.filePath,"a+",384);try{let R=await this.repairIncompleteTail(E),W=await this.readTailSeq(E),$=Z.stampSeqFrom(_,W),k=`${$.map((H)=>JSON.stringify(H)).join(`
|
|
4
|
+
`)}
|
|
5
|
+
`;return await E.appendFile(R+k,"utf8"),await E.sync(),$}finally{await E.close()}})}async createExclusive(_){if(_.length===0)throw Error("Cannot create an empty session transcript");await Y.mkdir(I.dirname(this.filePath),{recursive:!0,mode:493});let E;try{E=await Y.open(this.filePath,"wx",384);let W=`${Z.stampSeq(_,[]).map(($)=>JSON.stringify($)).join(`
|
|
6
|
+
`)}
|
|
7
|
+
`;await E.writeFile(W,"utf-8"),await E.sync()}catch(R){if(E)await E.close(),E=void 0,await Y.unlink(this.filePath).catch(()=>{return});throw R}finally{await E?.close()}}async readAll(){if(!x.existsSync(this.filePath))return[];let _=await Y.readFile(this.filePath,"utf-8");return w(_,this.filePath)}async readStream(_){return new Promise((E,R)=>{if(!x.existsSync(this.filePath)){E();return}let W=HE(this.filePath,"utf-8"),$=QE({input:W,crlfDelay:Number.POSITIVE_INFINITY}),k=0;$.on("line",async(H)=>{let Q=H.trim();if(Q.length===0)return;try{let X=JSON.parse(Q);if(k+=1,typeof X.seq!=="number")X.seq=k;await _(X)}catch(X){console.warn(`[JSONLStore] 解析 JSON 行失败: ${Q}`,X)}}),$.on("close",()=>E()),$.on("error",R),W.on("error",R)})}async filter(_){let E=[];return await this.readStream((R)=>{if(_(R))E.push(R)}),E}async readLast(_){return(await this.readAll()).slice(-_)}async readFromSeq(_){return(await this.readAll()).filter((R)=>(R.seq??0)>=_)}async getStats(){try{if(!x.existsSync(this.filePath))return{exists:!1,size:0,lineCount:0};let _=await Y.stat(this.filePath),R=(await Y.readFile(this.filePath,"utf-8")).split(`
|
|
8
|
+
`).filter((W)=>W.trim().length>0).length;return{exists:!0,size:_.size,lineCount:R}}catch(_){return console.error(`[JSONLStore] 获取统计信息失败: ${this.filePath}`,_),{exists:!1,size:0,lineCount:0}}}async exists(){try{return await Y.access(this.filePath),!0}catch{return!1}}async delete(){try{return await this.enqueue(async()=>{try{return await Y.unlink(this.filePath),!0}catch(_){if(_.code==="ENOENT")return!1;throw _}})}catch(_){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,_),_}}async deleteValidated(_){return this.enqueue(async()=>{let E;try{E=await Y.open(this.filePath,"r")}catch(W){if(W.code==="ENOENT")return!1;throw W}let R;try{R=w(await E.readFile("utf8"),"session transcript")}finally{await E.close()}if(!_(R))return!1;try{return await Y.unlink(this.filePath),!0}catch(W){if(W.code==="ENOENT")return!1;throw W}})}async appendValidated(_){await this.appendValidatedAsync(async(E)=>_(E))}async appendValidatedAsync(_){await this.enqueue(async()=>{let E=await Y.open(this.filePath,"r+");try{let{entries:R,separator:W,size:$}=await this.readCommittedState(E,"session transcript"),k=await _(R),[H]=Z.stampSeq([k],R),Q=`${W}${JSON.stringify(H)}
|
|
9
|
+
`;await E.write(Q,$,"utf8"),await E.sync()}finally{await E.close()}})}getFilePath(){return this.filePath}async enqueue(_){let R=(Z.appendQueues.get(this.filePath)??Promise.resolve()).catch(()=>{return}).then(_),W=R.then(()=>{return},()=>{return});Z.appendQueues.set(this.filePath,W);try{return await R}finally{if(Z.appendQueues.get(this.filePath)===W)Z.appendQueues.delete(this.filePath)}}async readCommittedState(_,E=this.filePath){let R=await this.repairIncompleteTail(_),W=await _.readFile("utf8"),$=w(W,E),{size:k}=await _.stat();return{entries:$,separator:R,size:k}}async readTailSeq(_){let{size:E}=await _.stat();if(E===0)return 0;let R=Math.max(0,E-c),W=Buffer.allocUnsafe(E-R);await _.read(W,0,W.length,R);let $=W.toString("utf8").split(`
|
|
10
|
+
`);for(let H=$.length-1;H>=0;H--){let Q=$[H].trim();if(!Q)continue;if(H===0&&R>0)break;try{let X=JSON.parse(Q).seq;if(typeof X==="number")return X}catch{}break}let k=await _.readFile("utf8");return Z.maxSeq(w(k,this.filePath))}async repairIncompleteTail(_){let{size:E}=await _.stat();if(E===0)return"";let R=Buffer.allocUnsafe(1);if(await _.read(R,0,1,E-1),R[0]===10)return"";let W=await this.findTailStart(_,E),$=Buffer.allocUnsafe(E-W);await _.read($,0,$.length,W);try{return JSON.parse($.toString("utf8").trim()),`
|
|
11
|
+
`}catch{return await _.truncate(W),""}}async findTailStart(_,E){let R=E;while(R>0){let W=Math.max(0,R-c),$=Buffer.allocUnsafe(R-W);await _.read($,0,$.length,W);let k=$.lastIndexOf(10);if(k>=0)return W+k+1;R=W}return 0}}function XE(){return typeof globalThis.Bun<"u"}function YE(_){return{exec:(E)=>_.exec(E),prepare:(E)=>{let R=_.prepare(E);return{run:(...W)=>{R.run(...W)},get:(...W)=>R.get(...W),all:(...W)=>R.all(...W)}},transaction:(E)=>_.transaction(E)(),pragma:(E)=>_.pragma(E,{simple:!0}),close:()=>_.close()}}function GE(_){return{exec:(E)=>_.exec(E),prepare:(E)=>{let R=_.query(E);return{run:(...W)=>{R.run(...W)},get:(...W)=>R.get(...W),all:(...W)=>R.all(...W)}},transaction:(E)=>_.transaction(E)(),pragma:(E)=>{let R=_.query(`PRAGMA ${E}`).get();if(!R)return;let W=Object.values(R);return W.length===1?W[0]:R},close:()=>_.close()}}var ZE=["PRAGMA journal_mode=WAL;","PRAGMA busy_timeout=5000;","PRAGMA synchronous=NORMAL;","PRAGMA foreign_keys=ON;"].join(`
|
|
12
|
+
`);async function m(_){try{let E;if(XE()){let{Database:W}=await import("bun:sqlite");E=GE(new W(_))}else{let $=(await import("better-sqlite3")).default;E=YE(new $(_))}return E.exec(ZE),E}catch{return null}}function h(_){let E=Number(_.pragma("user_version")??0);if(E===3)return;if(E>0&&E!==3)_.exec(`
|
|
13
|
+
DROP TABLE IF EXISTS parts_fts;
|
|
14
|
+
DROP TABLE IF EXISTS parts;
|
|
15
|
+
DROP TABLE IF EXISTS sessions;
|
|
16
|
+
DROP TABLE IF EXISTS projection_state;
|
|
17
|
+
`);_.exec(`
|
|
18
|
+
CREATE TABLE IF NOT EXISTS projection_state (
|
|
19
|
+
project_path TEXT NOT NULL,
|
|
20
|
+
session_id TEXT NOT NULL,
|
|
21
|
+
last_seq INTEGER NOT NULL DEFAULT 0,
|
|
22
|
+
file_size INTEGER NOT NULL DEFAULT 0,
|
|
23
|
+
mtime_ms INTEGER NOT NULL DEFAULT 0,
|
|
24
|
+
PRIMARY KEY (project_path, session_id)
|
|
25
|
+
);
|
|
26
|
+
|
|
27
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
28
|
+
project_path TEXT NOT NULL,
|
|
29
|
+
session_id TEXT NOT NULL,
|
|
30
|
+
root_id TEXT,
|
|
31
|
+
parent_id TEXT,
|
|
32
|
+
relation_type TEXT,
|
|
33
|
+
title TEXT,
|
|
34
|
+
agent_type TEXT,
|
|
35
|
+
model TEXT,
|
|
36
|
+
task_status TEXT,
|
|
37
|
+
archived_at TEXT,
|
|
38
|
+
last_message_time TEXT,
|
|
39
|
+
project_sort_key TEXT NOT NULL,
|
|
40
|
+
session_sort_key TEXT NOT NULL,
|
|
41
|
+
first_message_time TEXT,
|
|
42
|
+
message_count INTEGER NOT NULL DEFAULT 0,
|
|
43
|
+
has_errors INTEGER NOT NULL DEFAULT 0,
|
|
44
|
+
is_subagent INTEGER NOT NULL DEFAULT 0,
|
|
45
|
+
-- 完整 StoredSessionMetadata JSON,读回时直接反序列化,保证与 JSONL 路径一致。
|
|
46
|
+
metadata_json TEXT NOT NULL,
|
|
47
|
+
PRIMARY KEY (project_path, session_id)
|
|
48
|
+
);
|
|
49
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_catalog ON sessions(
|
|
50
|
+
last_message_time DESC,
|
|
51
|
+
project_sort_key ASC,
|
|
52
|
+
session_sort_key ASC
|
|
53
|
+
);
|
|
54
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_archived ON sessions(
|
|
55
|
+
archived_at,
|
|
56
|
+
project_path,
|
|
57
|
+
parent_id
|
|
58
|
+
);
|
|
59
|
+
|
|
60
|
+
CREATE TABLE IF NOT EXISTS parts (
|
|
61
|
+
project_path TEXT NOT NULL,
|
|
62
|
+
session_id TEXT NOT NULL,
|
|
63
|
+
part_id TEXT NOT NULL,
|
|
64
|
+
message_id TEXT,
|
|
65
|
+
part_type TEXT,
|
|
66
|
+
role TEXT,
|
|
67
|
+
seq INTEGER,
|
|
68
|
+
timestamp TEXT,
|
|
69
|
+
text TEXT,
|
|
70
|
+
PRIMARY KEY (project_path, session_id, part_id)
|
|
71
|
+
);
|
|
72
|
+
CREATE INDEX IF NOT EXISTS idx_parts_session ON parts(project_path, session_id);
|
|
73
|
+
|
|
74
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS parts_fts USING fts5(
|
|
75
|
+
text,
|
|
76
|
+
project_path UNINDEXED,
|
|
77
|
+
session_id UNINDEXED,
|
|
78
|
+
part_id UNINDEXED,
|
|
79
|
+
role UNINDEXED,
|
|
80
|
+
timestamp UNINDEXED,
|
|
81
|
+
seq UNINDEXED,
|
|
82
|
+
tokenize = 'unicode61'
|
|
83
|
+
);
|
|
84
|
+
`),_.exec("PRAGMA user_version=3;")}var KE=o("Service"),B;function d(){return A.join(y(),"index.db")}async function TE(){let _=d();if(B&&B.path===_)return B.db;let E=(async()=>{let R=await m(_);if(!R)return null;try{return h(R),R}catch{return null}})();return B={path:_,db:E},E}function UE(){B=void 0}function ME(_){if(_&&typeof _==="object"){let E=_.text;if(typeof E==="string")return E}return null}function FE(_,E,R,W){_.prepare("DELETE FROM parts WHERE project_path=? AND session_id=?").run(E,R),_.prepare("DELETE FROM parts_fts WHERE project_path=? AND session_id=?").run(E,R);let $=new Map;for(let Q of W)if(Q.type==="message_created")$.set(Q.data.messageId,Q.data.role);let k=_.prepare(`INSERT OR REPLACE INTO parts
|
|
85
|
+
(project_path, session_id, part_id, message_id, part_type, role, seq, timestamp, text)
|
|
86
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`),H=_.prepare(`INSERT INTO parts_fts (text, project_path, session_id, part_id, role, timestamp, seq)
|
|
87
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`);for(let Q of W){if(Q.type!=="part_created"&&Q.type!=="part_updated")continue;if(Q.data.partType!=="text")continue;let X=ME(Q.data.payload);if(X===null)continue;let G=$.get(Q.data.messageId)??"assistant",F=Q.seq??0;if(k.run(E,R,Q.data.partId,Q.data.messageId,Q.data.partType,G,F,Q.timestamp,X),G==="user"||G==="assistant")H.run(X,E,R,Q.data.partId,G,Q.timestamp,F)}}function DE(_,E){_.prepare(`INSERT INTO sessions
|
|
88
|
+
(project_path, session_id, root_id, parent_id, relation_type, title,
|
|
89
|
+
agent_type, model, task_status, archived_at, last_message_time, project_sort_key,
|
|
90
|
+
session_sort_key, first_message_time, message_count, has_errors,
|
|
91
|
+
is_subagent, metadata_json)
|
|
92
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
93
|
+
ON CONFLICT(project_path, session_id) DO UPDATE SET
|
|
94
|
+
root_id=excluded.root_id, parent_id=excluded.parent_id,
|
|
95
|
+
relation_type=excluded.relation_type, title=excluded.title,
|
|
96
|
+
agent_type=excluded.agent_type, model=excluded.model,
|
|
97
|
+
task_status=excluded.task_status, archived_at=excluded.archived_at,
|
|
98
|
+
last_message_time=excluded.last_message_time,
|
|
99
|
+
project_sort_key=excluded.project_sort_key,
|
|
100
|
+
session_sort_key=excluded.session_sort_key,
|
|
101
|
+
first_message_time=excluded.first_message_time, message_count=excluded.message_count,
|
|
102
|
+
has_errors=excluded.has_errors, is_subagent=excluded.is_subagent,
|
|
103
|
+
metadata_json=excluded.metadata_json`).run(E.projectPath,E.sessionId,E.rootId,E.parentId??null,E.relationType??null,E.title??null,E.agentType??null,E.model??null,E.taskStatus,E.archivedAt??null,E.lastMessageTime,q(E.projectPath),q(E.sessionId),E.firstMessageTime,E.messageCount,E.hasErrors?1:0,E.relationType==="subagent"?1:0,JSON.stringify(E))}function r(_,E,R){for(let W of["sessions","parts","parts_fts"])_.prepare(`DELETE FROM ${W} WHERE project_path=? AND session_id=?`).run(E,R)}function v(_,E,R){r(_,E,R),_.prepare("DELETE FROM projection_state WHERE project_path=? AND session_id=?").run(E,R)}function L(_,E,R,W,$,k){_.prepare(`INSERT INTO projection_state
|
|
104
|
+
(project_path, session_id, last_seq, file_size, mtime_ms)
|
|
105
|
+
VALUES (?, ?, ?, ?, ?)
|
|
106
|
+
ON CONFLICT(project_path, session_id) DO UPDATE SET
|
|
107
|
+
last_seq=excluded.last_seq, file_size=excluded.file_size,
|
|
108
|
+
mtime_ms=excluded.mtime_ms`).run(E,R,W,$,k)}async function BE(_,E,R,W,$=u(R,E)){let k;try{let V=await i($);k={size:V.size,mtimeMs:V.mtimeMs}}catch{return _.transaction(()=>v(_,R,E)),!0}let H=_.prepare("SELECT last_seq, file_size, mtime_ms FROM projection_state WHERE project_path=? AND session_id=?").get(R,E);if(H&&H.file_size===k.size&&H.mtime_ms===Math.floor(k.mtimeMs))return!1;let X=await new Z($).readAll(),G=X.reduce((V,T)=>typeof T.seq==="number"&&T.seq>V?T.seq:V,0),F=z(X),K=W(X,E,R);if(X.length===0||!K)return _.transaction(()=>{r(_,R,E),L(_,R,E,G,k.size,Math.floor(k.mtimeMs))}),!0;let D=_.prepare("SELECT last_message_time FROM sessions WHERE project_path=? AND session_id=?").get(K.projectPath,K.sessionId),g=A.resolve($)===A.resolve(u(K.projectPath,K.sessionId));if(D&&!g&&typeof D.last_message_time==="string"&&D.last_message_time>K.lastMessageTime)return L(_,R,E,G,k.size,Math.floor(k.mtimeMs)),!0;return _.transaction(()=>{DE(_,K),FE(_,K.projectPath,K.sessionId,F),L(_,R,E,G,k.size,Math.floor(k.mtimeMs))}),!0}var b=new WeakMap;async function AE(_,E,R=0){let W=b.get(_)??{};if(b.set(_,W),W.inFlight)return W.inFlight;if(R>0&&W.lastCompletedAt!==void 0&&Date.now()-W.lastCompletedAt<=R)return;let $=gE(_,E);W.inFlight=$;try{await $,W.lastCompletedAt=Date.now()}finally{if(W.inFlight===$)W.inFlight=void 0}}async function gE(_,E){let{readdir:R}=await import("node:fs/promises"),W=await n(),$=new Set,H=(await Promise.all(W.map(async(V)=>{let T=l(V),U=A.join(y(),"projects",V);try{return(await R(U)).flatMap((f)=>{if(!f.endsWith(".jsonl"))return[];let j=f.slice(0,-6);if(!C(j))return[];return[{filePath:A.join(U,f),projectPath:T,sessionId:j}]})}catch{return[]}}))).flat();for(let V of H)$.add(`${V.projectPath}\x00${V.sessionId}`);let Q=_.prepare(`SELECT project_path, session_id, last_seq, file_size, mtime_ms
|
|
109
|
+
FROM projection_state`).all(),X=new Map(Q.map((V)=>[`${V.project_path}\x00${V.session_id}`,V])),G=[],F=Math.min(128,H.length),K=0;await Promise.all(Array.from({length:F},async()=>{while(K<H.length){let V=H[K++];if(!V)continue;try{let T=await i(V.filePath),U=X.get(`${V.projectPath}\x00${V.sessionId}`);if(U&&U.file_size===T.size&&U.mtime_ms===Math.floor(T.mtimeMs))continue}catch{}G.push(V)}}));let D=Math.min(32,G.length),g=0;await Promise.all(Array.from({length:D},async()=>{while(g<G.length){let V=G[g++];if(!V)continue;try{await BE(_,V.sessionId,V.projectPath,E,V.filePath)}catch(T){if(T.code!=="ENOENT")KE.warn(`[SessionService] Skipping invalid session transcript: ${V.sessionId}`)}}}));for(let V of Q)if(!$.has(`${V.project_path}\x00${V.session_id}`))_.transaction(()=>v(_,V.project_path,V.session_id))}function nE(_,E,R){_.transaction(()=>v(_,R,E))}async function oE(_){let{rm:E}=await import("node:fs/promises");UE();let R=d();for(let k of["","-wal","-shm"])await E(`${R}${k}`,{force:!0}).catch(()=>{return});let W=await TE();if(!W)return null;return await AE(W,_),W.prepare("SELECT COUNT(*) c FROM sessions").get()?.c??0}function iE(_,E,R,W){let $=E.replace(/["*]/g," ").trim().split(/\s+/)[0];if(!$)return[];let k=`"${$}"*`,H=R?`SELECT session_id, role, timestamp, text FROM parts_fts
|
|
110
|
+
WHERE parts_fts MATCH ? AND project_path = ?
|
|
111
|
+
ORDER BY timestamp DESC LIMIT ?`:`SELECT session_id, role, timestamp, text FROM parts_fts
|
|
112
|
+
WHERE parts_fts MATCH ?
|
|
113
|
+
ORDER BY timestamp DESC LIMIT ?`,Q=_.prepare(H);return R?Q.all(k,R,W):Q.all(k,W)}
|
|
114
|
+
export{w as hb,Z as ib,q as jb,WE as kb,wE as lb,$E as mb,xE as nb,z as ob,fE as pb,qE as qb,d as rb,TE as sb,UE as tb,BE as ub,AE as vb,nE as wb,oE as xb,iE as yb};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import{q as o}from"./chunk-pms05z02.js";import{E as y,G as k,H as S,J as C,X as f,Y as u,Z as g,_ as c,t as K}from"./chunk-793k86j6.js";import{ia as n}from"./chunk-51wa5fct.js";import{qa as T,ta as M}from"./chunk-jzrqjzjm.js";import{La as A}from"./chunk-88vy9hh0.js";import{$a as I,_a as E,db as V,gb as U}from"./chunk-a8y9xbxw.js";import"./chunk-44wkjs2j.js";import"./chunk-kq5my0yy.js";import"./chunk-k6qwdjyy.js";import"./chunk-gafbzeyk.js";import{mc as i}from"./chunk-0h81hxkw.js";import"./chunk-af49jmns.js";import"./chunk-px5ck9pf.js";import{vc as a}from"./chunk-fjw32ex5.js";import"./chunk-29r7z43j.js";import"./chunk-j51fwecz.js";import{Sc as r}from"./chunk-d9ddpapp.js";import"./chunk-sndbq5xt.js";import"./chunk-hefv4415.js";import"./chunk-beqaxytd.js";import{dd as R}from"./chunk-jxv6r0c7.js";import"./chunk-3nx2579c.js";import"./chunk-4vaywb2r.js";import{be as q,ce as h,de as N}from"./chunk-qev36qrb.js";import{he as m}from"./chunk-vjpd3nee.js";import"./chunk-a7nbn5kf.js";import{ne as d,qe as l}from"./chunk-2beq0syt.js";import"./chunk-h7kj4gvj.js";import"./chunk-6hj2dk75.js";import"./chunk-6n5xdf2r.js";import"./chunk-8nm1hqr1.js";import"./chunk-mjp61rqd.js";import{Readable as zJ,Writable as WJ}from"node:stream";import*as O from"@agentclientprotocol/sdk";import p from"node:path";import{PROTOCOL_VERSION as $J}from"@agentclientprotocol/sdk";import{nanoid as P}from"nanoid";var G=R("Agent");function x(J){if(!J)return{};return Object.fromEntries(J.map((Z)=>[Z.name,Z.value]))}function e(J){if("command"in J)return{type:"stdio",command:J.command,args:J.args,env:x(J.env)};if("url"in J)return{type:J.type,url:J.url,headers:x("headers"in J?J.headers:void 0)};return null}function JJ(J){let Z={};for(let Q of J){let $=e(Q);if($)Z[Q.name]=$}return Z}function v(J){if(typeof J==="string")return J?[{type:"text",text:J}]:[];return J.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let Q=Z.image_url.url,$=/^data:([^;,]+);base64,(.+)$/s.exec(Q);if(!$)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:$[1]??"image/png",data:$[2]??""}]})}function QJ(J){let Z=I(J.metadata);return Z?[{type:"text",text:E(Z)}]:v(J.content)}function ZJ(J){return[`Status: ${J.status}`,`Exit code: ${J.exitCode??"null"}`,`Duration: ${(J.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
|
+
`)}class _{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingUserShell=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;messages;mode="default";constructor(J,Z,Q,$,D={}){this.id=J;this.cwd=Z;this.connection=Q;this.clientCapabilities=$;this.options=D;this.messages=[...D.initialMessages??[]]}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return C.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){G.debug(`[AcpSession ${this.id}] Initializing...`),K.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),G.debug(`[AcpSession ${this.id}] ACP service context initialized`);let J=this.options.mcpServers?JJ(this.options.mcpServers):void 0,Z=K.getInstance().getTerminalService(this.id);this.runtime=await y.create({sessionId:this.id,workspaceRoot:this.cwd,...J?{mcpServers:J}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async($,D)=>{let z=await Z.execute($,{cwd:D.cwd,env:D.env,timeout:D.timeoutMs,signal:D.signal,allowLocalFallback:!1,onOutput:(Y)=>D.onOutput?.("stdout",Y)});return{exitCode:z.exitCode,stdout:z.stdout,stderr:z.stderr,...z.error?{error:z.error}:{},timedOut:z.error==="Command timed out",aborted:z.error==="Command was aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),this.agent=await this.createAgent(),await u(this.cwd),G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=M.subscribe(($)=>{if($.sessionId!==this.id||$.projectPath!==this.cwd)return;if($.type==="task.delivery"){if(!$.properties.taskDelivery||typeof $.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":$.properties.taskDelivery,...$.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if($.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":$.properties.taskStatus,...typeof $.properties.taskStatusReason==="string"?{"blade/taskStatusReason":$.properties.taskStatusReason}:{},...$.properties.taskFailure&&typeof $.properties.taskFailure==="object"?{"blade/taskFailure":$.properties.taskFailure}:{},...typeof $.properties.taskStartedAt==="string"?{"blade/taskStartedAt":$.properties.taskStartedAt}:{},...typeof $.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":$.properties.taskCompletedAt}:{},...$.properties.taskDiffStat&&typeof $.properties.taskDiffStat==="object"?{"blade/taskDiffStat":$.properties.taskDiffStat}:{},...typeof $.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":$.properties.taskQueuePosition}:{},...typeof $.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":$.properties.taskQueueDepth}:{},...typeof $.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":$.properties.taskConcurrencyLimit}:{},...typeof $.properties.taskInFlight==="number"?{"blade/taskInFlight":$.properties.taskInFlight}:{}}})});let Q=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||Q?.status==="active")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;let Z=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!Z)continue;for(let Q of QJ(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Z,content:Q}))return}}if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(J,Z){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${J}`);let Q={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.messages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let W=await this.runtime.rewindSession(Y);return this.messages=[...W.messages],await this.agent?.destroy(),this.agent=await this.createAgent(),W}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Y)=>{if(await this.setReasoningEffort(Y),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Y)=>{if(await this.setServiceTier(Y),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Y)=>{if(await this.setResponseVerbosity(Y),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Y)=>{if(await this.setCommunicationStyle(Y),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Y,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let H=!1,F,j=(B)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:B.id,status:B.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:B.result?.message||B.result?.error||`Subagent ${B.status}`}}]})},X=this.runtime.resumeSubagent({agentId:Y,prompt:W,onCompleted:(B)=>{if(H)j(B);else F=B}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X.session.id,status:"in_progress",title:`Resuming ${X.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${X.source.id} at depth ${X.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),H=!0,F)j(F);return X}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Y)},getPrompt:async(Y,W,H)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Y,W,H)},complete:async(Y,W,H)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Y,W,H)},listTasks:async(Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Y)},getTask:async(Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Y)},cancelTask:async(Y,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Y,W)},getLogs:async(Y,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Y,W)},setLoggingLevel:async(Y,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Y,W)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},signal:Z,acp:{sendMessage:(Y)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y}})},sendToolStart:(Y,W,H)=>{let F=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,j=this.mapToolKind(H);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F,status:"in_progress",title:`${Y}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(W,null,2)}}],kind:j})},sendToolResult:(Y,W)=>{if(W.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.summary}})}}},$=await g(J,Q),D=$.data?.action;if(D==="start_goal"||D==="resume_goal")this.schedulePendingResume();if(D==="rewind_session"&&Array.isArray($.data?.messages))this.messages=[...$.data.messages];if(($.message==="compact_completed"||$.message==="compact_fallback")&&$.data?.compactedMessages)this.messages=[...$.data.compactedMessages];let z=$.content||$.message;if(z)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:z}});if($.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${$.error}`}});return{stopReason:$.success?"end_turn":"cancelled"}}catch(Q){return G.error(`[AcpSession ${this.id}] Slash command error:`,Q),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${Q instanceof Error?Q.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let J=c(this.cwd),Z=["model","permissions","theme","config","exit","ide"],$=J.filter((D)=>!Z.includes(D.name)).map((D)=>{let z;if(D.usage){let Y=D.usage.replace(/^\/\w+\s*/,"").trim();if(Y)z=Y}if(D.aliases?.length){let Y=`Aliases: ${D.aliases.join(", ")}`;z=z?`${z} | ${Y}`:Y}return{name:D.name,description:D.description,input:z?{hint:z}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify($.map((D)=>D.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:$}),G.info(`[AcpSession ${this.id}] Sent ${$.length} available commands`)}catch(J){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,J)}}async prompt(J,Z={}){if(K.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Q=this.resolvePrompt(J.prompt),$=Q.content,D=Q.displayText;if(D.trimStart().startsWith("!"))return this.handleUserShellCommand(D);if(this.pendingPrompt){if(/^\/goal(?:\s|$)/i.test(D.trim()))return this.handleSlashCommand(D,this.pendingPrompt.signal);let Y=await this.runtime.enqueueSteering($,{allowBeforeTurn:!0});if(!Y.accepted)throw Error(Y.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${Y.queued})`),Y.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let z=new AbortController;this.pendingPrompt=z;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${D.slice(0,100)}...`),f(D))return await this.handleSlashCommand(D,z.signal);let Y={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:z.signal,permissionMode:this.mapModeToPermissionMode(),...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(W)=>{return this.requestPermission(W)}}};if(await T(this.agent.chatStream($,Y,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly}),async(W)=>{switch(W.kind){case"content_delta":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:W.delta}});break;case"tool_start":{let H=W.toolCall,F=H.function.name,j=this.mapToolKind(W.toolKind),X=`Executing ${F}`;if(F==="Task"&&"function"in H)try{let B=JSON.parse(H.function.arguments),L=B.resume_from??B.resume;if(typeof L==="string")X=`Resuming ${String(B.subagent_type||"subagent")} from ${L}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:H.id,status:"in_progress",title:X,content:[],kind:j});break}case"tool_progress":{let H=W.toolCall;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:H.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:W.update.message}}]});break}case"tool_result":{let{toolCall:H,result:F}=W,j=[],X=F.metadata;if(X?.kind==="patch"&&Array.isArray(X.changes))for(let L of X.changes){if(!L||typeof L!=="object"||!("path"in L)||typeof L.path!=="string")continue;j.push({type:"diff",path:L.path,oldText:"oldContent"in L&&typeof L.oldContent==="string"?L.oldContent:null,newText:"newContent"in L&&typeof L.newContent==="string"?L.newContent:null})}else if(X?.kind==="edit"&&typeof X.file_path==="string"&&typeof X.oldContent==="string"&&(typeof X.newContent==="string"||X.newContent===void 0))j.push({type:"diff",path:X.file_path,oldText:X.oldContent,newText:X.newContent??null});else{let L=H.function.name,t=S(k(L,F));j.push({type:"content",content:{type:"text",text:t}})}let B=F.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:H.id,status:B,content:j});break}case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
|
|
3
|
+
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${W.contentKind} r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
|
|
4
|
+
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${W.revision} (${W.serverName}): ${W.uri}
|
|
5
|
+
`}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${W.revision} (${W.serverName}): ${W.phase} ${W.attempt}/${W.maxAttempts}
|
|
6
|
+
`}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${W.revision} (${W.serverName}) ${W.level}${W.logger?` logger=${W.logger}`:""}: ${W.message}
|
|
7
|
+
`}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${W.revision} (${W.serverName}): ${W.action}${W.detailsOmitted?" details-omitted":""}
|
|
8
|
+
`}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${W.revision} ${W.taskId} (${W.serverName}/${W.toolName}): ${W.status}${W.hasResult?" result-available":""}
|
|
9
|
+
`}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${W.files.length}${W.blockedWrite?" (write retry required)":""}
|
|
10
|
+
`}});break;case"task_update":this.sendPlanUpdate(W.tasks);break;case"steering_applied":break;case"follow_up_started":for(let H of W.messages){if(!H.recovered||H.persisted)continue;for(let F of v(H.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:F})}if(W.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${W.recovered} queued instruction${W.recovered===1?"":"s"} recovered after restart]
|
|
11
|
+
`}});break;case"goal_updated":if(W.goal&&W.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${W.goal.status}: ${W.goal.objective}]
|
|
12
|
+
`}});break;case"goal_continuation_started":break;default:break}}),this.messages=[...Y.messages],z.signal.aborted)return{stopReason:"cancelled"};return{stopReason:"end_turn"}}catch(Y){if(z.signal.aborted||Y instanceof Error&&Y.name==="AbortError")return{stopReason:"cancelled"};throw G.error(`[AcpSession ${this.id}] Prompt error:`,Y),Y}finally{if(this.pendingPrompt===z){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.schedulePendingResume()}}}async handleUserShellCommand(J){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let Z=J.trimStart().slice(1).trim();if(!Z)throw Error("User shell command cannot be empty");let Q=new AbortController;this.pendingUserShell=Q;let $,D="";try{let z=await this.runtime.executeUserShellCommand(Z,{signal:Q.signal,onEvent:async(Y)=>{if($=Y.executionId,Y.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Y.executionId,status:"in_progress",title:`! ${Y.command}`,content:[],kind:"execute"});return}if(Y.type==="output"){D+=Y.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Y.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:Y.chunk}}]});return}let W=E(Y.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Y.executionId,status:Y.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:D?ZJ(Y.record):W}}]})}});if(this.messages.push({role:"user",content:z.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(z.record))}}),z.delivery==="next_turn")this.schedulePendingResume();return{stopReason:z.record.status==="aborted"?"cancelled":"end_turn"}}catch(z){if($)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$,status:"failed",content:[{type:"content",content:{type:"text",text:z instanceof Error?z.message:String(z)}}]});if(Q.signal.aborted)return{stopReason:"cancelled"};throw z}finally{if(this.pendingUserShell===Q)this.pendingUserShell=null}}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.pendingUserShell||!this.runtime||!this.agent)return;let J=this.runtime.getPendingSteeringCount()>0,Q=(J?null:await this.runtime.getGoal())?.status==="active";if(!J&&!Q){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:J,goalContinuationOnly:Q}).catch(($)=>{G.error(`[AcpSession ${this.id}] Failed to resume pending input:`,$)})}cancel(){G.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1;let J=!1;if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,J=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,J=!0;if(!J)G.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(J){let Z=["default","auto-edit","yolo","plan"];this.mode=Z.includes(J)?J:"default",G.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(J){switch(this.mode){case"yolo":return!0;case"auto-edit":return J==="readonly"||J==="write";case"plan":return J==="readonly";case"default":default:return!1}}async setModel(J){if(G.info(`[AcpSession ${this.id}] Model set to: ${J}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCurrentModelId();await this.agent.switchModel(J);try{try{await U.updateSessionMetadata(this.id,this.cwd,{selectedModelId:J})}catch(Q){if(!(Q instanceof V)&&Q.code!=="ENOENT")throw Q;await U.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:J})}}catch(Q){if(Z&&Z!==J)await this.agent.switchModel(Z).catch(($)=>{G.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,$)});throw Q}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(J){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid reasoning effort")}if(Z.selection===J)return;await this.runtime.refresh({reasoningEffort:J});try{try{await U.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:J})}catch(Q){if(!(Q instanceof V)&&Q.code!=="ENOENT")throw Q;await U.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:J})}}catch(Q){throw await this.runtime.refresh({reasoningEffort:Z.selection}),Q}}async setServiceTier(J){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid service tier")}if(Z.selection===J)return;await this.runtime.refresh({serviceTier:J});try{try{await U.updateSessionMetadata(this.id,this.cwd,{serviceTier:J})}catch(Q){if(!(Q instanceof V)&&Q.code!=="ENOENT")throw Q;await U.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:J})}}catch(Q){throw await this.runtime.refresh({serviceTier:Z.selection}),Q}}async setResponseVerbosity(J){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid response verbosity")}if(Z.selection===J)return;await this.runtime.refresh({responseVerbosity:J});try{try{await U.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:J})}catch(Q){if(!(Q instanceof V)&&Q.code!=="ENOENT")throw Q;await U.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:J})}}catch(Q){throw await this.runtime.refresh({responseVerbosity:Z.selection}),Q}}async setCommunicationStyle(J){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCommunicationStyleConfiguration(),Q=this.runtime.resolveCommunicationStyleConfiguration(J);if(Q.source!=="built-in"&&!Q.contentSha256)throw Error("Custom communication style has no provenance");if(Z.selection===J)return;await this.runtime.refresh({communicationStyle:J});try{try{await U.updateSessionMetadata(this.id,this.cwd,{communicationStyle:J,communicationStyleDigest:Q.source==="built-in"?null:Q.contentSha256})}catch($){if(!($ instanceof V)&&$.code!=="ENOENT")throw $;await U.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:J,...Q.source!=="built-in"&&Q.contentSha256?{communicationStyleDigest:Q.contentSha256}:{}})}}catch($){throw await this.runtime.refresh({communicationStyle:Z.selection}),$}}getModelConfiguration(){if(!this.runtime)return;let J=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??J.currentModelId,models:J.models.map((Z)=>structuredClone(Z)),modelProviders:structuredClone(J.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}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 J=this.agent,Z=this.runtime;this.agent=null,this.runtime=null;let Q,$=async(D)=>{try{await D()}catch(z){Q??=z}};if(await $(()=>this.cancel()),J)await $(()=>J.destroy());if(Z)await $(()=>Z.dispose());if(await $(()=>K.destroySession(this.id)),G.debug(`[AcpSession ${this.id}] Destroyed`),Q!==void 0)throw Q}resolvePrompt(J){let Z=[],Q=[],$=0,D=0,z=0,Y=(H)=>{if(Q.length>0)Q.push({type:"text",text:`
|
|
13
|
+
`}),z+=1;if(Q.push(H),H.type==="text")z+=H.text.length};for(let H of J)if(H.type==="text")Z.push(H.text),Y({type:"text",text:H.text});else if(H.type==="image"){let F=`data:${H.mimeType};base64,${H.data}`;$+=1,D+=F.length,Z.push(`[Image: ${H.mimeType}]`),Y({type:"image_url",image_url:{url:F}})}else if(H.type==="resource"){let F=H.resource;if("text"in F){let j=`<file path="${F.uri}">
|
|
14
|
+
${F.text}
|
|
15
|
+
</file>`;Z.push(j),Y({type:"text",text:j})}}else if(H.type==="resource_link"){let F=`[Resource: ${H.uri}]`;Z.push(F),Y({type:"text",text:F})}if($>q)throw Error(`ACP prompt contains more than ${q} images`);if(D>h)throw Error("ACP prompt images exceed the 5 MiB limit");if(z>N)throw Error(`ACP prompt text exceeds ${N} characters`);let W=Z.join(`
|
|
16
|
+
`);return{content:$>0?Q:W,displayText:W}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted}async sendUpdateAndWait(J){if(!this.canSendUpdates())return!1;return await this.connection.sessionUpdate({sessionId:this.id,update:J}),this.canSendUpdates()}sendUpdate(J){if(!this.canSendUpdates())return;let Z={sessionId:this.id,update:J};this.connection.sessionUpdate(Z).catch((Q)=>{G.warn(`[AcpSession ${this.id}] Failed to send update:`,Q)})}sendPlanUpdate(J){let Z=J.map((Q)=>({content:Q.subject,priority:Q.priority,status:Q.status}));G.debug(`[AcpSession ${this.id}] Sending plan update with ${Z.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:Z})}async requestPermission(J){let Z=this.pendingPrompt?.signal;if(J.type==="askUserQuestion")return this.requestUserQuestions(J,Z);if(J.type==="mcpElicitation")return this.requestMcpElicitation(J,Z);let Q=J.kind?.toLowerCase()||"execute";if(J.type!=="mcpSampling"&&this.shouldAutoApprove(Q))return G.debug(`[AcpSession ${this.id}] Auto-approving ${Q} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(Q==="write"||Q==="execute"))return G.debug(`[AcpSession ${this.id}] Rejecting ${Q} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let $=P(),D=[];if(J.message)D.push({type:"content",content:{type:"text",text:J.message}});if(J.details)D.push({type:"content",content:{type:"text",text:J.details}});if(J.risks&&J.risks.length>0)D.push({type:"content",content:{type:"text",text:`Risks:
|
|
17
|
+
- ${J.risks.join(`
|
|
18
|
+
- `)}`}});let z=this.mapToolKind(Q),Y={sessionId:this.id,options:J.type==="mcpSampling"?[{optionId:"allow_once",name:"Allow this sampling request",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}]:[{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:$,status:"pending",title:J.title||"Permission Required",content:D,kind:z}},W=await this.waitForClientInteraction(this.connection.requestPermission(Y),Z);if(!W)return{approved:!1,reason:A};let H=W.outcome;if(H.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let F=H.optionId;if(F==="allow_always")return{approved:!0,scope:"project"};if(F==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let j=F==="allow_once";return{approved:j,scope:"once",reason:j?void 0:"User denied the operation"}}catch($){return G.warn(`[AcpSession ${this.id}] Permission request failed:`,$),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(J,Z){let Q=J.questions??[];if(Q.length===0)return{approved:!1,reason:"No structured questions were provided"};if(Q.some((D)=>D.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let $={};try{for(let[D,z]of Q.entries()){let Y=z.options.map((j,X)=>`answer:${D}:${X}`),W=`answer:${D}:cancel`,H=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...z.options.map((j,X)=>({optionId:Y[X],name:j.label,kind:"allow_once"})),{optionId:W,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:P(),status:"pending",title:z.header,kind:"think",content:[{type:"content",content:{type:"text",text:[z.question,...z.options.map((j)=>`${j.label}: ${j.description}`)].join(`
|
|
19
|
+
`)}}]}}),Z);if(!H)return{approved:!1,reason:A};if(H.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let F=Y.indexOf(H.outcome.optionId);if(F<0)return{approved:!1,reason:"User cancelled the question prompt"};$[z.header]=z.options[F].label}return{approved:!0,answers:$}}catch(D){return G.warn(`[AcpSession ${this.id}] Question request failed:`,D),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(J,Z){let Q=J.mcpElicitation;if(!Q)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(Q.mode==="url"){let D=await this.requestElicitationChoice("MCP external authorization",[Q.message,`Server: ${Q.serverName}`,`Domain: ${Q.domain??"unknown"}`,`URL: ${Q.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
|
|
20
|
+
`),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],Z);if(D==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:D==="decline"?"User declined URL":"User cancelled",elicitation:{action:D==="decline"?"decline":"cancel"}}}let $=Object.create(null);for(let D of Q.fields??[]){let z=await this.collectAcpElicitationField(D,Z);if(z.cancelled)return{approved:!1,reason:z.reason,elicitation:{action:"cancel"}};if(z.value!==void 0)$[D.name]=z.value}return{approved:!0,elicitation:{action:"accept",content:$}}}catch($){return G.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,$),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(J,Z){if(J.type==="select"||J.type==="boolean"){let Q=J.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(J.options??[]).map((z,Y)=>({id:`option:${Y}`,label:z.label,value:z.value})),$=await this.requestElicitationChoice(J.title,[J.description,J.required?"Required":"Optional"].filter(Boolean).join(`
|
|
21
|
+
`),[...Q.map((z)=>({id:z.id,label:z.label})),...!J.required?[{id:"skip",label:"Skip"}]:[]],Z);if($==="skip")return{cancelled:!1};let D=Q.find((z)=>z.id===$);if(!D)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:D.value}}if(J.defaultValue!==void 0){let Q=await this.requestElicitationChoice(J.title,[J.description,`ACP cannot collect ${J.type} input. Use the server default: ${String(J.defaultValue)}?`].filter(Boolean).join(`
|
|
22
|
+
`),[{id:"default",label:"Use default"},...!J.required?[{id:"skip",label:"Skip"}]:[]],Z);if(Q==="default")return{cancelled:!1,value:J.defaultValue};if(Q==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!J.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${J.type} field "${J.name}"`}}async requestElicitationChoice(J,Z,Q,$){let D=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Q.map((z)=>({optionId:z.id,name:z.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:P(),status:"pending",title:J,kind:"think",content:[{type:"content",content:{type:"text",text:Z}}]}}),$);return D?.outcome.outcome==="selected"?D.outcome.optionId:void 0}async waitForClientInteraction(J,Z){if(!Z)return J;if(Z.aborted)return;return new Promise((Q,$)=>{let D=!1,z=(W)=>{if(D)return;D=!0,Z.removeEventListener("abort",Y),W()},Y=()=>z(()=>Q(void 0));if(Z.addEventListener("abort",Y,{once:!0}),Z.aborted)Y();J.then((W)=>z(()=>Q(W)),(W)=>z(()=>$(W)))})}mapToolKind(J){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[J||""]||"other"}}var w=R("Agent");class b{connection;sessions=new Map;sessionLoadQueues=new Map;clientCapabilities;destroyed=!1;constructor(J){this.connection=J}async initialize(J){return w.info("[BladeAgent] Initializing ACP connection"),w.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(J.clientCapabilities)}`),this.clientCapabilities=J.clientCapabilities,{protocolVersion:$J,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(J){return}async newSession(J){this.assertNotDestroyed();let Z=i("acp"),Q=J.cwd||m(),$=J._meta?.["blade/taskIsolation"],D=$==="local"||$==="worktree"?$:void 0,z=J._meta?.["blade/taskPrompt"],Y=D?await o.createSessionTask({sessionId:Z,prompt:typeof z==="string"&&z.trim()?z:"ACP task session",sourceProjectPath:Q,isolation:D}):void 0,W=Y?.metadata.projectPath??Q;w.info(`[BladeAgent] Creating new session: ${Z}`),w.debug(`[BladeAgent] Session cwd: ${W}`);let H=new _(Z,W,this.connection,this.clientCapabilities,{mcpServers:J.mcpServers,...Y?.taskWorktree?{taskWorktree:Y.taskWorktree}:{},...Y?.metadata.taskIsolation?{taskIsolation:Y.metadata.taskIsolation}:{}});try{await H.initialize(),this.assertNotDestroyed()}catch(F){throw await H.destroy().catch(()=>{return}),F}return this.sessions.set(Z,H),w.info(`[BladeAgent] Session ${Z} created, scheduling available commands update`),H.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z,Y?.metadata,H.getModelConfiguration())}async listSessions(J){if(J.cwd!=null&&!p.isAbsolute(J.cwd))throw Error("ACP session list cwd must be absolute");let Z=await U.listSessionPage({cwd:J.cwd??void 0,cursor:J.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:Z.sessions.map((Q)=>({sessionId:Q.sessionId,cwd:Q.projectPath,title:Q.title??null,updatedAt:Q.lastMessageTime,_meta:{"blade/taskStatus":Q.taskStatus,...Q.taskStatusReason?{"blade/taskStatusReason":Q.taskStatusReason}:{},...Q.taskFailure?{"blade/taskFailure":Q.taskFailure}:{},...Q.taskStartedAt?{"blade/taskStartedAt":Q.taskStartedAt}:{},...Q.taskCompletedAt?{"blade/taskCompletedAt":Q.taskCompletedAt}:{},...Q.taskModelId?{"blade/taskModelId":Q.taskModelId}:{},...Q.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Q.taskRetriedFrom?{"blade/taskRetriedFrom":Q.taskRetriedFrom}:{},...Q.taskDelivery?{"blade/taskDelivery":Q.taskDelivery}:{},...Q.taskIsolation?{"blade/taskIsolation":Q.taskIsolation}:{},...Q.taskSourceProjectPath?{"blade/taskSourceProjectPath":Q.taskSourceProjectPath}:{},...Q.taskWorktreeBranch?{"blade/taskWorktreeBranch":Q.taskWorktreeBranch}:{},...Q.taskBaseCommit?{"blade/taskBaseCommit":Q.taskBaseCommit}:{},...Q.taskDiffStat?{"blade/taskDiffStat":Q.taskDiffStat}:{},...Q.taskQueuePosition?{"blade/taskQueuePosition":Q.taskQueuePosition}:{},...Q.taskQueueDepth!==void 0?{"blade/taskQueueDepth":Q.taskQueueDepth}:{},...Q.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":Q.taskConcurrencyLimit}:{}}})),nextCursor:Z.nextCursor}}async unstable_forkSession(J){if(this.assertNotDestroyed(),!p.isAbsolute(J.cwd))throw Error("ACP session fork cwd must be absolute");let Z=await U.forkSession(J.sessionId,{sourceProjectPath:J.cwd,targetProjectPath:J.cwd});this.assertNotDestroyed();let Q=new _(Z.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Z.messages,mcpServers:J.mcpServers});try{await Q.initialize(),this.assertNotDestroyed()}catch($){throw await Q.destroy().catch(()=>{return}),$}return this.sessions.set(Z.sessionId,Q),Q.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z.sessionId,Z.metadata,Q.getModelConfiguration())}async loadSession(J){this.assertNotDestroyed(),w.info(`[BladeAgent] Loading session: ${J.sessionId}`);let Q=(this.sessionLoadQueues.get(J.sessionId)??Promise.resolve()).then(()=>this.replaceSession(J)),$=Q.then(()=>{return},()=>{return});this.sessionLoadQueues.set(J.sessionId,$);try{return await Q}finally{if(this.sessionLoadQueues.get(J.sessionId)===$)this.sessionLoadQueues.delete(J.sessionId)}}async replaceSession(J){this.assertNotDestroyed(),await U.assertSessionWritable(J.sessionId,J.cwd);let Z=this.sessions.get(J.sessionId);if(Z)try{await Z.destroy()}finally{if(this.sessions.get(J.sessionId)===Z)this.sessions.delete(J.sessionId)}let Q=await U.loadSession(J.sessionId,J.cwd),$=new _(J.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Q,mcpServers:J.mcpServers});try{await $.initialize(),await $.replayHistory(),this.assertNotDestroyed()}catch(D){throw await $.destroy().catch(()=>{return}),D}return this.sessions.set(J.sessionId,$),$.sendAvailableCommandsDelayed(),this.buildSessionSetup($.getModelConfiguration())}buildChildSessionResponse(J,Z,Q){return{sessionId:J,...this.buildSessionSetup(Q),...Z?{_meta:{"blade/taskIsolation":Z.taskIsolation,"blade/taskSourceProjectPath":Z.taskSourceProjectPath,"blade/taskProjectPath":Z.projectPath,...Z.taskModelId?{"blade/taskModelId":Z.taskModelId}:{},...Z.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Z.taskRetriedFrom?{"blade/taskRetriedFrom":Z.taskRetriedFrom}:{},...Z.taskDelivery?{"blade/taskDelivery":Z.taskDelivery}:{},...Z.taskWorktreeBranch?{"blade/taskWorktreeBranch":Z.taskWorktreeBranch}:{},...Z.taskBaseCommit?{"blade/taskBaseCommit":Z.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}buildSessionSetup(J){let Z=J?.models??[],Q=(J?.currentModelId&&Z.some((z)=>z.id===J.currentModelId)?J.currentModelId:void 0)??Z[0]?.id,$=[{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"}],D=[];if(Z.length>0)D.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:Q,options:Z.map((z)=>({value:z.id,name:z.displayName??z.model,description:`${J?.modelProviders[z.provider]?.name??z.provider} · ${z.model}`}))});if(J?.reasoning)D.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:J.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${J.reasoning.effective})`},...J.reasoning.supported.map((z)=>({value:z,name:z[0].toUpperCase()+z.slice(1),description:z==="off"?"Disable model reasoning":`Use ${z} reasoning effort`}))]});if(J?.serviceTier)D.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:J.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...J.serviceTier.supported.map((z)=>({value:z,name:z[0].toUpperCase()+z.slice(1),description:z==="fast"?"Use the provider priority tier":z==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(J?.responseVerbosity)D.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:J.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...J.responseVerbosity.supported.map((z)=>({value:z,name:z[0].toUpperCase()+z.slice(1),description:`Use ${z} response verbosity`}))]});if(J?.communicationStyle)D.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:J.communicationStyle.selection,options:J.communicationStyle.supported.map((z)=>({value:z.id,name:z.name,description:`${z.description} · ${z.source}`}))});return{modes:{availableModes:$,currentModeId:"default"},configOptions:D.length>0?D:void 0}}async prompt(J){let Z=this.sessions.get(J.sessionId);if(!Z)throw Error(`Session not found: ${J.sessionId}`);return Z.prompt(J)}async cancel(J){w.info(`[BladeAgent] Cancel notification received for session: ${J.sessionId}`);let Z=this.sessions.get(J.sessionId);if(Z)w.info("[BladeAgent] Found session, calling session.cancel()"),Z.cancel();else w.warn(`[BladeAgent] Session not found for cancel: ${J.sessionId}`)}async setSessionMode(J){w.info(`[BladeAgent] Setting session mode: ${J.modeId}`);let Z=this.sessions.get(J.sessionId);if(Z)await Z.setMode(J.modeId);return{}}async setSessionConfigOption(J){let Z=this.sessions.get(J.sessionId);if(!Z)throw Error(`Session not found: ${J.sessionId}`);if(J.configId==="model"&&"value"in J&&typeof J.value==="string")w.info(`[BladeAgent] Setting session model: ${J.value}`),await Z.setModel(J.value);else if(J.configId==="reasoning_effort"&&"value"in J&&a(J.value))w.info(`[BladeAgent] Setting reasoning effort: ${J.value}`),await Z.setReasoningEffort(J.value);else if(J.configId==="service_tier"&&"value"in J&&l(J.value))w.info(`[BladeAgent] Setting service tier: ${J.value}`),await Z.setServiceTier(J.value);else if(J.configId==="response_verbosity"&&"value"in J&&d(J.value))w.info(`[BladeAgent] Setting response verbosity: ${J.value}`),await Z.setResponseVerbosity(J.value);else if(J.configId==="communication_style"&&"value"in J&&r(J.value))w.info(`[BladeAgent] Setting communication style: ${J.value}`),await Z.setCommunicationStyle(J.value);else throw Error(`Invalid session config option: ${J.configId}`);return{configOptions:this.buildSessionSetup(Z.getModelConfiguration()).configOptions??[]}}async destroy(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let J;for(let Z of this.sessions.values())try{await Z.destroy()}catch(Q){J??=Q}this.sessions.clear();try{await n.getInstance().disconnectAll()}catch(Z){J??=Z}if(J!==void 0)throw J}}async function uJ(){let J=WJ.toWeb(process.stdout),Z=zJ.toWeb(process.stdin),Q=O.ndJsonStream(J,Z);await new O.AgentSideConnection((D)=>new b(D),Q).closed}export{uJ as runAcpIntegration};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var g;((e)=>{e.DEFAULT="default";e.AUTO_EDIT="autoEdit";e.YOLO="yolo";e.PLAN="plan"})(g||={});import p from"typebox/schema";import u from"typebox/value";class s extends Error{issues;constructor(t){super(t.map((r)=>{return`${r.path.length>0?r.path.join("."):"root"}: ${r.message}`}).join("; "));this.issues=t;this.name="SchemaValidationError"}}function T(t){if(!t)return[];return t.split("/").slice(1).map((r)=>r.replace(/~1/g,"/").replace(/~0/g,"~")).map((r)=>/^(0|[1-9]\d*)$/.test(r)?Number(r):r)}function d(t,r){let n=t;for(let o of r){if(n===null||typeof n!=="object")return;n=n[o]}return n}function f(t,r){let[,n]=p.Errors(t,r);return n.map((o)=>{let e=T(o.instancePath);return{code:o.keyword,path:e,message:o.message,value:d(r,e)}})}function a(t,r){let n=u.Default(t,u.Clone(r)),o=f(t,n);if(o.length>0)return{success:!1,error:new s(o)};let e=u.Clean(t,n),c=f(t,e);if(c.length>0)return{success:!1,error:new s(c)};return{success:!0,data:e}}function i(t,r){let n=a(t,r);if(!n.success)throw n.error;return n.data}import l from"typebox";function m(t){return Object.defineProperties(t,{parse:{value:(r)=>i(t,r),enumerable:!1},safeParse:{value:(r)=>a(t,r),enumerable:!1}}),t}function N(t,r){return l.Optional({...t,default:r})}function R(t,r={}){return l.Unsafe({type:"string",enum:[...t],...r})}var _=100;function I(t){return Number.isInteger(t)&&t>=-1&&t<=100}function y(){return"-1, 0, or an integer from 1 to 100"}
|
|
2
|
+
export{g as Td,a as Ud,i as Vd,l as Wd,m as Xd,N as Yd,R as Zd,_ as _d,I as $d,y as ae};
|