blade-code 0.10.91 → 0.10.93
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/chunk-05fctawm.js +1 -0
- package/dist/{chunk-y7dtdwqx.js → chunk-0eqk29xr.js} +2 -2
- package/dist/{chunk-s8hdg5y9.js → chunk-0pnj92hk.js} +2 -2
- package/dist/{chunk-61sg8p2c.js → chunk-37csc3d2.js} +1 -1
- package/dist/{chunk-j0rkfsdy.js → chunk-3p7c1dsk.js} +2 -2
- package/dist/{chunk-tc1001nx.js → chunk-4cvmfne8.js} +1 -1
- package/dist/{chunk-r2nzt9jm.js → chunk-4jbpvete.js} +2 -2
- package/dist/chunk-54qgtz5s.js +1 -0
- package/dist/{chunk-7mj87nb9.js → chunk-5rtjx9xk.js} +3 -3
- package/dist/{chunk-6wbhsgqd.js → chunk-61efg3yh.js} +2 -2
- package/dist/{chunk-ckqz2btx.js → chunk-74yge4ka.js} +1 -1
- package/dist/chunk-7b718dgf.js +1 -0
- package/dist/{chunk-45a1tsk1.js → chunk-7dqh8bqm.js} +1 -1
- package/dist/{chunk-zg73wrze.js → chunk-7jgj63tj.js} +1 -1
- package/dist/{chunk-xxk5d2v6.js → chunk-7k5v52ct.js} +1 -1
- package/dist/{chunk-pxah309m.js → chunk-7wf2acxx.js} +2 -2
- package/dist/chunk-82n941y8.js +1 -0
- package/dist/{chunk-f7p7tzx2.js → chunk-8eh0vp98.js} +2 -2
- package/dist/{chunk-rj49h1x1.js → chunk-9318pj5k.js} +1 -1
- package/dist/chunk-93rvs2hb.js +10 -0
- package/dist/{chunk-qn8jacbk.js → chunk-96pnk11m.js} +1 -1
- package/dist/{chunk-11ajd6hj.js → chunk-9h756tk9.js} +2 -2
- package/dist/chunk-9kfk68qj.js +1 -0
- package/dist/{chunk-rm8w0qg7.js → chunk-am66822r.js} +1 -1
- package/dist/chunk-b9bbyzk4.js +1 -0
- package/dist/chunk-d45gd36e.js +1 -0
- package/dist/chunk-d83bfr0b.js +2 -0
- package/dist/{chunk-8mee32xq.js → chunk-dd99sgf8.js} +1 -1
- package/dist/{chunk-27h9k89q.js → chunk-dwttn5xg.js} +1 -1
- package/dist/{chunk-mh92e9gy.js → chunk-epmxrw4f.js} +1 -1
- package/dist/{chunk-4vng4fc2.js → chunk-fkhtff66.js} +2 -2
- package/dist/chunk-fs8ra760.js +8 -0
- package/dist/{chunk-xrpmfq5d.js → chunk-fyms8zy1.js} +1 -1
- package/dist/{chunk-xhhgpbzs.js → chunk-gbsxnvgg.js} +1 -1
- package/dist/chunk-gf2vdsx3.js +1 -0
- package/dist/chunk-gynpj5sv.js +1 -0
- package/dist/{chunk-hkh2nsam.js → chunk-h4j0nve8.js} +2 -2
- package/dist/{chunk-50zkdamf.js → chunk-hn1xztva.js} +2 -2
- package/dist/{chunk-33g68zy1.js → chunk-hrfh7wck.js} +1 -1
- package/dist/chunk-jaegtaq3.js +1 -0
- package/dist/{chunk-x4zy3sez.js → chunk-m4tpqesg.js} +288 -288
- package/dist/{chunk-7r2p609r.js → chunk-mmd1hx8c.js} +1 -1
- package/dist/chunk-n23chvhe.js +1 -0
- package/dist/{chunk-7a8j14gg.js → chunk-n4gtzx4x.js} +1 -1
- package/dist/{chunk-1mb2y0e0.js → chunk-na1cney5.js} +2 -2
- package/dist/{chunk-m5hnyxf3.js → chunk-nh45xp7r.js} +1 -1
- package/dist/chunk-nht2hy5h.js +1 -0
- package/dist/{chunk-j6tp0ny9.js → chunk-ns5vb2p4.js} +2 -2
- package/dist/{chunk-1g5s5vf3.js → chunk-qa4efys0.js} +1 -1
- package/dist/{chunk-cwtj154q.js → chunk-qern9m2c.js} +1 -1
- package/dist/{chunk-hjkz6k6v.js → chunk-qr3w31ys.js} +1 -1
- package/dist/{chunk-q15sm6vj.js → chunk-rsh4rw9k.js} +1 -1
- package/dist/{chunk-vyk5nxsz.js → chunk-rxbxvq67.js} +2 -2
- package/dist/{chunk-bvp5wpz8.js → chunk-rzja9zza.js} +2 -2
- package/dist/{chunk-c0ecz59a.js → chunk-sbrj2czw.js} +1 -1
- package/dist/{chunk-47xjtzq5.js → chunk-scfwdpph.js} +1 -1
- package/dist/{chunk-ne5w9ds8.js → chunk-t48zm299.js} +1 -1
- package/dist/{chunk-ff38sxd0.js → chunk-t7nj9vg8.js} +2 -2
- package/dist/{chunk-yr16h4mj.js → chunk-tt3n8gnq.js} +2 -2
- package/dist/{chunk-vxa67kca.js → chunk-v7rnx21e.js} +3 -3
- package/dist/{chunk-anpph83s.js → chunk-va1exak5.js} +1 -1
- package/dist/chunk-vy4dz3yz.js +1 -0
- package/dist/{chunk-rxjyc6ff.js → chunk-w63dfcx5.js} +2 -2
- package/dist/{chunk-x079eg84.js → chunk-wbfa6xce.js} +2 -2
- package/dist/{chunk-k38mgpj8.js → chunk-wgd4ject.js} +1 -1
- package/dist/{chunk-sa259vbs.js → chunk-xby5w74x.js} +2 -2
- package/dist/{chunk-e6gfpm6b.js → chunk-xh4pgtj2.js} +1 -1
- package/dist/{chunk-7avnhnjn.js → chunk-ya5p7mx7.js} +1 -1
- package/dist/{chunk-d83meq4k.js → chunk-yjh47zv6.js} +1 -1
- package/dist/chunk-z2asrfm1.js +1 -0
- package/dist/{chunk-ebxt5bv1.js → chunk-z5rtzcm4.js} +2 -2
- package/dist/{chunk-q8jfwyr4.js → chunk-z6xfknxe.js} +1 -1
- package/dist/{chunk-3aejg2jy.js → chunk-zj4kfyer.js} +1 -1
- package/dist/{chunk-dm1knbf8.js → chunk-ztp2ff01.js} +2 -2
- package/dist/web/assets/ChatView-D-UBHYgT.js +58 -0
- package/dist/web/assets/{CodeBlockHighlighter-BR4c98oZ.js → CodeBlockHighlighter-CjP3le5E.js} +2 -2
- package/dist/web/assets/FilePreview-DRJTAYmL.js +54 -0
- package/dist/web/assets/KanbanBoard-CRu-0zva.js +16 -0
- package/dist/web/assets/{MarkdownRenderer-BVPIxk31.js → MarkdownRenderer-fbB4bMCw.js} +12 -12
- package/dist/web/assets/{SettingsModal-CuUrUdWR.js → SettingsModal-RAG8JMXx.js} +22 -2
- package/dist/web/assets/TaskSwitcher-DC-7RPBv.js +26 -0
- package/dist/web/assets/TerminalPanel-CCB3heKF.js +6 -0
- package/dist/web/assets/arrow-left-Dwndq437.js +6 -0
- package/dist/web/assets/calendar-clock-CNd8rd6n.js +6 -0
- package/dist/web/assets/chevrons-up-down-DGxAunkR.js +11 -0
- package/dist/web/assets/clock-3-BEqhPeh5.js +6 -0
- package/dist/web/assets/external-link-ClLpF7at.js +11 -0
- package/dist/web/assets/folder-B5LF32bS.js +11 -0
- package/dist/web/assets/index-BgdiwWDg.js +271 -0
- package/dist/web/assets/index-C8M-7zAh.css +1 -0
- package/dist/web/assets/pause-B39o8olb.js +6 -0
- package/dist/web/assets/play-Bmh7JaqQ.js +6 -0
- package/dist/web/assets/teamService-4Cn4uKC9.js +1 -0
- package/dist/web/index.html +2 -3
- package/package.json +1 -1
- package/dist/chunk-12e2yj9p.js +0 -2
- package/dist/chunk-1gnq2qz3.js +0 -1
- package/dist/chunk-3xpgkrnw.js +0 -1
- package/dist/chunk-7zjzykx2.js +0 -8
- package/dist/chunk-85s1nyaz.js +0 -1
- package/dist/chunk-8zvjcxze.js +0 -1
- package/dist/chunk-a1hvqk3r.js +0 -1
- package/dist/chunk-aj647rtw.js +0 -1
- package/dist/chunk-hj41cbd6.js +0 -1
- package/dist/chunk-kbgsbq7k.js +0 -1
- package/dist/chunk-kq9xrrhg.js +0 -1
- package/dist/chunk-nvakshbb.js +0 -1
- package/dist/chunk-qsxt9ejm.js +0 -1
- package/dist/chunk-s1xrzd14.js +0 -1
- package/dist/chunk-scdfsyfc.js +0 -10
- package/dist/chunk-tja1sejx.js +0 -1
- package/dist/chunk-vs5bmzj8.js +0 -1
- package/dist/web/assets/ChatView-juDcmnHV.js +0 -18
- package/dist/web/assets/FilePreview-DKgh-Chb.js +0 -8
- package/dist/web/assets/KanbanBoard-CQU0UQP8.js +0 -1
- package/dist/web/assets/TaskSwitcher-DB7by2ch.js +0 -1
- package/dist/web/assets/TerminalPanel-BN9ftZUH.js +0 -1
- package/dist/web/assets/index-BdnOTMNi.css +0 -1
- package/dist/web/assets/index-ebnhtfFC.js +0 -11
- package/dist/web/assets/teamService-CFKFv0qS.js +0 -1
- package/dist/web/assets/vendor-icons-CX5BfgqQ.js +0 -431
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
2
|
+
import{re as W}from"./chunk-0pnj92hk.js";import{ue as F,ve as M}from"./chunk-ztp2ff01.js";import"./chunk-61efg3yh.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-5rtjx9xk.js";import"./chunk-74yge4ka.js";import"./chunk-7wf2acxx.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import{Hh as N,Ih as B}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import{hi as T}from"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-hn1xztva.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import{Qi as J}from"./chunk-nh45xp7r.js";import p from"node:path";var E=process.argv.slice(2),I=c(E),u=I!==null;if(I!==null)T.setGlobalDebug(I);function c(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 m(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 t(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 l(){if(m(E)){let{getVersion:K}=await import("./chunk-b9bbyzk4.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=t(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-9kfk68qj.js");K(U.map((Z)=>p.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-d45gd36e.js");await K.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(K&&!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:K}=await import("./chunk-qr3w31ys.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-qern9m2c.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-7jgj63tj.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{browserCommands:S},{doctorCommands:k},{installCommands:O},{mcpCommands:y},{projectsCommands:V},{scheduleCommands:b},{serveCommand:P},{updateCommands:x},{webCommand:A}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-jaegtaq3.js"),import("./chunk-nht2hy5h.js"),import("./chunk-dwttn5xg.js"),import("./chunk-9h756tk9.js"),import("./chunk-va1exak5.js"),import("./chunk-xh4pgtj2.js"),import("./chunk-epmxrw4f.js"),import("./chunk-am66822r.js"),import("./chunk-82n941y8.js"),import("./chunk-mmd1hx8c.js"),import("./chunk-93rvs2hb.js")]),h=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(S).command(y).command(V).command(b).command(k).command(x).command(O).command(A).command(P).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),u&&Z.stack)console.error(`
|
|
3
3
|
Stack trace:`),console.error(Z.stack);else console.error(`
|
|
4
4
|
Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
|
|
5
|
-
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-
|
|
5
|
+
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-z2asrfm1.js").then(({checkVersionOnStartup:v})=>v()),[{render:w},{createElement:j},{AppWrapper:C}]=await Promise.all([import("ink"),import("react"),import("./chunk-37csc3d2.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:f};delete H._,delete H.$0,delete H.message,w(j(C,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await h.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)l().catch(console.error);export{l as main};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Hd as a,Id as b,Jd as c,Kd as d,Ld as e,Md as f,Nd as g}from"./chunk-t7nj9vg8.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import"./chunk-z6xfknxe.js";import"./chunk-rsh4rw9k.js";import"./chunk-74yge4ka.js";import"./chunk-d83bfr0b.js";import"./chunk-qa4efys0.js";import"./chunk-h4j0nve8.js";import"./chunk-n4gtzx4x.js";import"./chunk-hn1xztva.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Mh as E_,Nh as qf,Oh as gf,Ph as __,Qh as Wf,Sh as $f,Uh as If,Wh as q,Xh as Kf,Zh as Df,_h as Cf,ai as s}from"./chunk-hrfh7wck.js";import{ii as l}from"./chunk-h4j0nve8.js";import{mi as AE,oi as Xf}from"./chunk-w63dfcx5.js";import{ri as lE}from"./chunk-n4gtzx4x.js";var I_={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},hE=(f)=>I_[f]||{};var D_=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function Vf(f){return typeof f==="string"&&D_.has(f)}function XT(f){if(!f.aborted)return;if(Vf(f.reason))return f.reason;return"user-cancel"}function WT(f){if(Vf(f))return!0;if(!(f instanceof Error))return!1;if(f.name==="AbortError")return!0;if(f instanceof DOMException&&f.name==="AbortError")return!0;if(f.message.includes("aborted"))return!0;return!1}function xE(...f){let E=f.filter(Boolean);if(E.length===0)return new AbortController().signal;if(E.length===1)return E[0];let _=AbortSignal;if(typeof _.any==="function")return _.any(E);for(let x of E)if(x.aborted)return x;let T=new AbortController,h=new Map;for(let x of E){let S=()=>{T.abort(x.reason);for(let[A,t]of h)A.removeEventListener("abort",t)};h.set(x,S)}for(let[x,S]of h)x.addEventListener("abort",S,{once:!0});return T.signal}function ff(f,E,_){let T=_?.throwOnAbort??!1;if(E?.aborted){if(T)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((h,x)=>{let S,A=setTimeout(()=>{if(E&&S)E.removeEventListener("abort",S);h()},f);if(E)S=()=>{if(clearTimeout(A),T)x(new DOMException("Aborted","AbortError"));else h()},E.addEventListener("abort",S,{once:!0})})}var H_=l("Chat"),U_={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function jf(f){if(typeof f==="string")return f;return f.filter((E)=>E.type==="text").map((E)=>E.text).join(`
|
|
2
2
|
`)}function Y_(f){if(!f)return{};try{let E=JSON.parse(f);return E&&typeof E==="object"&&!Array.isArray(E)?E:{}}catch{return H_.warn("[PiAIChatService] Invalid historical tool arguments",{value:f}),{}}}function B_(f){let E=f.match(/^data:([^;,]+);base64,(.+)$/s);return E?{mimeType:E[1],data:E[2]}:void 0}async function b_(f,E){let _=B_(f);if(_)return{type:"image",..._};if(!/^https?:\/\//i.test(f))return{type:"text",text:`[Unsupported image source: ${f}]`};let T=await fetch(f,{signal:E});if(!T.ok)throw Error(`Failed to load image ${f}: HTTP ${T.status}`);return{type:"image",mimeType:T.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await T.arrayBuffer()).toString("base64")}}async function RE(f,E,_,T,h){let x=f.filter((t)=>t.role==="system").map((t)=>jf(t.content)).filter(Boolean).join(`
|
|
3
3
|
|
|
4
4
|
`),S=[];for(let t of f){if(t.role==="system")continue;if(t.role==="user"){let N=E.input.includes("image"),R=typeof t.content==="string"?t.content:await Promise.all(t.content.map((M)=>M.type==="text"?Promise.resolve({type:"text",text:M.text}):N?b_(M.image_url.url,T):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})));S.push({role:"user",content:R,timestamp:Date.now()});continue}if(t.role==="assistant"){let N=[];if(t.reasoningContent?.trim())N.push({type:"thinking",thinking:t.reasoningContent});let R=jf(t.content);if(R)N.push({type:"text",text:R});for(let M of t.tool_calls??[]){if(!("function"in M))continue;N.push({type:"toolCall",id:M.id,name:M.function.name,arguments:Y_(M.function.arguments)})}S.push({role:"assistant",content:N,api:E.api,provider:E.provider,model:E.id,usage:U_,stopReason:t.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}S.push({role:"toolResult",toolCallId:t.tool_call_id??"",toolName:t.name??"unknown",content:[{type:"text",text:jf(t.content)}],isError:!1,timestamp:Date.now()})}let A=_?.filter((t)=>!h||t.name===h).map((t)=>({name:t.name,description:t.description,parameters:t.parameters,constrainedSampling:t.constrainedSampling})).sort((t,N)=>t.name<N.name?-1:t.name>N.name?1:0);return{...x?{systemPrompt:x}:{},messages:S,...A?.length?{tools:A}:{}}}function ME(f){let E=[];for(let _=0;_<f.length;_++){let T=f[_];if(T.role==="tool")continue;let h=T.role==="assistant"&&T.tool_calls?.length?T.tool_calls:void 0;if(!h){E.push(T);continue}let x=[],S=_+1;while(S<f.length&&f[S].role==="tool")x.push(f[S++]);let A=new Set(h.map((R)=>R.id)),t=x.filter((R)=>R.tool_call_id&&A.has(R.tool_call_id)),N=new Set(t.map((R)=>R.tool_call_id));if(A.size===h.length&&t.length===A.size&&N.size===A.size)E.push(T,...t);_=S-1}return E}function PE(f){return f.some((E)=>E.role==="assistant"&&Boolean(E.tool_calls?.length)&&!E.reasoningContent?.trim())}function SE(f,E){return{...f,...E.baseUrl?{baseUrl:AE(f.api,E.baseUrl)}:{},...E.maxOutputTokens?{maxTokens:E.maxOutputTokens}:{}}}function zf(f){let E=f.modelCatalog??Xf();return{models:E.models,model:SE(E.getModel(f.provider,f.model),f)}}function NE(f,E){let _=f.modelCatalog??Xf();return SE(_.getModel(E.provider,E.model),f)}import{createHash as O_}from"node:crypto";var c_=32,V_=1000,j_=512,X_=2000,z_=0.1,J_=0.05,W_=0.9,$_=300000,k_=3600000;class Jf{sessions=new Map;observe(f){if(f.retention==="none"){this.sessions.delete(f.sessionId);return}let E=f.now??Date.now(),_=L_(f,E),T=this.sessions.get(f.sessionId);if(_.callCount=(T?.callCount??0)+1,this.touch(f.sessionId,_),T&&_.contextEpoch!==T.contextEpoch)return;if(!T||T.cacheReadTokens<V_)return;let h=T.cacheReadTokens-_.cacheReadTokens,x=Math.min(X_,Math.max(j_,T.cacheReadTokens*z_));if(h<x||_.cacheReadTokens>=T.cacheReadTokens*(1-J_))return;let S=_.modelIdentity!==T.modelIdentity,A=_.systemHash!==T.systemHash,t=_.toolsHash!==T.toolsHash,N=_.policyHash!==T.policyHash;if(!(S||A||t||N)&&_.promptTokens<T.promptTokens*W_)return;let M=Math.max(0,E-T.recordedAt),I=T.retention==="long"?k_:$_,Y=S?"model_changed":A?"system_prompt_changed":t?"tools_changed":N?"request_policy_changed":M>=I?"ttl_expired":"server_side",$=G_(T,_);return{reason:Y,previousCacheReadTokens:T.cacheReadTokens,cacheReadTokens:_.cacheReadTokens,cacheWriteTokens:Math.max(0,f.usage.cacheCreationInputTokens??0),tokenDrop:h,elapsedMs:M,callNumber:_.callCount,systemPromptChanged:A,systemCharDelta:_.systemChars-T.systemChars,toolsChanged:t,addedToolCount:$.added,removedToolCount:$.removed,changedToolCount:$.changed,modelChanged:S,requestPolicyChanged:N}}clear(f){if(f)this.sessions.delete(f);else this.sessions.clear()}statsForTests(){return{sessions:this.sessions.size}}touch(f,E){this.sessions.delete(f),this.sessions.set(f,E);while(this.sessions.size>c_){let _=this.sessions.keys().next().value;if(_===void 0)break;this.sessions.delete(_)}}}function L_(f,E){let _=[...f.tools??f.context.tools??[]].map((T)=>({identityHash:Ef(T.name),contractHash:Ef(_f(T))})).sort((T,h)=>T.identityHash<h.identityHash?-1:T.identityHash>h.identityHash?1:0);return{modelIdentity:f.modelIdentity,systemHash:Ef(f.context.systemPrompt??""),systemChars:f.context.systemPrompt?.length??0,toolsHash:Ef(_f(_)),toolFingerprints:_,policyHash:Ef(_f(f.policy)),contextEpoch:f.contextEpoch??"",retention:f.retention,promptTokens:Number.isFinite(f.usage.promptTokens)?Math.max(0,f.usage.promptTokens):0,cacheReadTokens:Math.max(0,f.usage.cacheReadInputTokens??0),recordedAt:E,callCount:1}}function G_(f,E){let _=new Map(f.toolFingerprints.map((h)=>[h.identityHash,h.contractHash])),T=new Map(E.toolFingerprints.map((h)=>[h.identityHash,h.contractHash]));return{added:[...T.keys()].filter((h)=>!_.has(h)).length,removed:[..._.keys()].filter((h)=>!T.has(h)).length,changed:[...T].filter(([h,x])=>_.has(h)&&_.get(h)!==x).length}}function _f(f){if(f===null||typeof f!=="object")return JSON.stringify(f)??"undefined";if(Array.isArray(f))return`[${f.map(_f).join(",")}]`;let E=f;return`{${Object.keys(E).sort().map((_)=>`${JSON.stringify(_)}:${_f(E[_])}`).join(",")}}`}function Ef(f){return O_("sha256").update(f).digest("hex")}import{randomBytes as C_}from"node:crypto";import{createHmac as Z_}from"node:crypto";function Q_(f){try{let E=new URL(f);if(E.hash="",E.hostname=E.hostname.toLowerCase(),E.searchParams.sort(),E.pathname!=="/")E.pathname=E.pathname.replace(/\/+$/,"");return E.toString()}catch{return f.trim().replace(/\/+$/,"")}}function K_(f){if(!f)return[];return Object.entries(f).map(([E,_])=>[E.trim().toLowerCase(),_.trim()]).sort(([E],[_])=>E.localeCompare(_))}function Sf(f,E,_){let T=JSON.stringify([f.provider.trim(),String(f.api).trim(),Q_(f.baseUrl),f.model.trim(),f.serviceTier?.trim()??"",f.apiVersion?.trim()??"",f.apiKey??"",K_(f.customHeaders),_]);return Z_("sha256",Buffer.from(E)).update(T).digest("hex")}var F_=60000,o_=4,s_=0.8;var uf=300000,kf=600000;var uE=128,IE=256,v_=1800000,Nf=50;class hf extends Error{circuit;code="PROVIDER_CIRCUIT_OPEN";constructor(f){super(`Provider circuit open; retry after ${f.retryAfterMs??0}ms`);this.circuit=f;this.name="ProviderCircuitOpenError"}}function Lf(f){return f instanceof hf||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_CIRCUIT_OPEN"}function a(f,E){return f!==void 0&&Number.isSafeInteger(f)&&f>0?f:E}function w_(f,E){return f!==void 0&&Number.isFinite(f)&&f>0&&f<=1?f:E}function p_(f,E){return Sf(f,E,{providerCircuitOpenDurationMs:f.openDurationMs})}function Tf(f){let E=0;for(let _ of f)if(_.failure)E++;return E}function DE(f){return f!==void 0&&Number.isInteger(f)&&f>=100&&f<=599?f:void 0}function HE(f){if(f===void 0||!Number.isFinite(f)||f<0)return;return Math.min(Math.ceil(f),$f)}class YE{#x=new Map;#t=new WeakMap;#f;#_;#h;#T;constructor(f={}){this.#f=f.processSecret?new Uint8Array(f.processSecret):C_(32),this.#_=f.now??(()=>performance.now()),this.#h=f.wallNow??f.now??Date.now,this.#T={maxEntries:Math.min(a(f.maxEntries,uE),uE),maxWindowEntries:Math.min(a(f.maxWindowEntries,IE),IE),windowMs:a(f.windowMs,F_),minSamples:a(f.minSamples,o_),errorRateThreshold:w_(f.errorRateThreshold,s_),idleTtlMs:a(f.idleTtlMs,v_)}}get size(){return this.#x.size}get(f){if(f.openDurationMs===0)return this.#M();let E=this.#_();this.#B(E);let _=p_(f,this.#f),T=this.#x.get(_);if(T)return T.lastTouchedAt=E,this.#E(T,f.probeLeaseMs);if(this.#x.size>=this.#T.maxEntries)this.#D();if(this.#x.size>=this.#T.maxEntries)return this.#M();let h={key:_,state:"closed",samples:[],generation:0,nextAttemptId:1,nextProbeLeaseId:1,configuredOpenDurationMs:f.openDurationMs,effectiveOpenDurationMs:f.openDurationMs,lastTouchedAt:E,detached:!1};return this.#x.set(_,h),this.#E(h,f.probeLeaseMs)}#E(f,E){let _=this,T=Math.max(uf,Math.min(a(E,uf),kf));return{preflight:()=>_.#P(f),check:()=>_.#b(f,T),recordSuccess:(h)=>_.#R(h,"success"),recordFailure:(h,x)=>_.#R(h,"failure",x),recordNeutral:(h)=>_.#R(h,"neutral"),abandon:(h)=>_.#N(h),snapshot:()=>_.#j(f)}}#M(){let f=this;return{preflight:()=>({eligible:!0}),check:()=>{let E=Object.freeze({kind:"noop"});return f.#t.set(E,{generation:0,attemptId:0,kind:"noop",settled:!1}),{allowed:!0,probe:!1,token:E}},recordSuccess:(E)=>f.#S(E),recordFailure:(E)=>f.#S(E),recordNeutral:(E)=>f.#S(E),abandon:(E)=>f.#N(E),snapshot:()=>({state:"closed",sampleCount:0,failureCount:0,noop:!0,detached:!1})}}#S(f){let E=this.#t.get(f);if(E?.kind==="noop")E.settled=!0;return}#P(f){let E=this.#_();if(f.detached)return{eligible:!0};if(f.lastTouchedAt=E,this.#u(f,E),f.state==="closed")return{eligible:!0};if(f.state==="open"){let T=f.nextProbeAt??E;return E<T?this.#U(f,T-E):{eligible:!0}}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&E>=f.probeLeaseExpiresAt)return{eligible:!0};let _=Math.max(1,(f.probeLeaseExpiresAt??E+Nf)-E);return this.#U(f,Math.min(Nf,_))}#U(f,E){let{allowed:_,...T}=this.#A(f,E);return{eligible:!1,...T}}#b(f,E){let _=this.#_();if(f.detached)return this.#M().check();if(f.lastTouchedAt=_,this.#u(f,_),f.state==="closed")return this.#Y(f,"regular");if(f.state==="open"){let h=f.nextProbeAt??_;if(_<h)return this.#A(f,h-_);f.state="half_open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&_>=f.probeLeaseExpiresAt)return this.#O(f,_,E);let T=Math.max(1,(f.probeLeaseExpiresAt??_+Nf)-_);return this.#A(f,Math.min(Nf,T))}#Y(f,E,_){let T=Object.freeze({kind:E});return this.#t.set(T,{entry:f,generation:f.generation,attemptId:f.nextAttemptId++,kind:E,..._!==void 0?{probeLeaseId:_}:{},settled:!1}),{allowed:!0,probe:E==="probe",token:T}}#O(f,E,_){let T=f.nextProbeLeaseId++;f.probeLeaseId=T,f.probeLeaseExpiresAt=E+_,f.lastTouchedAt=E;let h=this.#Y(f,"probe",T),x=f.lastFailure??{reason:"server_error"};return{...h,reason:x.reason,...x.statusCode!==void 0?{statusCode:x.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:Tf(f.samples)}}#A(f,E){let _=f.lastFailure??{reason:"server_error"};return{allowed:!1,state:f.state==="open"?"open":"half_open",reason:_.reason,..._.statusCode!==void 0?{statusCode:_.statusCode}:{},retryAfterMs:Math.max(0,Math.ceil(E)),nextProbeAt:this.#h()+Math.max(0,Math.ceil(E)),openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:Tf(f.samples)}}#R(f,E,_){let T=this.#t.get(f);if(!T||T.settled)return;if(T.settled=!0,T.kind==="noop"||!T.entry)return;let h=T.entry;if(h.detached||T.generation!==h.generation||T.kind==="regular"&&h.state!=="closed"||T.kind==="probe"&&(h.state!=="half_open"||T.probeLeaseId!==h.probeLeaseId))return;let x=this.#_();if(h.lastTouchedAt=x,T.kind==="probe"){if(E==="failure"&&_)return this.#I(h,_,x,"reopened");return this.#c(h)}if(E==="neutral")return;if(this.#V(h,E==="failure",x),E!=="failure"||!_)return;let S=Tf(h.samples),A=h.samples.length===0?0:S/h.samples.length;if(h.samples.length>=this.#T.minSamples&&A>=this.#T.errorRateThreshold)return this.#I(h,_,x,"opened");return}#I(f,E,_,T){let h={reason:E.reason,...DE(E.statusCode)!==void 0?{statusCode:DE(E.statusCode)}:{},...HE(E.retryAfterMs)!==void 0?{retryAfterMs:HE(E.retryAfterMs)}:{}},x=h.retryAfterMs??0,S=Math.max(f.configuredOpenDurationMs,x);return f.state="open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.effectiveOpenDurationMs=S,f.nextProbeAt=_+S,f.lastFailure=h,{phase:T,reason:h.reason,...h.statusCode!==void 0?{statusCode:h.statusCode}:{},retryAfterMs:S,nextProbeAt:this.#h()+S,openDurationMs:S,sampleCount:f.samples.length,failureCount:Tf(f.samples)}}#c(f){let E=f.lastFailure??{reason:"server_error"};return f.state="closed",f.generation++,f.samples=[],f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.nextProbeAt=void 0,f.effectiveOpenDurationMs=f.configuredOpenDurationMs,{phase:"closed",reason:E.reason,...E.statusCode!==void 0?{statusCode:E.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:0,failureCount:0}}#N(f){let E=this.#t.get(f);if(!E||E.settled)return!1;if(E.settled=!0,E.kind==="noop")return!0;let _=E.entry;if(!_||_.detached||E.kind!=="probe"||E.generation!==_.generation||E.probeLeaseId!==_.probeLeaseId)return!1;return _.probeLeaseId=void 0,_.probeLeaseExpiresAt=void 0,_.lastTouchedAt=this.#_(),!0}#V(f,E,_){if(this.#u(f,_),f.samples.length>=this.#T.maxWindowEntries)f.samples.shift();f.samples.push({at:_,failure:E})}#u(f,E){let _=E-this.#T.windowMs,T=0;while(T<f.samples.length&&f.samples[T].at<_)T++;if(T>0)f.samples.splice(0,T)}#j(f){if(!f.detached)this.#u(f,this.#_());return{state:f.state,sampleCount:f.samples.length,failureCount:Tf(f.samples),...f.nextProbeAt!==void 0?{nextProbeAt:f.nextProbeAt}:{},noop:!1,detached:f.detached}}#B(f){for(let[E,_]of this.#x)if(_.state==="closed"&&f-_.lastTouchedAt>this.#T.idleTtlMs)this.#H(E,_)}#D(){let f;for(let E of this.#x.values())if(E.state==="closed"&&(!f||E.lastTouchedAt<f.lastTouchedAt))f=E;if(f)this.#H(f.key,f)}#H(f,E){E.detached=!0,this.#x.delete(f)}}var UE;function BE(){return UE??=new YE,UE}import{randomBytes as m_}from"node:crypto";var q_=16,bE=128,OE=32,g_=3,cE=16,VE=96,jE=24,XE=12,zE=16,JE=4,WE=4,$E=67108864,kE=33554432,l_=12,a_=2,LE=2,GE=1,FE=15000,ZE=30000;function Gf(){return{foreground:0,background:0,internal:0}}function Zf(){return{inFlight:Gf(),queued:Gf(),pendingBytes:Gf()}}function U(f){return f.foreground+f.background+f.internal}function W(f){return f.background+f.internal}function QE(f){return f.inFlight.foreground===0&&f.inFlight.background===0&&f.inFlight.internal===0&&f.queued.foreground===0&&f.queued.background===0&&f.queued.internal===0&&f.pendingBytes.foreground===0&&f.pendingBytes.background===0&&f.pendingBytes.internal===0}class xf extends Error{reason;scope;requestClass;resource;inFlight;limit;queued;maxWaitMs;code="PROVIDER_ADMISSION_BUSY";retryable;constructor(f,E,_,T,h,x,S,A){super(f==="queue_full"?`Provider request admission ${E} ${T} queue is full`:f==="wait_timeout"?`Provider request admission timed out waiting for ${E} capacity`:"Provider request admission scheduler is closed");this.reason=f;this.scope=E;this.requestClass=_;this.resource=T;this.inFlight=h;this.limit=x;this.queued=S;this.maxWaitMs=A;this.name="ProviderAdmissionError",this.retryable=f!=="closed"}}function tf(f){return f instanceof xf||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_ADMISSION_BUSY"}function z(f,E,_){if(f===void 0||!Number.isSafeInteger(f)||f<=0)return E;return Math.min(f,_)}function y_(f){let E=z(f.globalMaxInFlight,q_,Number.MAX_SAFE_INTEGER),_=z(f.globalMaxPending,bE,bE),T=z(f.domainMaxPending,OE,OE),h=Math.min(z(f.ownerMaxInFlight,g_,Number.MAX_SAFE_INTEGER),E),x=Math.min(z(f.ownerMaxPending,cE,cE),_),S=Math.min(z(f.nonForegroundGlobalMaxPending,Math.min(VE,Math.max(1,Math.floor(_*3/4))),VE),_),A=Math.min(z(f.nonForegroundDomainMaxPending,Math.min(jE,Math.max(1,Math.floor(T*3/4))),jE),T),t=Math.min(z(f.nonForegroundOwnerMaxPending,Math.min(XE,Math.max(1,Math.floor(x*3/4))),XE),x),N=Math.min(z(f.internalGlobalMaxPending,Math.min(zE,Math.max(1,Math.floor(_/8))),zE),S),R=Math.min(z(f.internalDomainMaxPending,Math.min(JE,Math.max(1,Math.floor(T/8))),JE),A),M=Math.min(z(f.internalOwnerMaxPending,Math.min(WE,Math.max(1,Math.floor(x/4))),WE),t),I=z(f.globalMaxPendingBytes,s,s),Y=Math.min(z(f.domainMaxPendingBytes,$E,$E),I),$=Math.min(z(f.ownerMaxPendingBytes,kE,kE),I),Q=Math.min(z(f.nonForegroundGlobalMaxInFlight,Math.min(l_,E),E),E),K=Math.min(z(f.nonForegroundOwnerMaxInFlight,Math.min(a_,h),h),h),o=Math.min(z(f.internalGlobalMaxInFlight,Math.min(LE,E),LE),E),Uf=z(f.internalDomainMaxInFlight,GE,GE),Rf=z(f.agingMs,ZE,ZE);return{globalMaxInFlight:E,globalMaxPending:_,domainMaxPending:T,ownerMaxInFlight:h,ownerMaxPending:x,nonForegroundGlobalMaxPending:S,nonForegroundDomainMaxPending:A,nonForegroundOwnerMaxPending:t,internalGlobalMaxPending:N,internalDomainMaxPending:R,internalOwnerMaxPending:M,globalMaxPendingBytes:I,domainMaxPendingBytes:Y,ownerMaxPendingBytes:$,nonForegroundGlobalMaxInFlight:Q,nonForegroundOwnerMaxInFlight:K,internalGlobalMaxInFlight:o,internalDomainMaxInFlight:Uf,agingMs:Rf,classLimitsEnabled:f.classLimitsEnabled!==!1}}function KE(f,E){if(!f.trim())throw Error(`${E} must not be blank`)}function e_(f){if(KE(f.sessionId,"sessionId"),KE(f.ownerId,"ownerId"),!Number.isSafeInteger(f.scope.maxConcurrent)||f.scope.maxConcurrent<If||f.scope.maxConcurrent>q)throw Error(`maxConcurrent must be between ${If} and ${q}`);if(!Number.isSafeInteger(f.scope.maxPendingBytes)||f.scope.maxPendingBytes<=0||f.scope.maxPendingBytes>s)throw Error(`maxPendingBytes must be between 1 and ${s}`);if(!Number.isSafeInteger(f.pendingBytes)||f.pendingBytes<=0||f.pendingBytes>s+1)throw Error(`pendingBytes must be between 1 and ${s+1}`);if(!Number.isSafeInteger(f.maxWaitMs)||f.maxWaitMs<0||f.maxWaitMs>Df)throw Error(`maxWaitMs must be 0-${Df}`)}function Qf(f,E){if(E!==void 0)return E;if(f?.reason!==void 0)return f.reason;return new DOMException("Provider request admission cancelled","AbortError")}function d_(f,E){return Sf(f,E,{providerRequestConcurrency:f.maxConcurrent,providerRequestPendingBytes:f.maxPendingBytes})}class oE{#x;#t;#f;#_=[];#h=new Map;#T=new Map;#E=Zf();#M=1;#S=0;#P=!1;constructor(f={}){this.#x=f.processSecret?new Uint8Array(f.processSecret):m_(32),this.#t=f.now??(()=>performance.now()),this.#f=y_(f)}admit(f){if(e_(f),this.#P)throw this.#X("closed",f,{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight},this.#_.length);if(f.signal?.aborted)throw Qf(f.signal);let E=d_(f.scope,this.#x),_=this.#h.get(E),T=this.#T.get(f.ownerId),h=_??this.#Y(f.scope.maxConcurrent),x=T??this.#O();if(this.#_.length===0&&this.#A(h,x,f.requestClass)){if(!_)this.#h.set(E,h);if(!T)this.#T.set(f.ownerId,x),this.#M++;let I=this.#I(E,f.ownerId,f.requestClass),Y=this.#k(f,0);return{ready:Promise.resolve(I),getSnapshot:()=>({...Y}),cancel:()=>{Y={...Y}}}}let S=this.#U(f,h,x);if(S)throw this.#X("queue_full",f,S,this.#_.length);let A=this.#R(h,x,f.requestClass);if(f.maxWaitMs===0)throw this.#X("wait_timeout",f,A,this.#_.length);if(!_)this.#h.set(E,h);if(!T)this.#T.set(f.ownerId,x),this.#M++;let t,N,R=new Promise((I,Y)=>{t=I,N=Y});R.catch(()=>{return});let M={domainKey:E,sessionId:f.sessionId,ownerId:f.ownerId,requestClass:f.requestClass,maxWaitMs:f.maxWaitMs,pendingBytes:f.pendingBytes,enqueuedAt:this.#t(),signal:f.signal,resolve:t,reject:N,settled:!1,admitted:!1};if(f.signal)M.abortListener=()=>this.#B(M,Qf(f.signal)),f.signal.addEventListener("abort",M.abortListener,{once:!0});return M.timer=setTimeout(()=>this.#j(M),f.maxWaitMs),M.timer.unref?.(),this.#_.push(M),this.#b(h,x,M),this.#N(),{ready:R,getSnapshot:()=>this.#$(M),cancel:(I)=>this.#B(M,Qf(f.signal,I))}}close(){if(this.#P)return;this.#P=!0;for(let f of[...this.#_]){let E=this.#h.get(f.domainKey),_=this.#T.get(f.ownerId),T=E&&_?this.#R(E,_,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};this.#D(f,new xf("closed",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}}getStats(){return{inFlight:U(this.#E.inFlight),queued:this.#_.length,pendingBytes:U(this.#E.pendingBytes),nonForegroundInFlight:W(this.#E.inFlight),internalInFlight:this.#E.inFlight.internal,nonForegroundQueued:W(this.#E.queued),internalQueued:this.#E.queued.internal,nonForegroundPendingBytes:W(this.#E.pendingBytes),internalPendingBytes:this.#E.pendingBytes.internal,domainCount:this.#h.size,ownerCount:this.#T.size,closed:this.#P}}#U(f,E,_){let T=(R,M,I)=>M>=I?{scope:R,resource:"pending_count",inFlight:M,limit:I}:void 0;if(this.#f.classLimitsEnabled&&f.requestClass==="internal"){let R=T("class",this.#E.queued.internal,this.#f.internalGlobalMaxPending)??T("class",_.counters.queued.internal,this.#f.internalOwnerMaxPending)??T("class",E.counters.queued.internal,this.#f.internalDomainMaxPending);if(R)return R}if(this.#f.classLimitsEnabled&&f.requestClass!=="foreground"){let R=T("class",W(this.#E.queued),this.#f.nonForegroundGlobalMaxPending)??T("class",W(_.counters.queued),this.#f.nonForegroundOwnerMaxPending)??T("class",W(E.counters.queued),this.#f.nonForegroundDomainMaxPending);if(R)return R}let h=T("global",this.#_.length,this.#f.globalMaxPending)??T("owner",U(_.counters.queued),this.#f.ownerMaxPending)??T("domain",U(E.counters.queued),this.#f.domainMaxPending);if(h)return h;let x=Math.min(f.scope.maxPendingBytes,this.#f.globalMaxPendingBytes),S=Math.min(x,this.#f.domainMaxPendingBytes),A=Math.min(x,this.#f.ownerMaxPendingBytes),t=(R,M)=>f.pendingBytes>M-R,N=(R)=>{if(R==="owner")return{scope:R,resource:"pending_bytes",inFlight:U(_.counters.inFlight),limit:this.#f.ownerMaxInFlight};if(R==="domain")return{scope:R,resource:"pending_bytes",inFlight:U(E.counters.inFlight),limit:E.maxConcurrent};return{scope:R,resource:"pending_bytes",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight}};if(f.requestClass==="internal"){let R=Math.max(1,Math.floor(x/8)),M=Math.max(1,Math.floor(S/4)),I=Math.max(1,Math.floor(A/4));if(t(this.#E.pendingBytes.internal,R)||t(_.counters.pendingBytes.internal,I)||t(E.counters.pendingBytes.internal,M))return N("class")}if(f.requestClass!=="foreground"){let R=Math.max(1,Math.floor(x*3/4)),M=Math.max(1,Math.floor(S*3/4)),I=Math.max(1,Math.floor(A/2));if(t(W(this.#E.pendingBytes),R)||t(W(_.counters.pendingBytes),I)||t(W(E.counters.pendingBytes),M))return N("class")}if(t(U(this.#E.pendingBytes),x))return N("global");if(t(U(_.counters.pendingBytes),A))return N("owner");if(t(U(E.counters.pendingBytes),S))return N("domain");return}#b(f,E,_){let{requestClass:T,pendingBytes:h}=_;this.#E.queued[T]++,f.counters.queued[T]++,E.counters.queued[T]++,this.#E.pendingBytes[T]+=h,f.counters.pendingBytes[T]+=h,E.counters.pendingBytes[T]+=h}#Y(f){return{maxConcurrent:f,counters:Zf()}}#O(){return{order:this.#M,counters:Zf()}}#A(f,E,_){if(U(this.#E.inFlight)>=this.#f.globalMaxInFlight)return!1;if(U(f.counters.inFlight)>=f.maxConcurrent)return!1;if(U(E.counters.inFlight)>=this.#f.ownerMaxInFlight)return!1;if(_==="foreground"||!this.#f.classLimitsEnabled)return!0;if(W(this.#E.inFlight)>=this.#f.nonForegroundGlobalMaxInFlight)return!1;if(W(E.counters.inFlight)>=this.#f.nonForegroundOwnerMaxInFlight)return!1;let T=Math.max(1,f.maxConcurrent-1);if(W(f.counters.inFlight)>=T)return!1;if(_!=="internal")return!0;return this.#E.inFlight.internal<this.#f.internalGlobalMaxInFlight&&f.counters.inFlight.internal<this.#f.internalDomainMaxInFlight}#R(f,E,_){if(U(E.counters.inFlight)>=this.#f.ownerMaxInFlight)return{scope:"owner",resource:"stream",inFlight:U(E.counters.inFlight),limit:this.#f.ownerMaxInFlight};if(this.#f.classLimitsEnabled&&_!=="foreground"&&W(E.counters.inFlight)>=this.#f.nonForegroundOwnerMaxInFlight)return{scope:"class",resource:"stream",inFlight:W(E.counters.inFlight),limit:this.#f.nonForegroundOwnerMaxInFlight};if(U(f.counters.inFlight)>=f.maxConcurrent)return{scope:"domain",resource:"stream",inFlight:U(f.counters.inFlight),limit:f.maxConcurrent};if(this.#f.classLimitsEnabled&&_!=="foreground"){let T=Math.max(1,f.maxConcurrent-1);if(W(f.counters.inFlight)>=T)return{scope:"class",resource:"stream",inFlight:W(f.counters.inFlight),limit:T}}if(this.#f.classLimitsEnabled&&_==="internal"&&f.counters.inFlight.internal>=this.#f.internalDomainMaxInFlight)return{scope:"class",resource:"stream",inFlight:f.counters.inFlight.internal,limit:this.#f.internalDomainMaxInFlight};if(U(this.#E.inFlight)>=this.#f.globalMaxInFlight)return{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};if(this.#f.classLimitsEnabled&&_!=="foreground"&&W(this.#E.inFlight)>=this.#f.nonForegroundGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:W(this.#E.inFlight),limit:this.#f.nonForegroundGlobalMaxInFlight};if(this.#f.classLimitsEnabled&&_==="internal"&&this.#E.inFlight.internal>=this.#f.internalGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#E.inFlight.internal,limit:this.#f.internalGlobalMaxInFlight};return{scope:"domain",resource:"stream",inFlight:U(f.counters.inFlight),limit:f.maxConcurrent}}#I(f,E,_){let T=this.#h.get(f),h=this.#T.get(E);if(!T||!h)throw Error("Provider admission accounting state is unavailable");this.#E.inFlight[_]++,T.counters.inFlight[_]++,h.counters.inFlight[_]++;let x=!1;return{release:()=>{if(x)return;x=!0,this.#c(f,E,_)}}}#c(f,E,_){let T=this.#h.get(f),h=this.#T.get(E);if(this.#E.inFlight[_]--,T)T.counters.inFlight[_]--;if(h)h.counters.inFlight[_]--;this.#z(f,E),this.#N()}#N(){if(this.#P)return;while(this.#_.length>0){let f=this.#t(),E=new Map;for(let[A,t]of this.#_.entries()){let N=this.#h.get(t.domainKey),R=this.#T.get(t.ownerId);if(N===void 0||R===void 0||!this.#A(N,R,t.requestClass))continue;let M=this.#V(t,f),I=E.get(t.ownerId);if(!I||M<I.rank||M===I.rank&&A<I.index)E.set(t.ownerId,{pending:t,rank:M,index:A})}let _=[...E.values()].filter(({pending:A})=>{let t=this.#h.get(A.domainKey),N=this.#T.get(A.ownerId);return t!==void 0&&N!==void 0&&this.#A(t,N,A.requestClass)}).map(({pending:A,rank:t})=>({pending:A,rank:t,order:this.#T.get(A.ownerId).order}));if(_.length===0)return;let T=Math.min(..._.map((A)=>A.rank)),h=_.filter((A)=>A.rank===T),S=h.filter((A)=>A.order>this.#S).sort((A,t)=>A.order-t.order)[0]??h.sort((A,t)=>A.order-t.order)[0];this.#u(S.pending,S.order)}}#V(f,E){let _=f.requestClass==="foreground"?0:f.requestClass==="background"?1:2,T=Math.floor(Math.max(0,E-f.enqueuedAt)/this.#f.agingMs);return Math.max(0,_-T)}#u(f,E){if(!this.#H(f,!1))return;f.settled=!0,f.admitted=!0,this.#S=E;let _=this.#I(f.domainKey,f.ownerId,f.requestClass);f.permit=_,f.resolve(_)}#j(f){let E=this.#h.get(f.domainKey),_=this.#T.get(f.ownerId),T=E&&_?this.#R(E,_,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};this.#D(f,new xf("wait_timeout",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}#B(f,E){this.#D(f,E)}#D(f,E){if(!this.#H(f))return;f.settled=!0,f.reject(E),this.#N()}#H(f,E=!0){if(f.settled||f.admitted)return!1;let _=this.#_.indexOf(f);if(_<0)return!1;this.#_.splice(_,1);let T=this.#h.get(f.domainKey),h=this.#T.get(f.ownerId);if(T&&h)this.#J(T,h,f);if(this.#W(f),E)this.#z(f.domainKey,f.ownerId);return!0}#J(f,E,_){let{requestClass:T,pendingBytes:h}=_;this.#E.queued[T]--,f.counters.queued[T]--,E.counters.queued[T]--,this.#E.pendingBytes[T]-=h,f.counters.pendingBytes[T]-=h,E.counters.pendingBytes[T]-=h}#W(f){if(f.timer)clearTimeout(f.timer);if(f.timer=void 0,f.signal&&f.abortListener)f.signal.removeEventListener("abort",f.abortListener);f.abortListener=void 0,f.signal=void 0}#z(f,E){let _=this.#h.get(f);if(_&&QE(_.counters))this.#h.delete(f);let T=this.#T.get(E);if(T&&QE(T.counters))this.#T.delete(E)}#$(f){let E=Math.max(0,Math.floor(this.#t()-f.enqueuedAt));if(f.admitted)return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight,waitMs:E,maxWaitMs:f.maxWaitMs};let _=this.#h.get(f.domainKey),T=this.#T.get(f.ownerId),h=_&&T?this.#R(_,T,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};return{state:"queued",requestClass:f.requestClass,resource:h.resource,scope:h.scope,reason:"capacity",queuePosition:this.#L(f,h.scope),queueDepth:this.#_.length,inFlight:h.inFlight,limit:h.limit,waitMs:E,maxWaitMs:f.maxWaitMs}}#k(f,E){return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight,waitMs:E,maxWaitMs:f.maxWaitMs}}#L(f,E){let _=this.#_.filter((T)=>{switch(E){case"owner":return T.ownerId===f.ownerId;case"domain":return T.domainKey===f.domainKey;case"class":return T.requestClass===f.requestClass;case"global":return!0}});return Math.max(1,_.indexOf(f)+1)}#X(f,E,_,T){return new xf(f,_.scope,E.requestClass,_.resource,_.inFlight,_.limit,T,E.maxWaitMs)}}var CE;function sE(f={}){return CE??=new oE(f),CE}function vE(f,E={}){let _=E.maxBytes??134217728,T=E.maxNodes??1e5;if(!Number.isSafeInteger(_)||_<=0||_>=Number.MAX_SAFE_INTEGER)throw Error("maxBytes must be a positive safe integer");if(!Number.isSafeInteger(T)||T<=0)throw Error("maxNodes must be a positive safe integer");let h=new WeakSet,x=0,S=0,A=!1,t=(R)=>{if(A||R<=0)return;if(!Number.isSafeInteger(R)||R>_-x){x=_+1,A=!0;return}x+=R},N=(R)=>{if(A)return;if(S+=1,S>T){t(_+1);return}if(R===null){t(4);return}switch(typeof R){case"string":t(Buffer.byteLength(R,"utf8"));return;case"number":case"bigint":t(8);return;case"boolean":t(4);return;case"undefined":case"function":case"symbol":return;case"object":break}if(h.has(R))return;if(h.add(R),ArrayBuffer.isView(R)){t(32+R.byteLength);return}if(R instanceof ArrayBuffer){t(32+R.byteLength);return}if(R instanceof Date){t(40);return}if(R instanceof RegExp){t(32+Buffer.byteLength(R.source,"utf8"));return}if(R instanceof Map){t(32);for(let[M,I]of R)if(N(M),N(I),A)return;return}if(R instanceof Set){t(32);for(let M of R)if(N(M),A)return;return}if(R instanceof WeakMap||R instanceof WeakSet){t(32);return}if(Array.isArray(R)){t(16);for(let M of R)if(N(M),A)return;return}t(32);for(let M of Reflect.ownKeys(R)){if(typeof M!=="string")continue;let I=Object.getOwnPropertyDescriptor(R,M);if(!I?.enumerable||!("value"in I))continue;if(t(8+Buffer.byteLength(M,"utf8")),N(I.value),A)return}};return N(f),x}function wE(f){return vE([f.messages,f.context,f.tools,f.requestOptions],{maxBytes:s})}var pE=new WeakSet;class y extends Error{budgetMs;elapsedMs;code="PROVIDER_RECOVERY_BUDGET_EXCEEDED";constructor(f,E){super(`Provider recovery budget exhausted after ${f}ms`);this.budgetMs=f;this.elapsedMs=E;this.name="ProviderRecoveryBudgetExceededError"}}class Ff extends Error{timeoutMs;code="PROVIDER_REQUEST_DEADLINE_EXCEEDED";constructor(f){super(`Provider request deadline exceeded after ${f}ms`);this.timeoutMs=f;this.name="ProviderRequestDeadlineExceededError"}}var n_=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],r_=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],i_=["econnreset","econnrefused","enotfound","eai_again","etimedout","fetch failed","network error","connection error","connection refused","connection lost","other side closed","socket hang up","socket connection was closed","upstream connect","reset before headers","websocket closed","websocket error","http2 request did not get a response"];function mE(f){return(f instanceof Error?f.message:String(f)).toLowerCase()}function fT(f){let E=mE(f);return r_.some((_)=>E.includes(_))}function of(f){if(f!==null&&typeof f==="object")pE.add(f)}function Rh(f){return f!==null&&typeof f==="object"&&pE.has(f)}function ET(f){return f!==null&&typeof f==="object"&&"code"in f?f.code:void 0}function _T(f){if(f===null||typeof f!=="object")return;let E=f;for(let _ of["status","statusCode"]){let T=E[_];if(typeof T==="number"&&Number.isInteger(T))return T}return}function TT(f){let E=f.match(/^(?:error:\s*)?(\d{3})\b/),_=f.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),T=Number(E?.[1]??_?.[1]);return Number.isInteger(T)?T:void 0}function e(f,E){let _=mE(f),T=ET(f);if(T==="STREAM_IDLE_TIMEOUT"||T==="PROVIDER_RECOVERY_BUDGET_EXCEEDED"||f instanceof Error&&f.name==="AbortError"||_.includes("request aborted")||_==="aborted")return{retryable:!1};if(n_.some((x)=>_.includes(x))||fT(f))return{retryable:!1};if(E?.shouldRetry==="false")return{retryable:!1,statusCode:E.statusCode};if(T==="PROVIDER_REQUEST_DEADLINE_EXCEEDED")return{retryable:!0,reason:"timeout"};let h=E?.statusCode??_T(f)??TT(_);if(E?.shouldRetry==="true")return{retryable:!0,reason:h===429?"rate_limit":h===408||h===409?"timeout":"server_error",statusCode:h};if(h===429)return{retryable:!0,reason:"rate_limit",statusCode:h};if(h===408||h===409)return{retryable:!0,reason:"timeout",statusCode:h};if(h!==void 0&&h>=500&&h<=599)return{retryable:!0,reason:"server_error",statusCode:h};if(T==="PROVIDER_STREAM_CLOSED"||_.includes("stream closed before completion")||_.includes("ended without")||_.includes("stream ended before"))return{retryable:!0,reason:"stream_closed",statusCode:h};if(i_.some((x)=>_.includes(x)))return{retryable:!0,reason:"transport",statusCode:h};if(_.includes("timeout")||_.includes("timed out")||_.includes("temporarily unavailable")||_.includes("upstream_error")||_.includes("overloaded")||_.includes("rate limit")||_.includes("too many requests")||_.includes("service unavailable")||_.includes("server error")||_.includes("internal error")||_.includes("please retry")||_.includes("try your request again"))return{retryable:!0,reason:_.includes("rate")||_.includes("too many")?"rate_limit":_.includes("timeout")||_.includes("timed out")?"timeout":"server_error",statusCode:h};return{retryable:!1,statusCode:h}}function sf(f,E){if(!f)return;if(f.retryAfterMs!==void 0){let h=Number.parseFloat(f.retryAfterMs);if(Number.isFinite(h))return Math.max(0,h)}if(f.retryAfter===void 0)return;let _=Number.parseFloat(f.retryAfter);if(Number.isFinite(_))return Math.max(0,_*1000);let T=Date.parse(f.retryAfter);return Number.isFinite(T)?Math.max(0,T-E):void 0}function qE(f,E,_={}){let T=_.now??Date.now(),h=_.maxDelayMs??60000,x=sf(E,T);if(x!==void 0)return Math.min(Math.ceil(x),h);let S=Math.max(0,f-1),A=_.maxExponentialDelayMs??8000,t=Math.min(500*2**S,A),N=Math.max(0,Math.min(1,_.random??Math.random())),R=t*(0.75+N*0.25);return Math.min(Math.round(R),h)}function aE(f,E){let _=f.onPayload;f.onPayload=async(T,h)=>{let x=_?await _(T,h):T;return E(x===void 0?T:x,h)}}function hT(f){if(!f.reasoningEnabled)return;return f.reasoningEffort??f.reasoningLevel??"high"}function vf(f,E,_){if(!f.enablePromptCaching)return"none";if(_&&E.api==="openai-completions"&&!E.baseUrl.includes("api.openai.com"))return"long";return"short"}function xT(f){switch(f){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function tT(f,E,_,T){let h=T?void 0:hT(_);if(!h){if(E.api==="anthropic-messages")f.thinkingEnabled=!1;if(E.api==="google-generative-ai"||E.api==="google-vertex")f.thinking={enabled:!1};return}switch(E.api){case"anthropic-messages":f.thinkingEnabled=!0,f.effort=h;break;case"google-generative-ai":case"google-vertex":f.thinking={enabled:!0,level:xT(h)};break;case"mistral-conversations":f.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":f.reasoning=h;break;default:f.reasoningEffort=h}}function RT(f,E,_){if(!_)return;switch(E){case"anthropic-messages":case"bedrock-converse-stream":f.toolChoice={type:"tool",name:_};break;case"openai-completions":case"mistral-conversations":case"pi-messages":f.toolChoice={type:"function",function:{name:_}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":f.toolChoice={type:"function",name:_};break;case"google-generative-ai":case"google-vertex":f.toolChoice="any";break}}function MT(f,E,_){let T=_.serviceTier;if(!T)return;if(E.api==="openai-responses"||E.api==="openai-codex-responses"||E.api==="azure-openai-responses"){f.serviceTier=T;return}if(E.api!=="openai-completions"&&!(E.api==="anthropic-messages"&&T==="fast"))return;aE(f,(h)=>{if(!h||typeof h!=="object"||Array.isArray(h))return h;return E.api==="anthropic-messages"?{...h,speed:"fast"}:{...h,service_tier:T}})}function PT(f,E,_){let T=_.responseVerbosity;if(!T)return;if(lE(E,T),E.api==="openai-codex-responses"){f.textVerbosity=T;return}aE(f,(h)=>{if(!h||typeof h!=="object"||Array.isArray(h))return h;if(E.api==="openai-completions")return{...h,verbosity:T};let x="text"in h&&h.text&&typeof h.text==="object"&&!Array.isArray(h.text)?h.text:{};return{...h,text:{...x,verbosity:T}}})}function yE(f,E,_,T,h=!1){let x={apiKey:f.apiKey,headers:f.customHeaders,signal:_,temperature:T?.temperature??f.temperature??0,maxTokens:T?.maxOutputTokens??f.maxOutputTokens,timeoutMs:f.timeout,maxRetries:0,cacheRetention:vf(f,E,T?.providerSessionId),sessionId:T?.providerSessionId};if(tT(x,E,f,h),RT(x,E.api,T?.toolChoice?.toolName),MT(x,E,f),PT(x,E,f),E.api==="azure-openai-responses")x.azureBaseUrl=f.baseUrl,x.azureApiVersion=f.apiVersion,x.azureDeploymentName=E.id;return x}function gE(f,E){let _=E.get("x-should-retry");return{statusCode:f,...E.get("retry-after")!==null?{retryAfter:E.get("retry-after")??void 0}:{},...E.get("retry-after-ms")!==null?{retryAfterMs:E.get("retry-after-ms")??void 0}:{},..._==="true"||_==="false"?{shouldRetry:_}:{}}}var AT=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function eE(f,E,_){let T=f.onResponse;if(f.onResponse=async(x,S)=>{let A=new Headers(x.headers);_(gE(x.status,A)),await T?.(x,S)},!AT.has(E.api)||typeof globalThis.fetch!=="function")return;let h=typeof f.fetch==="function"?f.fetch:globalThis.fetch.bind(globalThis);f.fetch=async(x,S)=>{let A=await h(x,S);return _(gE(A.status,A.headers)),A}}function dE(f){return{promptTokens:f.input+f.cacheRead+f.cacheWrite,completionTokens:f.output,totalTokens:f.totalTokens,costUsd:f.cost.total,...f.reasoning!==void 0?{reasoningTokens:f.reasoning}:{},...f.cacheWrite>0?{cacheCreationInputTokens:f.cacheWrite}:{},...f.cacheRead>0?{cacheReadInputTokens:f.cacheRead}:{}}}var Hf=300000,ST=30000;class nE extends Error{timeoutMs;code="STREAM_IDLE_TIMEOUT";constructor(f){super(`Provider stream idle timeout after ${f}ms without an event`);this.timeoutMs=f;this.name="StreamIdleTimeoutError"}}class rE extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function wf(f){return f.reason instanceof Error?f.reason:new DOMException("Aborted","AbortError")}function NT(f){return f.idleTimeoutMs&&f.idleTimeoutMs>0?f.idleTimeoutMs:Hf}function uT(f,E){if(E===0)return;let _=E!==void 0&&E>0?E:ST;return Math.max(1,Math.min(_,Math.floor(f/2)))}function IT(f,E,_){if(_?.aborted)return Promise.reject(wf(_));return new Promise((T,h)=>{let x=!1,S=()=>{clearTimeout(R),_?.removeEventListener("abort",N)},A=(M)=>{if(x)return;x=!0,S(),T(M)},t=(M)=>{if(x)return;x=!0,S(),h(M instanceof Error?M:Error(String(M)))},N=()=>{if(_)t(wf(_))},R=setTimeout(()=>A({kind:"timer"}),Math.max(0,E));if(_?.addEventListener("abort",N,{once:!0}),_?.aborted){N();return}f.then((M)=>A({kind:"next",result:M}),t)})}async function*DT(f,E,_){let T=NT(E),h=uT(T,E.stallWarningMs);if(E.signal?.aborted)throw wf(E.signal);let x=Date.now(),S=Promise.resolve().then(()=>f.next()),A;for(;;){let N=await IT(S,(A?T:h??T)-(Date.now()-x),E.signal);if(N.kind==="next"){if(A)yield{...A,phase:"recovered",durationMs:Math.max(A.durationMs,Date.now()-x)};return N.result}if(!A&&h!==void 0){_.stallCount++,A={phase:"detected",stallCount:_.stallCount,durationMs:h,warningAfterMs:h,timeoutMs:T,outputStarted:_.outputStarted},yield A;continue}let R=new nE(T);throw E.abort?.(R),R}}async function*iE(f,E,_,T,h={}){let S=f.stream(E,_,T)[Symbol.asyncIterator](),A=0,t=!1,N={stallCount:0,outputStarted:!1};try{while(!0){let R=DT(S,h,N),M=await R.next();while(!M.done)yield{providerStall:M.value},M=await R.next();let I=M.value;if(I.done)throw new rE;let Y=I.value;switch(Y.type){case"text_delta":N.outputStarted=!0,yield{content:Y.delta};break;case"thinking_delta":N.outputStarted=!0,yield{reasoningContent:Y.delta};break;case"toolcall_end":N.outputStarted=!0,yield{toolCalls:[{index:A++,id:Y.toolCall.id,type:"function",function:{name:Y.toolCall.name,arguments:JSON.stringify(Y.toolCall.arguments)}}]};break;case"done":t=!0,yield{finishReason:Y.reason,usage:dE(Y.message.usage)};return;case"error":throw Error(Y.error.errorMessage??`Request ${Y.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!t)Promise.resolve(S.return?.()).catch(()=>{return})}}var pf=l("Chat"),HT=1;function UT(f,E){let _=E.provider===f.provider,T=_&&E.channel===void 0,h=E.channel;return{...f,provider:E.provider,model:E.model,apiKey:h?.apiKey??(T?f.apiKey:void 0),baseUrl:h?.baseUrl??(T?f.baseUrl:void 0),temperature:h?.temperature??f.temperature,maxOutputTokens:h?.maxOutputTokens??(T?f.maxOutputTokens:void 0),timeout:h?.timeout??f.timeout,streamIdleTimeout:h?.streamIdleTimeout??f.streamIdleTimeout,apiVersion:h?.apiVersion??(T?f.apiVersion:void 0),customHeaders:h?.customHeaders??(T?f.customHeaders:void 0),enablePromptCaching:h?.enablePromptCaching??(T?f.enablePromptCaching:void 0),serviceTier:_?f.serviceTier:void 0,responseVerbosity:_?f.responseVerbosity:void 0,fallbackModels:void 0}}function YT(f){return Boolean(f&&f.role==="user"&&Array.isArray(f.content)&&f.content.some((E)=>E.type==="image_url"))}function BT(f){let _=f.findLast((T)=>{let h=T.metadata;return h!==null&&typeof h==="object"&&!Array.isArray(h)&&h.isCompactSummary===!0})?.metadata;return _!==null&&typeof _==="object"&&!Array.isArray(_)&&typeof _.parentId==="string"?_.parentId:""}function bT(f,E){let _=e(f,E);if(!_.retryable||!_.reason)return;let T=_.statusCode;switch(_.reason){case"rate_limit":if(T!==429)return;break;case"server_error":if(T===void 0||T<500||T>599)return;break;case"transport":case"stream_closed":break;case"timeout":return}let h=sf(E,Date.now());return{reason:_.reason,...T!==void 0?{statusCode:T}:{},...h!==void 0?{retryAfterMs:h}:{}}}function mf(f){return f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT"}class lf{config;models;model;promptCacheBreakMonitor=new Jf;providerAdmissionScheduler;admissionFallbackOwnerId=`pi-service-${process.pid}-${HT++}`;constructor(f){let E=zf(f);this.config={...f,maxContextTokens:E.model.contextWindow,maxOutputTokens:f.maxOutputTokens??E.model.maxTokens},this.models=E.models,this.model=E.model,this.providerAdmissionScheduler=f_(this.config),pf.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(f,E,_,T){let h="",x="",S=[],A,t;for await(let N of this.streamChat(f,E,_,T)){h+=N.content??"",x+=N.reasoningContent??"";for(let R of N.toolCalls??[])if(R.id&&R.type==="function"&&R.function?.name)S.push(R);A=N.usage??A,t=N.finishReason??t}return{content:h,...x?{reasoningContent:x}:{},...S.length>0?{toolCalls:S}:{},usage:A,finishReason:t}}async*streamChat(f,E,_,T){let h=T?.toolChoice?.toolName;if(h&&!E?.some((P)=>P.name===h))throw Error(`Required tool is unavailable: ${h}`);let x=ME(f);if(x.some((P)=>YT(P))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let S=Boolean(h)||PE(x),A=await RE(x,this.model,E,_,h),t=(P,u)=>{let c=T?.providerSessionId;if(!c||!P.usage)return P;if(!this.config.enablePromptCaching)return this.promptCacheBreakMonitor.clear(c),P;let B=vf(this.config,u,c),H=this.promptCacheBreakMonitor.observe({sessionId:c,modelIdentity:`${u.provider}\x00${u.api}\x00${u.id}`,context:A,retention:B,contextEpoch:BT(x),policy:{baseUrl:u.baseUrl??this.config.baseUrl??"",retention:B,requiredTool:h??"",reasoningEnabled:this.config.reasoningEnabled??!1,reasoningEffort:this.config.reasoningEffort??this.config.reasoningLevel??"",serviceTier:this.config.serviceTier??"",responseVerbosity:this.config.responseVerbosity??"",temperature:T?.temperature??this.config.temperature??0,maxOutputTokens:T?.maxOutputTokens??this.config.maxOutputTokens??0,customHeaders:this.config.customHeaders??{}},usage:P.usage});if(!H)return P;return pf.warn("[PiAIChatService] Prompt cache break detected",{reason:H.reason,previousCacheReadTokens:H.previousCacheReadTokens,cacheReadTokens:H.cacheReadTokens,tokenDrop:H.tokenDrop,callNumber:H.callNumber}),{...P,usage:{...P.usage,promptCacheBreak:H}}},N=wE({messages:x,context:A,tools:E,requestOptions:T}),R=T?.providerRecovery;if(R&&!__(R.budgetMs))throw Error("Invalid bounded foreground Provider recovery budget");let M=R?.mode==="bounded_foreground"&&R.budgetMs>0?{budgetMs:R.budgetMs,startedAt:void 0}:void 0,I=M?"bounded_foreground":"standard",Y=this.config.maxRetries??2,$=this.config.maxRetries??(M?E_:2),Q=M!==void 0&&this.config.maxRetries===void 0,K=0,o,Uf=this.config.providerCircuitRegistry??BE(),Rf=this.config.providerCircuitBreakerOpenMs??Wf,T_=Math.max(uf,Math.min(this.config.streamIdleTimeout??Hf,kf)),af=this.providerAdmissionScheduler,h_=this.config.providerRequestConcurrency??q,yf=this.config.providerRequestAdmissionMs??Kf,x_=this.config.providerRequestPendingBytes??Cf,Yf=T?.providerAdmission??{sessionId:this.admissionFallbackOwnerId,ownerId:this.admissionFallbackOwnerId,requestClass:"internal"},t_=(P,u)=>Uf.get({provider:P.provider,api:P.api,baseUrl:P.baseUrl??u.baseUrl??"",model:P.id,serviceTier:u.serviceTier,apiVersion:u.apiVersion,apiKey:u.apiKey,customHeaders:u.customHeaders,openDurationMs:Rf,probeLeaseMs:T_}),R_=(P,u)=>({provider:P.provider,api:P.api,baseUrl:P.baseUrl??u.baseUrl??"",model:P.id,serviceTier:u.serviceTier,apiVersion:u.apiVersion,apiKey:u.apiKey,customHeaders:u.customHeaders,maxConcurrent:h_,maxPendingBytes:x_}),j=(P=Date.now())=>{if(!M)return;let u=M.startedAt===void 0?0:Math.min(M.budgetMs,Math.max(0,P-M.startedAt));return{recoveryBudgetMs:M.budgetMs,recoveryElapsedMs:u,recoveryRemainingMs:Math.max(0,M.budgetMs-u)}},v=()=>({mode:I,...j()??{}}),ef=()=>{if(M&&M.startedAt===void 0)M.startedAt=Date.now()},w=()=>{let P=j();return new y(M?.budgetMs??0,P?.recoveryElapsedMs??0)},d=()=>!Q||K<$+1,Bf=(P,u)=>{let{state:c,...B}=u;return{phase:P,...B,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}},df=(P)=>({phase:"rejected",requestClass:P.requestClass,resource:P.resource,scope:P.scope,reason:P.reason,queuePosition:0,queueDepth:Math.max(0,P.queued),inFlight:Math.max(0,P.inFlight),limit:Math.max(0,P.limit),waitMs:P.reason==="wait_timeout"?P.maxWaitMs:0,maxWaitMs:P.maxWaitMs,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),M_=async function*(P,u){if(!af)return{release:()=>{return}};let c=j()?.recoveryRemainingMs,B=c!==void 0&&M?.startedAt!==void 0?Math.min(yf,c):yf,H;try{H=af.admit({scope:R_(P,u),sessionId:Yf.sessionId,ownerId:Yf.ownerId,requestClass:Yf.requestClass,maxWaitMs:B,pendingBytes:N,signal:_})}catch(b){if(tf(b)){if(b.reason==="wait_timeout"&&M?.startedAt!==void 0&&(j()?.recoveryRemainingMs??0)<=0)throw w();yield{providerAdmission:df(b)}}throw b}let L=H.getSnapshot();if(L.state==="admitted")return await H.ready;yield{providerAdmission:Bf("queued",L)};let F=H.ready.then((b)=>({kind:"ready",permit:b}),(b)=>({kind:"error",error:b}));while(!0){let b=H.getSnapshot(),O=Math.max(1,Math.min(FE,Math.max(1,B-b.waitMs))),J,X=new Promise((p)=>{J=setTimeout(()=>p({kind:"heartbeat"}),O),J.unref?.()}),G=await Promise.race([F,X]);if(J)clearTimeout(J);if(G.kind==="heartbeat"){yield{providerAdmission:Bf("queued",H.getSnapshot())};continue}if(G.kind==="error"){if(tf(G.error)){if(G.error.reason==="wait_timeout"&&M?.startedAt!==void 0&&(j()?.recoveryRemainingMs??0)<=0)throw w();yield{providerAdmission:df(G.error)}}throw G.error}return yield{providerAdmission:Bf("admitted",H.getSnapshot())},G.permit}},P_=(P,u)=>{if(!d())throw w();if(Q)K++;o=void 0;let c=new AbortController,B=_?xE(_,c.signal):c.signal,H=typeof u.timeout==="number"&&Number.isFinite(u.timeout)&&u.timeout>0?Math.max(1,Math.floor(u.timeout)):void 0,L;if(M?.startedAt!==void 0){let O=j()?.recoveryRemainingMs??0;if(O<=0)throw w();L={remainingMs:O,error:new y(M.budgetMs,M.budgetMs)}}let F=yE(u,P,B,T,S);eE(F,P,(O)=>{o=O});let b=iE(this.models,P,A,F,{idleTimeoutMs:u.streamIdleTimeout??Hf,signal:B,abort:(O)=>c.abort(O)});return async function*(){let O,J;try{if(H!==void 0&&(L===void 0||H<L.remainingMs)){let X=new Ff(H);O=setTimeout(()=>c.abort(X),H),O.unref?.()}if(L){let X=L;J=setTimeout(()=>c.abort(X.error),X.remainingMs),J.unref?.()}yield*b}finally{if(O)clearTimeout(O);if(J)clearTimeout(J)}}()},nf=this,g=(P)=>({phase:P.phase,reason:P.reason,...P.statusCode!==void 0?{statusCode:P.statusCode}:{},...P.retryAfterMs!==void 0?{retryAfterMs:P.retryAfterMs}:{},...P.nextProbeAt!==void 0?{nextProbeAt:P.nextProbeAt}:{},openDurationMs:P.openDurationMs,sampleCount:P.sampleCount,failureCount:P.failureCount,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),rf=(P,u)=>({phase:P,reason:u.reason,...u.statusCode!==void 0?{statusCode:u.statusCode}:{},retryAfterMs:u.retryAfterMs,...u.nextProbeAt!==void 0?{nextProbeAt:u.nextProbeAt}:{},openDurationMs:u.openDurationMs,sampleCount:u.sampleCount,failureCount:u.failureCount,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),A_=(P)=>({phase:"probe",reason:P.reason??"server_error",...P.statusCode!==void 0?{statusCode:P.statusCode}:{},openDurationMs:P.openDurationMs??Rf,...P.sampleCount!==void 0?{sampleCount:P.sampleCount}:{},...P.failureCount!==void 0?{failureCount:P.failureCount}:{},...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),bf=(P,u,c)=>({providerRetry:{phase:"exhausted",attempt:P,maxRetries:$,reason:u,...c!==void 0?{statusCode:c}:{},...v(),exhaustedBy:"recovery_budget"}}),fE=async function*(P,u,c,B,H){let L,F=!1,b,O,J=t_(P,u);for(let X=0;X<=B;X++){if(!d())break;let G,p;while(!G){let D=J.preflight();while(!D.eligible){if(b=D.reason,O=D.statusCode,!M||!H){let C=rf("rejected",D);throw yield{providerCircuit:C},new hf(C)}ef();let V=j()?.recoveryRemainingMs??0;if(V<=0){let C=w();throw yield bf(Q?Math.max(0,K-1):X,D.reason,D.statusCode),C}yield{providerCircuit:rf("waiting",D)};let m=Math.min(Math.max(1,D.retryAfterMs),qf,V);if(await ff(m,_,{throwOnAbort:!0}),(j()?.recoveryRemainingMs??0)<=0){let C=w();throw yield bf(Q?Math.max(0,K-1):X,D.reason,D.statusCode),C}D=J.preflight()}try{p=yield*M_(P,u)}catch(Z){if(Z instanceof y)yield bf(Q?Math.max(0,K-1):X,b??"timeout",O);throw Z}let k=J.check();if(k.allowed)G=k;else p.release(),p=void 0}let n=G.token;if(G.probe)yield{providerCircuit:A_(G)};try{let D=!1,k=!1;for await(let Z of P_(P,u)){if(Z.providerStall){yield Z;continue}let V=Q?K-1:X;if(V>0&&b&&!D)D=!0,yield{providerRetry:{phase:"recovered",attempt:V,maxRetries:$,reason:b,...O!==void 0?{statusCode:O}:{},...v()}};if(!k){k=!0;let m=J.recordSuccess(n);if(m)yield{providerCircuit:g(m)}}F=!0,c(),yield t(Z,P)}if(!k){let Z=J.recordSuccess(n);if(Z)yield{providerCircuit:g(Z)}}return}catch(D){if(p?.release(),L=D,nf.logIdleTimeout(D,F,P),await nf.handleAbort(_),D instanceof y){if(F)throw of(D),D;throw yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):X,maxRetries:$,reason:b??"timeout",...O!==void 0?{statusCode:O}:{},...v(),exhaustedBy:"recovery_budget"}},D}let k=e(D,o);if(F)throw of(D),D;let Z=bT(D,o),V=Z?J.recordFailure(n,Z):o&&!mf(D)?J.recordNeutral(n):void 0;if(V)yield{providerCircuit:g(V)};if(!k.retryable||!k.reason){if(X>0&&b)yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):X,maxRetries:$,reason:b,...O!==void 0?{statusCode:O}:{},...v()}};throw D}b=k.reason,O=k.statusCode;let m=X<B&&d();if(V&&V.phase!=="closed"&&m&&(!M||!H)){let C={...g(V),phase:"rejected"};throw yield{providerCircuit:C},new hf(C)}if(m){ef();let C=Q?K:X+1,N_=qE(C,o,M?{maxDelayMs:gf,maxExponentialDelayMs:gf}:void 0),_E=V&&V.phase!=="closed"?V.retryAfterMs??0:0;if(M&&_E>0&&V)yield{providerCircuit:{...g(V),phase:"waiting"}};let u_=j(),cf=Math.max(N_,_E),r=M?Math.min(cf,u_?.recoveryRemainingMs??cf):cf,Pf={attempt:C,maxRetries:$,reason:k.reason,...k.statusCode!==void 0?{statusCode:k.statusCode}:{}};if(yield{providerRetry:{phase:"scheduled",...Pf,delayMs:r,nextRetryAt:Date.now()+r,...v()}},M){let i=r;while(i>0){let TE=Math.min(i,qf);if(await ff(TE,_,{throwOnAbort:!0}),i-=TE,(j()?.recoveryRemainingMs??0)<=0){let Af=w();throw yield{providerRetry:{phase:"exhausted",...Pf,...v(),exhaustedBy:"recovery_budget"}},Af}if(i>0){if(V&&V.phase!=="closed"&&V.nextProbeAt!==void 0){let Af=Math.max(0,V.nextProbeAt-Date.now());if(Af>0)yield{providerCircuit:{...g(V),phase:"waiting",retryAfterMs:Af}}}yield{providerRetry:{phase:"waiting",...Pf,delayMs:r,nextRetryAt:Date.now()+i,...v()}}}}}else await ff(r,_,{throwOnAbort:!0});yield{providerRetry:{phase:"attempt",...Pf,...v()}}}else yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):X,maxRetries:$,reason:k.reason,...k.statusCode!==void 0?{statusCode:k.statusCode}:{},...v(),...M&&(H||!d())?{exhaustedBy:"attempt_limit"}:{}}}}finally{J.abandon(n),p?.release()}}throw L},Of,EE=!1,Mf=this.config.fallbackModels??[],S_=M&&Mf.length>0?Math.min(Y,$):$;try{for await(let P of fE(this.model,this.config,()=>{EE=!0},S_,Mf.length===0))yield P;return}catch(P){if(Of=P,EE||!tf(P)&&!Lf(P)&&!mf(P)&&!e(P,o).retryable)throw P}for(let[P,u]of Mf.entries()){if(!d())break;yield{modelFallback:!0};let c=!1;try{let B=UT(this.config,u),H=NE(B,u),L=P===Mf.length-1,F=M&&!L?Math.min(Y,$):$;for await(let b of fE(H,B,()=>{c=!0},F,L))yield b;return}catch(B){if(Of=B,c||!tf(B)&&!Lf(B)&&!mf(B)&&!e(B,o).retryable)throw B}}throw Of}async handleAbort(f){if(f?.aborted)await ff(0,f,{throwOnAbort:!0})}logIdleTimeout(f,E,_){if(f===null||typeof f!=="object"||!("code"in f)||f.code!=="STREAM_IDLE_TIMEOUT"||!("timeoutMs"in f)||typeof f.timeoutMs!=="number")return;pf.warn("[PiAIChatService] Provider stream idle timeout",{provider:_.provider,model:_.id,timeoutMs:f.timeoutMs,replayBoundaryCrossed:E})}getConfig(){return{...this.config}}updateConfig(f){let E={...this.config,...f},_=zf(E);this.config={...E,maxContextTokens:_.model.contextWindow,maxOutputTokens:E.maxOutputTokens??_.model.maxTokens},this.models=_.models,this.model=_.model,this.providerAdmissionScheduler=f_(this.config)}}function f_(f){if(f.providerRequestAdmissionScheduler)return f.providerRequestAdmissionScheduler;if(f.providerRequestConcurrency===void 0&&f.providerGlobalConcurrency===void 0&&f.providerOwnerConcurrency===void 0)return;let E=f.providerGlobalConcurrency??Number.MAX_SAFE_INTEGER,_=f.providerOwnerConcurrency??Number.MAX_SAFE_INTEGER;return sE({globalMaxInFlight:E,ownerMaxInFlight:_,nonForegroundGlobalMaxInFlight:E,nonForegroundOwnerMaxInFlight:_,internalGlobalMaxInFlight:E,internalDomainMaxInFlight:f.providerRequestConcurrency??q,classLimitsEnabled:!1})}var OT=l("Service");async function Gh(f){let E=f;if(E.provider){let _=hE(E.provider);if(Object.keys(_).length>0)E={...E,customHeaders:{..._,...E.customHeaders}},OT.debug(`Injected ${E.provider} specific headers:`,Object.keys(_))}return cT(E)}function cT(f){return new lf(f)}
|
|
5
|
-
export{XT as
|
|
5
|
+
export{XT as Ye,WT as Ze,xE as _e,ff as $e,tf as af,vE as bf,fT as cf,Rh as df,e as ef,qE as ff,lf as gf,Gh as hf};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{He as N}from"./chunk-61efg3yh.js";import{jg as $}from"./chunk-5rtjx9xk.js";import{Ih as _}from"./chunk-qa4efys0.js";import{gi as Y,ii as Z}from"./chunk-h4j0nve8.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
|
|
2
2
|
再按一次 Ctrl+C 退出
|
|
3
3
|
`)}),this.initialized=!0,z.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),z.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),z.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){z.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0;try{N().command.actions.abort("process-shutdown")}catch(A){z.warn("[GracefulShutdown] Failed to abort the active command",A)}z.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);let Q=setTimeout(()=>{X(),process.exit(q)},5000);Q.unref?.();let U=4000,K;try{await Promise.race([this.runCleanupHandlers(),new Promise((A,J)=>{K=setTimeout(()=>{J(Error(`清理超时 (${U}ms)`))},U),K.unref?.()})])}catch(A){console.error("[GracefulShutdown] 清理过程中发生错误:",A)}finally{if(K)clearTimeout(K)}try{let A=$.getInstance(),J=N(),V=J.session?.sessionId||"unknown",W=J.session?.workspaceRoot||_();if(A.isEnabled(W,V)){let v=J.config?.config?.permissionMode||"default";await A.executeSessionEndHooks(E(b),{projectDir:W,sessionId:V,permissionMode:v})}}catch(A){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",A)}try{await Y()}catch{}clearTimeout(Q),X(),setTimeout(()=>{process.exit(q)},100)}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let F=q();if(F instanceof Promise)await F}catch(F){console.error("[GracefulShutdown] 清理函数执行失败:",F)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var O=()=>{return B.getInstance()},y=(b)=>{return O().registerCleanup(b)},j=()=>{O().initialize()},C=(b=0)=>{O().shutdown("normal",b)};
|
|
4
|
-
export{O as
|
|
4
|
+
export{O as pe,y as qe,j as re,C as se};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{e as DJ,f as VJ}from"./chunk-
|
|
1
|
+
import{e as DJ,f as VJ}from"./chunk-7k5v52ct.js";import{i as RY,j as MY,k as TY}from"./chunk-scfwdpph.js";import{u as s2}from"./chunk-fyms8zy1.js";import{$ as z2,B as c6,F as gY,H as OQ,I as XQ,J as v6,O as A6,P as P6,T as j1,V as e4,W as $6,Z as y6,aa as nJ,ba as tJ,ea as sJ,fa as eJ,ja as L4,ka as $9,ma as t6,na as s6,oa as mY,pa as O6,ra as z6,ta as x6}from"./chunk-m4tpqesg.js";import"./chunk-z5rtzcm4.js";import{Ba as qJ,Ca as OJ,Da as zJ,Ga as EY}from"./chunk-3p7c1dsk.js";import{Ia as b6}from"./chunk-8eh0vp98.js";import{Cb as w6,Lb as QQ,pb as L6,qb as B6}from"./chunk-v7rnx21e.js";import{Wb as W2}from"./chunk-ya5p7mx7.js";import{Ad as Z6,Cd as d2,Kd as O2,Nd as C0,_c as _6,md as t4,rd as s4,yd as Y6,zd as $Q}from"./chunk-t7nj9vg8.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{oe as PY}from"./chunk-wbfa6xce.js";import{pe as H2,qe as e2,se as C1}from"./chunk-0pnj92hk.js";import"./chunk-ztp2ff01.js";import{Ae as g$,Be as r2,Ce as v9,De as Q4,Ee as MJ,Fe as D9,Ge as V$,He as l0,Ie as jY,Je as o0,Ke as AY,Le as D8,Me as N2,Pe as U6,We as p0,we as k$,xe as a0,ye as Q$,ze as jQ}from"./chunk-61efg3yh.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import{kf as J4}from"./chunk-rxbxvq67.js";import"./chunk-z6xfknxe.js";import"./chunk-ns5vb2p4.js";import{Ef as iJ,Nf as hY,wf as Q8,zf as _Y}from"./chunk-tt3n8gnq.js";import"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import{hg as gQ,jg as q1}from"./chunk-5rtjx9xk.js";import"./chunk-74yge4ka.js";import{lh as DY,qh as oJ,rh as VY}from"./chunk-7wf2acxx.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import{Ah as m$,Bh as a2,Dh as mQ}from"./chunk-d83bfr0b.js";import{Ih as d0}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import{fi as vY,ii as t1}from"./chunk-h4j0nve8.js";import{ki as kJ,li as SJ,oi as h1}from"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import{Ai as bJ}from"./chunk-hn1xztva.js";import{Di as F4}from"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import{Oi as e8}from"./chunk-na1cney5.js";import{Qi as EQ}from"./chunk-nh45xp7r.js";import{useMemoizedFn as u8}from"ahooks";import{useEffect as S7,useState as l8}from"react";import{useMemoizedFn as s0}from"ahooks";import{Box as z$}from"ink";import{useEffect as _$,useMemo as R7,useRef as p8}from"react";import{useShallow as uY}from"zustand/react/shallow";import{useStore as xY}from"zustand";function t($){return xY(V$,$)}var lY=[],j$=()=>t(($)=>$.session.sessionId),T1=()=>t(($)=>$.session.workspaceRoot),B4=()=>t(($)=>$.session.messages),w4=()=>t(($)=>$.session.clearCount),b4=()=>t(($)=>$.session.isCompacting),A4=()=>t(($)=>$.session.tokenUsage.estimatedCostUsd),P4=()=>t(($)=>{let{totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}=$.session.tokenUsage;return L4({totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}).hitRate}),y4=()=>t(($)=>$.session.providerCircuit),R4=()=>t(($)=>$.session.providerAdmission),M4=()=>t(($)=>$.session.providerRetry),T4=()=>t(($)=>$.session.providerStall),C4=()=>t(($)=>$.session.actionStationarity),i1=()=>t(($)=>$.session.actions),I4=()=>t(($)=>{let{totalTokens:Q,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let J=Math.max(0,100-Q/Y*100);return Math.round(J)}),f4=()=>t(($)=>$.app.initializationStatus),k4=()=>t(($)=>$.app.initializationError),D2=()=>t(($)=>$.app.activeModal),S4=()=>t(($)=>$.app.tasks),v4=()=>t(($)=>$.app.modelEditorTarget),D4=()=>t(($)=>$.app.sessionSelectorData),V4=()=>t(($)=>$.app.awaitingSecondCtrlC),n1=()=>t(($)=>$.app.actions),V2=()=>t(($)=>$.app.sideConversation),j4=()=>t(($)=>$.app.teams),j2=()=>t(($)=>$.app.initializationStatus==="ready"),h4=()=>t(($)=>$.app.tasks.length>0),h$=()=>t(($)=>$.config.config?.permissionMode||"default"),E4=()=>t(($)=>$.config.config?.models??lY),h2=()=>t(($)=>{let Q=$.config.config;if(!Q)return;let Y=Q.currentModelId;return Q.models.find((Z)=>Z.id===Y)??Q.models[0]}),E2=()=>t(($)=>$.config.config?.currentModelId),g4=()=>t(($)=>$.config.config?.agentTeamsEnabled===!0),b0=()=>t(($)=>{return a0.getTheme()}),m4=()=>t(($)=>$.config.config?.codeTheme??"default"),e0=()=>t(($)=>$.focus.currentFocus),p4=()=>t(($)=>$.focus.actions),E$=()=>t(($)=>$.command.isProcessing),c4=()=>t(($)=>$.command.actions),g2=()=>t(($)=>$.command.pendingCommands),x4=()=>t(($)=>$.command.recoveredSteeringCount),m2=()=>t(($)=>$.app.reasoningEffort!=="off"),p2=()=>t(($)=>$.app.reasoningEffort),c2=()=>t(($)=>$.app.serviceTier),x2=()=>t(($)=>$.app.responseVerbosity),u2=()=>t(($)=>$.app.communicationStyle),u4=()=>t(($)=>$.session.currentThinkingContent),l4=()=>t(($)=>$.session.thinkingExpanded),d4=()=>t(($)=>$.session.currentStreamingMessageId),r4=()=>t(uY(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),a4=()=>t(($)=>$.session.finalizingStreamingMessageId),o4=()=>t(($)=>$.session.historyExpanded),i4=()=>t(($)=>$.session.expandedMessageCount);import{useMemoizedFn as s1}from"ahooks";import{useEffect as c$,useRef as s8}from"react";function dY($){if(!($ instanceof Error))return"未知错误";let J=$.lastError??$;if(J.responseBody)try{let K=JSON.parse(J.responseBody)?.error?.message;if(K){let U=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${K}${U}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function rY($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function aY($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function l2($){let Q=rY($),Y=aY($),J;if(Y)J="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else J=dY($);return{displayMessage:J,isAbort:Q,isVisionNotSupported:Y}}import{appendFileSync as oY,mkdirSync as iY,writeFileSync as nY}from"node:fs";import tY from"node:os";import a8 from"node:path";var n4=null;function sY(){let $=process.env.BLADE_STORAGE_ROOT||a8.join(tY.homedir(),".blade");return a8.join($,"logs","stream-debug.log")}function eY($){if(n4===$)return;let Q=a8.dirname($);iY(Q,{recursive:!0,mode:493}),nY($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
|
|
2
2
|
`),n4=$}function o8($,Q,Y){try{let J=sY();eY(J);let Z=new Date().toISOString(),X=Y?` | ${JSON.stringify(Y)}`:"",K=`[${Z}] [${$}] ${Q}${X}
|
|
3
3
|
`;oY(J,K)}catch{}}var q2=t1("UI");function Q6($,Q){let Y=!1;return(J)=>{switch(J.kind){case"content_delta":if(Y||$.signal.aborted)break;Q.contentDeltaCount++,Q.contentDeltaTotalLen+=J.delta.length,o8("loopEventHandler","onContentDelta",{callCount:Q.contentDeltaCount,deltaLen:J.delta.length,totalLen:Q.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(J.delta);break;case"thinking_delta":if(Y||$.signal.aborted)break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(J.delta);break;case"stream_end":{if($.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),q2.debug("[loopEventHandler] stream_end",{contentDeltaCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),o8("loopEventHandler","onStreamEnd",{contentDeltaCallCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),Y||$.signal.aborted){Y=!0;break}let{extraContent:Z,extraThinking:X}=$.streamingBuffer.drainPendingBuffers(),K=$.getStreamingMessageId();if(K){if(Z)g$(K,Z);r2(K)}$.sessionActions.finalizeStreamingMessage(Z,X),Y=!0;break}case"model_fallback":Y=!0,$.sessionActions.setProviderAdmission(null),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),$.streamingBuffer.resetStreamingBuffers(),$.sessionActions.discardStreamingMessage(),$.sessionActions.setCurrentThinkingContent(null);break;case"provider_admission":{let{kind:Z,...X}=J;$.sessionActions.setProviderAdmission(J.phase==="queued"?X:null);break}case"provider_circuit":{let{kind:Z,...X}=J;$.sessionActions.setProviderCircuit(J.phase==="closed"?null:X);break}case"provider_retry":{let{kind:Z,...X}=J;$.sessionActions.setProviderRetry(J.phase==="recovered"?null:X);break}case"provider_stall":{let{kind:Z,...X}=J;$.sessionActions.setProviderStall(J.phase==="detected"?X:null);break}case"action_stationarity":{let{kind:Z,...X}=J;$.sessionActions.setActionStationarity(J.phase==="recovered"?null:X);break}case"tool_start":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===d2)break;if(q2.debug("[loopEventHandler] tool_start",{toolName:Z.function.name,toolKind:J.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(Z.function.name))break;try{let X=JSON.parse(Z.function.arguments),K=e4(Z.function.name,X);$.sessionActions.addToolMessage(K,{toolCallId:Z.id,toolName:Z.function.name,phase:"start",summary:K,params:X})}catch(X){q2.error("[loopEventHandler] onToolStart error:",X)}break}case"tool_progress":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===d2)break;let X=J.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((J.update.progress??0)/J.update.total*100)))}%`:"",K=`${Z.function.name}${X}: ${J.update.message}`;$.sessionActions.addToolMessage(K,{toolCallId:Z.id,toolName:Z.function.name,phase:"progress",summary:K,...J.update.admission?{admission:J.update.admission}:{}});break}case"tool_result":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===d2)break;q2.debug("[loopEventHandler] tool_result",{toolName:Z.function.name,success:J.result.success});let X=s4($6(Z.function.name,J.result),t4);$.sessionActions.addToolMessage(X.summary,{toolCallId:Z.id,toolName:Z.function.name,phase:"complete",summary:X.summary,detail:X.detail});break}case"structured_output":$.sessionActions.replaceLastAssistantMessage(JSON.stringify(J.output,null,2));break;case"token_usage":$.sessionActions.updateTokenUsage(J.usage);break;case"compaction":if($.sessionActions.setCompacting(J.phase==="start"),J.phase==="end"){if($.sessionActions.resetContextUsage(),J.outcome!=="failed")Q.compactionCount=(Q.compactionCount??0)+1}break;case"turn_start":q2.debug("[loopEventHandler] turn_start",{turn:J.turn,maxTurns:J.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:J.turn}),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y=!1;break;case"task_update":$.appActions.setTasks(J.tasks);break;case"mcp_catalog_changed":{let Z=`MCP catalog r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Catalog",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`
|
|
4
4
|
`)});break}case"mcp_content_changed":{let Z=`MCP ${J.contentKind} r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Content",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Wb as Xt,Xb as fn,Yb as yn,Zb as En}from"./chunk-ya5p7mx7.js";import{jg as Bt}from"./chunk-5rtjx9xk.js";import{Ag as dn,Bg as on,Cg as pn,Dg as lt,Eg as cn,Fg as un,Gg as Mn,Ig as S,Lg as wn,Mg as Gt,Ng as Ut,Og as h,Pg as Ht,og as gt,pg as vi,qg as sn,rg as zt,sg as U,tg as en,ug as xt,vg as mt,xg as rn,yg as Tn,zg as B}from"./chunk-7wf2acxx.js";import{uh as X,wh as g}from"./chunk-7dqh8bqm.js";import{Ih as It}from"./chunk-qa4efys0.js";import{wi as tn,xi as nn}from"./chunk-hn1xztva.js";import{Qi as ns}from"./chunk-nh45xp7r.js";import{EventEmitter as bs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
|
|
2
2
|
${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
|
|
3
3
|
`)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(t,i,n,s,e){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function jt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isConcurrencySafe:t.isConcurrencySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
|
|
4
4
|
|
|
@@ -22,4 +22,4 @@ ${u}
|
|
|
22
22
|
|
|
23
23
|
Preview (tail):
|
|
24
24
|
${M}`,c=!0}return{isError:t.isError===!0,llmContent:o,metadata:{contentCount:t.content.length,textBytes:n.textBytes,structuredBytes:r?.bytes??0,artifactCount:e.length,truncated:c,binaryOmitted:n.binaryBytes>0,artifacts:e}}}function yt(t){let i=t instanceof Error?t.message:String(t),n=xn(i.replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]")).trim();return wt(n||"MCP tool execution failed",Cn)}function Tt(t,i,n,s,e){let r=n.inputSchema&&typeof n.inputSchema==="object"?g.Unsafe(n.inputSchema):g.Any(),o=s||n.name;return jt({name:o,displayName:`${i}: ${n.name}`,kind:"execute",schema:r,description:{short:n.description||`MCP Tool: ${n.name}`,important:[`From MCP server: ${i}`,"Executes external tools; user confirmation required",...n.taskSupport==="required"?["This tool requires MCP task execution and returns an opaque task ID.","Use TaskOutput to retrieve the eventual result."]:[]]},category:"MCP tool",tags:["mcp","external",i],async execute(c,d){try{let p={...d.confirmationHandler?{confirmationHandler:d.confirmationHandler}:{},...d.mcpSamplingHandler?{samplingHandler:d.mcpSamplingHandler}:{},...d.onProgressUpdate?{progressHandler:d.onProgressUpdate}:{},...d.sessionId?{sessionId:d.sessionId}:{},...d.workspaceRoot?{workspaceRoot:d.workspaceRoot}:{},...d.permissionMode?{permissionMode:d.permissionMode}:{}};if(n.taskSupport==="required"){if(!d.sessionId)throw Error("MCP tasks require an active Session");let y=await T.getInstance().start({client:t,serverName:i,toolName:n.name,arguments:c,owner:{sessionId:d.sessionId,projectPath:Un.resolve(d.workspaceRoot||It())},interactionContext:p,signal:d.signal});return{success:!0,llmContent:{task_id:y.taskId,type:"mcp",status:y.status,message:`MCP task started. Use TaskOutput(task_id: "${y.taskId}") to retrieve its result.`},metadata:{summary:`Started MCP task ${y.taskId}`,serverName:i,toolName:n.name,task_id:y.taskId,taskType:"mcp",taskStatus:y.status,background:!0}}}let u=await t.callTool(n.name,c,{...d.signal?{signal:d.signal}:{},...p}),M=await j(u,e),w={summary:`MCP ${n.name} 执行${M.isError?"失败":"成功"}`,serverName:i,toolName:n.name,mcpResult:{isError:M.isError,...M.metadata}};if(M.isError){let y=yt(M.llmContent);return{success:!1,llmContent:y,error:{type:"execution_error",message:y},metadata:w}}return{success:!0,llmContent:M.llmContent,metadata:w}}catch(p){let u=yt(p);return{success:!1,llmContent:`MCP tool execution failed: ${u}`,error:{type:"execution_error",message:u},metadata:{summary:`MCP ${n.name} 执行失败`,serverName:i,toolName:n.name}}}}})}import{realpathSync as ss}from"node:fs";import Ni from"node:path";import{pathToFileURL as es}from"node:url";import{Client as rs}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as ds}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as os}from"@modelcontextprotocol/sdk/client/stdio.js";import{CallToolResultSchema as St,CreateMessageRequestSchema as ps,ElicitationCompleteNotificationSchema as cs,ElicitRequestSchema as us,ErrorCode as R,ListRootsRequestSchema as Ms,LoggingMessageNotificationSchema as ws,McpError as P,ResourceUpdatedNotificationSchema as ys,TaskStatusNotificationSchema as Ts}from"@modelcontextprotocol/sdk/types.js";import{EventEmitter as fs}from"events";import Es from"open";import{EventEmitter as Bn}from"events";function ft(t,i,n,s,e){if(t===void 0)return i;if(typeof t!=="number"||!Number.isFinite(t)||!Number.isInteger(t)||t<s||t>e)throw Error(`${n} must be an integer between ${s} and ${e}`);return t}class Et extends Bn{client;config;checkTimer=null;isChecking=!1;running=!1;consecutiveFailures=0;lastCheckTime=0;currentStatus="healthy";constructor(t,i={}){super();if(this.client=t,i.enabled!==void 0&&typeof i.enabled!=="boolean")throw Error("MCP health check enabled must be a boolean");this.config={interval:ft(i.interval,30000,"MCP health check interval",10,300000),timeout:ft(i.timeout,1e4,"MCP health check timeout",10,60000),enabled:i.enabled??!1,failureThreshold:ft(i.failureThreshold,3,"MCP health check failureThreshold",1,10)}}start(){if(this.running||!this.config.enabled)return;this.running=!0,this.scheduleNextCheck()}stop(){if(this.running=!1,this.checkTimer)clearTimeout(this.checkTimer),this.checkTimer=null}scheduleNextCheck(){if(!this.running)return;this.checkTimer=setTimeout(async()=>{this.checkTimer=null,await this.performHealthCheck().catch(()=>{return}),this.scheduleNextCheck()},this.config.interval),this.checkTimer.unref()}async performHealthCheck(){if(this.isChecking)return this.getLastResult();this.isChecking=!0,this.lastCheckTime=Date.now(),this.setStatus("checking");try{let t=this.client.connectionStatus;if(t==="connected"){await this.client.ping(this.config.timeout),this.consecutiveFailures=0,this.setStatus("healthy");let i={status:"healthy",timestamp:Date.now(),consecutiveFailures:0};return this.emit("healthCheck",i),i}else throw Error(`连接状态异常: ${t}`)}catch(t){this.consecutiveFailures++;let i=t,n;if(this.consecutiveFailures>=this.config.failureThreshold)n="unhealthy",this.emit("unhealthy",this.consecutiveFailures,i),this.client.requestRecovery(i,"health_check");else n="degraded";this.setStatus(n);let s={status:n,timestamp:Date.now(),consecutiveFailures:this.consecutiveFailures,lastError:i};return this.emit("healthCheck",s),s}finally{this.isChecking=!1}}setStatus(t){if(this.currentStatus!==t){let i=this.currentStatus;this.currentStatus=t,this.emit("statusChanged",t,i)}}getStatus(){return this.currentStatus}getLastResult(){return{status:this.currentStatus,timestamp:this.lastCheckTime,consecutiveFailures:this.consecutiveFailures}}getStatistics(){return{status:this.currentStatus,consecutiveFailures:this.consecutiveFailures,lastCheckTime:this.lastCheckTime,isChecking:this.isChecking,config:this.config}}async checkNow(){return this.performHealthCheck()}resetFailureCount(){if(this.consecutiveFailures=0,this.currentStatus!=="checking")this.setStatus("healthy")}}import{createHash as Xn}from"node:crypto";import{UriTemplate as zn}from"@modelcontextprotocol/sdk/shared/uriTemplate.js";var ti=100,Yn=4096,Dn=65536,bt=1048576,ii=32,ni=65536,oi=4,ht=15000,si=256,ei=16384,Fn=256,Jn=8192,Vn=/[\p{Cf}\p{Co}\p{Cn}]/u;function jn(t){return[...new Set(new zn(t).variableNames)]}function pi(t,i){let n=G(t.argument.name,"completion argument name",si),s=ri(t.argument.value,"completion argument value",ei),e,r;if(t.reference.type==="prompt"){let p=G(t.reference.name,"completion prompt name",Fn),u=i.prompts.find((M)=>M.name===p);if(!u)throw Error(`MCP prompt "${p}" is not present in the current catalog`);e=new Set(u.arguments.map((M)=>M.name)),r={type:"ref/prompt",name:p}}else{let p=G(t.reference.uri,"completion resource template URI",Jn);if(!i.resourceTemplates.find((w)=>w.uriTemplate===p))throw Error(`MCP resource template "${p}" is not present in the current catalog`);let M;try{M=jn(p)}catch{throw Error(`MCP resource template "${p}" is invalid`)}e=new Set(M),r={type:"ref/resource",uri:p}}if(!e.has(n))throw Error(`MCP ${t.reference.type} completion argument "${n}" is not declared`);let o=Object.entries(t.context??{});if(o.length>ii)throw Error(`MCP completion context exceeds ${ii} arguments`);let c=Object.create(null),d=0;for(let[p,u]of o){let M=G(p,"completion context argument name",si);if(wi(M))throw Error(`Unsafe MCP completion context argument "${M}"`);if(!e.has(M))throw Error(`Unknown MCP completion context argument "${M}"`);let w=ri(u,`completion context argument "${M}"`,ei);if(d+=Buffer.byteLength(M)+Buffer.byteLength(w),d>ni)throw Error(`MCP completion context exceeds ${ni} bytes`);c[M]=w}return{ref:r,argument:{name:n,value:s},...o.length>0?{context:{arguments:c}}:{}}}function ci(t){let i=t.completion,n=JSON.stringify(i),s=Buffer.byteLength(n),e=Xn("sha256").update(n).digest("hex"),r=i.values.length,o=[],c=new Set,d=0,p=0,u=r>ti||s>bt;for(let w of i.values.slice(0,ti)){let y=Buffer.byteLength(w),f=Math.max(0,bt-p);if(f===0){u=!0;break}let a=di(w,Math.min(bt,f));if(p+=Buffer.byteLength(a),y>Buffer.byteLength(a))u=!0;let Dt=ui(a),L=di(Dt,Yn);if(Buffer.byteLength(L)<Buffer.byteLength(Dt))u=!0;if(c.has(L))continue;let Ft=Buffer.byteLength(L);if(d+Ft>Dn){u=!0;break}c.add(L),o.push(L),d+=Ft}if(o.length<r)u=!0;let M=i.total!==void 0&&Number.isSafeInteger(i.total)&&i.total>=0?i.total:void 0;return{values:o,...M!==void 0?{total:M}:{},hasMore:i.hasMore===!0||u||M!==void 0&&M>o.length,sourceValueCount:r,sourceBytes:s,projectedBytes:d,sha256:e,truncated:u}}function ui(t){return[...t.normalize("NFKC")].filter((i)=>{let n=i.codePointAt(0)??0;if(n<32||n===127)return!1;return!Vn.test(i)}).join("")}function G(t,i,n){if(typeof t!=="string"||!t||Buffer.byteLength(t)>n)throw Error(`MCP ${i} is invalid`);if(ui(t)!==t||Mi(t))throw Error(`MCP ${i} contains unsafe characters`);if(wi(t))throw Error(`MCP ${i} is unsafe`);return t}function ri(t,i,n){if(typeof t!=="string"||Buffer.byteLength(t)>n)throw Error(`MCP ${i} exceeds ${n} bytes`);if(Mi(t))throw Error(`MCP ${i} contains control characters`);return t}function Mi(t){return[...t].some((i)=>{let n=i.codePointAt(0)??0;return n<32||n===127})}function wi(t){return["__proto__","constructor","prototype"].includes(t)}function di(t,i){let n=Buffer.from(t);if(n.length<=i)return t;let s=n.subarray(0,Math.max(0,i)).toString("utf8");while(Buffer.byteLength(s)>i)s=s.slice(0,-1);return s}var At=20,_t=300000;function yi(t,i,n,s,e){if(t===void 0)return i;if(typeof t!=="number"||!Number.isFinite(t))throw Error(`${n} must be a finite number`);if(t<s||t>e)throw Error(`${n} must be between ${s} and ${e}`);return t}function H(t,i,n,s,e){let r=yi(t,i,n,s,e);if(!Number.isInteger(r))throw Error(`${n} must be an integer`);return r}function Ti(t){let i=t.recovery;if(i!==void 0&&(i===null||typeof i!=="object"||Array.isArray(i)))throw Error("MCP recovery configuration must be an object");let n=i?.enabled??!0;if(typeof n!=="boolean")throw Error("MCP recovery enabled must be a boolean");let s=H(i?.maxAttempts,5,"MCP recovery maxAttempts",0,20),e=H(i?.initialDelayMs,1000,"MCP recovery initialDelayMs",10,300000),r=H(i?.maxDelayMs,30000,"MCP recovery maxDelayMs",e,300000),o=yi(i?.jitterRatio,0.2,"MCP recovery jitterRatio",0,1),c=H(i?.terminalErrorThreshold,3,"MCP recovery terminalErrorThreshold",1,10);return{enabled:n,maxAttempts:s,initialDelayMs:e,maxDelayMs:r,jitterRatio:o,terminalErrorThreshold:c}}function fi(t,i,n=Math.random){let s=Math.max(0,i-1),e=Math.min(t.initialDelayMs*2**s,t.maxDelayMs);if(t.jitterRatio===0)return e;let r=Math.min(1,Math.max(0,n())),o=1-t.jitterRatio+2*t.jitterRatio*r;return Math.max(0,Math.round(e*o))}function k(t){let n=(t instanceof Error?t.message:String(t)).replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]").replace(/[\r\n\t]+/g," ").trim();if(Buffer.byteLength(n)<=512)return n;let s=Buffer.from(n).subarray(0,512).toString("utf8");while(Buffer.byteLength(s)>512)s=s.slice(0,-1);return s}function Ei(t){let n=(t instanceof Error?t.message:String(t)).toLowerCase();return(n.includes("404")||n.includes("-32001"))&&(n.includes("session")||n.includes("not found"))}function bi(t){let n=(t instanceof Error?t.message:String(t)).toLowerCase();return["econnreset","etimedout","epipe","ehostunreach","econnrefused","body timeout error","socket hang up","connection closed","connection terminated","sse stream disconnected","failed to reconnect sse stream","maximum reconnection attempts"].some((s)=>n.includes(s))}function C(t){return new DOMException(String(t||"MCP connection recovery cancelled"),"AbortError")}async function Rt(t,i,n=!0){if(i.aborted)throw C(i.reason);await new Promise((s,e)=>{let o=setTimeout(()=>{i.removeEventListener("abort",c),s()},t);if(n)o.unref();let c=()=>{clearTimeout(o),i.removeEventListener("abort",c),e(C(i.reason))};i.addEventListener("abort",c,{once:!0})})}import{createHash as ai}from"node:crypto";var Pt=100,q=1000,K=1000,W=1000,at=100,hi=64,Z=1048576,_=4194304,A=256,N=8192,x=256,m=16384,Ai=64,Gn=4096,_i=4194304,Ri=128;function $i(t){return[...t].some((i)=>{let n=i.charCodeAt(0);return n<=31||n===127})}function Hn(t){return[...t].some((i)=>{let n=i.charCodeAt(0);return n===0||n>=1&&n<=8||n===11||n===12||n>=14&&n<=31||n===127})}function E(t,i,n){if(t===void 0)return;if(i==="description"?Hn(t):$i(t))throw Error(`MCP ${i} contains control characters`);if(Buffer.byteLength(t)>n)throw Error(`MCP ${i} exceeds ${n} bytes`);return t}function b(t,i,n){let s=t.trim();if(!s||s.length>n||$i(s))throw Error(`MCP ${i} is invalid`);return s}function $t(t){return Buffer.byteLength(JSON.stringify(t))}function Ct(t,i){if($t(t)>_i)throw Error(`MCP ${i} catalog exceeds ${_i} bytes`)}function Q(t,i){let n=new Set;for(let s of t){if(n.has(s))throw Error(`MCP ${i} catalog contains duplicate "${s}"`);n.add(s)}}function Ci(t){if(t.length>q)throw Error(`MCP resource catalog exceeds ${q} entries`);let i=t.map((n)=>({uri:b(n.uri,"resource URI",N),name:b(n.name,"resource name",A),...E(n.title,"resource title",A)?{title:n.title}:{},...E(n.description,"description",m)?{description:n.description}:{},...E(n.mimeType,"resource MIME type",x)?{mimeType:n.mimeType}:{},...n.size!==void 0&&Number.isSafeInteger(n.size)&&n.size>=0?{size:n.size}:{}}));return Q(i.map((n)=>n.uri),"resource"),Ct(i,"resource"),i}function ki(t){if(t.length>K)throw Error(`MCP resource template catalog exceeds ${K} entries`);let i=t.map((n)=>({uriTemplate:b(n.uriTemplate,"resource template URI",N),name:b(n.name,"resource template name",A),...E(n.title,"resource template title",A)?{title:n.title}:{},...E(n.description,"description",m)?{description:n.description}:{},...E(n.mimeType,"resource template MIME type",x)?{mimeType:n.mimeType}:{}}));return Q(i.map((n)=>n.uriTemplate),"resource template"),Ct(i,"resource template"),i}function Oi(t){if(t.length>W)throw Error(`MCP prompt catalog exceeds ${W} entries`);let i=t.map((n)=>{if((n.arguments?.length??0)>Ai)throw Error(`MCP prompt "${n.name}" exceeds ${Ai} arguments`);let s=(n.arguments??[]).map((e)=>{let r=b(e.name,"prompt argument name",A);if(["__proto__","constructor","prototype"].includes(r))throw Error(`MCP prompt argument name "${r}" is unsafe`);return{name:r,...E(e.description,"description",Gn)?{description:e.description}:{},required:e.required===!0}});return Q(s.map((e)=>e.name),`prompt "${n.name}" argument`),{name:b(n.name,"prompt name",A),...E(n.title,"prompt title",A)?{title:n.title}:{},...E(n.description,"description",m)?{description:n.description}:{},arguments:s}});return Q(i.map((n)=>n.name),"prompt"),Ct(i,"prompt"),i}function Pi(t){return ai("sha256").update(JSON.stringify(t)).digest("hex")}function I(t,i,n){let s=new Map(t.map((r)=>[n(r),Pi(r)])),e=new Map(i.map((r)=>[n(r),Pi(r)]));return{added:[...e.keys()].filter((r)=>!s.has(r)).sort(),removed:[...s.keys()].filter((r)=>!e.has(r)).sort(),updated:[...e.keys()].filter((r)=>s.has(r)&&s.get(r)!==e.get(r)).sort()}}function Li(t){return t.added.length>0||t.removed.length>0||t.updated.length>0}function kt(t,i,n){if(t.bytes+=i,t.bytes>_)throw Error(`MCP ${n} exceeds ${_} total bytes`)}function Si(t,i,n){if(t.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw Error(`MCP ${i} contains invalid base64`);let s=Buffer.from(t,"base64");if(s.length>_)throw Error(`MCP ${i} exceeds ${_} decoded bytes`);return kt(n,s.length,i),{size:s.length,sha256:ai("sha256").update(s).digest("hex"),omitted:!0}}function gi(t,i){let n=b(typeof t.uri==="string"?t.uri:"","resource content URI",N),s=typeof t.mimeType==="string"?E(t.mimeType,"resource MIME type",x):void 0;if(typeof t.text==="string"){let e=Buffer.byteLength(t.text);if(e>Z)throw Error(`MCP resource text exceeds ${Z} bytes`);return kt(i,e,"resource result"),{uri:n,...s?{mimeType:s}:{},text:t.text}}if(typeof t.blob==="string")return{uri:n,...s?{mimeType:s}:{},binary:Si(t.blob,"resource blob",i)};throw Error("MCP resource content has neither text nor blob data")}function xi(t){let i=t&&typeof t==="object"&&Array.isArray(t.contents)?t.contents:[];if(i.length>hi)throw Error(`MCP resource result exceeds ${hi} contents`);let n={bytes:0},s=i.map((e)=>{if(!e||typeof e!=="object"||Array.isArray(e))throw Error("MCP resource content is malformed");return gi(e,n)});if($t(s)>_)throw Error(`MCP resource result exceeds ${_} bytes`);return{contents:s}}function mi(t){if(!t||typeof t!=="object"||Array.isArray(t))throw Error("MCP prompt result is malformed");let i=t,n=Array.isArray(i.messages)?i.messages:[];if(n.length>Ri)throw Error(`MCP prompt exceeds ${Ri} messages`);let s={bytes:0},e=n.map((r)=>{if(!r||typeof r!=="object"||Array.isArray(r))throw Error("MCP prompt message is malformed");let o=r,c=o.role;if(c!=="user"&&c!=="assistant")throw Error("MCP prompt message has an invalid role");let d=o.content;if(!d||typeof d!=="object"||Array.isArray(d))throw Error("MCP prompt message content is malformed");let p=d;if(p.type==="text"&&typeof p.text==="string"){let u=Buffer.byteLength(p.text);if(u>Z)throw Error(`MCP prompt text exceeds ${Z} bytes`);return kt(s,u,"prompt result"),{role:c,content:{type:"text",text:p.text}}}if((p.type==="image"||p.type==="audio")&&typeof p.data==="string"&&typeof p.mimeType==="string")return{role:c,content:{type:p.type,mimeType:b(p.mimeType,"prompt content MIME type",x),binary:Si(p.data,`prompt ${p.type}`,s)}};if(p.type==="resource"&&p.resource&&typeof p.resource==="object"&&!Array.isArray(p.resource))return{role:c,content:{type:"resource",resource:gi(p.resource,s)}};if(p.type==="resource_link"&&typeof p.uri==="string"&&typeof p.name==="string")return{role:c,content:{type:"resource_link",uri:b(p.uri,"prompt resource link URI",N),name:b(p.name,"prompt resource link name",A),...typeof p.mimeType==="string"?{mimeType:b(p.mimeType,"prompt resource link MIME type",x)}:{},...typeof p.description==="string"?{description:E(p.description,"description",m)}:{}}};throw Error(`Unsupported MCP prompt content type: ${String(p.type)}`)});if($t(e)>_)throw Error(`MCP prompt result exceeds ${_} bytes`);return{...typeof i.description==="string"?{description:E(i.description,"description",m)}:{},messages:e}}var li=4000,Ui=4096,Bi=32,qn=128,Xi=1000,zi=100,Yi=65536,Kn=new Set(["__proto__","constructor","prototype"]);function Di(t,i){if(!t.trim())throw Error("MCP elicitation server name is empty");if(!i.message.trim())throw Error("MCP elicitation message is empty");if(i.message.length>li)throw Error(`MCP elicitation message exceeds ${li} characters`);if(i.mode==="url"){let e=Nn(i.url);if(!i.elicitationId.trim())throw Error("MCP URL elicitation ID is empty");return{serverName:t,mode:"url",message:i.message,url:e.toString(),domain:e.hostname,elicitationId:i.elicitationId}}let n=Object.entries(i.requestedSchema.properties);if(n.length>Bi)throw Error(`MCP elicitation exceeds the ${Bi} field limit`);let s=new Set(i.requestedSchema.required??[]);for(let e of s)if(!Object.hasOwn(i.requestedSchema.properties,e))throw Error(`MCP elicitation requires an unknown field: ${e}`);return{serverName:t,mode:"form",message:i.message,fields:n.map(([e,r])=>Wn(e,r,s.has(e))),requestedSchema:structuredClone(i.requestedSchema)}}function vs(t){let i=Object.create(null);for(let n of t.fields??[])if(n.defaultValue!==void 0)i[n.name]=Array.isArray(n.defaultValue)?[...n.defaultValue]:n.defaultValue;return i}function te(t,i){let n=i.trim();if(!n){if(t.defaultValue!==void 0)return t.defaultValue;if(!t.required)return;throw Error(`${t.title} is required`)}if(t.type==="number"||t.type==="integer"){let s=Number(n);if(!Number.isFinite(s))throw Error(`${t.title} must be a finite number`);if(t.type==="integer"&&!Number.isSafeInteger(s))throw Error(`${t.title} must be a safe integer`);return s}if(t.type==="boolean"){if(["true","yes","y","1"].includes(n.toLowerCase()))return!0;if(["false","no","n","0"].includes(n.toLowerCase()))return!1;throw Error(`${t.title} must be true or false`)}return n}function Fi(t,i){if(i.action!=="accept")return{action:i.action};if(t.mode==="url")return{action:"accept"};if(!t.requestedSchema)throw Error("MCP form elicitation schema is unavailable");let n=i.content??{};if(Buffer.byteLength(JSON.stringify(n),"utf8")>Yi)throw Error(`MCP elicitation response exceeds ${Yi} bytes`);for(let r of Object.keys(n))Ji(r);for(let r of Object.values(n))if(typeof r==="number"&&(!Number.isFinite(r)||Number.isInteger(r)&&!Number.isSafeInteger(r)))throw Error("MCP elicitation response contains an unsafe number");let s=g.Unsafe({...t.requestedSchema,additionalProperties:!1}),e=X(s,n);if(!e.success)throw Error(`Invalid MCP elicitation response: ${e.error.message}`);return{action:"accept",content:e.data}}function Wn(t,i,n){Ji(t);let s=tt(i.title?.trim()||t,"field title"),e=i.description?tt(i.description,"field description"):void 0,r={name:t,title:s,description:e,required:n};if(i.type==="boolean")return{...r,type:"boolean",...typeof i.default==="boolean"?{defaultValue:i.default}:{}};if(i.type==="number"||i.type==="integer")return{...r,type:i.type,...typeof i.default==="number"?{defaultValue:i.default}:{},...i.minimum!==void 0?{minimum:i.minimum}:{},...i.maximum!==void 0?{maximum:i.maximum}:{}};if(i.type==="array"){let c=Qn(i);return{...r,type:"multi-select",options:c,...Array.isArray(i.default)&&i.default.every((d)=>typeof d==="string")?{defaultValue:[...i.default]}:{},...i.minItems!==void 0?{minItems:i.minItems}:{},...i.maxItems!==void 0?{maxItems:i.maxItems}:{}}}let o=Zn(i);if(o)return{...r,type:"select",options:o,...typeof i.default==="string"?{defaultValue:i.default}:{}};return{...r,type:"string",...typeof i.default==="string"?{defaultValue:i.default}:{},...i.format?{format:i.format}:{},...i.minLength!==void 0?{minLength:i.minLength}:{},...i.maxLength!==void 0?{maxLength:i.maxLength}:{}}}function Zn(t){if(t.oneOf)return v(t.oneOf.map((i)=>({value:i.const,label:i.title})));if(!t.enum)return;return v(t.enum.map((i,n)=>({value:i,label:t.enumNames?.[n]??i})))}function Qn(t){if(t.items?.anyOf)return v(t.items.anyOf.map((i)=>({value:i.const,label:i.title})));if(t.items?.enum)return v(t.items.enum.map((i)=>({value:i,label:i})));throw Error("MCP multi-select elicitation is missing enum options")}function v(t){if(t.length===0||t.length>zi)throw Error(`MCP elicitation options must contain 1-${zi} items`);let i=new Set;return t.map((n)=>{if(i.has(n.value))throw Error(`MCP elicitation contains duplicate option: ${n.value}`);return i.add(n.value),{value:tt(n.value,"option value"),label:tt(n.label,"option label")}})}function Ji(t){if(!t||t.length>qn||Kn.has(t))throw Error(`Unsafe MCP elicitation field name: ${t||"(empty)"}`)}function tt(t,i){if(t.length>Xi)throw Error(`MCP elicitation ${i} exceeds ${Xi} characters`);return t}function Nn(t){if(t.length>Ui)throw Error(`MCP elicitation URL exceeds ${Ui} characters`);let i;try{i=new URL(t)}catch{throw Error("MCP elicitation URL is invalid")}if(!["http:","https:"].includes(i.protocol))throw Error(`MCP elicitation URL protocol is not allowed: ${i.protocol}`);if(i.username||i.password)throw Error("MCP elicitation URL must not contain credentials");return i}import{createHash as Ki}from"node:crypto";var l=1000,it=100,In=256,Vi=16384,ji=262144,Gi=4194304,Hi=24;function vn(t,i=10){return Ki("sha256").update(t).digest("hex").slice(0,i)}function Ot(t){if(Array.isArray(t))return t.map(Ot);if(!t||typeof t!=="object")return t;let i=t;return Object.fromEntries(Object.keys(i).sort().map((n)=>[n,Ot(i[n])]))}function Wi(t){let i=t.normalize("NFKC"),n=i.replace(/[^A-Za-z0-9_-]/g,"_");if(n&&n===i&&n.length<=Hi)return n;return`${(n||"unnamed").slice(0,Hi-11)}_${vn(i)}`}function Lt(t,i){return`${ts(t)}${Wi(i)}`}function ts(t){return`mcp__${Wi(t)}__`}function qi(t){return Ki("sha256").update(JSON.stringify(Ot({name:t.name,description:t.description,inputSchema:t.inputSchema,taskSupport:t.taskSupport}))).digest("hex")}function is(t){return[...t].some((i)=>{let n=i.charCodeAt(0);return n<=31||n===127})}function Zi(t){if(t.length>l)throw Error(`MCP tool catalog exceeds ${l} tools`);let i=new Set,n=[],s=0;for(let e of t){let r=e.name.trim();if(!r||r.length>In||is(r))throw Error("MCP tool catalog contains an invalid tool name");if(i.has(r))throw Error(`MCP tool catalog contains duplicate tool "${r}"`);i.add(r);let o=e.description??"";if(Buffer.byteLength(o)>Vi)throw Error(`MCP tool "${r}" description exceeds ${Vi} bytes`);let c=JSON.stringify(e.inputSchema),d=Buffer.byteLength(c);if(d>ji)throw Error(`MCP tool "${r}" schema exceeds ${ji} bytes`);if(s+=Buffer.byteLength(r)+Buffer.byteLength(o)+d,s>Gi)throw Error(`MCP tool catalog exceeds ${Gi} bytes`);n.push({name:r,description:o,inputSchema:JSON.parse(c),...e.execution?.taskSupport?{taskSupport:e.execution.taskSupport}:{}})}return n}function Qi(t,i){let n=new Map(t.map((e)=>[e.name,qi(e)])),s=new Map(i.map((e)=>[e.name,qi(e)]));return{added:[...s.keys()].filter((e)=>!n.has(e)).sort(),removed:[...n.keys()].filter((e)=>!s.has(e)).sort(),updated:[...s.keys()].filter((e)=>n.has(e)&&n.get(e)!==s.get(e)).sort()}}function nt(t){return t.added.length>0||t.removed.length>0||t.updated.length>0}function Ii(t){if(t instanceof zt||t instanceof U)return{type:"auth_error",isRetryable:!1,originalError:t};if(!(t instanceof Error))return{type:"unknown",isRetryable:!1,originalError:Error(String(t))};let i=t.message.toLowerCase();if(["command not found","no such file","permission denied","invalid configuration","malformed","syntax error"].some((e)=>i.includes(e)))return{type:"config_error",isRetryable:!1,originalError:t};if(i.includes("unauthorized")||i.includes("401")||i.includes("authentication failed"))return{type:"auth_error",isRetryable:!1,originalError:t};if(["timeout","connection refused","network error","temporary","try again","rate limit","too many requests","service unavailable","socket hang up","econnreset","enotfound","econnrefused","etimedout","503","429"].some((e)=>i.includes(e)))return{type:"network_temporary",isRetryable:!0,originalError:t};return{type:"unknown",isRetryable:!0,originalError:t}}class Yt extends fs{config;runtimeOptions;status="disconnected";sdkClient=null;tools=new Map;toolCatalogRevision=0;toolRefreshPromise;toolRefreshRequested=!1;resources=[];resourceTemplates=[];prompts=[];contentCatalogRevision=0;contentRefreshPromise;requestedContentCatalogs=new Set;contentRefreshReason="manual";catalogGeneration=0;desiredResourceSubscriptions=new Set;activeResourceSubscriptions=new Set;serverInfo=null;serverInstructions;completionCallsInFlight=0;loggingPolicy;logWindowStartedAt=0;logEventsInWindow=0;logRateWarningEmitted=!1;recoveryPolicy;desiredConnected=!1;connectionGeneration=0;connectPromise;connectAbortController;recoveryPromise;recoveryAbortController;recoveryState;consecutiveTerminalErrors=0;oauthProvider=null;serverName;healthMonitor=null;activeInteraction;taskInteractions=new Map;taskPolicy;roots;constructor(t,i,n,s={}){super();this.config=t;this.runtimeOptions=s;this.serverName=i||"default",this.recoveryPolicy=Ti(t),this.loggingPolicy=dn(t),this.taskPolicy=wn(t.tasks),this.roots=(s.roots??[]).map((r)=>{let o=ss.native(Ni.resolve(r));return{uri:es(o).href,name:Ni.basename(o)||o}});let e=vi(t);if(this.config={...t,...e?{oauth:e}:{}},e?.enabled&&t.url&&s.oauthCredentialAccess!==!1)this.oauthProvider=new en(this.serverName,t.url,e,s.oauthStorageRoot?{tokenStorage:new sn(s.oauthStorageRoot)}:{});if(n?.enabled)this.healthMonitor=new Et(this,n),this.healthMonitor.on("unhealthy",(r,o)=>{this.emit("unhealthy",r,o)})}get connectionStatus(){return this.status}get availableTools(){return Array.from(this.tools.values())}get contentCatalog(){return{resources:structuredClone(this.resources),resourceTemplates:structuredClone(this.resourceTemplates),prompts:structuredClone(this.prompts)}}get completionSupported(){return Boolean(this.sdkClient?.getServerCapabilities()?.completions)}get tasks(){return{...this.taskPolicy}}get server(){return this.serverInfo}get instructions(){return this.serverInstructions?structuredClone(this.serverInstructions):void 0}get healthCheck(){return this.healthMonitor}get recovery(){return this.recoveryState?structuredClone(this.recoveryState):void 0}get logging(){return{...this.loggingPolicy}}get oauthEnabled(){return this.config.oauth?.enabled===!0}async getOAuthStatus(){if(!this.oauthEnabled)return"disabled";if(this.runtimeOptions.oauthCredentialAccess===!1)return"unavailable";return this.oauthProvider?.getStatus()??"error"}async beginOAuthLogin(t={}){if(!this.oauthEnabled)throw Error(`MCP server "${this.serverName}" does not enable OAuth`);if(this.runtimeOptions.oauthCredentialAccess===!1||!this.oauthProvider)throw new U(this.serverName);return t.openBrowser?this.oauthProvider.openAuthorization():this.oauthProvider.beginAuthorization()}async logoutOAuth(){if(!this.oauthEnabled)throw Error(`MCP server "${this.serverName}" does not enable OAuth`);if(this.runtimeOptions.oauthCredentialAccess===!1||!this.oauthProvider)throw new U(this.serverName);if(this.status!=="disconnected")await this.disconnect();await this.oauthProvider.logout()}async connect(){return this.connectWithRetry(3,1000)}async connectWithRetry(t=3,i=1000){if(!Number.isInteger(t)||t<1||t>At)throw Error(`MCP connection maxRetries must be an integer between 1 and ${At}`);if(!Number.isFinite(i)||i<0||i>_t)throw Error(`MCP connection initialDelay must be between 0 and ${_t}`);if(this.status==="connected")return;if(this.recoveryPromise)return this.recoveryPromise;if(this.connectPromise)return this.connectPromise;this.desiredConnected=!0;let n=++this.connectionGeneration,s=new AbortController;this.connectAbortController=s;let e=this.runInitialConnection(Math.max(1,t),Math.max(0,i),n,s.signal).finally(()=>{if(this.connectPromise===e)this.connectPromise=void 0;if(this.connectAbortController===s)this.connectAbortController=void 0});return this.connectPromise=e,e}async runInitialConnection(t,i,n,s){let e;for(let o=1;o<=t;o++){this.assertConnectionGeneration(n,s);try{await this.doConnect(n,!1);return}catch(c){if(!this.isConnectionGenerationCurrent(n)||s.aborted)throw C(s.reason);if(e=c instanceof Error?c:Error(String(c)),!Ii(e).isRetryable||o===t)break;await Rt(i*2**Math.max(0,o-1),s,!1)}}let r=e??Error("MCP connection failed");if(this.isConnectionGenerationCurrent(n))this.invalidateLiveConnection(!1),this.setStatus("error"),this.emitClientError(r);throw r}async doConnect(t,i){let n;try{this.assertConnectionGeneration(t),this.setStatus(i?"reconnecting":"connecting");let s=un(this.config.sampling),e={...s,enabled:s.enabled&&this.runtimeOptions.samplingAvailable===!0};n=new rs({name:nn(),version:tn()},{capabilities:{roots:{listChanged:!1},elicitation:{form:{applyDefaults:!1},url:{}},...e.enabled?{sampling:{}}:{}},listChanged:{tools:{autoRefresh:!1,debounceMs:0,onChanged:()=>{this.refreshTools("notification")}},resources:{autoRefresh:!1,debounceMs:0,onChanged:()=>{this.refreshContentCatalogs("notification",["resources"])}},prompts:{autoRefresh:!1,debounceMs:0,onChanged:()=>{this.refreshContentCatalogs("notification",["prompts"])}}}});let r=n;if(this.sdkClient=r,this.resetCatalogRefreshState(),this.registerElicitationHandlers(r),this.registerRootHandler(r),e.enabled)this.registerSamplingHandler(r,e);if(this.registerResourceNotificationHandler(r),this.registerLoggingHandler(r),this.taskPolicy.enabled)this.registerTaskStatusHandler(r);r.onclose=()=>{this.handleUnexpectedClose(r,t)},r.onerror=(d)=>{this.handleTransportError(r,t,d)};let o=await this.createTransport();this.assertConnectionGeneration(t),await r.connect(o),this.assertConnectionGeneration(t);let c=r.getServerVersion();this.serverInfo={name:c?.name||"Unknown",version:c?.version||"0.0.0"},this.serverInstructions=yn(r.getInstructions(),{exposeDetails:this.runtimeOptions.exposeInstructions}),await this.configureLogging(r),await this.refreshTools("initial"),await this.refreshContentCatalogs("initial").catch(()=>{return}),await this.reconcileResourceSubscriptions(r),this.assertConnectionGeneration(t),this.consecutiveTerminalErrors=0,this.setStatus("connected"),this.emit("connected",this.serverInfo),this.healthMonitor?.resetFailureCount(),this.healthMonitor?.start()}catch(s){if(n&&this.sdkClient===n)this.sdkClient=null;if(n)n.onclose=void 0,n.onerror=void 0,await n.close().catch(()=>{return});throw s}}handleUnexpectedClose(t,i){if(this.sdkClient!==t||!this.isConnectionGenerationCurrent(i)||this.status!=="connected")return;this.startRecovery(Error(`MCP server "${this.serverName}" connection closed`),"transport_closed",!1)}handleTransportError(t,i,n){if(this.sdkClient!==t||!this.isConnectionGenerationCurrent(i)||this.status!=="connected")return;if(this.emit("transportError",{serverName:this.serverName,error:k(n)}),Ei(n)){this.startRecovery(n,"session_expired",!0);return}if(!bi(n)){this.consecutiveTerminalErrors=0;return}if(this.consecutiveTerminalErrors++,n.message.toLowerCase().includes("maximum reconnection attempts")||this.consecutiveTerminalErrors>=this.recoveryPolicy.terminalErrorThreshold)this.startRecovery(n,"transport_error",!0)}requestRecovery(t,i){if(!this.desiredConnected||this.status!=="connected"||this.recoveryPromise)return;this.startRecovery(t,i,!0)}startRecovery(t,i,n){if(!this.desiredConnected||this.recoveryPromise)return;let s=this.sdkClient;if(this.sdkClient=null,s)s.onclose=void 0,s.onerror=void 0;this.healthMonitor?.stop(),this.invalidateLiveConnection(!0);let e=++this.connectionGeneration,r=new AbortController;if(this.recoveryAbortController=r,this.setStatus("reconnecting"),n&&s)s.close().catch(()=>{return});let o=Promise.resolve().then(()=>this.runRecoveryLoop(t,i,e,r.signal)).finally(()=>{if(this.recoveryPromise===o)this.recoveryPromise=void 0;if(this.recoveryAbortController===r)this.recoveryAbortController=void 0});this.recoveryPromise=o,o.catch(()=>{return})}async runRecoveryLoop(t,i,n,s){let e=t;if(!this.recoveryPolicy.enabled||this.recoveryPolicy.maxAttempts===0){this.failRecovery(e,i,0,n);return}for(let r=1;r<=this.recoveryPolicy.maxAttempts;r++){this.assertConnectionGeneration(n,s);let o=fi(this.recoveryPolicy,r,this.runtimeOptions.recoveryRandom),c=Date.now()+o;this.publishConnectionLifecycle({phase:"reconnecting",reason:i,attempt:r,maxAttempts:this.recoveryPolicy.maxAttempts,nextRetryAt:c,error:k(e)}),await Rt(o,s),this.assertConnectionGeneration(n,s);try{await this.doConnect(n,!0),this.healthMonitor?.resetFailureCount(),this.publishConnectionLifecycle({phase:"recovered",reason:i,attempt:r,maxAttempts:this.recoveryPolicy.maxAttempts}),this.emit("reconnected");return}catch(d){if(!this.isConnectionGenerationCurrent(n)||s.aborted)throw C(s.reason);if(e=d instanceof Error?d:Error(String(d)),!Ii(e).isRetryable){this.failRecovery(e,i,r,n);return}}}this.failRecovery(e,i,this.recoveryPolicy.maxAttempts,n)}failRecovery(t,i,n,s){if(!this.isConnectionGenerationCurrent(s))return;this.setStatus("error"),this.publishConnectionLifecycle({phase:"failed",reason:i,attempt:n,maxAttempts:this.recoveryPolicy.maxAttempts,error:k(t)}),this.emit("reconnectFailed",t)}publishConnectionLifecycle(t){this.recoveryState=structuredClone(t),this.emit("connectionLifecycleChanged",structuredClone(t))}isConnectionGenerationCurrent(t){return this.desiredConnected&&this.connectionGeneration===t}assertConnectionGeneration(t,i){if(i?.aborted||!this.desiredConnected||this.connectionGeneration!==t)throw C(i?.reason)}invalidateLiveConnection(t){if(this.resetCatalogRefreshState(),this.tools.clear(),this.resources=[],this.resourceTemplates=[],this.prompts=[],this.activeResourceSubscriptions.clear(),!t)this.desiredResourceSubscriptions.clear();if(!t)this.taskInteractions.clear();this.serverInfo=null,this.serverInstructions=void 0,this.consecutiveTerminalErrors=0}resetCatalogRefreshState(){this.catalogGeneration++,this.toolRefreshPromise=void 0,this.toolRefreshRequested=!1,this.contentRefreshPromise=void 0,this.requestedContentCatalogs.clear(),this.contentRefreshReason="manual"}emitClientError(t){if(this.listenerCount("error")>0)this.emit("error",t)}async ping(t=1e4){let i=this.sdkClient;if(!i||this.status!=="connected")throw Error(`MCP server "${this.serverName}" is not connected`);let n=new AbortController,s=setTimeout(()=>n.abort("MCP health check timeout"),t);s.unref();try{await i.ping({signal:n.signal,timeout:t,maxTotalTimeout:t})}catch(e){if(n.signal.aborted)throw Error(`MCP server "${this.serverName}" health check timed out after ${t}ms`);throw e}finally{clearTimeout(s)}}async disconnect(){this.desiredConnected=!1,this.connectionGeneration++,this.connectAbortController?.abort("MCP client disconnected"),this.recoveryAbortController?.abort("MCP client disconnected"),this.healthMonitor?.stop();let t=this.sdkClient;if(this.sdkClient=null,t)t.onclose=void 0,t.onerror=void 0,await t.close().catch(()=>{return});await Promise.allSettled([this.connectPromise,this.recoveryPromise].filter((i)=>i!==void 0)),this.invalidateLiveConnection(!1),this.recoveryState=void 0,await this.oauthProvider?.dispose(),this.setStatus("disconnected"),this.emit("disconnected")}async callTool(t,i={},n={}){let s=this.sdkClient;if(!s||this.status!=="connected")throw Error("客户端未连接到服务器");if(!this.tools.has(t))throw Error(`工具 "${t}" 不存在`);if(this.activeInteraction)throw Error(`MCP server "${this.serverName}" does not allow overlapping interactive tool calls`);let e=xt(this.config),r=Symbol(t);this.activeInteraction={token:r,context:n,samplingRequests:0,samplingInFlight:!1};let o=new AbortController,c=setTimeout(()=>o.abort("mcp-tool-timeout"),e.totalTimeoutMs);c.unref();let d=n.signal?AbortSignal.any([n.signal,o.signal]):o.signal,p={count:0};try{return await s.callTool({name:t,arguments:i},St,{signal:d,timeout:e.idleTimeoutMs,resetTimeoutOnProgress:!0,maxTotalTimeout:e.totalTimeoutMs,onprogress:(M)=>{let w=mt(M,p,e);if(w&&!d.aborted&&this.activeInteraction?.token===r)n.progressHandler?.(w),this.emit("toolProgress",{serverName:this.serverName,toolName:t,...w})}})}catch(u){if(n.signal?.aborted)throw new DOMException(String(n.signal.reason||"MCP tool call cancelled"),"AbortError");if(o.signal.aborted&&!n.signal?.aborted)throw new P(R.RequestTimeout,`MCP server "${this.serverName}" tool "${t}" timed out after ${e.totalTimeoutMs}ms`);throw console.error(`[McpClient] 调用工具 "${t}" 失败:`,u),u}finally{if(clearTimeout(c),this.activeInteraction?.token===r)this.activeInteraction=void 0}}getToolTaskSupport(t){return this.tools.get(t)?.taskSupport}async createToolTask(t,i,n,s,e){let r=this.sdkClient;if(!r||this.status!=="connected")throw Error("MCP client is not connected");if(!this.taskPolicy.enabled)throw Error(`MCP tasks are disabled for server "${this.serverName}"`);if(!r.getServerCapabilities()?.tasks?.requests?.tools?.call)throw Error(`MCP server "${this.serverName}" does not support task-augmented tools/call`);let o=this.getToolTaskSupport(t);if(o!=="required"&&o!=="optional")throw Error(`MCP tool "${t}" does not support task execution`);if(this.activeInteraction)throw Error(`MCP server "${this.serverName}" does not allow overlapping interactive task creation`);let c=xt(this.config),d=Symbol(t),p={token:d,context:{...n,signal:s},samplingRequests:0,samplingInFlight:!1};this.activeInteraction=p;let u={count:0},M=r.experimental.tasks.callToolStream({name:t,arguments:i},St,{signal:s,task:{ttl:e??this.taskPolicy.defaultTtlMs,pollInterval:this.taskPolicy.pollIntervalMs},timeout:c.idleTimeoutMs,maxTotalTimeout:c.totalTimeoutMs,resetTimeoutOnProgress:!0,onprogress:(y)=>{let f=mt(y,u,c);if(f&&!s.aborted&&this.hasInteractionToken(d))n.progressHandler?.(f),this.emit("toolProgress",{serverName:this.serverName,toolName:t,...f})}}),w=!1;try{let y=await M.next();if(await M.return(void 0),y.done||y.value.type!=="taskCreated"){if(!y.done&&y.value.type==="error")throw y.value.error;throw Error(`MCP tool "${t}" did not create a task`)}if(this.sdkClient!==r)throw Error("MCP client changed while creating a task");let f=Ut(y.value.task,this.taskPolicy);return this.taskInteractions.set(f.taskId,p),w=!0,this.emit("taskCreated",{serverName:this.serverName,toolName:t,task:f}),f}finally{if(this.activeInteraction?.token===d)this.activeInteraction=void 0;if(!w){for(let[y,f]of this.taskInteractions)if(f.token===d)this.taskInteractions.delete(y)}}}async getToolTask(t,i,n){let s=this.requireTaskClient(),e=await s.experimental.tasks.getTask(t,{signal:n,timeout:this.taskPolicy.pollIntervalMs+1e4,maxTotalTimeout:this.taskPolicy.pollIntervalMs+1e4});if(this.sdkClient!==s)throw Error("MCP client changed while reading a task");return Ut(e,this.taskPolicy,{taskId:t,createdAt:i})}async getToolTaskResult(t,i,n=this.taskPolicy.maxLifetimeMs){let s=this.requireTaskClient(),e=Math.max(1,Math.min(n,this.taskPolicy.maxLifetimeMs)),r=await s.experimental.tasks.getTaskResult(t,St,{signal:i,timeout:e,maxTotalTimeout:e});if(this.sdkClient!==s)throw Error("MCP client changed while reading a task result");return r}async cancelToolTask(t,i){let n=this.requireTaskClient();if(!n.getServerCapabilities()?.tasks?.cancel)throw Error(`MCP server "${this.serverName}" does not support task cancellation`);if(await n.experimental.tasks.cancelTask(t,{signal:i,timeout:15000,maxTotalTimeout:15000}),this.sdkClient!==n)throw Error("MCP client changed while cancelling a task")}async normalizeToolTaskResult(t){return j(t,this.runtimeOptions.artifactWriter)}releaseTaskInteraction(t){this.taskInteractions.delete(t)}async waitUntilConnected(t,i){if(this.status==="connected"&&this.sdkClient)return;if(!this.desiredConnected)throw Error(`MCP server "${this.serverName}" is disconnected`);await new Promise((n,s)=>{let e=setTimeout(()=>{d(),s(Error(`MCP server "${this.serverName}" recovery timed out`))},i);e.unref();let r=()=>{d(),n()},o=()=>{if(this.desiredConnected)return;d(),s(Error(`MCP server "${this.serverName}" was disconnected`))},c=()=>{d(),s(new DOMException(String(t.reason||"MCP task recovery cancelled"),"AbortError"))},d=()=>{clearTimeout(e),this.off("connected",r),this.off("disconnected",o),t.removeEventListener("abort",c)};if(this.on("connected",r),this.on("disconnected",o),t.addEventListener("abort",c,{once:!0}),t.aborted)c()})}requireTaskClient(){let t=this.sdkClient;if(!t||this.status!=="connected"||!this.taskPolicy.enabled)throw Error(`MCP server "${this.serverName}" task client is unavailable`);if(!t.getServerCapabilities()?.tasks?.requests?.tools?.call)throw Error(`MCP server "${this.serverName}" does not support task-augmented tools/call`);return t}hasInteractionToken(t){if(this.activeInteraction?.token===t)return!0;return[...this.taskInteractions.values()].some((i)=>i.token===t)}registerRootHandler(t){t.setRequestHandler(Ms,async()=>({roots:this.roots.map((i)=>({...i}))}))}resolveInteraction(t){let i=t._meta?.["io.modelcontextprotocol/related-task"]?.taskId;return i?this.taskInteractions.get(i):this.activeInteraction}registerTaskStatusHandler(t){t.setNotificationHandler(Ts,(i)=>{this.emit("taskStatus",i.params)})}registerSamplingHandler(t,i){t.setRequestHandler(ps,async(n,s)=>{let e=this.resolveInteraction(n.params);if(!e?.context.confirmationHandler||!e.context.samplingHandler)throw new P(R.InvalidRequest,"MCP sampling requires an active interactive Session");if(e.samplingInFlight)throw new P(R.InvalidRequest,"MCP server does not allow overlapping sampling requests");e.samplingInFlight=!0;try{if(e.samplingRequests++,e.samplingRequests>i.maxRequestsPerToolCall)throw new P(R.InvalidRequest,`MCP sampling exceeded ${i.maxRequestsPerToolCall} requests for one tool call`);let r=e.context.signal?AbortSignal.any([e.context.signal,s.signal]):s.signal;if(r.aborted)throw new P(R.InvalidRequest,"MCP sampling was cancelled");let o;try{o=Mn(n.params,i)}catch(p){throw new P(R.InvalidRequest,p instanceof Error?p.message:String(p))}let c=await e.context.confirmationHandler.requestConfirmation({type:"mcpSampling",kind:"execute",toolName:`MCP sampling: ${this.serverName}`,title:"MCP model sampling request",message:`MCP server "${this.serverName}" wants to call the current Session model with up to ${o.maxTokens} output tokens.`,details:o.preview,risks:[`May consume up to ${o.maxTokens} output tokens`,"The model response will be returned to the MCP server"]},r);if(r.aborted||c.reason===Xt||c.reason==="timeout")throw new P(R.InvalidRequest,"MCP sampling was cancelled");if(!c.approved)throw new P(R.InvalidRequest,"MCP sampling was denied");let d=await e.context.samplingHandler(o,r);return this.emit("samplingCompleted",{serverName:this.serverName,model:d.model,maxTokens:o.maxTokens}),d}finally{e.samplingInFlight=!1}})}registerElicitationHandlers(t){t.setRequestHandler(us,async(i,n)=>{let s=this.resolveInteraction(i.params)?.context;if(!s?.confirmationHandler)return this.emit("elicitationCancelled",{serverName:this.serverName,reason:"no-interaction-handler"}),{action:"cancel"};let e=s.signal?AbortSignal.any([s.signal,n.signal]):n.signal;if(e.aborted)return{action:"cancel"};let r;try{r=Di(this.serverName,i.params)}catch(o){return this.emit("elicitationRejected",{serverName:this.serverName,reason:o instanceof Error?o.message:String(o)}),{action:"decline"}}try{let o=s.sessionId&&s.workspaceRoot&&s.permissionMode?{projectDir:s.workspaceRoot,sessionId:s.sessionId,permissionMode:s.permissionMode,abortSignal:e}:void 0,c=o?await Bt.getInstance().executeElicitationHooks(r,o):{},d;if(c.blockedReason)d={action:"decline"};else if(c.response)d=c.response;else{let M=await s.confirmationHandler.requestConfirmation({type:"mcpElicitation",message:r.message,title:`MCP input requested by ${this.serverName}`,mcpElicitation:r},e),w=this.resolveElicitationAction(M,e);if(d=M.elicitation??{action:w},w==="accept"&&r.mode==="url"&&M.openExternalUrl&&r.url)await Es(r.url,{wait:!1})}let p=o?await Bt.getInstance().executeElicitationResultHooks(r,d,o):{};if(p.blockedReason)d={action:"cancel"};else if(p.response)d=p.response;let u=Fi(r,d);return this.emit("elicitationResolved",{serverName:this.serverName,mode:r.mode,action:u.action,elicitationId:r.elicitationId}),u}catch(o){return this.emit("elicitationCancelled",{serverName:this.serverName,reason:o instanceof Error?o.message:String(o)}),{action:"cancel"}}}),t.setNotificationHandler(cs,(i)=>{this.emit("elicitationCompleted",{serverName:this.serverName,elicitationId:i.params.elicitationId})})}resolveElicitationAction(t,i){if(i.aborted||t.reason===Xt||t.reason==="timeout")return"cancel";if(t.elicitation)return t.elicitation.action;return t.approved?"accept":"decline"}async createTransport(){let{type:t,command:i,args:n,env:s,cwd:e,url:r,headers:o,oauth:c}=this.config,d;if(c?.enabled){if(this.runtimeOptions.oauthCredentialAccess===!1||!this.oauthProvider)throw new U(this.serverName);if(!await this.oauthProvider.hasUsableCredentials())throw new zt(this.serverName);d=this.oauthProvider}if(t==="stdio"){if(!i)throw Error("stdio 传输需要 command 参数");let p={};for(let[u,M]of Object.entries(process.env))if(M!==void 0)p[u]=M;return new os({command:i,args:n||[],env:{...p,...s},cwd:e,stderr:"ignore"})}else if(t==="sse"){if(!r)throw Error("sse 传输需要 url 参数");return new ds(new URL(r),{requestInit:{headers:o},...c?.enabled?{fetch:gt}:{},...d?{authProvider:d}:{}})}else if(t==="http"){if(!r)throw Error("http 传输需要 url 参数");let{StreamableHTTPClientTransport:p}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");return new p(new URL(r),{requestInit:{headers:o},...c?.enabled?{fetch:gt}:{},...d?{authProvider:d}:{}})}throw Error(`不支持的传输类型: ${t}`)}async refreshTools(t="manual"){if(this.toolRefreshRequested=!0,this.toolRefreshPromise)return this.toolRefreshPromise;let i=this.catalogGeneration,n=(t==="notification"?new Promise((s)=>{setTimeout(s,25).unref()}):Promise.resolve()).then(()=>this.runToolRefresh(t)).finally(()=>{if(i!==this.catalogGeneration||this.toolRefreshPromise!==n)return;let s=this.toolRefreshRequested;if(this.toolRefreshPromise=void 0,this.toolRefreshRequested=!1,s&&this.sdkClient)this.refreshTools("notification")});return this.toolRefreshPromise=n,n}async waitForToolRefresh(){while(this.toolRefreshPromise)await this.toolRefreshPromise}async runToolRefresh(t){let i=t;for(let n=0;n<3&&this.toolRefreshRequested;n++){this.toolRefreshRequested=!1;try{await this.fetchAndPublishTools(i)}catch(s){if(this.emit("toolsRefreshFailed",{serverName:this.serverName,reason:i,error:s instanceof Error?s:Error(String(s))}),i!=="notification")throw s;return}i="notification"}}async fetchAndPublishTools(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");let n=[],s=new Set,e;for(let p=0;p<it;p++){let u=await i.listTools(e?{cursor:e}:void 0);if(n.push(...u.tools),n.length>l)throw Error(`MCP tool catalog exceeds ${l} tools`);if(e=u.nextCursor,!e)break;if(s.has(e))throw Error("MCP tool catalog returned a repeated cursor");if(s.add(e),p===it-1)throw Error(`MCP tool catalog exceeds ${it} pages`)}let r=Zi(n);if(this.sdkClient!==i)throw Error("MCP client changed while refreshing tools");let o=this.availableTools,c=Qi(o,r);if(this.tools=new Map(r.map((p)=>[p.name,p])),!nt(c))return;this.toolCatalogRevision++;let d={revision:this.toolCatalogRevision,reason:t,...c};this.emit("toolsUpdated",this.availableTools,d)}async refreshContentCatalogs(t="manual",i=["resources","prompts"]){let n=this.sdkClient?.getServerCapabilities();for(let r of i){if(r==="resources"&&n?.resources)this.requestedContentCatalogs.add(r);if(r==="prompts"&&n?.prompts)this.requestedContentCatalogs.add(r)}if(this.requestedContentCatalogs.size===0)return;if(this.contentRefreshPromise){if(t!=="notification")this.contentRefreshReason=t;return this.contentRefreshPromise}this.contentRefreshReason=t;let s=this.catalogGeneration,e=(t==="notification"?new Promise((r)=>{setTimeout(r,25).unref()}):Promise.resolve()).then(()=>this.runContentCatalogRefresh()).finally(()=>{if(s!==this.catalogGeneration||this.contentRefreshPromise!==e)return;let r=this.requestedContentCatalogs.size>0;if(this.contentRefreshPromise=void 0,this.contentRefreshReason="manual",r&&this.sdkClient)this.refreshContentCatalogs("notification")});return this.contentRefreshPromise=e,e}async waitForCatalogRefresh(){while(this.toolRefreshPromise||this.contentRefreshPromise)await Promise.all([this.toolRefreshPromise??Promise.resolve(),this.contentRefreshPromise??Promise.resolve()])}async runContentCatalogRefresh(){for(let t=0;t<3&&this.requestedContentCatalogs.size>0;t++){let i=[...this.requestedContentCatalogs];this.requestedContentCatalogs.clear();let n=this.contentRefreshReason;this.contentRefreshReason="notification";let s=[];for(let e of i)try{if(e==="resources")await this.fetchAndPublishResourceCatalog(n);else await this.fetchAndPublishPromptCatalog(n)}catch(r){let o=r instanceof Error?r:Error(String(r));s.push(o),this.emit("contentCatalogRefreshFailed",{serverName:this.serverName,catalog:e,reason:n,error:o})}if(s.length>0&&n!=="notification")throw AggregateError(s,`Failed to refresh MCP content catalogs for "${this.serverName}"`)}}async fetchAndPublishResourceCatalog(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");let n=await this.fetchContentPages("resource",q,(d)=>i.listResources(d?{cursor:d}:void 0),(d)=>d.resources),s=await this.fetchContentPages("resource template",K,(d)=>i.listResourceTemplates(d?{cursor:d}:void 0),(d)=>d.resourceTemplates),e=Ci(n),r=ki(s);if(this.sdkClient!==i)throw Error("MCP client changed while refreshing resource catalogs");let o=I(this.resources,e,(d)=>d.uri),c=I(this.resourceTemplates,r,(d)=>d.uriTemplate);this.resources=e,this.resourceTemplates=r,await this.reconcileResourceSubscriptions(i),this.publishContentCatalogDelta("resources",t,o),this.publishContentCatalogDelta("resourceTemplates",t,c)}async fetchAndPublishPromptCatalog(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");let n=await this.fetchContentPages("prompt",W,(r)=>i.listPrompts(r?{cursor:r}:void 0),(r)=>r.prompts),s=Oi(n);if(this.sdkClient!==i)throw Error("MCP client changed while refreshing prompts");let e=I(this.prompts,s,(r)=>r.name);this.prompts=s,this.publishContentCatalogDelta("prompts",t,e)}async fetchContentPages(t,i,n,s){let e=[],r=new Set,o;for(let c=0;c<Pt;c++){let d=await n(o);if(e.push(...s(d)),e.length>i)throw Error(`MCP ${t} catalog exceeds ${i} entries`);if(o=d.nextCursor,!o)return e;if(r.has(o))throw Error(`MCP ${t} catalog returned a repeated cursor`);r.add(o)}throw Error(`MCP ${t} catalog exceeds ${Pt} pages`)}publishContentCatalogDelta(t,i,n){if(!Li(n))return;this.contentCatalogRevision++;let s={revision:this.contentCatalogRevision,kind:t,reason:i,...n};this.emit("contentCatalogUpdated",this.contentCatalog,s)}registerResourceNotificationHandler(t){t.setNotificationHandler(ys,(i)=>{let n=i.params.uri;if(this.sdkClient!==t||!this.activeResourceSubscriptions.has(n))return;this.contentCatalogRevision++,this.emit("resourceUpdated",{revision:this.contentCatalogRevision,serverName:this.serverName,uri:n})})}registerLoggingHandler(t){t.setNotificationHandler(ws,(i)=>{if(this.sdkClient!==t||!this.loggingPolicy.enabled||!pn(i.params.level,this.loggingPolicy.level))return;let n=Date.now();if(n-this.logWindowStartedAt>=1000)this.logWindowStartedAt=n,this.logEventsInWindow=0,this.logRateWarningEmitted=!1;if(this.logEventsInWindow>=rn){if(!this.logRateWarningEmitted)this.logRateWarningEmitted=!0,this.emit("log",cn(1,{now:n}));return}this.logEventsInWindow++;let s=lt({level:i.params.level,logger:i.params.logger,data:i.params.data},{exposeDetails:this.runtimeOptions.exposeLogDetails,now:n});this.emit("log",s)})}async configureLogging(t){if(this.logWindowStartedAt=Date.now(),this.logEventsInWindow=0,this.logRateWarningEmitted=!1,!this.loggingPolicy.enabled||!t.getServerCapabilities()?.logging)return;try{await t.setLoggingLevel(this.loggingPolicy.level)}catch(i){if(this.sdkClient!==t)return;let n={serverName:this.serverName,level:this.loggingPolicy.level,error:k(i)};this.emit("loggingSetupFailed",n),this.emit("log",{...lt({level:"warning",logger:"blade.mcp.logging",data:`Failed to set MCP logging level: ${n.error}`},{exposeDetails:this.runtimeOptions.exposeLogDetails}),synthetic:!0})}}async setLoggingLevel(t){if(!on(t))throw Error("Invalid MCP logging level");let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");if(!i.getServerCapabilities()?.logging)throw Error(`MCP server "${this.serverName}" does not support logging`);if(await i.setLoggingLevel(t),this.sdkClient!==i)throw Error("MCP client changed while setting logging level");this.loggingPolicy={enabled:!0,level:t},this.emit("loggingLevelChanged",{serverName:this.serverName,level:t})}async complete(t,i){let n=this.sdkClient;if(!n||this.status!=="connected")throw Error("MCP client is not connected");if(!n.getServerCapabilities()?.completions)throw Error(`MCP server "${this.serverName}" does not support completions`);if(this.completionCallsInFlight>=oi)throw Error(`MCP server "${this.serverName}" has too many completion requests`);let s=pi(t,this.contentCatalog);this.completionCallsInFlight++;try{let e=await n.complete(s,{signal:i,timeout:ht,maxTotalTimeout:ht});if(this.sdkClient!==n)throw Error("MCP client changed while completing an argument");return ci(e)}catch(e){if(i?.aborted)throw new DOMException(String(i.reason||"MCP completion cancelled"),"AbortError");throw e}finally{this.completionCallsInFlight--}}async readResource(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");if(!this.resources.some((n)=>n.uri===t))throw Error(`MCP resource "${t}" is not present in server "${this.serverName}" catalog`);return xi(await i.readResource({uri:t}))}async getPrompt(t,i={}){let n=this.sdkClient;if(!n)throw Error("MCP client is not connected");let s=this.prompts.find((r)=>r.name===t);if(!s)throw Error(`MCP prompt "${t}" is not present in server "${this.serverName}" catalog`);let e=new Set(s.arguments.map((r)=>r.name));for(let[r,o]of Object.entries(i)){if(["__proto__","constructor","prototype"].includes(r))throw Error(`Unsafe argument "${r}" for MCP prompt "${t}"`);if(!e.has(r))throw Error(`Unknown argument "${r}" for MCP prompt "${t}"`);if(Buffer.byteLength(o)>16384)throw Error(`Argument "${r}" for MCP prompt "${t}" is too large`)}for(let r of s.arguments)if(r.required&&i[r.name]===void 0)throw Error(`Required argument "${r.name}" is missing for MCP prompt "${t}"`);return mi(await n.getPrompt({name:t,arguments:i}))}async setResourceSubscription(t,i){let n=this.sdkClient;if(!n)throw Error("MCP client is not connected");if(i){if(!this.resources.some((s)=>s.uri===t))throw Error(`MCP resource "${t}" is not present in server "${this.serverName}" catalog`);if(this.desiredResourceSubscriptions.has(t)&&this.activeResourceSubscriptions.has(t))return;if(!this.desiredResourceSubscriptions.has(t)&&this.desiredResourceSubscriptions.size>=at)throw Error(`MCP resource subscriptions exceed ${at}`);if(!n.getServerCapabilities()?.resources?.subscribe)throw Error(`MCP server "${this.serverName}" does not support resource subscriptions`);if(await n.subscribeResource({uri:t}),this.sdkClient!==n)throw Error("MCP client changed while subscribing to resource");this.desiredResourceSubscriptions.add(t),this.activeResourceSubscriptions.add(t);return}if(!this.desiredResourceSubscriptions.has(t))return;if(this.activeResourceSubscriptions.has(t)){if(await n.unsubscribeResource({uri:t}),this.sdkClient!==n)throw Error("MCP client changed while unsubscribing from resource")}this.activeResourceSubscriptions.delete(t),this.desiredResourceSubscriptions.delete(t)}async reconcileResourceSubscriptions(t){if(this.sdkClient!==t)return;let i=new Set(this.resources.map((n)=>n.uri));for(let n of this.activeResourceSubscriptions)if(!i.has(n))this.activeResourceSubscriptions.delete(n);if(!t.getServerCapabilities()?.resources?.subscribe){this.activeResourceSubscriptions.clear();return}for(let n of this.desiredResourceSubscriptions){if(!i.has(n)||this.activeResourceSubscriptions.has(n))continue;try{if(await t.subscribeResource({uri:n}),this.sdkClient!==t)return;this.activeResourceSubscriptions.add(n)}catch(s){this.emit("resourceSubscriptionRestoreFailed",{serverName:this.serverName,uri:n,error:k(s)})}}}setStatus(t){let i=this.status;if(i===t)return;this.status=t,this.emit("statusChanged",t,i)}async initialize(){return this.connect()}async destroy(){return this.disconnect()}async connectToServer(t){return this.connect()}async disconnectFromServer(t){return this.disconnect()}async listResources(t){return structuredClone(this.resources)}async listResourceTemplates(){return structuredClone(this.resourceTemplates)}async listPrompts(){return structuredClone(this.prompts)}async listTools(t){return this.availableTools}}class O extends bs{runtimeOptions;static instance=null;servers=new Map;isDiscovering=!1;catalogRevision=0;contentCatalogRevision=0;connectionRevision=0;logRevision=0;instructionsRevision=0;logEntries=[];projectedTools=new Map;constructor(t={}){super();this.runtimeOptions=t}static getInstance(){if(!O.instance)O.instance=new O;return O.instance}static createIsolated(t={}){return new O(t)}async registerServer(t,i,n={}){if(this.servers.has(t))throw Error(`MCP服务器 "${t}" 已经注册`);let s=new Yt(i,t,i.healthCheck,this.runtimeOptions),e={config:i,client:s,status:"disconnected",tools:[],contentCatalog:{resources:[],resourceTemplates:[],prompts:[]},logging:s.logging};if(this.setupClientEventHandlers(s,e,t),this.servers.set(t,e),this.emit("serverRegistered",t,e),n.connect===!1)return;try{await this.connectServer(t)}catch(r){console.warn(`MCP服务器 "${t}" 连接失败:`,r)}}async unregisterServer(t){let i=this.servers.get(t);if(!i)return;try{await T.getInstance().cancelClient(i.client),await i.client.disconnect()}catch(n){console.warn(`断开MCP服务器 "${t}" 时出错:`,n)}this.servers.delete(t),this.logEntries=this.logEntries.filter((n)=>n.serverName!==t),this.emit("serverUnregistered",t)}async connectServer(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);if(i.status==="connected")return;try{i.status="connecting",await i.client.connect(),i.connectedAt=new Date,i.lastError=void 0,i.tools=i.client.availableTools}catch(n){throw i.lastError=n,i.status="error",n}}async disconnectServer(t){let i=this.servers.get(t);if(!i)return;await T.getInstance().cancelClient(i.client),await i.client.disconnect(),i.connectedAt=void 0}async reconnectServer(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);await T.getInstance().cancelClient(i.client),await i.client.disconnect();try{i.status="connecting",await i.client.connect(),i.connectedAt=new Date,i.lastError=void 0,i.tools=i.client.availableTools}catch(n){throw i.lastError=n,i.status="error",n}}async getAvailableTools(){return[...this.projectedTools.values()]}getCatalogSnapshot(){return{revision:this.catalogRevision,tools:[...this.projectedTools.values()]}}async waitForCatalogIdle(){await Promise.all([...this.servers.values()].map((t)=>t.client.waitForCatalogRefresh()))}getContentCatalogSnapshot(){let t=[],i=[],n=[];for(let[s,e]of this.servers){if(e.status!=="connected")continue;t.push(...e.contentCatalog.resources.map((r)=>({server:s,...structuredClone(r)}))),i.push(...e.contentCatalog.resourceTemplates.map((r)=>({server:s,...structuredClone(r)}))),n.push(...e.contentCatalog.prompts.map((r)=>({server:s,...structuredClone(r)})))}return{revision:this.contentCatalogRevision,resources:t,resourceTemplates:i,prompts:n}}getLogSnapshot(t,i={}){let n=Number.isSafeInteger(i.afterRevision)&&(i.afterRevision??0)>=0?i.afterRevision??0:0,s=Number.isSafeInteger(i.limit)&&(i.limit??0)>=1&&(i.limit??0)<=B?i.limit??B:B,e=this.logEntries.filter((r)=>r.revision>n&&(!t||r.serverName===t)).slice(-s).map((r)=>structuredClone(r));return{revision:this.logRevision,entries:e}}getInstructionsSnapshot(){let t=[];for(let[i,n]of this.servers){if(n.status!=="connected"||!n.instructions)continue;t.push({serverName:i,...structuredClone(n.instructions)})}return t.sort((i,n)=>i.serverName.localeCompare(n.serverName)),{revision:this.instructionsRevision,instructions:t}}async refreshContentCatalogs(t){if(t){await this.requireConnectedServer(t).client.refreshContentCatalogs("manual");return}await Promise.all([...this.servers.values()].filter((i)=>i.status==="connected").map((i)=>i.client.refreshContentCatalogs("manual")))}async readResource(t,i){return this.requireConnectedServer(t).client.readResource(i)}async getPrompt(t,i,n={}){return this.requireConnectedServer(t).client.getPrompt(i,n)}async complete(t,i,n){return this.requireConnectedServer(t).client.complete(i,n)}async startTask(t,i,n,s,e,r,o){let c=this.requireConnectedServer(t);if(!c.tools.some((d)=>d.name===i))throw Error(`MCP tool "${i}" is not present in server "${t}" catalog`);return T.getInstance().start({client:c.client,serverName:t,toolName:i,arguments:n,owner:s,interactionContext:e,signal:r,ttlMs:o})}listTasks(t,i){return T.getInstance().list(t,i)}getTask(t,i){return T.getInstance().get(t,i)}waitForTask(t,i,n,s){return T.getInstance().wait(t,i,n,s)}cancelTask(t,i,n){return T.getInstance().cancel(t,i,n)}async setResourceSubscription(t,i,n){await this.requireConnectedServer(t).client.setResourceSubscription(i,n)}async setServerLoggingLevel(t,i){let n=this.requireConnectedServer(t);await n.client.setLoggingLevel(i),n.logging=n.client.logging}async findTool(t){return this.projectedTools.get(t)??null}getToolsByServer(t){let i=this.servers.get(t);if(!i||i.status!=="connected")return[];return i.tools.map((n)=>Tt(i.client,t,n,Lt(t,n.name),this.runtimeOptions.artifactWriter))}getServerStatus(t){return this.servers.get(t)||null}getAllServers(){return new Map(this.servers)}async getServerOAuthStatus(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);return i.client.getOAuthStatus()}async beginOAuthLogin(t,i={}){let n=this.servers.get(t);if(!n)throw Error(`MCP服务器 "${t}" 未注册`);let s=await n.client.beginOAuthLogin(i);this.emit("serverOAuthStatusChanged",t,"authorizing");let e=s.completion.then(async()=>{this.emit("serverOAuthCompleted",t),this.emit("serverOAuthStatusChanged",t,"authenticated");try{await this.reconnectServer(t)}catch(r){n.lastError=r instanceof Error?r:Error(String(r)),n.status="error",this.emit("serverError",t,n.lastError)}},(r)=>{throw n.lastError=r instanceof Error?r:Error(String(r)),this.emit("serverOAuthError",t,n.lastError),this.emit("serverOAuthStatusChanged",t,"error"),n.lastError});return e.catch(()=>{return}),{...s,completion:e}}async logoutOAuth(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);await i.client.logoutOAuth(),i.status="disconnected",i.connectedAt=void 0,i.lastError=void 0,i.tools=[],this.emit("serverOAuthStatusChanged",t,"unauthenticated")}async refreshAllTools(){let t=[];for(let[i,n]of this.servers)if(n.status==="connected")t.push(this.refreshServerTools(i));await Promise.allSettled(t)}async refreshServerTools(t){let i=this.servers.get(t);if(!i||i.status!=="connected")return;try{await i.client.refreshTools("manual")}catch(n){throw console.warn(`刷新服务器 "${t}" 工具列表失败:`,n),n}}setupClientEventHandlers(t,i,n){t.on("connected",(s)=>{if(i.status="connected",i.connectedAt=new Date,i.lastError=void 0,i.tools=t.availableTools,i.contentCatalog=t.contentCatalog,i.logging=t.logging,i.instructions=this.fitInstructionBudget(n,t.instructions),this.publishCatalog(n,"connection"),this.publishInitialContentCatalog(n,i.contentCatalog),i.instructions)this.publishInstructions(n,"added","connection",i.instructions);this.emit("serverConnected",n,s)}),t.on("disconnected",()=>{i.status="disconnected",i.connectedAt=void 0,i.lastError=void 0,i.recovery=void 0,this.invalidateServerProjection(n,i),this.emit("serverDisconnected",n)}),t.on("error",(s)=>{i.status="error",i.lastError=s,this.invalidateServerProjection(n,i),this.emit("serverError",n,s)}),t.on("connectionLifecycleChanged",(s)=>{if(i.recovery=structuredClone(s),s.phase==="reconnecting")i.status="reconnecting",i.connectedAt=void 0,i.lastError=s.error?Error(s.error):i.lastError,this.invalidateServerProjection(n,i);else if(s.phase==="recovered")i.status="connected",i.lastError=void 0;else i.status="error",i.connectedAt=void 0,i.lastError=s.error?Error(s.error):i.lastError;this.publishConnectionLifecycle(n,s)}),t.on("toolsUpdated",(s,e)=>{let r=i.tools.length;if(i.tools=s,i.status==="connected"&&e)this.publishCatalog(n,e.reason);this.emit("toolsUpdated",n,s,r)}),t.on("toolsRefreshFailed",(s)=>{this.emit("catalogRefreshFailed",{serverName:n,...s})}),t.on("contentCatalogUpdated",(s,e)=>{if(i.contentCatalog=s,i.status!=="connected")return;this.publishContentCatalogChange(n,e.kind,e.reason,{added:e.added,removed:e.removed,updated:e.updated})}),t.on("contentCatalogRefreshFailed",(s)=>{this.emit("contentCatalogRefreshFailed",{serverName:n,...s})}),t.on("resourceUpdated",(s)=>{if(i.status!=="connected")return;this.contentCatalogRevision++;let e={revision:this.contentCatalogRevision,serverName:n,uri:s.uri};this.emit("resourceUpdated",e)}),t.on("statusChanged",(s,e)=>{if(i.status=s,s==="reconnecting"&&e==="connected")i.connectedAt=void 0,this.invalidateServerProjection(n,i);this.emit("serverStatusChanged",n,s,e)}),t.on("loggingLevelChanged",()=>{i.logging=t.logging,this.emit("serverLoggingLevelChanged",n,i.logging.level)}),t.on("log",(s)=>{this.publishLog(n,s)})}publishLog(t,i){this.logRevision++;let n={revision:this.logRevision,serverName:t,...structuredClone(i)};this.logEntries.push(n);let s=0;for(let e=this.logEntries.length-1;e>=0;e--){if(this.logEntries[e]?.serverName!==t)continue;if(s++,s>Tn)this.logEntries.splice(e,1)}while(this.logEntries.length>B)this.logEntries.shift();this.emit("log",structuredClone(n))}invalidateServerProjection(t,i){let n=i.contentCatalog,s=i.instructions!==void 0;if(i.tools=[],i.contentCatalog={resources:[],resourceTemplates:[],prompts:[]},i.instructions=void 0,this.publishCatalog(t,"disconnection"),this.publishRemovedContentCatalog(t,n),s)this.publishInstructions(t,"removed","disconnection")}fitInstructionBudget(t,i){if(!i)return;let n=0;for(let[s,e]of this.servers){if(s===t)continue;n+=e.instructions?.projectedBytes??0}return En(i,Math.max(0,fn-n))}publishInstructions(t,i,n,s){this.instructionsRevision++;let e={revision:this.instructionsRevision,serverName:t,action:i,reason:n,...s?{instruction:structuredClone(s)}:{}};this.emit("instructionsChanged",e)}publishConnectionLifecycle(t,i){this.connectionRevision++;let n={revision:this.connectionRevision,serverName:t,...structuredClone(i)};this.emit("connectionLifecycleChanged",n)}publishCatalog(t,i){let n=new Map;for(let[c,d]of this.servers){if(d.status!=="connected")continue;for(let p of d.tools){let u=Lt(c,p.name);if(n.has(u))throw Error(`Duplicate projected MCP tool "${u}"`);n.set(u,Tt(d.client,c,p,u,this.runtimeOptions.artifactWriter))}}let s=new Map([...this.projectedTools].map(([c,d])=>[c,JSON.stringify(d.getFunctionDeclaration())])),e=new Map([...n].map(([c,d])=>[c,JSON.stringify(d.getFunctionDeclaration())])),r={added:[...n.keys()].filter((c)=>!this.projectedTools.has(c)).sort(),removed:[...this.projectedTools.keys()].filter((c)=>!n.has(c)).sort(),updated:[...n.keys()].filter((c)=>this.projectedTools.has(c)&&s.get(c)!==e.get(c)).sort()};if(this.projectedTools=n,!nt(r))return;this.catalogRevision++;let o={revision:this.catalogRevision,serverName:t,reason:i,tools:[...n.values()],...r};this.emit("catalogChanged",o)}publishInitialContentCatalog(t,i){this.publishContentCatalogChange(t,"resources","connection",{added:i.resources.map((n)=>n.uri).sort(),removed:[],updated:[]}),this.publishContentCatalogChange(t,"resourceTemplates","connection",{added:i.resourceTemplates.map((n)=>n.uriTemplate).sort(),removed:[],updated:[]}),this.publishContentCatalogChange(t,"prompts","connection",{added:i.prompts.map((n)=>n.name).sort(),removed:[],updated:[]})}publishRemovedContentCatalog(t,i){this.publishContentCatalogChange(t,"resources","disconnection",{added:[],removed:i.resources.map((n)=>n.uri).sort(),updated:[]}),this.publishContentCatalogChange(t,"resourceTemplates","disconnection",{added:[],removed:i.resourceTemplates.map((n)=>n.uriTemplate).sort(),updated:[]}),this.publishContentCatalogChange(t,"prompts","disconnection",{added:[],removed:i.prompts.map((n)=>n.name).sort(),updated:[]})}publishContentCatalogChange(t,i,n,s){if(s.added.length===0&&s.removed.length===0&&s.updated.length===0)return;this.contentCatalogRevision++;let e={revision:this.contentCatalogRevision,serverName:t,kind:i,reason:n,...s};this.emit("contentCatalogChanged",e)}requireConnectedServer(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);if(i.status!=="connected")throw Error(`MCP服务器 "${t}" 未连接`);return i}async discoverServers(){if(this.isDiscovering)return Array.from(this.servers.values());this.isDiscovering=!0,this.emit("discoveryStarted");try{return Array.from(this.servers.values())}finally{this.isDiscovering=!1,this.emit("discoveryCompleted")}}async registerServers(t){let i=Object.entries(t).map(([n,s])=>this.registerServer(n,s).catch((e)=>{return console.warn(`注册MCP服务器 "${n}" 失败:`,e),e}));await Promise.allSettled(i)}getStatistics(){let t=0,i=0,n=0;for(let s of this.servers.values())if(s.status==="connected")t++,i+=s.tools.length;else if(s.status==="error")n++;return{totalServers:this.servers.size,connectedServers:t,errorServers:n,totalTools:i,isDiscovering:this.isDiscovering}}async disconnectAll(){let t=[];for(let[i,n]of this.servers)t.push(T.getInstance().cancelClient(n.client).then(()=>n.client.disconnect()).catch((s)=>{console.warn(`断开 MCP 服务器 "${i}" 时出错:`,s)}));await Promise.allSettled(t),this.servers.clear(),this.projectedTools.clear(),this.logEntries=[]}}
|
|
25
|
-
export{jt as
|
|
25
|
+
export{jt as ya,T as za,jn as Aa,vs as Ba,te as Ca,Fi as Da,Lt as Ea,ts as Fa,O as Ga};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
function v(b){switch(b){case"default":case"ignore":case void 0:return"default";case"acceptEdits":return"autoEdit";case"dontAsk":case"bypassPermissions":return"yolo";case"plan":return"plan";default:return"default"}}
|
|
2
|
-
export{v as
|
|
2
|
+
export{v as gg};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ii as r}from"./chunk-h4j0nve8.js";import{Gi as d,Ii as x,Ki as j,Oi as u,Pi as i}from"./chunk-na1cney5.js";import{Qi as y}from"./chunk-nh45xp7r.js";import{stat as a}from"node:fs/promises";import k from"node:path";import*as U from"node:path";var e=50,__=100,E_=new Set(["queued","running","completed","failed","cancelled","interrupted"]),R_=new Set(["high","medium","low"]),W_=/^[A-Za-z0-9_-]+$/,$_=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function H_(_){return typeof _==="string"&&$_.test(_)&&Number.isFinite(Date.parse(_))}function v(_){return typeof _==="string"&&U.isAbsolute(_)}function M_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function Q_(_){try{if(!W_.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||v(R.cwd))||!H_(R.lastMessageTime)||!v(R.projectPath)||!x(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function J(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function V_(_){if(!_.cursor)return;let E=Q_(_.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 O_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:H=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let M=W===void 0?e:W;if(!Number.isInteger(M)||M<1||M>__)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:M,includeSubagents:$,archived:H}}function N_(_={}){let E=c(_.taskStatus,E_,"task status"),R=c(_.taskPriority,R_,"task priority"),W=S(_.taskDueAfter,"taskDueAfter"),$=S(_.taskDueBefore,"taskDueBefore");return X_(W,$),{...E?{taskStatuses:E}:{},...R?{taskPriorities:R}:{},...W?{taskDueAfter:W}:{},...$?{taskDueBefore:$}:{}}}function c(_,E,R){if(_===void 0)return;let W=Array.isArray(_)?_:[_];if(W.length===0)return;let $=new Set;for(let H of W){if(typeof H!=="string"||!E.has(H))throw Error(`Invalid session ${R} filter`);$.add(H)}return[...$].sort()}function S(_,E){if(_===void 0)return;if(typeof _!=="string"||!Number.isFinite(Date.parse(_)))throw Error(`Invalid session ${E} filter`);return new Date(_).toISOString()}function X_(_,E){if(_!==void 0&&E!==void 0&&_>E)throw Error("Session task due range is inverted")}function Y_(_,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 f_(_,E){let R=[..._],W=V_(E);if(W)R=R.filter((M)=>Y_(M,{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 H=$[$.length-1];return{sessions:$,nextCursor:M_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:H.lastMessageTime,projectPath:H.projectPath,sessionId:H.sessionId})}}function G_(_){return _.type==="message_created"||_.type==="token_budget_handoff_recorded"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}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:m(_,E),createdAt:R.data.createdAt}}function m(_,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 h(_,E){N(_,E);let R=_.findIndex((M)=>M.type==="message_created"&&M.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,H=new Set(_.flatMap((M)=>M.type==="turn_started"&&$&&M.data.inputMessageIds?.includes($)?[M.data.turnId]:[]));return _.filter((M,Q)=>{if((M.type==="turn_started"||M.type==="turn_completed"||M.type==="turn_aborted")&&H.has(M.data.turnId))return!1;return Q<R||!G_(M)})}function D(_){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=h(E,R.data.targetMessageId)}return E}function j_(_){let E=D(_);return E.filter(O).map((R)=>({messageId:R.data.messageId,preview:m(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function u_(_,E){let R=D(_),W=N(R,E),$=R.findIndex((M)=>M.type==="message_created"&&M.data.messageId===E),H=R.slice($);return{checkpoint:W,projectedEntries:h(R,E),removedTurns:H.filter(O).length,snapshotMessageIds:H.flatMap((M)=>M.type==="part_created"&&M.data.partType==="tool_call"?[M.data.partId]:[])}}import*as I from"node:fs";import{createReadStream as T_}from"node:fs";import*as X from"node:fs/promises";import*as f from"node:path";import{createInterface as Z_}from"node:readline";var b=65536;function w(_){let E=_.data;if(E===null||typeof E!=="object"||Array.isArray(E))throw Error("Session event data must be a JSON object");return JSON.stringify(_)}function g_(_,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 z(_,E="session transcript"){let R=_.split(`
|
|
2
2
|
`),W=!_.endsWith(`
|
|
3
3
|
`),$=[];for(let[H,M]of R.entries())try{let Q=g_(M,H+1,E);if(Q){if(typeof Q.seq!=="number")Q.seq=$.length+1;$.push(Q)}}catch(Q){if(W&&H===R.length-1)break;throw Q}return $}class G{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 G.stampSeqFrom(_,G.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 X.mkdir(f.dirname(this.filePath),{recursive:!0,mode:493});let E=await X.open(this.filePath,"a+",384);try{let R=await this.repairIncompleteTail(E),W=await this.readTailSeq(E),$=G.stampSeqFrom(_,W),H=`${$.map(w).join(`
|
|
4
4
|
`)}
|
|
@@ -137,4 +137,4 @@ CREATE VIRTUAL TABLE IF NOT EXISTS parts_fts USING fts5(
|
|
|
137
137
|
ORDER BY timestamp DESC LIMIT ?`:`SELECT session_id, role, timestamp, text FROM parts_fts
|
|
138
138
|
WHERE parts_fts MATCH ?
|
|
139
139
|
ORDER BY timestamp DESC LIMIT ?`,Q=_.prepare(M);return R?Q.all(H,R,W):Q.all(H,W)}
|
|
140
|
-
export{D as
|
|
140
|
+
export{D as Sd,j_ as Td,u_ as Ud,z as Vd,G as Wd,J as Xd,V_ as Yd,O_ as Zd,N_ as _d,Y_ as $d,f_ as ae,s as be,k_ as ce,A_ as de,z_ as ee,I_ as fe,t_ as ge,e_ as he,_E as ie};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{if as a,jf as b,kf as c}from"./chunk-rxbxvq67.js";import"./chunk-z6xfknxe.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
|