blade-code 0.10.133 → 0.10.137

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.
Files changed (142) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-h6tr3zz7.js → chunk-0c82q1sz.js} +1 -1
  3. package/dist/chunk-0ccm29qy.js +2 -0
  4. package/dist/{chunk-fjvt9mwv.js → chunk-0k2x2ae6.js} +1 -1
  5. package/dist/{chunk-7hxyxv4x.js → chunk-1evc05gr.js} +2 -2
  6. package/dist/chunk-35668hyn.js +1 -0
  7. package/dist/{chunk-d881py5y.js → chunk-39de5k03.js} +2 -2
  8. package/dist/chunk-3gmcvd0c.js +1 -0
  9. package/dist/{chunk-7j628q12.js → chunk-4jqw75ce.js} +1 -1
  10. package/dist/chunk-5774a669.js +1 -0
  11. package/dist/chunk-5btfnf2r.js +14 -0
  12. package/dist/{chunk-bj8cgfbr.js → chunk-5dwmhsrx.js} +1 -1
  13. package/dist/chunk-5sf2rc1z.js +171 -0
  14. package/dist/{chunk-nfdfthhb.js → chunk-69nwa6bn.js} +1 -1
  15. package/dist/{chunk-2nv0kg12.js → chunk-69rjav47.js} +1 -1
  16. package/dist/{chunk-w3y69e4e.js → chunk-6e3mh79j.js} +1 -1
  17. package/dist/{chunk-3csj18f1.js → chunk-6xvrrypm.js} +1 -1
  18. package/dist/{chunk-87ycd3f8.js → chunk-74bswv4z.js} +2 -2
  19. package/dist/{chunk-ndgdf5jx.js → chunk-75yy9yre.js} +1 -1
  20. package/dist/chunk-7n035mhg.js +1 -0
  21. package/dist/{chunk-e1q1hvty.js → chunk-7ykqvsph.js} +2 -2
  22. package/dist/chunk-9a7bppj7.js +2 -0
  23. package/dist/{chunk-cfamqqgv.js → chunk-9frd4fpk.js} +2 -2
  24. package/dist/chunk-a26vtcv5.js +5 -0
  25. package/dist/{chunk-0ap8b3sw.js → chunk-affzv7f1.js} +1 -1
  26. package/dist/chunk-b08thknq.js +1 -0
  27. package/dist/{chunk-f1wnva76.js → chunk-bx75fd0d.js} +396 -394
  28. package/dist/chunk-bzqbmz6t.js +171 -0
  29. package/dist/{chunk-yvk8w63g.js → chunk-c2mx5zg0.js} +1 -1
  30. package/dist/chunk-chspy9f8.js +23 -0
  31. package/dist/chunk-d6tbr25k.js +1 -0
  32. package/dist/chunk-dt9n4f4e.js +1 -0
  33. package/dist/{chunk-ms360ds6.js → chunk-e76gej4y.js} +2 -2
  34. package/dist/{chunk-bzp08nf6.js → chunk-e8pfbb6c.js} +1 -1
  35. package/dist/chunk-ermypm1x.js +2 -0
  36. package/dist/chunk-esp69w6w.js +1 -0
  37. package/dist/{chunk-z5mm9g1y.js → chunk-etf3e9kt.js} +1 -1
  38. package/dist/{chunk-x1w3fvhr.js → chunk-f2b9cyj5.js} +2 -2
  39. package/dist/chunk-g1y60ey9.js +1 -0
  40. package/dist/{chunk-be2csw9m.js → chunk-g799czsy.js} +1 -1
  41. package/dist/{chunk-dnt4c3gy.js → chunk-g9vdmvk2.js} +2 -2
  42. package/dist/chunk-gf5v8aff.js +1 -0
  43. package/dist/chunk-gpj7k3er.js +6 -0
  44. package/dist/{chunk-mkvqtawj.js → chunk-h05qhgrb.js} +2 -2
  45. package/dist/{chunk-2qyh6qhb.js → chunk-h74p51hg.js} +2 -2
  46. package/dist/{chunk-1tfjaazq.js → chunk-karq4wfd.js} +1 -1
  47. package/dist/{chunk-cz9mqkn2.js → chunk-ky9br0z8.js} +1 -1
  48. package/dist/chunk-m9kh7djg.js +6 -0
  49. package/dist/{chunk-gv24cgpb.js → chunk-mavranwn.js} +3 -3
  50. package/dist/{chunk-0xph7bhe.js → chunk-mthf5akx.js} +2 -2
  51. package/dist/{chunk-8xem2mzy.js → chunk-mzye1ah2.js} +1 -1
  52. package/dist/chunk-na4wzne8.js +1 -0
  53. package/dist/chunk-ntmkzrs8.js +1 -0
  54. package/dist/{chunk-961nemng.js → chunk-nxnmqk4s.js} +1 -1
  55. package/dist/{chunk-h123tjsg.js → chunk-p0gbxaqz.js} +2 -2
  56. package/dist/chunk-pj15kt5b.js +10 -0
  57. package/dist/chunk-pv1vwasz.js +1 -0
  58. package/dist/{chunk-r4bgsfj6.js → chunk-q0s3gcjm.js} +1 -1
  59. package/dist/{chunk-jy61b0v8.js → chunk-ramana2t.js} +2 -2
  60. package/dist/{chunk-ks67gd2j.js → chunk-rgjr7jsd.js} +1 -1
  61. package/dist/chunk-v5503t2t.js +25 -0
  62. package/dist/chunk-vda03kxj.js +1 -0
  63. package/dist/{chunk-4xhawy0e.js → chunk-vg3zwv4g.js} +1 -1
  64. package/dist/chunk-vp6d1fqp.js +3 -0
  65. package/dist/{chunk-nyk5q71k.js → chunk-w9z34f27.js} +1 -1
  66. package/dist/{chunk-5x3h9ak8.js → chunk-wa71vstt.js} +1 -1
  67. package/dist/{chunk-f4pn5tmr.js → chunk-wc9wsyrc.js} +1 -1
  68. package/dist/{chunk-0d440hhe.js → chunk-wxtj6gqb.js} +1 -1
  69. package/dist/{chunk-rmm7n9n3.js → chunk-wxypv01z.js} +2 -2
  70. package/dist/{chunk-77efqpdc.js → chunk-wzkh3e6a.js} +1 -1
  71. package/dist/{chunk-rcthrb7h.js → chunk-xg9fyvw0.js} +2 -2
  72. package/dist/{chunk-7zvwfz85.js → chunk-xt0ktytp.js} +2 -2
  73. package/dist/{chunk-xgz1yanb.js → chunk-y6jee9w7.js} +1 -1
  74. package/dist/{chunk-3ndwbb7h.js → chunk-ybc5myz7.js} +1 -1
  75. package/dist/{chunk-53h87fmt.js → chunk-z3hpstky.js} +1 -1
  76. package/dist/{chunk-555ffyze.js → chunk-zk9rf1d7.js} +2 -2
  77. package/dist/web/assets/ChatView-DpvPjAh7.js +63 -0
  78. package/dist/web/assets/{CodeBlockHighlighter-D0yM8QTf.js → CodeBlockHighlighter-Czp4VZIg.js} +1 -1
  79. package/dist/web/assets/{FilePreview-CaTCjV5i.js → FilePreview-BJWuYfyF.js} +15 -20
  80. package/dist/web/assets/{KanbanBoard-BY0SXCol.js → KanbanBoard-DrYzt5Kh.js} +4 -4
  81. package/dist/web/assets/{MarkdownRenderer-zKto-Pty.js → MarkdownRenderer-DxkR5r7t.js} +3 -3
  82. package/dist/web/assets/{ScrollArea-1qPJ8lcT.js → ScrollArea-D71pJjgW.js} +1 -1
  83. package/dist/web/assets/{SessionHistorySurface-Ce9xX62q.js → SessionHistorySurface-2y9bnndm.js} +2 -2
  84. package/dist/web/assets/{SettingsModal-BxKOMuIm.js → SettingsModal-BbaTL5Rk.js} +1 -1
  85. package/dist/web/assets/{Sidebar-CEF6lGps.js → Sidebar-COZltpL9.js} +1 -1
  86. package/dist/web/assets/{TaskSwitcher-C-EY0nVG.js → TaskSwitcher-3giB7l1P.js} +2 -2
  87. package/dist/web/assets/{TerminalPanel-C3PVDyAr.js → TerminalPanel-gvTTiTgX.js} +2 -2
  88. package/dist/web/assets/{archive-D5Nuw__Q.js → archive-DndqAA2q.js} +1 -1
  89. package/dist/web/assets/{arrow-left-DaOpfgEz.js → arrow-left-XNYfpUAb.js} +1 -1
  90. package/dist/web/assets/{calendar-clock-DA_D4ppV.js → calendar-clock-BQOfNcCK.js} +1 -1
  91. package/dist/web/assets/{chevron-right-COQAoZf3.js → chevron-right-Cvq3LzHK.js} +1 -1
  92. package/dist/web/assets/chevrons-up-down-Dia1U9Sz.js +16 -0
  93. package/dist/web/assets/{clock-3-DJ-pSj3t.js → clock-3-CnxLS8cv.js} +1 -1
  94. package/dist/web/assets/{copy-5c0ESKoo.js → copy-CWCS3Lql.js} +1 -1
  95. package/dist/web/assets/{download-VkaTciEH.js → download-DXdsM18t.js} +1 -1
  96. package/dist/web/assets/{external-link-BypdqupZ.js → external-link-1IN2ZfaO.js} +1 -1
  97. package/dist/web/assets/{folder-B8znObPL.js → folder-Bpq602dI.js} +1 -1
  98. package/dist/web/assets/index-57UZsfTt.css +1 -0
  99. package/dist/web/assets/index-DEOQizD2.js +203 -0
  100. package/dist/web/assets/{pause-BWbHHYG6.js → pause-BYhoGDZq.js} +1 -1
  101. package/dist/web/assets/{pencil-BPyvvR59.js → pencil-pRZQVHFU.js} +1 -1
  102. package/dist/web/assets/{play-CLJgUH4S.js → play-DGZdCyPk.js} +1 -1
  103. package/dist/web/assets/{plus-D1VVvu-z.js → plus-CAQ3qlUJ.js} +1 -1
  104. package/dist/web/assets/session-events-C5_Q0kZV.js +29 -0
  105. package/dist/web/assets/{settings-CGCgC_NX.js → settings-BPfzj_Vf.js} +1 -1
  106. package/dist/web/assets/teamService-BScT9o9A.js +1 -0
  107. package/dist/web/assets/{terminal-pA96HZrI.js → terminal-CldJbdMr.js} +1 -1
  108. package/dist/web/index.html +2 -2
  109. package/package.json +1 -1
  110. package/dist/chunk-00zazdct.js +0 -25
  111. package/dist/chunk-04yas0t8.js +0 -1
  112. package/dist/chunk-2242dshn.js +0 -2
  113. package/dist/chunk-2nxev7f2.js +0 -1
  114. package/dist/chunk-43a0n5rw.js +0 -1
  115. package/dist/chunk-679b7s58.js +0 -2
  116. package/dist/chunk-78wwep9f.js +0 -1
  117. package/dist/chunk-88jmtcv7.js +0 -171
  118. package/dist/chunk-ar3sdj0w.js +0 -3
  119. package/dist/chunk-avf9spct.js +0 -1
  120. package/dist/chunk-azv25dg2.js +0 -10
  121. package/dist/chunk-b8c1vj8c.js +0 -1
  122. package/dist/chunk-bbw6s542.js +0 -1
  123. package/dist/chunk-eetva9y8.js +0 -1
  124. package/dist/chunk-kjjpn49y.js +0 -1
  125. package/dist/chunk-kx61g7xw.js +0 -1
  126. package/dist/chunk-m30sbsnw.js +0 -1
  127. package/dist/chunk-n589jxsm.js +0 -1
  128. package/dist/chunk-n7pydthh.js +0 -6
  129. package/dist/chunk-nry7d26k.js +0 -2
  130. package/dist/chunk-p8y5kk56.js +0 -6
  131. package/dist/chunk-py92cy57.js +0 -14
  132. package/dist/chunk-rkjrft19.js +0 -5
  133. package/dist/chunk-sr9gqacp.js +0 -1
  134. package/dist/chunk-sxqydew5.js +0 -1
  135. package/dist/chunk-t52v91dy.js +0 -23
  136. package/dist/chunk-v7zt3pft.js +0 -171
  137. package/dist/web/assets/ChatView-hYd9mmJ6.js +0 -53
  138. package/dist/web/assets/chevrons-up-down-B_WSFixv.js +0 -11
  139. package/dist/web/assets/index-B4186fIT.css +0 -1
  140. package/dist/web/assets/index-DorkRCqS.js +0 -210
  141. package/dist/web/assets/session-events-C6fPz20c.js +0 -22
  142. package/dist/web/assets/teamService-DsYRmp6u.js +0 -1
@@ -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 ch};
2
+ export{v as lh};
@@ -1 +1 @@
1
- import{Ca as h,Ea as f,Fa as k}from"./chunk-2qyh6qhb.js";import"./chunk-w3y69e4e.js";var p={command:"status",describe:"Check the pinned Playwright Chromium installation",handler:async()=>{let c=await f();if(console.log(`Playwright: ${c.playwrightVersion}`),console.log(`Chromium executable: ${c.executablePath}`),!c.installed){console.error(`Chromium: unavailable (${c.error??"unknown error"})`),console.error(`Install with: ${h}`),process.exitCode=1;return}console.log(`Chromium: ${c.browserVersion}`),console.log("Status: ready")}},q={command:"install",describe:"Install Chromium for the pinned Playwright runtime",handler:async()=>{try{await k();let c=await f();if(!c.installed)throw Error(c.error??"Chromium is not runnable after installation");console.log(`Chromium installed: Playwright ${c.playwrightVersion}, ${c.browserVersion}`)}catch(c){console.error(`Browser installation failed: ${c instanceof Error?c.message:String(c)}`),process.exitCode=1}}},x={command:"browser",describe:"Manage the native Browser Tool runtime",builder:(c)=>c.command(p).command(q).demandCommand(1).strict(),handler:()=>{return}};export{p as browserStatusCommand,q as browserInstallCommand,x as browserCommands};
1
+ import{Ea as h,Ga as f,Ha as k}from"./chunk-h74p51hg.js";import"./chunk-6e3mh79j.js";var p={command:"status",describe:"Check the pinned Playwright Chromium installation",handler:async()=>{let c=await f();if(console.log(`Playwright: ${c.playwrightVersion}`),console.log(`Chromium executable: ${c.executablePath}`),!c.installed){console.error(`Chromium: unavailable (${c.error??"unknown error"})`),console.error(`Install with: ${h}`),process.exitCode=1;return}console.log(`Chromium: ${c.browserVersion}`),console.log("Status: ready")}},q={command:"install",describe:"Install Chromium for the pinned Playwright runtime",handler:async()=>{try{await k();let c=await f();if(!c.installed)throw Error(c.error??"Chromium is not runnable after installation");console.log(`Chromium installed: Playwright ${c.playwrightVersion}, ${c.browserVersion}`)}catch(c){console.error(`Browser installation failed: ${c instanceof Error?c.message:String(c)}`),process.exitCode=1}}},x={command:"browser",describe:"Manage the native Browser Tool runtime",builder:(c)=>c.command(p).command(q).demandCommand(1).strict(),handler:()=>{return}};export{p as browserStatusCommand,q as browserInstallCommand,x as browserCommands};
@@ -1,2 +1,2 @@
1
1
  import{createRequire as a}from"node:module";var c=a(import.meta.url);
2
- export{c as sk};
2
+ export{c as Bk};
@@ -1,2 +1,2 @@
1
1
  var F;((D)=>{D.DEFAULT="default";D.AUTO_EDIT="autoEdit";D.YOLO="yolo";D.PLAN="plan"})(F||={});import{Mutex as G}from"async-mutex";class H{entries=new Map;async runExclusive(C,E){let B=this.entries.get(C);if(!B)B={mutex:new G,operations:0},this.entries.set(C,B);B.operations++;try{return await B.mutex.runExclusive(E)}finally{if(B.operations--,B.operations===0&&this.entries.get(C)===B)this.entries.delete(C)}}getStats(){let C=0;for(let E of this.entries.values())C+=E.operations;return{keys:this.entries.size,operations:C}}}
2
- export{F as zi,H as Ai};
2
+ export{F as Ii,H as Ji};
@@ -1,2 +1,2 @@
1
- import{eg as B}from"./chunk-7j628q12.js";import{vj as Y}from"./chunk-rcthrb7h.js";import{Bj as $,yj as Z}from"./chunk-0d440hhe.js";import{createHash as H}from"node:crypto";var N="fast-mode-2026-02-01";function R(q,x,z){if(x.api!=="anthropic-messages"||z.providerValue!=="fast")return q;let J={...q},w=Object.keys(J).find((G)=>G.toLowerCase()==="anthropic-beta")??"anthropic-beta",Q=new Set((J[w]??"").split(",").map((G)=>G.trim()).filter(Boolean));return Q.add(N),J[w]=[...Q].join(","),J}function D(q){return`BLADE_MODEL_API_KEY_${H("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function F(q,x){if(!q.fallbackModels?.length)return;return q.fallbackModels.map((z)=>{let J=(x.models??[]).filter((G)=>G.provider===z.provider&&G.model===z.model),w=z.configId?(x.models??[]).find((G)=>G.id===z.configId):J.length===1?J[0]:void 0;if(z.configId&&!w)throw Error(`Unknown fallback model config ID: ${z.configId}`);if(w&&(w.provider!==z.provider||w.model!==z.model))throw Error(`Fallback model config ${w.id} does not match ${z.provider}/${z.model}`);if(!z.configId&&J.length>1)throw Error(`Fallback model ${z.provider}/${z.model} is ambiguous; set configId`);if(!w)return z;let Q=w.provider===q.provider;return{...z,configId:w.id,channel:{apiKey:process.env[D(w.id)]??(Q?process.env.BLADE_API_KEY:void 0),baseUrl:w.overrides?.baseUrl??(Q?process.env.BLADE_BASE_URL:void 0),temperature:w.overrides?.temperature??x.temperature,maxOutputTokens:w.overrides?.maxOutputTokens,timeout:w.overrides?.timeout??x.timeout,streamIdleTimeout:w.overrides?.streamIdleTimeout,apiVersion:w.overrides?.apiVersion,customHeaders:w.overrides?.customHeaders,enablePromptCaching:w.overrides?.enablePromptCaching}}})}function h(q,x,z,J=Y(),w="auto",Q="auto"){let G=J.resolveConfig(q),U=B(G,z),W=$(G,w),X=Z(G,Q),L=q.overrides;return{config:q,model:G,displayName:q.displayName??G.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[D(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??L?.baseUrl,temperature:L?.temperature??x.temperature,maxContextTokens:G.contextWindow,maxOutputTokens:L?.maxOutputTokens,timeout:L?.timeout??x.timeout,streamIdleTimeout:L?.streamIdleTimeout,reasoningEnabled:U.effective!=="off",...U.effective==="off"?{}:{reasoningEffort:U.effective},...W.providerValue?{serviceTier:W.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:F(q,x),enablePromptCaching:L?.enablePromptCaching,customHeaders:R(L?.customHeaders,G,W),apiVersion:L?.apiVersion,maxRetries:L?.maxRetries,providerCircuitBreakerOpenMs:x.providerCircuitBreakerOpenMs,providerRequestConcurrency:x.providerRequestConcurrency,providerGlobalConcurrency:x.providerGlobalConcurrency,providerOwnerConcurrency:x.providerOwnerConcurrency,providerRequestAdmissionMs:x.providerRequestAdmissionMs,providerRequestPendingBytes:x.providerRequestPendingBytes,modelCatalog:J},reasoning:U,serviceTier:W,responseVerbosity:X}}function j(q,x=Y()){try{return q.displayName??x.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
2
- export{D as ag,h as bg,j as cg};
1
+ import{ng as B}from"./chunk-4jqw75ce.js";import{Ej as Y}from"./chunk-xg9fyvw0.js";import{Hj as Z,Kj as $}from"./chunk-wxtj6gqb.js";import{createHash as H}from"node:crypto";var N="fast-mode-2026-02-01";function R(q,x,z){if(x.api!=="anthropic-messages"||z.providerValue!=="fast")return q;let J={...q},w=Object.keys(J).find((G)=>G.toLowerCase()==="anthropic-beta")??"anthropic-beta",Q=new Set((J[w]??"").split(",").map((G)=>G.trim()).filter(Boolean));return Q.add(N),J[w]=[...Q].join(","),J}function D(q){return`BLADE_MODEL_API_KEY_${H("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function F(q,x){if(!q.fallbackModels?.length)return;return q.fallbackModels.map((z)=>{let J=(x.models??[]).filter((G)=>G.provider===z.provider&&G.model===z.model),w=z.configId?(x.models??[]).find((G)=>G.id===z.configId):J.length===1?J[0]:void 0;if(z.configId&&!w)throw Error(`Unknown fallback model config ID: ${z.configId}`);if(w&&(w.provider!==z.provider||w.model!==z.model))throw Error(`Fallback model config ${w.id} does not match ${z.provider}/${z.model}`);if(!z.configId&&J.length>1)throw Error(`Fallback model ${z.provider}/${z.model} is ambiguous; set configId`);if(!w)return z;let Q=w.provider===q.provider;return{...z,configId:w.id,channel:{apiKey:process.env[D(w.id)]??(Q?process.env.BLADE_API_KEY:void 0),baseUrl:w.overrides?.baseUrl??(Q?process.env.BLADE_BASE_URL:void 0),temperature:w.overrides?.temperature??x.temperature,maxOutputTokens:w.overrides?.maxOutputTokens,timeout:w.overrides?.timeout??x.timeout,streamIdleTimeout:w.overrides?.streamIdleTimeout,apiVersion:w.overrides?.apiVersion,customHeaders:w.overrides?.customHeaders,enablePromptCaching:w.overrides?.enablePromptCaching}}})}function h(q,x,z,J=Y(),w="auto",Q="auto"){let G=J.resolveConfig(q),U=B(G,z),W=$(G,w),X=Z(G,Q),L=q.overrides;return{config:q,model:G,displayName:q.displayName??G.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[D(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??L?.baseUrl,temperature:L?.temperature??x.temperature,maxContextTokens:G.contextWindow,maxOutputTokens:L?.maxOutputTokens,timeout:L?.timeout??x.timeout,streamIdleTimeout:L?.streamIdleTimeout,reasoningEnabled:U.effective!=="off",...U.effective==="off"?{}:{reasoningEffort:U.effective},...W.providerValue?{serviceTier:W.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:F(q,x),enablePromptCaching:L?.enablePromptCaching,customHeaders:R(L?.customHeaders,G,W),apiVersion:L?.apiVersion,maxRetries:L?.maxRetries,providerCircuitBreakerOpenMs:x.providerCircuitBreakerOpenMs,providerRequestConcurrency:x.providerRequestConcurrency,providerGlobalConcurrency:x.providerGlobalConcurrency,providerOwnerConcurrency:x.providerOwnerConcurrency,providerRequestAdmissionMs:x.providerRequestAdmissionMs,providerRequestPendingBytes:x.providerRequestPendingBytes,modelCatalog:J},reasoning:U,serviceTier:W,responseVerbosity:X}}function j(q,x=Y()){try{return q.displayName??x.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
2
+ export{D as jg,h as kg,j as lg};
@@ -1 +1 @@
1
- import{Ra as V,Ta as W,Ua as O,kb as J}from"./chunk-2242dshn.js";import"./chunk-7zvwfz85.js";import"./chunk-nry7d26k.js";import{Ji as Q}from"./chunk-be2csw9m.js";import"./chunk-679b7s58.js";import"./chunk-ar3sdj0w.js";import"./chunk-fjvt9mwv.js";import"./chunk-w3y69e4e.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
1
+ import{$a as O,Ya as V,_a as W,rb as J}from"./chunk-ermypm1x.js";import"./chunk-xt0ktytp.js";import"./chunk-0ccm29qy.js";import"./chunk-9a7bppj7.js";import{Si as Q}from"./chunk-g799czsy.js";import"./chunk-vp6d1fqp.js";import"./chunk-0k2x2ae6.js";import"./chunk-6e3mh79j.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
@@ -0,0 +1 @@
1
+ import{kf as a,lf as b,mf as c}from"./chunk-gpj7k3er.js";import"./chunk-39de5k03.js";import"./chunk-v5503t2t.js";import"./chunk-v508x7cg.js";import"./chunk-q0s3gcjm.js";import"./chunk-69nwa6bn.js";import"./chunk-ramana2t.js";import"./chunk-6xvrrypm.js";import"./chunk-9a7bppj7.js";import"./chunk-g799czsy.js";import"./chunk-mzye1ah2.js";import"./chunk-vp6d1fqp.js";import"./chunk-xg9fyvw0.js";import"./chunk-wxtj6gqb.js";import"./chunk-g9vdmvk2.js";import"./chunk-wxypv01z.js";import"./chunk-nxnmqk4s.js";import"./chunk-0k2x2ae6.js";import"./chunk-6e3mh79j.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -1,4 +1,4 @@
1
- import{cc as Xt,dc as En,ec as yn,fc as bn}from"./chunk-77efqpdc.js";import{fh as Bt}from"./chunk-gv24cgpb.js";import{Ah as un,Bh as cn,Ch as Mn,Eh as S,Hh as wn,Ih as Gt,Jh as Ut,Kh as h,Lh as Ht,kh as xt,lh as vi,mh as sn,nh as zt,oh as U,ph as en,qh as gt,rh as mt,th as rn,uh as Tn,vh as B,wh as dn,xh as on,yh as pn,zh as lt}from"./chunk-jy61b0v8.js";import{Ji as It}from"./chunk-be2csw9m.js";import{Ki as X,Mi as x}from"./chunk-679b7s58.js";import{Dj as tn,Ej as nn}from"./chunk-dnt4c3gy.js";import{sk as ns}from"./chunk-w3y69e4e.js";import{EventEmitter as fs}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} 个错误):
1
+ import{jc as Xt,kc as En,lc as yn,mc as bn}from"./chunk-wzkh3e6a.js";import{oh as Bt}from"./chunk-mavranwn.js";import{Ah as mt,Ch as rn,Dh as Tn,Eh as B,Fh as dn,Gh as on,Hh as pn,Ih as lt,Jh as un,Kh as cn,Lh as Mn,Nh as S,Qh as wn,Rh as Gt,Sh as Ut,Th as h,Uh as Ht,th as xt,uh as vi,vh as sn,wh as zt,xh as U,yh as en,zh as gt}from"./chunk-ramana2t.js";import{Si as It}from"./chunk-g799czsy.js";import{uj as X,wj as x}from"./chunk-vp6d1fqp.js";import{Mj as tn,Nj as nn}from"./chunk-g9vdmvk2.js";import{Bk as ns}from"./chunk-6e3mh79j.js";import{EventEmitter as fs}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;isRetrySafe;constructor(t,i,n,s,e,r=!1){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e;this.isRetrySafe=r}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,isRetrySafe:t.isRetrySafe??!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 @@ ${c}
22
22
 
23
23
  Preview (tail):
24
24
  ${M}`,u=!0}return{isError:t.isError===!0,llmContent:o,metadata:{contentCount:t.content.length,textBytes:n.textBytes,structuredBytes:r?.bytes??0,artifactCount:e.length,truncated:u,binaryOmitted:n.binaryBytes>0,artifacts:e}}}function yt(t){let i=t instanceof Error?t.message:String(t),n=gn(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"?x.Unsafe(n.inputSchema):x.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(u,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:u,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 c=await t.callTool(n.name,u,{...d.signal?{signal:d.signal}:{},...p}),M=await j(c,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 c=yt(p);return{success:!1,llmContent:`MCP tool execution failed: ${c}`,error:{type:"execution_error",message:c},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 us,ElicitRequestSchema as cs,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 Es}from"events";import bs from"open";import{EventEmitter as Bn}from"events";function Et(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 bt 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:Et(i.interval,30000,"MCP health check interval",10,300000),timeout:Et(i.timeout,1e4,"MCP health check timeout",10,60000),enabled:i.enabled??!1,failureThreshold:Et(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,ft=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),c=i.prompts.find((M)=>M.name===p);if(!c)throw Error(`MCP prompt "${p}" is not present in the current catalog`);e=new Set(c.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 u=Object.create(null),d=0;for(let[p,c]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(c,`completion context argument "${M}"`,ei);if(d+=Buffer.byteLength(M)+Buffer.byteLength(w),d>ni)throw Error(`MCP completion context exceeds ${ni} bytes`);u[M]=w}return{ref:r,argument:{name:n,value:s},...o.length>0?{context:{arguments:u}}:{}}}function ui(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=[],u=new Set,d=0,p=0,c=r>ti||s>ft;for(let w of i.values.slice(0,ti)){let y=Buffer.byteLength(w),E=Math.max(0,ft-p);if(E===0){c=!0;break}let a=di(w,Math.min(ft,E));if(p+=Buffer.byteLength(a),y>Buffer.byteLength(a))c=!0;let Dt=ci(a),L=di(Dt,Yn);if(Buffer.byteLength(L)<Buffer.byteLength(Dt))c=!0;if(u.has(L))continue;let Ft=Buffer.byteLength(L);if(d+Ft>Dn){c=!0;break}u.add(L),o.push(L),d+=Ft}if(o.length<r)c=!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||c||M!==void 0&&M>o.length,sourceValueCount:r,sourceBytes:s,projectedBytes:d,sha256:e,truncated:c}}function ci(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(ci(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),u=H(i?.terminalErrorThreshold,3,"MCP recovery terminalErrorThreshold",1,10);return{enabled:n,maxAttempts:s,initialDelayMs:e,maxDelayMs:r,jitterRatio:o,terminalErrorThreshold:u}}function Ei(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 bi(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 fi(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",u),s()},t);if(n)o.unref();let u=()=>{clearTimeout(o),i.removeEventListener("abort",u),e(C(i.reason))};i.addEventListener("abort",u,{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,g=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 b(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 f(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:f(n.uri,"resource URI",N),name:f(n.name,"resource name",A),...b(n.title,"resource title",A)?{title:n.title}:{},...b(n.description,"description",m)?{description:n.description}:{},...b(n.mimeType,"resource MIME type",g)?{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:f(n.uriTemplate,"resource template URI",N),name:f(n.name,"resource template name",A),...b(n.title,"resource template title",A)?{title:n.title}:{},...b(n.description,"description",m)?{description:n.description}:{},...b(n.mimeType,"resource template MIME type",g)?{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=f(e.name,"prompt argument name",A);if(["__proto__","constructor","prototype"].includes(r))throw Error(`MCP prompt argument name "${r}" is unsafe`);return{name:r,...b(e.description,"description",Gn)?{description:e.description}:{},required:e.required===!0}});return Q(s.map((e)=>e.name),`prompt "${n.name}" argument`),{name:f(n.name,"prompt name",A),...b(n.title,"prompt title",A)?{title:n.title}:{},...b(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 xi(t,i){let n=f(typeof t.uri==="string"?t.uri:"","resource content URI",N),s=typeof t.mimeType==="string"?b(t.mimeType,"resource MIME type",g):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 gi(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 xi(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,u=o.role;if(u!=="user"&&u!=="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 c=Buffer.byteLength(p.text);if(c>Z)throw Error(`MCP prompt text exceeds ${Z} bytes`);return kt(s,c,"prompt result"),{role:u,content:{type:"text",text:p.text}}}if((p.type==="image"||p.type==="audio")&&typeof p.data==="string"&&typeof p.mimeType==="string")return{role:u,content:{type:p.type,mimeType:f(p.mimeType,"prompt content MIME type",g),binary:Si(p.data,`prompt ${p.type}`,s)}};if(p.type==="resource"&&p.resource&&typeof p.resource==="object"&&!Array.isArray(p.resource))return{role:u,content:{type:"resource",resource:xi(p.resource,s)}};if(p.type==="resource_link"&&typeof p.uri==="string"&&typeof p.name==="string")return{role:u,content:{type:"resource_link",uri:f(p.uri,"prompt resource link URI",N),name:f(p.name,"prompt resource link name",A),...typeof p.mimeType==="string"?{mimeType:f(p.mimeType,"prompt resource link MIME type",g)}:{},...typeof p.description==="string"?{description:b(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:b(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=x.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 u=Qn(i);return{...r,type:"multi-select",options:u,...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 u=JSON.stringify(e.inputSchema),d=Buffer.byteLength(u);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(u),...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 Es{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 bt(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(u){if(!this.isConnectionGenerationCurrent(n)||s.aborted)throw C(s.reason);if(e=u instanceof Error?u:Error(String(u)),!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=cn(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 u=r.getServerVersion();this.serverInfo={name:u?.name||"Unknown",version:u?.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)}),bi(n)){this.startRecovery(n,"session_expired",!0);return}if(!fi(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=Ei(this.recoveryPolicy,r,this.runtimeOptions.recoveryRandom),u=Date.now()+o;this.publishConnectionLifecycle({phase:"reconnecting",reason:i,attempt:r,maxAttempts:this.recoveryPolicy.maxAttempts,nextRetryAt:u,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=gt(this.config),r=Symbol(t);this.activeInteraction={token:r,context:n,samplingRequests:0,samplingInFlight:!1};let o=new AbortController,u=setTimeout(()=>o.abort("mcp-tool-timeout"),e.totalTimeoutMs);u.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(c){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}" 失败:`,c),c}finally{if(clearTimeout(u),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 u=gt(this.config),d=Symbol(t),p={token:d,context:{...n,signal:s},samplingRequests:0,samplingInFlight:!1};this.activeInteraction=p;let c={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:u.idleTimeoutMs,maxTotalTimeout:u.totalTimeoutMs,resetTimeoutOnProgress:!0,onprogress:(y)=>{let E=mt(y,c,u);if(E&&!s.aborted&&this.hasInteractionToken(d))n.progressHandler?.(E),this.emit("toolProgress",{serverName:this.serverName,toolName:t,...E})}}),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 E=Ut(y.value.task,this.taskPolicy);return this.taskInteractions.set(E.taskId,p),w=!0,this.emit("taskCreated",{serverName:this.serverName,toolName:t,task:E}),E}finally{if(this.activeInteraction?.token===d)this.activeInteraction=void 0;if(!w){for(let[y,E]of this.taskInteractions)if(E.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`))},u=()=>{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",u)};if(this.on("connected",r),this.on("disconnected",o),t.addEventListener("abort",u,{once:!0}),t.aborted)u()})}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 u=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||u.reason===Xt||u.reason==="timeout")throw new P(R.InvalidRequest,"MCP sampling was cancelled");if(!u.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(cs,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,u=o?await Bt.getInstance().executeElicitationHooks(r,o):{},d;if(u.blockedReason)d={action:"decline"};else if(u.response)d=u.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 bs(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 c=Fi(r,d);return this.emit("elicitationResolved",{serverName:this.serverName,mode:r.mode,action:c.action,elicitationId:r.elicitationId}),c}catch(o){return this.emit("elicitationCancelled",{serverName:this.serverName,reason:o instanceof Error?o.message:String(o)}),{action:"cancel"}}}),t.setNotificationHandler(us,(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:u}=this.config,d;if(u?.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[c,M]of Object.entries(process.env))if(M!==void 0)p[c]=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},...u?.enabled?{fetch:xt}:{},...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},...u?.enabled?{fetch:xt}:{},...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 c=await i.listTools(e?{cursor:e}:void 0);if(n.push(...c.tools),n.length>l)throw Error(`MCP tool catalog exceeds ${l} tools`);if(e=c.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,u=Qi(o,r);if(this.tools=new Map(r.map((p)=>[p.name,p])),!nt(u))return;this.toolCatalogRevision++;let d={revision:this.toolCatalogRevision,reason:t,...u};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),u=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,u)}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 u=0;u<Pt;u++){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",un(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 ui(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 gi(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 fs{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 u=this.requireConnectedServer(t);if(!u.tools.some((d)=>d.name===i))throw Error(`MCP tool "${i}" is not present in server "${t}" catalog`);return T.getInstance().start({client:u.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 bn(i,Math.max(0,En-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[u,d]of this.servers){if(d.status!=="connected")continue;for(let p of d.tools){let c=Lt(u,p.name);if(n.has(c))throw Error(`Duplicate projected MCP tool "${c}"`);n.set(c,Tt(d.client,u,p,c,this.runtimeOptions.artifactWriter))}}let s=new Map([...this.projectedTools].map(([u,d])=>[u,JSON.stringify(d.getFunctionDeclaration())])),e=new Map([...n].map(([u,d])=>[u,JSON.stringify(d.getFunctionDeclaration())])),r={added:[...n.keys()].filter((u)=>!this.projectedTools.has(u)).sort(),removed:[...this.projectedTools.keys()].filter((u)=>!n.has(u)).sort(),updated:[...n.keys()].filter((u)=>this.projectedTools.has(u)&&s.get(u)!==e.get(u)).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 Ga,T as Ha,jn as Ia,vs as Ja,te as Ka,Fi as La,Lt as Ma,ts as Na,O as Oa};
25
+ export{jt as Ia,T as Ja,jn as Ka,vs as La,te as Ma,Fi as Na,Lt as Oa,ts as Pa,O as Qa};
@@ -0,0 +1,2 @@
1
+ var _=20,E=5242880,T=32768,A=1e6,S=4194304;
2
+ export{_ as Ki,E as Li,T as Mi,A as Ni,S as Oi};
@@ -1,4 +1,4 @@
1
- import{Gi as L,Ji as _}from"./chunk-be2csw9m.js";import{execSync as F}from"child_process";import{existsSync as Q,readFileSync as O,realpathSync as b}from"fs";import*as V from"os";import*as H from"path";import{basename as J,isAbsolute as j,resolve as R}from"path";function G(z=_()){let q=z,M=f(q);return{workingDirectory:q,projectRoot:M,platform:`${V.platform()} (${V.arch()})`,nodeVersion:process.version,currentDate:new Date().toISOString().split("T")[0],homeDirectory:V.homedir()}}function Y(z,q){try{return F(q,{cwd:z,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return null}}function v(z={}){let{includeGitSnapshot:q=!0,includeDirectoryListing:M=!0,workingDirectory:W}=z,B=G(W),$=Q(H.join(B.projectRoot,".git")),T=J(process.env.SHELL||"unknown"),A=["package.json","tsconfig.json","BLADE.md",".env.example"].filter((K)=>Q(H.join(B.projectRoot,K))).map((K)=>`- \`${H.join(B.projectRoot,K)}\``),N=`# Environment
1
+ import{Pi as L,Si as _}from"./chunk-g799czsy.js";import{execSync as F}from"child_process";import{existsSync as Q,readFileSync as O,realpathSync as b}from"fs";import*as V from"os";import*as H from"path";import{basename as J,isAbsolute as j,resolve as R}from"path";function G(z=_()){let q=z,M=f(q);return{workingDirectory:q,projectRoot:M,platform:`${V.platform()} (${V.arch()})`,nodeVersion:process.version,currentDate:new Date().toISOString().split("T")[0],homeDirectory:V.homedir()}}function Y(z,q){try{return F(q,{cwd:z,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return null}}function v(z={}){let{includeGitSnapshot:q=!0,includeDirectoryListing:M=!0,workingDirectory:W}=z,B=G(W),$=Q(H.join(B.projectRoot,".git")),T=J(process.env.SHELL||"unknown"),A=["package.json","tsconfig.json","BLADE.md",".env.example"].filter((K)=>Q(H.join(B.projectRoot,K))).map((K)=>`- \`${H.join(B.projectRoot,K)}\``),N=`# Environment
2
2
  You have been invoked in the following environment:
3
3
  - Primary working directory: ${B.workingDirectory}
4
4
  - Is a git repository: ${$?"true":"false"}
@@ -25,4 +25,4 @@ ${I.join(`
25
25
 
26
26
  Project root directory listing:
27
27
  ${K}`}return N}function f(z){let q=z,M=null;while(q!==H.dirname(q)){if(Q(H.join(q,".git")))return q;if(Q(H.join(q,".blade")))return q;if(Q(H.join(q,".claude")))return q;if(!M&&Q(H.join(q,"package.json")))M=q;q=H.dirname(q)}return M??z}function x(z,q){let M=j(z)?z:R(q||process.cwd(),z),W;try{W=b(M)}catch{W=M}L(W)}
28
- export{v as lf,f as mf,x as nf};
28
+ export{v as sf,f as tf,x as uf};
@@ -0,0 +1,5 @@
1
+ import{ig as wf}from"./chunk-0ccm29qy.js";import{Wi as t_,Xi as lf,Yi as yf,Zi as R_,_i as $f,aj as Lf,cj as Hf,ej as g,fj as Kf,hj as Uf,ij as Cf,kj as s}from"./chunk-mzye1ah2.js";import{sj as a}from"./chunk-vp6d1fqp.js";import{Cj as DE,Ej as zf}from"./chunk-xg9fyvw0.js";import{Hj as nE}from"./chunk-wxtj6gqb.js";var B_={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},tE=(f)=>B_[f]||{};var b_=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function cf(f){return typeof f==="string"&&b_.has(f)}function LT(f){if(!f.aborted)return;if(cf(f.reason))return f.reason;return"user-cancel"}function ZT(f){if(cf(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 RE(...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 N=()=>{T.abort(x.reason);for(let[A,M]of h)A.removeEventListener("abort",M)};h.set(x,N)}for(let[x,N]of h)x.addEventListener("abort",N,{once:!0});return T.signal}function _f(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 N,A=setTimeout(()=>{if(E&&N)E.removeEventListener("abort",N);h()},f);if(E)N=()=>{if(clearTimeout(A),T)x(new DOMException("Aborted","AbortError"));else h()},E.addEventListener("abort",N,{once:!0})})}var O_=a("Chat"),V_={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function AE(f){if(typeof f==="string")return f;return f.filter((E)=>E.type==="text").map((E)=>E.text).join(`
2
+ `)}function j_(f){if(!f)return{};try{let E=JSON.parse(f);return E&&typeof E==="object"&&!Array.isArray(E)?E:{}}catch{return O_.warn("[PiAIChatService] Invalid historical tool arguments",{value:f}),{}}}function X_(f){let E=f.match(/^data:([^;,]+);base64,(.+)$/s);return E?{mimeType:E[1],data:E[2]}:void 0}async function c_(f,E){let _=X_(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 PE(f,E,_){return Promise.all(f.map((T)=>T.type==="text"?Promise.resolve({type:"text",text:T.text}):E?c_(T.image_url.url,_):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})))}async function ME(f,E,_,T,h){let x=f.filter((S)=>S.role==="system").map((S)=>AE(S.content)).filter(Boolean).join(`
3
+
4
+ `),N=[],A=E.input.includes("image");for(let S of f){if(S.role==="system")continue;if(S.role==="user"){let t=typeof S.content==="string"?S.content:await PE(S.content,A,T);N.push({role:"user",content:t,timestamp:Date.now()});continue}if(S.role==="assistant"){let t=[];if(S.reasoningContent?.trim())t.push({type:"thinking",thinking:S.reasoningContent});let P=AE(S.content);if(P)t.push({type:"text",text:P});for(let D of S.tool_calls??[]){if(!("function"in D))continue;t.push({type:"toolCall",id:D.id,name:D.function.name,arguments:j_(D.function.arguments)})}N.push({role:"assistant",content:t,api:E.api,provider:E.provider,model:E.id,usage:V_,stopReason:S.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}N.push({role:"toolResult",toolCallId:S.tool_call_id??"",toolName:S.name??"unknown",content:typeof S.content==="string"?[{type:"text",text:S.content}]:await PE(S.content,A,T),isError:!1,timestamp:Date.now()})}let M=_?.filter((S)=>!h||S.name===h).map((S)=>({name:S.name,description:S.description,parameters:S.parameters,constrainedSampling:S.constrainedSampling})).sort((S,t)=>S.name<t.name?-1:S.name>t.name?1:0);return{...x?{systemPrompt:x}:{},messages:N,...M?.length?{tools:M}:{}}}function NE(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=[],N=_+1;while(N<f.length&&f[N].role==="tool")x.push(f[N++]);let A=new Set(h.map((t)=>t.id)),M=x.filter((t)=>t.tool_call_id&&A.has(t.tool_call_id)),S=new Set(M.map((t)=>t.tool_call_id));if(A.size===h.length&&M.length===A.size&&S.size===A.size)E.push(T,...M);_=N-1}return E}function uE(f){return f.some((E)=>E.role==="assistant"&&Boolean(E.tool_calls?.length)&&!E.reasoningContent?.trim())}function IE(f,E){return{...f,...E.baseUrl?{baseUrl:DE(f.api,E.baseUrl)}:{},...E.maxOutputTokens?{maxTokens:E.maxOutputTokens}:{}}}function Jf(f){let E=f.modelCatalog??zf();return{models:E.models,model:IE(E.getModel(f.provider,f.model),f)}}function HE(f,E){let _=f.modelCatalog??zf();return IE(_.getModel(E.provider,E.model),f)}import{createHash as z_}from"node:crypto";var J_=32,W_=1000,$_=512,L_=2000,G_=0.1,k_=0.05,Z_=0.9,Q_=300000,K_=3600000;class Wf{sessions=new Map;observe(f){if(f.retention==="none"){this.sessions.delete(f.sessionId);return}let E=f.now??Date.now(),_=C_(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<W_)return;let h=T.cacheReadTokens-_.cacheReadTokens,x=Math.min(L_,Math.max($_,T.cacheReadTokens*G_));if(h<x||_.cacheReadTokens>=T.cacheReadTokens*(1-k_))return;let N=_.modelIdentity!==T.modelIdentity,A=_.systemHash!==T.systemHash,M=_.toolsHash!==T.toolsHash,S=_.policyHash!==T.policyHash;if(!(N||A||M||S)&&_.promptTokens<T.promptTokens*Z_)return;let P=Math.max(0,E-T.recordedAt),D=T.retention==="long"?K_:Q_,Y=N?"model_changed":A?"system_prompt_changed":M?"tools_changed":S?"request_policy_changed":P>=D?"ttl_expired":"server_side",$=F_(T,_);return{reason:Y,previousCacheReadTokens:T.cacheReadTokens,cacheReadTokens:_.cacheReadTokens,cacheWriteTokens:Math.max(0,f.usage.cacheCreationInputTokens??0),tokenDrop:h,elapsedMs:P,callNumber:_.callCount,systemPromptChanged:A,systemCharDelta:_.systemChars-T.systemChars,toolsChanged:M,addedToolCount:$.added,removedToolCount:$.removed,changedToolCount:$.changed,modelChanged:N,requestPolicyChanged:S}}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>J_){let _=this.sessions.keys().next().value;if(_===void 0)break;this.sessions.delete(_)}}}function C_(f,E){let _=[...f.tools??f.context.tools??[]].map((T)=>({identityHash:Tf(T.name),contractHash:Tf(hf(T))})).sort((T,h)=>T.identityHash<h.identityHash?-1:T.identityHash>h.identityHash?1:0);return{modelIdentity:f.modelIdentity,systemHash:Tf(f.context.systemPrompt??""),systemChars:f.context.systemPrompt?.length??0,toolsHash:Tf(hf(_)),toolFingerprints:_,policyHash:Tf(hf(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 F_(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 hf(f){if(f===null||typeof f!=="object")return JSON.stringify(f)??"undefined";if(Array.isArray(f))return`[${f.map(hf).join(",")}]`;let E=f;return`{${Object.keys(E).sort().map((_)=>`${JSON.stringify(_)}:${hf(E[_])}`).join(",")}}`}function Tf(f){return z_("sha256").update(f).digest("hex")}import{randomBytes as o_}from"node:crypto";import{createHmac as v_}from"node:crypto";function s_(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 w_(f){if(!f)return[];return Object.entries(f).map(([E,_])=>[E.trim().toLowerCase(),_.trim()]).sort(([E],[_])=>E.localeCompare(_))}function uf(f,E,_){let T=JSON.stringify([f.provider.trim(),String(f.api).trim(),s_(f.baseUrl),f.model.trim(),f.serviceTier?.trim()??"",f.apiVersion?.trim()??"",f.apiKey??"",w_(f.customHeaders),_]);return v_("sha256",Buffer.from(E)).update(T).digest("hex")}var p_=60000,m_=4,q_=0.8;var If=300000,Gf=600000;var UE=128,YE=256,g_=1800000,Df=50;class tf 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 Rf(f){return f instanceof tf||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_CIRCUIT_OPEN"}function d(f,E){return f!==void 0&&Number.isSafeInteger(f)&&f>0?f:E}function l_(f,E){return f!==void 0&&Number.isFinite(f)&&f>0&&f<=1?f:E}function y_(f,E){return uf(f,E,{providerCircuitOpenDurationMs:f.openDurationMs})}function xf(f){let E=0;for(let _ of f)if(_.failure)E++;return E}function BE(f){return f!==void 0&&Number.isInteger(f)&&f>=100&&f<=599?f:void 0}function bE(f){if(f===void 0||!Number.isFinite(f)||f<0)return;return Math.min(Math.ceil(f),Lf)}class VE{#x=new Map;#t=new WeakMap;#f;#_;#h;#T;constructor(f={}){this.#f=f.processSecret?new Uint8Array(f.processSecret):o_(32),this.#_=f.now??(()=>performance.now()),this.#h=f.wallNow??f.now??Date.now,this.#T={maxEntries:Math.min(d(f.maxEntries,UE),UE),maxWindowEntries:Math.min(d(f.maxWindowEntries,YE),YE),windowMs:d(f.windowMs,p_),minSamples:d(f.minSamples,m_),errorRateThreshold:l_(f.errorRateThreshold,q_),idleTtlMs:d(f.idleTtlMs,g_)}}get size(){return this.#x.size}get(f){if(f.openDurationMs===0)return this.#A();let E=this.#_();this.#B(E);let _=y_(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.#I();if(this.#x.size>=this.#T.maxEntries)return this.#A();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(If,Math.min(d(E,If),Gf));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:()=>_.#X(f)}}#A(){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.#M(E),recordFailure:(E)=>f.#M(E),recordNeutral:(E)=>f.#M(E),abandon:(E)=>f.#N(E),snapshot:()=>({state:"closed",sampleCount:0,failureCount:0,noop:!0,detached:!1})}}#M(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+Df)-E);return this.#U(f,Math.min(Df,_))}#U(f,E){let{allowed:_,...T}=this.#S(f,E);return{eligible:!1,...T}}#b(f,E){let _=this.#_();if(f.detached)return this.#A().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.#S(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??_+Df)-_);return this.#S(f,Math.min(Df,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:xf(f.samples)}}#S(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:xf(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.#D(h,_,x,"reopened");return this.#V(h)}if(E==="neutral")return;if(this.#j(h,E==="failure",x),E!=="failure"||!_)return;let N=xf(h.samples),A=h.samples.length===0?0:N/h.samples.length;if(h.samples.length>=this.#T.minSamples&&A>=this.#T.errorRateThreshold)return this.#D(h,_,x,"opened");return}#D(f,E,_,T){let h={reason:E.reason,...BE(E.statusCode)!==void 0?{statusCode:BE(E.statusCode)}:{},...bE(E.retryAfterMs)!==void 0?{retryAfterMs:bE(E.retryAfterMs)}:{}},x=h.retryAfterMs??0,N=Math.max(f.configuredOpenDurationMs,x);return f.state="open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.effectiveOpenDurationMs=N,f.nextProbeAt=_+N,f.lastFailure=h,{phase:T,reason:h.reason,...h.statusCode!==void 0?{statusCode:h.statusCode}:{},retryAfterMs:N,nextProbeAt:this.#h()+N,openDurationMs:N,sampleCount:f.samples.length,failureCount:xf(f.samples)}}#V(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}#j(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)}#X(f){if(!f.detached)this.#u(f,this.#_());return{state:f.state,sampleCount:f.samples.length,failureCount:xf(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,_)}#I(){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 OE;function jE(){return OE??=new VE,OE}import{randomBytes as a_}from"node:crypto";var d_=16,XE=128,cE=32,e_=3,zE=16,JE=96,WE=24,$E=12,LE=16,GE=4,kE=4,ZE=67108864,QE=33554432,n_=12,r_=2,KE=2,CE=1,oE=15000,FE=30000;function kf(){return{foreground:0,background:0,internal:0}}function Zf(){return{inFlight:kf(),queued:kf(),pendingBytes:kf()}}function U(f){return f.foreground+f.background+f.internal}function W(f){return f.background+f.internal}function vE(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 Af extends Error{reason;scope;requestClass;resource;inFlight;limit;queued;maxWaitMs;code="PROVIDER_ADMISSION_BUSY";retryable;constructor(f,E,_,T,h,x,N,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=N;this.maxWaitMs=A;this.name="ProviderAdmissionError",this.retryable=f!=="closed"}}function l(f){return f instanceof Af||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 i_(f){let E=z(f.globalMaxInFlight,d_,Number.MAX_SAFE_INTEGER),_=z(f.globalMaxPending,XE,XE),T=z(f.domainMaxPending,cE,cE),h=Math.min(z(f.ownerMaxInFlight,e_,Number.MAX_SAFE_INTEGER),E),x=Math.min(z(f.ownerMaxPending,zE,zE),_),N=Math.min(z(f.nonForegroundGlobalMaxPending,Math.min(JE,Math.max(1,Math.floor(_*3/4))),JE),_),A=Math.min(z(f.nonForegroundDomainMaxPending,Math.min(WE,Math.max(1,Math.floor(T*3/4))),WE),T),M=Math.min(z(f.nonForegroundOwnerMaxPending,Math.min($E,Math.max(1,Math.floor(x*3/4))),$E),x),S=Math.min(z(f.internalGlobalMaxPending,Math.min(LE,Math.max(1,Math.floor(_/8))),LE),N),t=Math.min(z(f.internalDomainMaxPending,Math.min(GE,Math.max(1,Math.floor(T/8))),GE),A),P=Math.min(z(f.internalOwnerMaxPending,Math.min(kE,Math.max(1,Math.floor(x/4))),kE),M),D=z(f.globalMaxPendingBytes,s,s),Y=Math.min(z(f.domainMaxPendingBytes,ZE,ZE),D),$=Math.min(z(f.ownerMaxPendingBytes,QE,QE),D),Q=Math.min(z(f.nonForegroundGlobalMaxInFlight,Math.min(n_,E),E),E),K=Math.min(z(f.nonForegroundOwnerMaxInFlight,Math.min(r_,h),h),h),F=Math.min(z(f.internalGlobalMaxInFlight,Math.min(KE,E),KE),E),Bf=z(f.internalDomainMaxInFlight,CE,CE),Pf=z(f.agingMs,FE,FE);return{globalMaxInFlight:E,globalMaxPending:_,domainMaxPending:T,ownerMaxInFlight:h,ownerMaxPending:x,nonForegroundGlobalMaxPending:N,nonForegroundDomainMaxPending:A,nonForegroundOwnerMaxPending:M,internalGlobalMaxPending:S,internalDomainMaxPending:t,internalOwnerMaxPending:P,globalMaxPendingBytes:D,domainMaxPendingBytes:Y,ownerMaxPendingBytes:$,nonForegroundGlobalMaxInFlight:Q,nonForegroundOwnerMaxInFlight:K,internalGlobalMaxInFlight:F,internalDomainMaxInFlight:Bf,agingMs:Pf,classLimitsEnabled:f.classLimitsEnabled!==!1}}function sE(f,E){if(!f.trim())throw Error(`${E} must not be blank`)}function fT(f){if(sE(f.sessionId,"sessionId"),sE(f.ownerId,"ownerId"),!Number.isSafeInteger(f.scope.maxConcurrent)||f.scope.maxConcurrent<Hf||f.scope.maxConcurrent>g)throw Error(`maxConcurrent must be between ${Hf} and ${g}`);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>Uf)throw Error(`maxWaitMs must be 0-${Uf}`)}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 ET(f,E){return uf(f,E,{providerRequestConcurrency:f.maxConcurrent,providerRequestPendingBytes:f.maxPendingBytes})}class pE{#x;#t;#f;#_=[];#h=new Map;#T=new Map;#E=Zf();#A=1;#M=0;#P=!1;constructor(f={}){this.#x=f.processSecret?new Uint8Array(f.processSecret):a_(32),this.#t=f.now??(()=>performance.now()),this.#f=i_(f)}admit(f){if(fT(f),this.#P)throw this.#c("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=ET(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.#S(h,x,f.requestClass)){if(!_)this.#h.set(E,h);if(!T)this.#T.set(f.ownerId,x),this.#A++;let D=this.#D(E,f.ownerId,f.requestClass),Y=this.#L(f,0);return{ready:Promise.resolve(D),getSnapshot:()=>({...Y}),cancel:()=>{Y={...Y}}}}let N=this.#U(f,h,x);if(N)throw this.#c("queue_full",f,N,this.#_.length);let A=this.#R(h,x,f.requestClass);if(f.maxWaitMs===0)throw this.#c("wait_timeout",f,A,this.#_.length);if(!_)this.#h.set(E,h);if(!T)this.#T.set(f.ownerId,x),this.#A++;let M,S,t=new Promise((D,Y)=>{M=D,S=Y});t.catch(()=>{return});let P={domainKey:E,sessionId:f.sessionId,ownerId:f.ownerId,requestClass:f.requestClass,maxWaitMs:f.maxWaitMs,pendingBytes:f.pendingBytes,enqueuedAt:this.#t(),signal:f.signal,resolve:M,reject:S,settled:!1,admitted:!1};if(f.signal)P.abortListener=()=>this.#B(P,Qf(f.signal)),f.signal.addEventListener("abort",P.abortListener,{once:!0});return P.timer=setTimeout(()=>this.#X(P),f.maxWaitMs),P.timer.unref?.(),this.#_.push(P),this.#b(h,x,P),this.#N(),{ready:t,getSnapshot:()=>this.#$(P),cancel:(D)=>this.#B(P,Qf(f.signal,D))}}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.#I(f,new Af("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=(t,P,D)=>P>=D?{scope:t,resource:"pending_count",inFlight:P,limit:D}:void 0;if(this.#f.classLimitsEnabled&&f.requestClass==="internal"){let t=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(t)return t}if(this.#f.classLimitsEnabled&&f.requestClass!=="foreground"){let t=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(t)return t}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),N=Math.min(x,this.#f.domainMaxPendingBytes),A=Math.min(x,this.#f.ownerMaxPendingBytes),M=(t,P)=>f.pendingBytes>P-t,S=(t)=>{if(t==="owner")return{scope:t,resource:"pending_bytes",inFlight:U(_.counters.inFlight),limit:this.#f.ownerMaxInFlight};if(t==="domain")return{scope:t,resource:"pending_bytes",inFlight:U(E.counters.inFlight),limit:E.maxConcurrent};return{scope:t,resource:"pending_bytes",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight}};if(f.requestClass==="internal"){let t=Math.max(1,Math.floor(x/8)),P=Math.max(1,Math.floor(N/4)),D=Math.max(1,Math.floor(A/4));if(M(this.#E.pendingBytes.internal,t)||M(_.counters.pendingBytes.internal,D)||M(E.counters.pendingBytes.internal,P))return S("class")}if(f.requestClass!=="foreground"){let t=Math.max(1,Math.floor(x*3/4)),P=Math.max(1,Math.floor(N*3/4)),D=Math.max(1,Math.floor(A/2));if(M(W(this.#E.pendingBytes),t)||M(W(_.counters.pendingBytes),D)||M(W(E.counters.pendingBytes),P))return S("class")}if(M(U(this.#E.pendingBytes),x))return S("global");if(M(U(_.counters.pendingBytes),A))return S("owner");if(M(U(E.counters.pendingBytes),N))return S("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.#A,counters:Zf()}}#S(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}}#D(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.#V(f,E,_)}}}#V(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,M]of this.#_.entries()){let S=this.#h.get(M.domainKey),t=this.#T.get(M.ownerId);if(S===void 0||t===void 0||!this.#S(S,t,M.requestClass))continue;let P=this.#j(M,f),D=E.get(M.ownerId);if(!D||P<D.rank||P===D.rank&&A<D.index)E.set(M.ownerId,{pending:M,rank:P,index:A})}let _=[...E.values()].filter(({pending:A})=>{let M=this.#h.get(A.domainKey),S=this.#T.get(A.ownerId);return M!==void 0&&S!==void 0&&this.#S(M,S,A.requestClass)}).map(({pending:A,rank:M})=>({pending:A,rank:M,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),N=h.filter((A)=>A.order>this.#M).sort((A,M)=>A.order-M.order)[0]??h.sort((A,M)=>A.order-M.order)[0];this.#u(N.pending,N.order)}}#j(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.#M=E;let _=this.#D(f.domainKey,f.ownerId,f.requestClass);f.permit=_,f.resolve(_)}#X(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.#I(f,new Af("wait_timeout",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}#B(f,E){this.#I(f,E)}#I(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(_&&vE(_.counters))this.#h.delete(f);let T=this.#T.get(E);if(T&&vE(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.#G(f,h.scope),queueDepth:this.#_.length,inFlight:h.inFlight,limit:h.limit,waitMs:E,maxWaitMs:f.maxWaitMs}}#L(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}}#G(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)}#c(f,E,_,T){return new Af(f,_.scope,E.requestClass,_.resource,_.inFlight,_.limit,T,E.maxWaitMs)}}var wE;function mE(f={}){return wE??=new pE(f),wE}var qE=new WeakSet;class e 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 _T=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],TT=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],hT=["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 gE(f){return(f instanceof Error?f.message:String(f)).toLowerCase()}function xT(f){let E=gE(f);return TT.some((_)=>E.includes(_))}function vf(f){if(f!==null&&typeof f==="object")qE.add(f)}function Rh(f){return f!==null&&typeof f==="object"&&qE.has(f)}function tT(f){return f!==null&&typeof f==="object"&&"code"in f?f.code:void 0}function RT(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 AT(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 o(f,E){let _=gE(f),T=tT(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(_T.some((x)=>_.includes(x))||xT(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??RT(f)??AT(_);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(hT.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 lE(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 N=Math.max(0,f-1),A=_.maxExponentialDelayMs??8000,M=Math.min(500*2**N,A),S=Math.max(0,Math.min(1,_.random??Math.random())),t=M*(0.75+S*0.25);return Math.min(Math.round(t),h)}function of(f,E){return{provider:wf(f),model:wf(E)}}function yE(f,E){if(l(f))return{source:"admission",reason:f.reason};if(Rf(f))return{source:"circuit",reason:f.circuit.reason,...f.circuit.statusCode!==void 0?{statusCode:f.circuit.statusCode}:{}};if(f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT")return{source:"stall",reason:"timeout"};let _=o(f,E);if(_.retryable&&_.reason)return{source:"retry",reason:_.reason,..._.statusCode!==void 0?{statusCode:_.statusCode}:{}};throw Error("Provider fallback trigger is not classified")}function aE(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,N=0,A=!1,M=(t)=>{if(A||t<=0)return;if(!Number.isSafeInteger(t)||t>_-x){x=_+1,A=!0;return}x+=t},S=(t)=>{if(A)return;if(N+=1,N>T){M(_+1);return}if(t===null){M(4);return}switch(typeof t){case"string":M(Buffer.byteLength(t,"utf8"));return;case"number":case"bigint":M(8);return;case"boolean":M(4);return;case"undefined":case"function":case"symbol":return;case"object":break}if(h.has(t))return;if(h.add(t),ArrayBuffer.isView(t)){M(32+t.byteLength);return}if(t instanceof ArrayBuffer){M(32+t.byteLength);return}if(t instanceof Date){M(40);return}if(t instanceof RegExp){M(32+Buffer.byteLength(t.source,"utf8"));return}if(t instanceof Map){M(32);for(let[P,D]of t)if(S(P),S(D),A)return;return}if(t instanceof Set){M(32);for(let P of t)if(S(P),A)return;return}if(t instanceof WeakMap||t instanceof WeakSet){M(32);return}if(Array.isArray(t)){M(16);for(let P of t)if(S(P),A)return;return}M(32);for(let P of Reflect.ownKeys(t)){if(typeof P!=="string")continue;let D=Object.getOwnPropertyDescriptor(t,P);if(!D?.enumerable||!("value"in D))continue;if(M(8+Buffer.byteLength(P,"utf8")),S(D.value),A)return}};return S(f),x}function dE(f){return aE([f.messages,f.context,f.tools,f.requestOptions],{maxBytes:s})}function rE(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 PT(f){if(!f.reasoningEnabled)return;return f.reasoningEffort??f.reasoningLevel??"high"}function pf(f,E,_){if(!f.enablePromptCaching)return"none";if(_&&E.api==="openai-completions"&&!E.baseUrl.includes("api.openai.com"))return"long";return"short"}function ST(f){switch(f){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function MT(f,E,_,T){let h=T?void 0:PT(_);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:ST(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 NT(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 uT(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;rE(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 DT(f,E,_){let T=_.responseVerbosity;if(!T)return;if(nE(E,T),E.api==="openai-codex-responses"){f.textVerbosity=T;return}rE(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 iE(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:pf(f,E,T?.providerSessionId),sessionId:T?.providerSessionId};if(MT(x,E,f,h),NT(x,E.api,T?.toolChoice?.toolName),uT(x,E,f),DT(x,E,f),E.api==="azure-openai-responses")x.azureBaseUrl=f.baseUrl,x.azureApiVersion=f.apiVersion,x.azureDeploymentName=E.id;return x}function eE(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 IT=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function f_(f,E,_){let T=f.onResponse;if(f.onResponse=async(x,N)=>{let A=new Headers(x.headers);_(eE(x.status,A)),await T?.(x,N)},!IT.has(E.api)||typeof globalThis.fetch!=="function")return;let h=typeof f.fetch==="function"?f.fetch:globalThis.fetch.bind(globalThis);f.fetch=async(x,N)=>{let A=await h(x,N);return _(eE(A.status,A.headers)),A}}function E_(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 Yf=300000,HT=30000;class __ 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 T_ extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function mf(f){return f.reason instanceof Error?f.reason:new DOMException("Aborted","AbortError")}function UT(f){return f.idleTimeoutMs&&f.idleTimeoutMs>0?f.idleTimeoutMs:Yf}function YT(f,E){if(E===0)return;let _=E!==void 0&&E>0?E:HT;return Math.max(1,Math.min(_,Math.floor(f/2)))}function BT(f,E,_){if(_?.aborted)return Promise.reject(mf(_));return new Promise((T,h)=>{let x=!1,N=()=>{clearTimeout(t),_?.removeEventListener("abort",S)},A=(P)=>{if(x)return;x=!0,N(),T(P)},M=(P)=>{if(x)return;x=!0,N(),h(P instanceof Error?P:Error(String(P)))},S=()=>{if(_)M(mf(_))},t=setTimeout(()=>A({kind:"timer"}),Math.max(0,E));if(_?.addEventListener("abort",S,{once:!0}),_?.aborted){S();return}f.then((P)=>A({kind:"next",result:P}),M)})}async function*bT(f,E,_){let T=UT(E),h=YT(T,E.stallWarningMs);if(E.signal?.aborted)throw mf(E.signal);let x=Date.now(),N=Promise.resolve().then(()=>f.next()),A;for(;;){let S=await BT(N,(A?T:h??T)-(Date.now()-x),E.signal);if(S.kind==="next"){if(A)yield{...A,phase:"recovered",durationMs:Math.max(A.durationMs,Date.now()-x)};return S.result}if(!A&&h!==void 0){_.stallCount++,A={phase:"detected",stallCount:_.stallCount,durationMs:h,warningAfterMs:h,timeoutMs:T,outputStarted:_.outputStarted},yield A;continue}let t=new __(T);throw E.abort?.(t),t}}async function*h_(f,E,_,T,h={}){let N=f.stream(E,_,T)[Symbol.asyncIterator](),A=0,M=!1,S={stallCount:0,outputStarted:!1};try{while(!0){let t=bT(N,h,S),P=await t.next();while(!P.done)yield{providerStall:P.value},P=await t.next();let D=P.value;if(D.done)throw new T_;let Y=D.value;switch(Y.type){case"text_delta":S.outputStarted=!0,yield{content:Y.delta};break;case"thinking_delta":S.outputStarted=!0,yield{reasoningContent:Y.delta};break;case"toolcall_end":S.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":M=!0,yield{finishReason:Y.reason,usage:E_(Y.message.usage)};return;case"error":throw Error(Y.error.errorMessage??`Request ${Y.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!M)Promise.resolve(N.return?.()).catch(()=>{return})}}var qf=a("Chat"),OT=1;function VT(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 jT(f){return Boolean(f&&f.role==="user"&&Array.isArray(f.content)&&f.content.some((E)=>E.type==="image_url"))}function XT(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 cT(f,E){let _=o(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 gf(f){return f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT"}class af{config;models;model;promptCacheBreakMonitor=new Wf;providerAdmissionScheduler;admissionFallbackOwnerId=`pi-service-${process.pid}-${OT++}`;constructor(f){let E=Jf(f);this.config={...f,maxContextTokens:E.model.contextWindow,maxOutputTokens:f.maxOutputTokens??E.model.maxTokens},this.models=E.models,this.model=E.model,this.providerAdmissionScheduler=x_(this.config),qf.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(f,E,_,T){let h="",x="",N=[],A,M;for await(let S of this.streamChat(f,E,_,T)){h+=S.content??"",x+=S.reasoningContent??"";for(let t of S.toolCalls??[])if(t.id&&t.type==="function"&&t.function?.name)N.push(t);A=S.usage??A,M=S.finishReason??M}return{content:h,...x?{reasoningContent:x}:{},...N.length>0?{toolCalls:N}:{},usage:A,finishReason:M}}async*streamChat(f,E,_,T){let h=T?.toolChoice?.toolName;if(h&&!E?.some((R)=>R.name===h))throw Error(`Required tool is unavailable: ${h}`);let x=NE(f);if(x.some((R)=>jT(R))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let N=Boolean(h)||uE(x),A=await ME(x,this.model,E,_,h),M=(R,u)=>{let V=T?.providerSessionId;if(!V||!R.usage)return R;if(!this.config.enablePromptCaching)return this.promptCacheBreakMonitor.clear(V),R;let B=pf(this.config,u,V),I=this.promptCacheBreakMonitor.observe({sessionId:V,modelIdentity:`${u.provider}\x00${u.api}\x00${u.id}`,context:A,retention:B,contextEpoch:XT(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:R.usage});if(!I)return R;return qf.warn("[PiAIChatService] Prompt cache break detected",{reason:I.reason,previousCacheReadTokens:I.previousCacheReadTokens,cacheReadTokens:I.cacheReadTokens,tokenDrop:I.tokenDrop,callNumber:I.callNumber}),{...R,usage:{...R.usage,promptCacheBreak:I}}},S=dE({messages:x,context:A,tools:E,requestOptions:T}),t=T?.providerRecovery;if(t&&!R_(t.budgetMs))throw Error("Invalid bounded foreground Provider recovery budget");let P=t?.mode==="bounded_foreground"&&t.budgetMs>0?{budgetMs:t.budgetMs,startedAt:void 0}:void 0,D=P?"bounded_foreground":"standard",Y=this.config.maxRetries??2,$=this.config.maxRetries??(P?t_:2),Q=P!==void 0&&this.config.maxRetries===void 0,K=0,F,Bf=this.config.providerCircuitRegistry??jE(),Pf=this.config.providerCircuitBreakerOpenMs??$f,A_=Math.max(If,Math.min(this.config.streamIdleTimeout??Yf,Gf)),df=this.providerAdmissionScheduler,P_=this.config.providerRequestConcurrency??g,ef=this.config.providerRequestAdmissionMs??Kf,S_=this.config.providerRequestPendingBytes??Cf,bf=T?.providerAdmission??{sessionId:this.admissionFallbackOwnerId,ownerId:this.admissionFallbackOwnerId,requestClass:"internal"},M_=(R,u)=>Bf.get({provider:R.provider,api:R.api,baseUrl:R.baseUrl??u.baseUrl??"",model:R.id,serviceTier:u.serviceTier,apiVersion:u.apiVersion,apiKey:u.apiKey,customHeaders:u.customHeaders,openDurationMs:Pf,probeLeaseMs:A_}),N_=(R,u)=>({provider:R.provider,api:R.api,baseUrl:R.baseUrl??u.baseUrl??"",model:R.id,serviceTier:u.serviceTier,apiVersion:u.apiVersion,apiKey:u.apiKey,customHeaders:u.customHeaders,maxConcurrent:P_,maxPendingBytes:S_}),X=(R=Date.now())=>{if(!P)return;let u=P.startedAt===void 0?0:Math.min(P.budgetMs,Math.max(0,R-P.startedAt));return{recoveryBudgetMs:P.budgetMs,recoveryElapsedMs:u,recoveryRemainingMs:Math.max(0,P.budgetMs-u)}},w=()=>({mode:D,...X()??{}}),nf=()=>{if(P&&P.startedAt===void 0)P.startedAt=Date.now()},p=()=>{let R=X();return new e(P?.budgetMs??0,R?.recoveryElapsedMs??0)},n=()=>!Q||K<$+1,Of=(R,u)=>{let{state:V,...B}=u;return{phase:R,...B,...X()?{recoveryRemainingMs:X()?.recoveryRemainingMs}:{}}},rf=(R)=>({phase:"rejected",requestClass:R.requestClass,resource:R.resource,scope:R.scope,reason:R.reason,queuePosition:0,queueDepth:Math.max(0,R.queued),inFlight:Math.max(0,R.inFlight),limit:Math.max(0,R.limit),waitMs:R.reason==="wait_timeout"?R.maxWaitMs:0,maxWaitMs:R.maxWaitMs,...X()?{recoveryRemainingMs:X()?.recoveryRemainingMs}:{}}),u_=async function*(R,u){if(!df)return{release:()=>{return}};let V=X()?.recoveryRemainingMs,B=V!==void 0&&P?.startedAt!==void 0?Math.min(ef,V):ef,I;try{I=df.admit({scope:N_(R,u),sessionId:bf.sessionId,ownerId:bf.ownerId,requestClass:bf.requestClass,maxWaitMs:B,pendingBytes:S,signal:_})}catch(b){if(l(b)){if(b.reason==="wait_timeout"&&P?.startedAt!==void 0&&(X()?.recoveryRemainingMs??0)<=0)throw p();yield{providerAdmission:rf(b)}}throw b}let G=I.getSnapshot();if(G.state==="admitted")return await I.ready;yield{providerAdmission:Of("queued",G)};let v=I.ready.then((b)=>({kind:"ready",permit:b}),(b)=>({kind:"error",error:b}));while(!0){let b=I.getSnapshot(),O=Math.max(1,Math.min(oE,Math.max(1,B-b.waitMs))),J,c=new Promise((m)=>{J=setTimeout(()=>m({kind:"heartbeat"}),O),J.unref?.()}),k=await Promise.race([v,c]);if(J)clearTimeout(J);if(k.kind==="heartbeat"){yield{providerAdmission:Of("queued",I.getSnapshot())};continue}if(k.kind==="error"){if(l(k.error)){if(k.error.reason==="wait_timeout"&&P?.startedAt!==void 0&&(X()?.recoveryRemainingMs??0)<=0)throw p();yield{providerAdmission:rf(k.error)}}throw k.error}return yield{providerAdmission:Of("admitted",I.getSnapshot())},k.permit}},D_=(R,u)=>{if(!n())throw p();if(Q)K++;F=void 0;let V=new AbortController,B=_?RE(_,V.signal):V.signal,I=typeof u.timeout==="number"&&Number.isFinite(u.timeout)&&u.timeout>0?Math.max(1,Math.floor(u.timeout)):void 0,G;if(P?.startedAt!==void 0){let O=X()?.recoveryRemainingMs??0;if(O<=0)throw p();G={remainingMs:O,error:new e(P.budgetMs,P.budgetMs)}}let v=iE(u,R,B,T,N);f_(v,R,(O)=>{F=O});let b=h_(this.models,R,A,v,{idleTimeoutMs:u.streamIdleTimeout??Yf,signal:B,abort:(O)=>V.abort(O)});return async function*(){let O,J;try{if(I!==void 0&&(G===void 0||I<G.remainingMs)){let c=new Ff(I);O=setTimeout(()=>V.abort(c),I),O.unref?.()}if(G){let c=G;J=setTimeout(()=>V.abort(c.error),c.remainingMs),J.unref?.()}yield*b}finally{if(O)clearTimeout(O);if(J)clearTimeout(J)}}()},fE=this,y=(R)=>({phase:R.phase,reason:R.reason,...R.statusCode!==void 0?{statusCode:R.statusCode}:{},...R.retryAfterMs!==void 0?{retryAfterMs:R.retryAfterMs}:{},...R.nextProbeAt!==void 0?{nextProbeAt:R.nextProbeAt}:{},openDurationMs:R.openDurationMs,sampleCount:R.sampleCount,failureCount:R.failureCount,...X()?{recoveryRemainingMs:X()?.recoveryRemainingMs}:{}}),EE=(R,u)=>({phase:R,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,...X()?{recoveryRemainingMs:X()?.recoveryRemainingMs}:{}}),I_=(R)=>({phase:"probe",reason:R.reason??"server_error",...R.statusCode!==void 0?{statusCode:R.statusCode}:{},openDurationMs:R.openDurationMs??Pf,...R.sampleCount!==void 0?{sampleCount:R.sampleCount}:{},...R.failureCount!==void 0?{failureCount:R.failureCount}:{},...X()?{recoveryRemainingMs:X()?.recoveryRemainingMs}:{}}),Vf=(R,u,V)=>({providerRetry:{phase:"exhausted",attempt:R,maxRetries:$,reason:u,...V!==void 0?{statusCode:V}:{},...w(),exhaustedBy:"recovery_budget"}}),_E=async function*(R,u,V,B,I){let G,v=!1,b,O,J=M_(R,u);for(let c=0;c<=B;c++){if(!n())break;let k,m;while(!k){let H=J.preflight();while(!H.eligible){if(b=H.reason,O=H.statusCode,!P||!I){let C=EE("rejected",H);throw yield{providerCircuit:C},new tf(C)}nf();let j=X()?.recoveryRemainingMs??0;if(j<=0){let C=p();throw yield Vf(Q?Math.max(0,K-1):c,H.reason,H.statusCode),C}yield{providerCircuit:EE("waiting",H)};let q=Math.min(Math.max(1,H.retryAfterMs),lf,j);if(await _f(q,_,{throwOnAbort:!0}),(X()?.recoveryRemainingMs??0)<=0){let C=p();throw yield Vf(Q?Math.max(0,K-1):c,H.reason,H.statusCode),C}H=J.preflight()}try{m=yield*u_(R,u)}catch(Z){if(Z instanceof e)yield Vf(Q?Math.max(0,K-1):c,b??"timeout",O);throw Z}let L=J.check();if(L.allowed)k=L;else m.release(),m=void 0}let i=k.token;if(k.probe)yield{providerCircuit:I_(k)};try{let H=!1,L=!1;for await(let Z of D_(R,u)){if(Z.providerStall){yield Z;continue}let j=Q?K-1:c;if(j>0&&b&&!H)H=!0,yield{providerRetry:{phase:"recovered",attempt:j,maxRetries:$,reason:b,...O!==void 0?{statusCode:O}:{},...w()}};if(!L){L=!0;let q=J.recordSuccess(i);if(q)yield{providerCircuit:y(q)}}v=!0,V(),yield M(Z,R)}if(!L){let Z=J.recordSuccess(i);if(Z)yield{providerCircuit:y(Z)}}return}catch(H){if(m?.release(),G=H,fE.logIdleTimeout(H,v,R),await fE.handleAbort(_),H instanceof e){if(v)throw vf(H),H;throw yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):c,maxRetries:$,reason:b??"timeout",...O!==void 0?{statusCode:O}:{},...w(),exhaustedBy:"recovery_budget"}},H}let L=o(H,F);if(v)throw vf(H),H;let Z=cT(H,F),j=Z?J.recordFailure(i,Z):F&&!gf(H)?J.recordNeutral(i):void 0;if(j)yield{providerCircuit:y(j)};if(!L.retryable||!L.reason){if(c>0&&b)yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):c,maxRetries:$,reason:b,...O!==void 0?{statusCode:O}:{},...w()}};throw H}b=L.reason,O=L.statusCode;let q=c<B&&n();if(j&&j.phase!=="closed"&&q&&(!P||!I)){let C={...y(j),phase:"rejected"};throw yield{providerCircuit:C},new tf(C)}if(q){nf();let C=Q?K:c+1,U_=lE(C,F,P?{maxDelayMs:yf,maxExponentialDelayMs:yf}:void 0),hE=j&&j.phase!=="closed"?j.retryAfterMs??0:0;if(P&&hE>0&&j)yield{providerCircuit:{...y(j),phase:"waiting"}};let Y_=X(),Xf=Math.max(U_,hE),ff=P?Math.min(Xf,Y_?.recoveryRemainingMs??Xf):Xf,Mf={attempt:C,maxRetries:$,reason:L.reason,...L.statusCode!==void 0?{statusCode:L.statusCode}:{}};if(yield{providerRetry:{phase:"scheduled",...Mf,delayMs:ff,nextRetryAt:Date.now()+ff,...w()}},P){let Ef=ff;while(Ef>0){let xE=Math.min(Ef,lf);if(await _f(xE,_,{throwOnAbort:!0}),Ef-=xE,(X()?.recoveryRemainingMs??0)<=0){let Nf=p();throw yield{providerRetry:{phase:"exhausted",...Mf,...w(),exhaustedBy:"recovery_budget"}},Nf}if(Ef>0){if(j&&j.phase!=="closed"&&j.nextProbeAt!==void 0){let Nf=Math.max(0,j.nextProbeAt-Date.now());if(Nf>0)yield{providerCircuit:{...y(j),phase:"waiting",retryAfterMs:Nf}}}yield{providerRetry:{phase:"waiting",...Mf,delayMs:ff,nextRetryAt:Date.now()+Ef,...w()}}}}}else await _f(ff,_,{throwOnAbort:!0});yield{providerRetry:{phase:"attempt",...Mf,...w()}}}else yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):c,maxRetries:$,reason:L.reason,...L.statusCode!==void 0?{statusCode:L.statusCode}:{},...w(),...P&&(I||!n())?{exhaustedBy:"attempt_limit"}:{}}}}finally{J.abandon(i),m?.release()}}throw G},Sf,TE=!1,jf=this.model,r=this.config.fallbackModels??[],H_=P&&r.length>0?Math.min(Y,$):$;try{for await(let R of _E(this.model,this.config,()=>{TE=!0},H_,r.length===0))yield R;return}catch(R){if(Sf=R,TE||!l(R)&&!Rf(R)&&!gf(R)&&!o(R,F).retryable)throw R}for(let[R,u]of r.entries()){if(!n())break;let V=!1;try{let B=VT(this.config,u),I=HE(B,u);yield{modelFallback:{from:of(jf.provider,jf.id),to:of(I.provider,I.id),candidate:R+1,candidateCount:r.length,trigger:yE(Sf,F)}},jf=I;let G=R===r.length-1,v=P&&!G?Math.min(Y,$):$;for await(let b of _E(I,B,()=>{V=!0},v,G))yield b;return}catch(B){if(Sf=B,V||!l(B)&&!Rf(B)&&!gf(B)&&!o(B,F).retryable)throw B}}throw Sf}async handleAbort(f){if(f?.aborted)await _f(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;qf.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},_=Jf(E);this.config={...E,maxContextTokens:_.model.contextWindow,maxOutputTokens:E.maxOutputTokens??_.model.maxTokens},this.models=_.models,this.model=_.model,this.providerAdmissionScheduler=x_(this.config)}}function x_(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 mE({globalMaxInFlight:E,ownerMaxInFlight:_,nonForegroundGlobalMaxInFlight:E,nonForegroundOwnerMaxInFlight:_,internalGlobalMaxInFlight:E,internalDomainMaxInFlight:f.providerRequestConcurrency??g,classLimitsEnabled:!1})}var zT=a("Service");async function mh(f){let E=f;if(E.provider){let _=tE(E.provider);if(Object.keys(_).length>0)E={...E,customHeaders:{..._,...E.customHeaders}},zT.debug(`Injected ${E.provider} specific headers:`,Object.keys(_))}return JT(E)}function JT(f){return new af(f)}
5
+ export{LT as Xf,ZT as Yf,RE as Zf,_f,l as $f,xT as ag,Rh as bg,o as cg,lE as dg,aE as eg,af as fg,mh as gg};
@@ -1,4 +1,4 @@
1
- import{Oa as H}from"./chunk-e1q1hvty.js";import"./chunk-77efqpdc.js";import"./chunk-53h87fmt.js";import{If as $,Of as T}from"./chunk-00zazdct.js";import"./chunk-v508x7cg.js";import"./chunk-r4bgsfj6.js";import"./chunk-gv24cgpb.js";import"./chunk-yvk8w63g.js";import"./chunk-jy61b0v8.js";import"./chunk-3csj18f1.js";import"./chunk-nry7d26k.js";import{Ji as k}from"./chunk-be2csw9m.js";import"./chunk-679b7s58.js";import"./chunk-8xem2mzy.js";import"./chunk-ar3sdj0w.js";import"./chunk-rcthrb7h.js";import"./chunk-0d440hhe.js";import"./chunk-dnt4c3gy.js";import"./chunk-rmm7n9n3.js";import"./chunk-961nemng.js";import"./chunk-fjvt9mwv.js";import"./chunk-w3y69e4e.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
1
+ import{Qa as H}from"./chunk-7ykqvsph.js";import"./chunk-wzkh3e6a.js";import"./chunk-z3hpstky.js";import{Pf as $,Vf as T}from"./chunk-v5503t2t.js";import"./chunk-v508x7cg.js";import"./chunk-q0s3gcjm.js";import"./chunk-mavranwn.js";import"./chunk-c2mx5zg0.js";import"./chunk-ramana2t.js";import"./chunk-6xvrrypm.js";import"./chunk-9a7bppj7.js";import{Si as k}from"./chunk-g799czsy.js";import"./chunk-mzye1ah2.js";import"./chunk-vp6d1fqp.js";import"./chunk-xg9fyvw0.js";import"./chunk-wxtj6gqb.js";import"./chunk-g9vdmvk2.js";import"./chunk-wxypv01z.js";import"./chunk-nxnmqk4s.js";import"./chunk-0k2x2ae6.js";import"./chunk-6e3mh79j.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
2
2
  blade mcp
3
3
  `),console.log(`管理 MCP 服务器
4
4
  `),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
@@ -0,0 +1 @@
1
+ import{Ff as a,Gf as b,Hf as c,If as d,Jf as e,Kf as f,Lf as g,Mf as h,Nf as i,Of as j,Pf as k,Qf as l,Rf as m,Sf as n,Tf as o,Uf as p,Vf as q}from"./chunk-v5503t2t.js";import"./chunk-v508x7cg.js";import"./chunk-q0s3gcjm.js";import"./chunk-ramana2t.js";import"./chunk-6xvrrypm.js";import"./chunk-9a7bppj7.js";import"./chunk-g799czsy.js";import"./chunk-mzye1ah2.js";import"./chunk-vp6d1fqp.js";import"./chunk-xg9fyvw0.js";import"./chunk-wxtj6gqb.js";import"./chunk-g9vdmvk2.js";import"./chunk-wxypv01z.js";import"./chunk-nxnmqk4s.js";import"./chunk-0k2x2ae6.js";import"./chunk-6e3mh79j.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};