blade-code 0.10.138 → 0.10.140

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 (130) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-6qhbdcse.js → chunk-08z32sky.js} +2 -2
  3. package/dist/{chunk-egadh3e9.js → chunk-0c2y17xy.js} +1 -1
  4. package/dist/{chunk-mjnkxem3.js → chunk-0kghtvxj.js} +2 -2
  5. package/dist/{chunk-3eskgvpy.js → chunk-0sx7ak0b.js} +1 -1
  6. package/dist/{chunk-d11mqbqk.js → chunk-15fpc0qg.js} +1 -1
  7. package/dist/{chunk-2t0wp7gm.js → chunk-19zsecpx.js} +2 -2
  8. package/dist/{chunk-byeq45rv.js → chunk-1myft5nb.js} +1 -1
  9. package/dist/chunk-1nreg14s.js +1 -0
  10. package/dist/{chunk-z9qv0d6k.js → chunk-2d3zksr0.js} +1 -1
  11. package/dist/{chunk-ec7ykyqz.js → chunk-2ff55pvt.js} +3 -3
  12. package/dist/{chunk-65c3vjwm.js → chunk-2g8avyq6.js} +1 -1
  13. package/dist/chunk-3kvt23m3.js +1 -0
  14. package/dist/chunk-4rh40xhc.js +1 -0
  15. package/dist/chunk-4xr4hz19.js +2 -0
  16. package/dist/{chunk-fndqbf45.js → chunk-50m1czz9.js} +1 -1
  17. package/dist/{chunk-earhezc8.js → chunk-5cw3bevx.js} +1 -1
  18. package/dist/{chunk-9m7d3ajv.js → chunk-5jq1mrqd.js} +1 -1
  19. package/dist/chunk-61yd46c0.js +1 -0
  20. package/dist/{chunk-8py443a5.js → chunk-6zxm9pen.js} +1 -1
  21. package/dist/{chunk-7vdf66jp.js → chunk-7eepxhcp.js} +34 -34
  22. package/dist/{chunk-jy7k2dwm.js → chunk-85b3kacc.js} +2 -2
  23. package/dist/chunk-8774agqd.js +1 -0
  24. package/dist/chunk-8brb7c6j.js +6 -0
  25. package/dist/{chunk-hrcz179j.js → chunk-8fx20am1.js} +2 -2
  26. package/dist/{chunk-16648v5c.js → chunk-8vqhcx3s.js} +1 -1
  27. package/dist/{chunk-6ezffjq1.js → chunk-9ced7jf0.js} +1 -1
  28. package/dist/chunk-abpmpyqa.js +1 -0
  29. package/dist/{chunk-yvmexv2c.js → chunk-ascjys4e.js} +1 -1
  30. package/dist/chunk-bb0z7c3g.js +1 -0
  31. package/dist/{chunk-5j68055h.js → chunk-c562kd2m.js} +1 -1
  32. package/dist/{chunk-he0f6h5q.js → chunk-cf3dvysj.js} +1 -1
  33. package/dist/{chunk-bq6d0v5b.js → chunk-cww9pp1q.js} +2 -2
  34. package/dist/{chunk-7j4s1nrc.js → chunk-d1qe06f0.js} +1 -1
  35. package/dist/{chunk-atdq9btn.js → chunk-e6j4vzta.js} +2 -2
  36. package/dist/{chunk-92n2p24j.js → chunk-eh901zhx.js} +2 -2
  37. package/dist/{chunk-14j2dbd6.js → chunk-eqe3smcg.js} +2 -2
  38. package/dist/{chunk-a5hkv8er.js → chunk-es0cbtx1.js} +2 -2
  39. package/dist/{chunk-r7bv1hmq.js → chunk-ffkzessq.js} +1 -1
  40. package/dist/{chunk-dv2m2xe5.js → chunk-g38d2ezm.js} +1 -1
  41. package/dist/{chunk-v2fewxvw.js → chunk-g4kydkyz.js} +2 -2
  42. package/dist/{chunk-5bfvdy62.js → chunk-g5scqxq3.js} +2 -2
  43. package/dist/{chunk-8rccn1y2.js → chunk-gq727fet.js} +1 -1
  44. package/dist/{chunk-56py3ryh.js → chunk-hj1yrssp.js} +1 -1
  45. package/dist/{chunk-d64b7wta.js → chunk-hvmrcd84.js} +1 -1
  46. package/dist/{chunk-zx78c1an.js → chunk-kmg8ad2j.js} +1 -1
  47. package/dist/{chunk-5v1pjexj.js → chunk-kxwc5wrx.js} +1 -1
  48. package/dist/chunk-m9dv5177.js +10 -0
  49. package/dist/{chunk-az08pq83.js → chunk-ma1mn6hn.js} +1 -1
  50. package/dist/{chunk-t88sfhjj.js → chunk-mnk0b4nz.js} +1 -1
  51. package/dist/chunk-mwgx87vw.js +1 -0
  52. package/dist/{chunk-nqts5by0.js → chunk-n6tvswa8.js} +2 -2
  53. package/dist/{chunk-fbrdcveb.js → chunk-n8qg68y2.js} +1 -1
  54. package/dist/chunk-ntq4h4jh.js +1 -0
  55. package/dist/{chunk-1bqatrxs.js → chunk-nxsarfy6.js} +1 -1
  56. package/dist/{chunk-ft1bdqbs.js → chunk-pg7cgvs8.js} +2 -2
  57. package/dist/{chunk-y66f1t18.js → chunk-ppmy3n74.js} +219 -218
  58. package/dist/chunk-pw9axk0e.js +5 -0
  59. package/dist/{chunk-2m79vd9p.js → chunk-pwct7cj7.js} +1 -1
  60. package/dist/{chunk-23c4pys6.js → chunk-q9qts6bq.js} +2 -2
  61. package/dist/chunk-r324qme7.js +1 -0
  62. package/dist/{chunk-rhwkvx96.js → chunk-r4q06wbs.js} +1 -1
  63. package/dist/chunk-ra6ksfdy.js +1 -0
  64. package/dist/{chunk-gcg56vaw.js → chunk-rrtptbzv.js} +2 -2
  65. package/dist/{chunk-jb4hmk56.js → chunk-svsgtj41.js} +2 -2
  66. package/dist/{chunk-j21hez8g.js → chunk-tagzy876.js} +6 -6
  67. package/dist/{chunk-516adpx6.js → chunk-tecbx0ek.js} +1 -1
  68. package/dist/chunk-tnts2de5.js +1 -0
  69. package/dist/chunk-w0710yj4.js +1 -0
  70. package/dist/{chunk-npc7jt96.js → chunk-w2m4yczv.js} +1 -1
  71. package/dist/{chunk-nyw686sf.js → chunk-w5057h27.js} +2 -2
  72. package/dist/chunk-we13xwds.js +180 -0
  73. package/dist/{chunk-nnas8tdt.js → chunk-xagh2qb6.js} +2 -2
  74. package/dist/{chunk-k10d8t4f.js → chunk-y5bqd8gh.js} +1 -1
  75. package/dist/{chunk-awheqy52.js → chunk-zfaenqqx.js} +2 -2
  76. package/dist/chunk-zp5097qk.js +2 -0
  77. package/dist/web/assets/ChatView-BlAGPVC-.js +63 -0
  78. package/dist/web/assets/{CodeBlockHighlighter-6-iPmomS.js → CodeBlockHighlighter-BM1MZv6w.js} +1 -1
  79. package/dist/web/assets/{FilePreview-D0aSwNF3.js → FilePreview-P77KS9tr.js} +1 -1
  80. package/dist/web/assets/{KanbanBoard-xPziptbY.js → KanbanBoard-B0c7sE2y.js} +1 -1
  81. package/dist/web/assets/{MarkdownRenderer-TWNqhwrr.js → MarkdownRenderer-DHa0FqU0.js} +3 -3
  82. package/dist/web/assets/{ScrollArea-CSQyGeWr.js → ScrollArea-C6yf2fqq.js} +1 -1
  83. package/dist/web/assets/{SessionHistorySurface-PRpOrUav.js → SessionHistorySurface-CXYBWqlN.js} +1 -1
  84. package/dist/web/assets/{SettingsModal-Ds-Uf-3r.js → SettingsModal-BVjVlENY.js} +1 -1
  85. package/dist/web/assets/{Sidebar-D6VyjkRY.js → Sidebar-DDW9Xs6e.js} +1 -1
  86. package/dist/web/assets/{TaskSwitcher-BEsAgt0k.js → TaskSwitcher-D74_5q1F.js} +1 -1
  87. package/dist/web/assets/{TerminalPanel-C_2lnmKH.js → TerminalPanel-DNEKapEi.js} +1 -1
  88. package/dist/web/assets/{archive-CPBIxP8f.js → archive-Ao0WD7pU.js} +1 -1
  89. package/dist/web/assets/{arrow-left-z3DhPgf-.js → arrow-left-a5_iLemp.js} +1 -1
  90. package/dist/web/assets/{calendar-clock-tYt1E6zR.js → calendar-clock-BKbdz6Cu.js} +1 -1
  91. package/dist/web/assets/{chevron-right-BGTvSaVS.js → chevron-right-8qYRfCj4.js} +1 -1
  92. package/dist/web/assets/{chevrons-up-down-Jw3ElnjQ.js → chevrons-up-down-BXNG4GvK.js} +1 -1
  93. package/dist/web/assets/{clock-3-v0h4RrLK.js → clock-3-DEL1ixyh.js} +1 -1
  94. package/dist/web/assets/{copy-CF3TUa0u.js → copy-Bd5v-KkM.js} +1 -1
  95. package/dist/web/assets/{download-ZG8PfhmH.js → download-CIKvpDBW.js} +1 -1
  96. package/dist/web/assets/{external-link-BKCjDDt-.js → external-link-B33h3DQN.js} +1 -1
  97. package/dist/web/assets/{folder-M-NM2bQG.js → folder-lOczceoh.js} +1 -1
  98. package/dist/web/assets/index-hZ37pkxs.js +203 -0
  99. package/dist/web/assets/{pause-CP_wlUro.js → pause-nnvVbgsj.js} +1 -1
  100. package/dist/web/assets/{pencil-U3n9D8ed.js → pencil-_yfoOmUq.js} +1 -1
  101. package/dist/web/assets/{play-NBWnc2gU.js → play-BilJ7SDs.js} +1 -1
  102. package/dist/web/assets/{plus-CmPqJgff.js → plus-BqqpYKaK.js} +1 -1
  103. package/dist/web/assets/{session-events-DKjIMNKI.js → session-events-FPOvcMBw.js} +19 -19
  104. package/dist/web/assets/{settings-CVFpbh_y.js → settings-CmJXtYTH.js} +1 -1
  105. package/dist/web/assets/{team-B9Na0Ocd.js → team-Bb04o2Tb.js} +1 -1
  106. package/dist/web/assets/{teamService-ZQZLqsjy.js → teamService-B5w9cpsa.js} +1 -1
  107. package/dist/web/assets/{terminal-BdmigqIS.js → terminal-DOjdChj0.js} +1 -1
  108. package/dist/web/index.html +1 -1
  109. package/package.json +1 -1
  110. package/dist/chunk-03zfvfen.js +0 -10
  111. package/dist/chunk-303b3x5q.js +0 -1
  112. package/dist/chunk-3g2z6hae.js +0 -1
  113. package/dist/chunk-3t5r41yh.js +0 -1
  114. package/dist/chunk-59980a8h.js +0 -1
  115. package/dist/chunk-5gy3x011.js +0 -1
  116. package/dist/chunk-5xgyx25z.js +0 -2
  117. package/dist/chunk-8cnxy251.js +0 -1
  118. package/dist/chunk-8cqm87j5.js +0 -1
  119. package/dist/chunk-ar85hxx2.js +0 -5
  120. package/dist/chunk-ddcz0nwv.js +0 -1
  121. package/dist/chunk-e71y87zg.js +0 -1
  122. package/dist/chunk-h2gp7smy.js +0 -1
  123. package/dist/chunk-j58wrt5n.js +0 -171
  124. package/dist/chunk-mc2mr1kn.js +0 -2
  125. package/dist/chunk-n2tfj82m.js +0 -1
  126. package/dist/chunk-pty1ncam.js +0 -6
  127. package/dist/chunk-qdjqbgts.js +0 -1
  128. package/dist/chunk-wv1mnf2m.js +0 -1
  129. package/dist/web/assets/ChatView-CZLmEMBO.js +0 -63
  130. package/dist/web/assets/index-VQVOzFZT.js +0 -203
@@ -0,0 +1,5 @@
1
+ import{og as of}from"./chunk-cww9pp1q.js";import{aj as t_,bj as yf,cj as af,dj as R_,ej as Lf,gj as Gf,ij as Hf,kj as g,lj as Cf,nj as Uf,oj as Ff,qj as s}from"./chunk-n8qg68y2.js";import{yj as a}from"./chunk-pg7cgvs8.js";import{Ij as IE,Kj as Jf}from"./chunk-svsgtj41.js";import{Nj as eE}from"./chunk-2g8avyq6.js";var B_={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},RE=(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 PE(...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[P,M]of h)P.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,P=setTimeout(()=>{if(E&&N)E.removeEventListener("abort",N);h()},f);if(E)N=()=>{if(clearTimeout(P),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 SE(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 NE(f,E,_,T,h){let x=f.filter((S)=>S.role==="system").map((S)=>AE(S.content)).filter(Boolean).join(`
3
+
4
+ `),N=[],P=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 SE(S.content,P,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 A=AE(S.content);if(A)t.push({type:"text",text:A});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 SE(S.content,P,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 uE(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 P=new Set(h.map((t)=>t.id)),M=x.filter((t)=>t.tool_call_id&&P.has(t.tool_call_id)),S=new Set(M.map((t)=>t.tool_call_id));if(P.size===h.length&&M.length===P.size&&S.size===P.size)E.push(T,...M);_=N-1}return E}function DE(f){return f.some((E)=>E.role==="assistant"&&Boolean(E.tool_calls?.length)&&!E.reasoningContent?.trim())}function HE(f,E){return{...f,...E.baseUrl?{baseUrl:IE(f.api,E.baseUrl)}:{},...E.maxOutputTokens?{maxTokens:E.maxOutputTokens}:{}}}function Wf(f){let E=f.modelCatalog??Jf();return{models:E.models,model:HE(E.getModel(f.provider,f.model),f)}}function UE(f,E){let _=f.modelCatalog??Jf();return HE(_.getModel(E.provider,E.model),f)}import{createHash as J_}from"node:crypto";var W_=32,$_=1000,z_=512,L_=2000,G_=0.1,k_=0.05,Z_=0.9,Q_=300000,K_=3600000;class $f{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<$_)return;let h=T.cacheReadTokens-_.cacheReadTokens,x=Math.min(L_,Math.max(z_,T.cacheReadTokens*G_));if(h<x||_.cacheReadTokens>=T.cacheReadTokens*(1-k_))return;let N=_.modelIdentity!==T.modelIdentity,P=_.systemHash!==T.systemHash,M=_.toolsHash!==T.toolsHash,S=_.policyHash!==T.policyHash;if(!(N||P||M||S)&&_.promptTokens<T.promptTokens*Z_)return;let A=Math.max(0,E-T.recordedAt),D=T.retention==="long"?K_:Q_,Y=N?"model_changed":P?"system_prompt_changed":M?"tools_changed":S?"request_policy_changed":A>=D?"ttl_expired":"server_side",z=F_(T,_);return{reason:Y,previousCacheReadTokens:T.cacheReadTokens,cacheReadTokens:_.cacheReadTokens,cacheWriteTokens:Math.max(0,f.usage.cacheCreationInputTokens??0),tokenDrop:h,elapsedMs:A,callNumber:_.callCount,systemPromptChanged:P,systemCharDelta:_.systemChars-T.systemChars,toolsChanged:M,addedToolCount:z.added,removedToolCount:z.removed,changedToolCount:z.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>W_){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 J_("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,kf=600000;var YE=128,BE=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 zf(f){if(f===void 0||!Number.isFinite(f)||f<0)return;return Math.min(Math.ceil(f),Gf)}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,YE),YE),maxWindowEntries:Math.min(d(f.maxWindowEntries,BE),BE),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.#P();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.#P();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),kf));return{preflight:()=>_.#A(f),check:()=>_.#b(f,T),recordSuccess:(h)=>_.#R(h,"success"),recordFailure:(h,x)=>_.#R(h,"failure",x),recordNeutral:(h)=>_.#R(h,"neutral"),abandon:(h)=>_.#u(h),snapshot:()=>_.#X(f)}}#P(){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.#u(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}#A(f){let E=this.#_();if(f.detached)return{eligible:!0};if(f.lastTouchedAt=E,this.#D(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.#P().check();if(f.lastTouchedAt=_,this.#D(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.#N(h,_,x,"reopened");return this.#V(h)}if(E==="neutral")return;if(this.#j(h,E==="failure",x),E!=="failure"||!_)return;let N=zf(_.retryAfterMs);if(_.reason==="rate_limit"&&_.statusCode===429&&N!==void 0&&N>0)return this.#N(h,{..._,retryAfterMs:N},x,"opened");let P=xf(h.samples),M=h.samples.length===0?0:P/h.samples.length;if(h.samples.length>=this.#T.minSamples&&M>=this.#T.errorRateThreshold)return this.#N(h,_,x,"opened");return}#N(f,E,_,T){let h={reason:E.reason,...bE(E.statusCode)!==void 0?{statusCode:bE(E.statusCode)}:{},...zf(E.retryAfterMs)!==void 0?{retryAfterMs:zf(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}}#u(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.#D(f,_),f.samples.length>=this.#T.maxWindowEntries)f.samples.shift();f.samples.push({at:_,failure:E})}#D(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.#D(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,n_=3,JE=16,WE=96,$E=24,zE=12,LE=16,GE=4,kE=4,ZE=67108864,QE=33554432,e_=12,r_=2,KE=2,CE=1,oE=15000,FE=30000;function Zf(){return{foreground:0,background:0,internal:0}}function Qf(){return{inFlight:Zf(),queued:Zf(),pendingBytes:Zf()}}function U(f){return f.foreground+f.background+f.internal}function $(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 Pf extends Error{reason;scope;requestClass;resource;inFlight;limit;queued;maxWaitMs;code="PROVIDER_ADMISSION_BUSY";retryable;constructor(f,E,_,T,h,x,N,P){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=P;this.name="ProviderAdmissionError",this.retryable=f!=="closed"}}function l(f){return f instanceof Pf||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_ADMISSION_BUSY"}function J(f,E,_){if(f===void 0||!Number.isSafeInteger(f)||f<=0)return E;return Math.min(f,_)}function i_(f){let E=J(f.globalMaxInFlight,d_,Number.MAX_SAFE_INTEGER),_=J(f.globalMaxPending,XE,XE),T=J(f.domainMaxPending,cE,cE),h=Math.min(J(f.ownerMaxInFlight,n_,Number.MAX_SAFE_INTEGER),E),x=Math.min(J(f.ownerMaxPending,JE,JE),_),N=Math.min(J(f.nonForegroundGlobalMaxPending,Math.min(WE,Math.max(1,Math.floor(_*3/4))),WE),_),P=Math.min(J(f.nonForegroundDomainMaxPending,Math.min($E,Math.max(1,Math.floor(T*3/4))),$E),T),M=Math.min(J(f.nonForegroundOwnerMaxPending,Math.min(zE,Math.max(1,Math.floor(x*3/4))),zE),x),S=Math.min(J(f.internalGlobalMaxPending,Math.min(LE,Math.max(1,Math.floor(_/8))),LE),N),t=Math.min(J(f.internalDomainMaxPending,Math.min(GE,Math.max(1,Math.floor(T/8))),GE),P),A=Math.min(J(f.internalOwnerMaxPending,Math.min(kE,Math.max(1,Math.floor(x/4))),kE),M),D=J(f.globalMaxPendingBytes,s,s),Y=Math.min(J(f.domainMaxPendingBytes,ZE,ZE),D),z=Math.min(J(f.ownerMaxPendingBytes,QE,QE),D),Q=Math.min(J(f.nonForegroundGlobalMaxInFlight,Math.min(e_,E),E),E),K=Math.min(J(f.nonForegroundOwnerMaxInFlight,Math.min(r_,h),h),h),F=Math.min(J(f.internalGlobalMaxInFlight,Math.min(KE,E),KE),E),Bf=J(f.internalDomainMaxInFlight,CE,CE),Af=J(f.agingMs,FE,FE);return{globalMaxInFlight:E,globalMaxPending:_,domainMaxPending:T,ownerMaxInFlight:h,ownerMaxPending:x,nonForegroundGlobalMaxPending:N,nonForegroundDomainMaxPending:P,nonForegroundOwnerMaxPending:M,internalGlobalMaxPending:S,internalDomainMaxPending:t,internalOwnerMaxPending:A,globalMaxPendingBytes:D,domainMaxPendingBytes:Y,ownerMaxPendingBytes:z,nonForegroundGlobalMaxInFlight:Q,nonForegroundOwnerMaxInFlight:K,internalGlobalMaxInFlight:F,internalDomainMaxInFlight:Bf,agingMs:Af,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 Kf(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=Qf();#P=1;#M=0;#A=!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.#A)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 Kf(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.#P++;let D=this.#N(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 P=this.#R(h,x,f.requestClass);if(f.maxWaitMs===0)throw this.#c("wait_timeout",f,P,this.#_.length);if(!_)this.#h.set(E,h);if(!T)this.#T.set(f.ownerId,x),this.#P++;let M,S,t=new Promise((D,Y)=>{M=D,S=Y});t.catch(()=>{return});let A={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)A.abortListener=()=>this.#B(A,Kf(f.signal)),f.signal.addEventListener("abort",A.abortListener,{once:!0});return A.timer=setTimeout(()=>this.#X(A),f.maxWaitMs),A.timer.unref?.(),this.#_.push(A),this.#b(h,x,A),this.#u(),{ready:t,getSnapshot:()=>this.#z(A),cancel:(D)=>this.#B(A,Kf(f.signal,D))}}close(){if(this.#A)return;this.#A=!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 Pf("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:$(this.#E.inFlight),internalInFlight:this.#E.inFlight.internal,nonForegroundQueued:$(this.#E.queued),internalQueued:this.#E.queued.internal,nonForegroundPendingBytes:$(this.#E.pendingBytes),internalPendingBytes:this.#E.pendingBytes.internal,domainCount:this.#h.size,ownerCount:this.#T.size,closed:this.#A}}#U(f,E,_){let T=(t,A,D)=>A>=D?{scope:t,resource:"pending_count",inFlight:A,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",$(this.#E.queued),this.#f.nonForegroundGlobalMaxPending)??T("class",$(_.counters.queued),this.#f.nonForegroundOwnerMaxPending)??T("class",$(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),P=Math.min(x,this.#f.ownerMaxPendingBytes),M=(t,A)=>f.pendingBytes>A-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)),A=Math.max(1,Math.floor(N/4)),D=Math.max(1,Math.floor(P/4));if(M(this.#E.pendingBytes.internal,t)||M(_.counters.pendingBytes.internal,D)||M(E.counters.pendingBytes.internal,A))return S("class")}if(f.requestClass!=="foreground"){let t=Math.max(1,Math.floor(x*3/4)),A=Math.max(1,Math.floor(N*3/4)),D=Math.max(1,Math.floor(P/2));if(M($(this.#E.pendingBytes),t)||M($(_.counters.pendingBytes),D)||M($(E.counters.pendingBytes),A))return S("class")}if(M(U(this.#E.pendingBytes),x))return S("global");if(M(U(_.counters.pendingBytes),P))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:Qf()}}#O(){return{order:this.#P,counters:Qf()}}#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($(this.#E.inFlight)>=this.#f.nonForegroundGlobalMaxInFlight)return!1;if($(E.counters.inFlight)>=this.#f.nonForegroundOwnerMaxInFlight)return!1;let T=Math.max(1,f.maxConcurrent-1);if($(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"&&$(E.counters.inFlight)>=this.#f.nonForegroundOwnerMaxInFlight)return{scope:"class",resource:"stream",inFlight:$(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($(f.counters.inFlight)>=T)return{scope:"class",resource:"stream",inFlight:$(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"&&$(this.#E.inFlight)>=this.#f.nonForegroundGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:$(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}}#N(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.#J(f,E),this.#u()}#u(){if(this.#A)return;while(this.#_.length>0){let f=this.#t(),E=new Map;for(let[P,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 A=this.#j(M,f),D=E.get(M.ownerId);if(!D||A<D.rank||A===D.rank&&P<D.index)E.set(M.ownerId,{pending:M,rank:A,index:P})}let _=[...E.values()].filter(({pending:P})=>{let M=this.#h.get(P.domainKey),S=this.#T.get(P.ownerId);return M!==void 0&&S!==void 0&&this.#S(M,S,P.requestClass)}).map(({pending:P,rank:M})=>({pending:P,rank:M,order:this.#T.get(P.ownerId).order}));if(_.length===0)return;let T=Math.min(..._.map((P)=>P.rank)),h=_.filter((P)=>P.rank===T),N=h.filter((P)=>P.order>this.#M).sort((P,M)=>P.order-M.order)[0]??h.sort((P,M)=>P.order-M.order)[0];this.#D(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)}#D(f,E){if(!this.#H(f,!1))return;f.settled=!0,f.admitted=!0,this.#M=E;let _=this.#N(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 Pf("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.#u()}#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.#W(T,h,f);if(this.#$(f),E)this.#J(f.domainKey,f.ownerId);return!0}#W(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}#$(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}#J(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)}#z(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 Pf(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 n 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 vf 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 sf(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 PT(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)??PT(_);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 wf(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=wf(E,T);if(x!==void 0)return Math.min(Math.ceil(x),h);let N=Math.max(0,f-1),P=_.maxExponentialDelayMs??8000,M=Math.min(500*2**N,P),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 pf(f,E){return{provider:of(f),model:of(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,P=!1,M=(t)=>{if(P||t<=0)return;if(!Number.isSafeInteger(t)||t>_-x){x=_+1,P=!0;return}x+=t},S=(t)=>{if(P)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[A,D]of t)if(S(A),S(D),P)return;return}if(t instanceof Set){M(32);for(let A of t)if(S(A),P)return;return}if(t instanceof WeakMap||t instanceof WeakSet){M(32);return}if(Array.isArray(t)){M(16);for(let A of t)if(S(A),P)return;return}M(32);for(let A of Reflect.ownKeys(t)){if(typeof A!=="string")continue;let D=Object.getOwnPropertyDescriptor(t,A);if(!D?.enumerable||!("value"in D))continue;if(M(8+Buffer.byteLength(A,"utf8")),S(D.value),P)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 AT(f){if(!f.reasoningEnabled)return;return f.reasoningEffort??f.reasoningLevel??"high"}function mf(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:AT(_);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(eE(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:mf(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 nE(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 P=new Headers(x.headers);_(nE(x.status,P)),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 P=await h(x,N);return _(nE(P.status,P.headers)),P}}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 qf(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(qf(_));return new Promise((T,h)=>{let x=!1,N=()=>{clearTimeout(t),_?.removeEventListener("abort",S)},P=(A)=>{if(x)return;x=!0,N(),T(A)},M=(A)=>{if(x)return;x=!0,N(),h(A instanceof Error?A:Error(String(A)))},S=()=>{if(_)M(qf(_))},t=setTimeout(()=>P({kind:"timer"}),Math.max(0,E));if(_?.addEventListener("abort",S,{once:!0}),_?.aborted){S();return}f.then((A)=>P({kind:"next",result:A}),M)})}async function*bT(f,E,_){let T=UT(E),h=YT(T,E.stallWarningMs);if(E.signal?.aborted)throw qf(E.signal);let x=Date.now(),N=Promise.resolve().then(()=>f.next()),P;for(;;){let S=await BT(N,(P?T:h??T)-(Date.now()-x),E.signal);if(S.kind==="next"){if(P)yield{...P,phase:"recovered",durationMs:Math.max(P.durationMs,Date.now()-x)};return S.result}if(!P&&h!==void 0){_.stallCount++,P={phase:"detected",stallCount:_.stallCount,durationMs:h,warningAfterMs:h,timeoutMs:T,outputStarted:_.outputStarted},yield P;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](),P=0,M=!1,S={stallCount:0,outputStarted:!1};try{while(!0){let t=bT(N,h,S),A=await t.next();while(!A.done)yield{providerStall:A.value},A=await t.next();let D=A.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:P++,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 gf=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=wf(E,Date.now());return{reason:_.reason,...T!==void 0?{statusCode:T}:{},...h!==void 0?{retryAfterMs:h}:{}}}function lf(f){return f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT"}class df{config;models;model;promptCacheBreakMonitor=new $f;providerAdmissionScheduler;admissionFallbackOwnerId=`pi-service-${process.pid}-${OT++}`;constructor(f){let E=Wf(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),gf.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(f,E,_,T){let h="",x="",N=[],P,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);P=S.usage??P,M=S.finishReason??M}return{content:h,...x?{reasoningContent:x}:{},...N.length>0?{toolCalls:N}:{},usage:P,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=uE(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)||DE(x),P=await NE(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=mf(this.config,u,V),I=this.promptCacheBreakMonitor.observe({sessionId:V,modelIdentity:`${u.provider}\x00${u.api}\x00${u.id}`,context:P,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 gf.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:P,tools:E,requestOptions:T}),t=T?.providerRecovery;if(t&&!R_(t.budgetMs))throw Error("Invalid bounded foreground Provider recovery budget");let A=t?.mode==="bounded_foreground"&&t.budgetMs>0?{budgetMs:t.budgetMs,startedAt:void 0}:void 0,D=A?"bounded_foreground":"standard",Y=this.config.maxRetries??2,z=this.config.maxRetries??(A?t_:2),Q=A!==void 0&&this.config.maxRetries===void 0,K=0,F,Bf=this.config.providerCircuitRegistry??jE(),Af=this.config.providerCircuitBreakerOpenMs??Lf,P_=Math.max(If,Math.min(this.config.streamIdleTimeout??Yf,kf)),nf=this.providerAdmissionScheduler,A_=this.config.providerRequestConcurrency??g,ef=this.config.providerRequestAdmissionMs??Cf,S_=this.config.providerRequestPendingBytes??Ff,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:Af,probeLeaseMs:P_}),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:A_,maxPendingBytes:S_}),X=(R=Date.now())=>{if(!A)return;let u=A.startedAt===void 0?0:Math.min(A.budgetMs,Math.max(0,R-A.startedAt));return{recoveryBudgetMs:A.budgetMs,recoveryElapsedMs:u,recoveryRemainingMs:Math.max(0,A.budgetMs-u)}},w=()=>({mode:D,...X()??{}}),rf=()=>{if(A&&A.startedAt===void 0)A.startedAt=Date.now()},p=()=>{let R=X();return new n(A?.budgetMs??0,R?.recoveryElapsedMs??0)},e=()=>!Q||K<z+1,Of=(R,u)=>{let{state:V,...B}=u;return{phase:R,...B,...X()?{recoveryRemainingMs:X()?.recoveryRemainingMs}:{}}},fE=(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(!nf)return{release:()=>{return}};let V=X()?.recoveryRemainingMs,B=V!==void 0&&A?.startedAt!==void 0?Math.min(ef,V):ef,I;try{I=nf.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"&&A?.startedAt!==void 0&&(X()?.recoveryRemainingMs??0)<=0)throw p();yield{providerAdmission:fE(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))),W,c=new Promise((m)=>{W=setTimeout(()=>m({kind:"heartbeat"}),O),W.unref?.()}),k=await Promise.race([v,c]);if(W)clearTimeout(W);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"&&A?.startedAt!==void 0&&(X()?.recoveryRemainingMs??0)<=0)throw p();yield{providerAdmission:fE(k.error)}}throw k.error}return yield{providerAdmission:Of("admitted",I.getSnapshot())},k.permit}},D_=(R,u)=>{if(!e())throw p();if(Q)K++;F=void 0;let V=new AbortController,B=_?PE(_,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(A?.startedAt!==void 0){let O=X()?.recoveryRemainingMs??0;if(O<=0)throw p();G={remainingMs:O,error:new n(A.budgetMs,A.budgetMs)}}let v=iE(u,R,B,T,N);f_(v,R,(O)=>{F=O});let b=h_(this.models,R,P,v,{idleTimeoutMs:u.streamIdleTimeout??Yf,signal:B,abort:(O)=>V.abort(O)});return async function*(){let O,W;try{if(I!==void 0&&(G===void 0||I<G.remainingMs)){let c=new vf(I);O=setTimeout(()=>V.abort(c),I),O.unref?.()}if(G){let c=G;W=setTimeout(()=>V.abort(c.error),c.remainingMs),W.unref?.()}yield*b}finally{if(O)clearTimeout(O);if(W)clearTimeout(W)}}()},EE=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}:{}}),_E=(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??Af,...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:z,reason:u,...V!==void 0?{statusCode:V}:{},...w(),exhaustedBy:"recovery_budget"}}),TE=async function*(R,u,V,B,I){let G,v=!1,b,O,W=M_(R,u);for(let c=0;c<=B;c++){if(!e())break;let k,m;while(!k){let H=W.preflight();while(!H.eligible){if(b=H.reason,O=H.statusCode,!A||!I){let C=_E("rejected",H);throw yield{providerCircuit:C},new tf(C)}rf();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:_E("waiting",H)};let q=Math.min(Math.max(1,H.retryAfterMs),yf,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=W.preflight()}try{m=yield*u_(R,u)}catch(Z){if(Z instanceof n)yield Vf(Q?Math.max(0,K-1):c,b??"timeout",O);throw Z}let L=W.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:z,reason:b,...O!==void 0?{statusCode:O}:{},...w()}};if(!L){L=!0;let q=W.recordSuccess(i);if(q)yield{providerCircuit:y(q)}}v=!0,V(),yield M(Z,R)}if(!L){let Z=W.recordSuccess(i);if(Z)yield{providerCircuit:y(Z)}}return}catch(H){if(m?.release(),G=H,EE.logIdleTimeout(H,v,R),await EE.handleAbort(_),H instanceof n){if(v)throw sf(H),H;throw yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):c,maxRetries:z,reason:b??"timeout",...O!==void 0?{statusCode:O}:{},...w(),exhaustedBy:"recovery_budget"}},H}let L=o(H,F);if(v)throw sf(H),H;let Z=cT(H,F),j=Z?W.recordFailure(i,Z):F&&!lf(H)?W.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:z,reason:b,...O!==void 0?{statusCode:O}:{},...w()}};throw H}b=L.reason,O=L.statusCode;let q=c<B&&e();if(j&&j.phase!=="closed"&&q&&(!A||!I)){let C={...y(j),phase:"rejected"};throw yield{providerCircuit:C},new tf(C)}if(q){rf();let C=Q?K:c+1,U_=lE(C,F,A?{maxDelayMs:af,maxExponentialDelayMs:af}:void 0),xE=j&&j.phase!=="closed"?j.retryAfterMs??0:0;if(A&&xE>0&&j)yield{providerCircuit:{...y(j),phase:"waiting"}};let Y_=X(),Xf=Math.max(U_,xE),ff=A?Math.min(Xf,Y_?.recoveryRemainingMs??Xf):Xf,Mf={attempt:C,maxRetries:z,reason:L.reason,...L.statusCode!==void 0?{statusCode:L.statusCode}:{}};if(yield{providerRetry:{phase:"scheduled",...Mf,delayMs:ff,nextRetryAt:Date.now()+ff,...w()}},A){let Ef=ff;while(Ef>0){let tE=Math.min(Ef,yf);if(await _f(tE,_,{throwOnAbort:!0}),Ef-=tE,(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:z,reason:L.reason,...L.statusCode!==void 0?{statusCode:L.statusCode}:{},...w(),...A&&(I||!e())?{exhaustedBy:"attempt_limit"}:{}}}}finally{W.abandon(i),m?.release()}}throw G},Sf,hE=!1,jf=this.model,r=this.config.fallbackModels??[],H_=A&&r.length>0?Math.min(Y,z):z;try{for await(let R of TE(this.model,this.config,()=>{hE=!0},H_,r.length===0))yield R;return}catch(R){if(Sf=R,hE||!l(R)&&!Rf(R)&&!lf(R)&&!o(R,F).retryable)throw R}for(let[R,u]of r.entries()){if(!e())break;let V=!1;try{let B=VT(this.config,u),I=UE(B,u);yield{modelFallback:{from:pf(jf.provider,jf.id),to:pf(I.provider,I.id),candidate:R+1,candidateCount:r.length,trigger:yE(Sf,F)}},jf=I;let G=R===r.length-1,v=A&&!G?Math.min(Y,z):z;for await(let b of TE(I,B,()=>{V=!0},v,G))yield b;return}catch(B){if(Sf=B,V||!l(B)&&!Rf(B)&&!lf(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;gf.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},_=Wf(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 JT=a("Service");async function mh(f){let E=f;if(E.provider){let _=RE(E.provider);if(Object.keys(_).length>0)E={...E,customHeaders:{..._,...E.customHeaders}},JT.debug(`Injected ${E.provider} specific headers:`,Object.keys(_))}return WT(E)}function WT(f){return new df(f)}
5
+ export{LT as bg,ZT as cg,PE as dg,_f as eg,l as fg,xT as gg,Rh as hg,o as ig,lE as jg,aE as kg,df as lg,mh as mg};
@@ -1,4 +1,4 @@
1
- import{mc as Xt,nc as En,oc as yn,pc as bn}from"./chunk-3eskgvpy.js";import{rh as Bt}from"./chunk-ec7ykyqz.js";import{Ah as U,Bh as en,Ch as gt,Dh as mt,Fh as rn,Gh as Tn,Hh as B,Ih as dn,Jh as on,Kh as pn,Lh as lt,Mh as un,Nh as cn,Oh as Mn,Qh as S,Th as wn,Uh as Gt,Vh as Ut,Wh as h,Xh as Ht,wh as xt,xh as vi,yh as sn,zh as zt}from"./chunk-atdq9btn.js";import{Vi as It}from"./chunk-dv2m2xe5.js";import{xj as X,zj as x}from"./chunk-ft1bdqbs.js";import{Pj as tn,Qj as nn}from"./chunk-2t0wp7gm.js";import{Ek as ns}from"./chunk-516adpx6.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{pc as Xt,qc as En,rc as yn,sc as bn}from"./chunk-0sx7ak0b.js";import{uh as Bt}from"./chunk-2ff55pvt.js";import{Ah as vi,Bh as sn,Ch as zt,Dh as U,Eh as en,Fh as gt,Gh as mt,Ih as rn,Jh as Tn,Kh as B,Lh as dn,Mh as on,Nh as pn,Oh as lt,Ph as un,Qh as cn,Rh as Mn,Th as S,Wh as wn,Xh as Gt,Yh as Ut,Zh as h,_h as Ht,zh as xt}from"./chunk-e6j4vzta.js";import{Yi as It}from"./chunk-g38d2ezm.js";import{Aj as X,Cj as x}from"./chunk-pg7cgvs8.js";import{Sj as tn,Tj as nn}from"./chunk-19zsecpx.js";import{Hk as ns}from"./chunk-tecbx0ek.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
 
@@ -1,4 +1,4 @@
1
- import{v as HH,w as JH}from"./chunk-56py3ryh.js";import{A as S,x as Cz,y as fz,z as uz}from"./chunk-he0f6h5q.js";import{B as zH,C as xz,D as bz,E as Rz,F as Sz,G as Mz}from"./chunk-d11mqbqk.js";import{Aa as yz,Ba as hz,Ca as kz,N as R,W as Az,X as Oz,ca as Ez,fa as qz,ga as Tz,ja as Pz,za as Iz}from"./chunk-y66f1t18.js";import"./chunk-16648v5c.js";import{Qa as ez}from"./chunk-2m79vd9p.js";import{Sa as Nz,Wa as i,Za as a}from"./chunk-5xgyx25z.js";import{Ib as Kz,Ub as wz,bc as l}from"./chunk-j58wrt5n.js";import{mc as d}from"./chunk-3eskgvpy.js";import{Gd as I,Hd as v,Id as Gz,Nd as Vz,Qd as jz,Sd as M,Vd as Dz,_d as Fz,be as F,wd as Bz}from"./chunk-nqts5by0.js";import"./chunk-zx78c1an.js";import{Ge as r,He as Uz,ze as _z}from"./chunk-a5hkv8er.js";import"./chunk-awheqy52.js";import{sf as LH}from"./chunk-92n2p24j.js";import"./chunk-6qhbdcse.js";import{Nf as oz,Of as nz}from"./chunk-mjnkxem3.js";import"./chunk-v508x7cg.js";import{Zf as e}from"./chunk-5j68055h.js";import{cg as Wz}from"./chunk-ar85hxx2.js";import{kg as m}from"./chunk-bq6d0v5b.js";import"./chunk-hrcz179j.js";import{pg as sz}from"./chunk-d64b7wta.js";import"./chunk-14j2dbd6.js";import"./chunk-nnas8tdt.js";import"./chunk-yvmexv2c.js";import{jh as tz}from"./chunk-rhwkvx96.js";import"./chunk-az08pq83.js";import"./chunk-ec7ykyqz.js";import"./chunk-1bqatrxs.js";import{mi as az,pi as rz}from"./chunk-atdq9btn.js";import"./chunk-npc7jt96.js";import{Ni as g,Oi as Xz,Qi as c,Ri as p}from"./chunk-mc2mr1kn.js";import{Vi as t}from"./chunk-dv2m2xe5.js";import"./chunk-fbrdcveb.js";import{vj as y}from"./chunk-ft1bdqbs.js";import"./chunk-jb4hmk56.js";import{Ij as lz,Lj as iz}from"./chunk-65c3vjwm.js";import"./chunk-2t0wp7gm.js";import"./chunk-jy7k2dwm.js";import"./chunk-earhezc8.js";import{Zj as $z,_j as dz,ck as zz,gk as Hz,hk as vz,ik as Jz}from"./chunk-t88sfhjj.js";import"./chunk-516adpx6.js";import{Readable as KH,Writable as wH}from"node:stream";import*as f from"@agentclientprotocol/sdk";import o from"node:path";import{PROTOCOL_VERSION as GH,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as gz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var G=y("Agent");function P(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function Zz(z){if(!z)return{};return Object.fromEntries(z.map((H)=>[H.name,H.value]))}function ZH(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:Zz(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:Zz("headers"in z?z.headers:void 0)};return null}function $H(z){let H={};for(let L of z){let Y=ZH(L);if(Y)H[L.name]=Y}return H}function cz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((H)=>{if(H.type==="text")return H.text?[{type:"text",text:H.text}]:[];let L=H.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(L);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function XH(z){let H=Uz(z.metadata);return H?[{type:"text",text:r(H)}]:cz(z.content)}function WH(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
1
+ import{v as HH,w as JH}from"./chunk-hj1yrssp.js";import{A as S,x as Cz,y as fz,z as uz}from"./chunk-cf3dvysj.js";import{B as zH,C as xz,D as bz,E as Rz,F as Sz,G as Mz}from"./chunk-15fpc0qg.js";import{Aa as yz,Ba as hz,Ca as kz,N as R,W as Az,X as Oz,ca as Ez,fa as qz,ga as Tz,ja as Pz,za as Iz}from"./chunk-ppmy3n74.js";import"./chunk-8vqhcx3s.js";import{Qa as ez}from"./chunk-pwct7cj7.js";import{Sa as Nz,Wa as i,Za as a}from"./chunk-4xr4hz19.js";import{Kb as Kz,Wb as wz,ec as l}from"./chunk-we13xwds.js";import{pc as d}from"./chunk-0sx7ak0b.js";import{Jd as I,Kd as v,Ld as Gz,Qd as Vz,Td as jz,Vd as M,Yd as Dz,be as Fz,ee as F,zd as Bz}from"./chunk-n6tvswa8.js";import"./chunk-kmg8ad2j.js";import{Ce as _z,Je as r,Ke as Uz}from"./chunk-es0cbtx1.js";import"./chunk-zfaenqqx.js";import{vf as LH}from"./chunk-eh901zhx.js";import"./chunk-08z32sky.js";import{Qf as oz,Rf as nz}from"./chunk-0kghtvxj.js";import"./chunk-v508x7cg.js";import{ag as e}from"./chunk-c562kd2m.js";import{fg as Wz}from"./chunk-pw9axk0e.js";import{ng as m}from"./chunk-cww9pp1q.js";import"./chunk-8fx20am1.js";import{sg as sz}from"./chunk-hvmrcd84.js";import"./chunk-eqe3smcg.js";import"./chunk-xagh2qb6.js";import"./chunk-ascjys4e.js";import{mh as tz}from"./chunk-r4q06wbs.js";import"./chunk-ma1mn6hn.js";import"./chunk-2ff55pvt.js";import"./chunk-nxsarfy6.js";import{pi as az,si as rz}from"./chunk-e6j4vzta.js";import"./chunk-w2m4yczv.js";import{Qi as g,Ri as Xz,Ti as c,Ui as p}from"./chunk-zp5097qk.js";import{Yi as t}from"./chunk-g38d2ezm.js";import"./chunk-n8qg68y2.js";import{yj as y}from"./chunk-pg7cgvs8.js";import"./chunk-svsgtj41.js";import{Lj as lz,Oj as iz}from"./chunk-2g8avyq6.js";import"./chunk-19zsecpx.js";import"./chunk-85b3kacc.js";import"./chunk-5cw3bevx.js";import{ak as $z,bk as dz,fk as zz,jk as Hz,kk as vz,lk as Jz}from"./chunk-mnk0b4nz.js";import"./chunk-tecbx0ek.js";import{Readable as KH,Writable as wH}from"node:stream";import*as f from"@agentclientprotocol/sdk";import o from"node:path";import{PROTOCOL_VERSION as GH,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as gz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var G=y("Agent");function P(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function Zz(z){if(!z)return{};return Object.fromEntries(z.map((H)=>[H.name,H.value]))}function ZH(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:Zz(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:Zz("headers"in z?z.headers:void 0)};return null}function $H(z){let H={};for(let L of z){let Y=ZH(L);if(Y)H[L.name]=Y}return H}function cz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((H)=>{if(H.type==="text")return H.text?[{type:"text",text:H.text}]:[];let L=H.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(L);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function XH(z){let H=Uz(z.metadata);return H?[{type:"text",text:r(H)}]:cz(z.content)}function WH(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
2
  `)}function BH(z){if(!Wz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...I("capacity"),resource:z.resource}}function _H(z){if(!(z instanceof gz)||!z.data||typeof z.data!=="object")return;let H=z.data;if(!Gz(H.taskFailure)||H.toolExecutionStarted!==!1||!Number.isInteger(H.toolCallsCount)||H.toolCallsCount<0||H.outputStarted!==!1)return;return{taskFailure:H.taskFailure,toolExecutionStarted:H.toolExecutionStarted,toolCallsCount:H.toolCallsCount,outputStarted:H.outputStarted}}function UH(z){return{version:z.version,pending:z.pending,mutable:z.mutable,locked:z.locked,internal:z.internal}}class x{id;roots;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;pendingResumeAttempt=0;projectedPendingResumeInputIds=new Set;pendingResumeRecoveryStartedAt=0;pendingResumeInFlight=!1;pendingResumeScheduled=!1;pendingResumeGeneration=0;pendingResumeTimer=null;pendingResumeCompletion=null;pendingResumeNextDelayMs=null;availableCommandsTimer=null;taskStatusUnsubscribe;lastTurnActivityGeneration;lastTurnActivityRevision=-1;destroyed=!1;destroyFinished=!1;destroyPromise;serviceRegistration;messages;contextMessages;mode;updateEgress;constructor(z,H,L,Y,$={}){this.id=z;this.roots=H;this.connection=L;this.clientCapabilities=Y;this.options=$;this.messages=[...$.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode($.permissionMode),this.updateEgress=new Mz({maxPendingItems:xz,maxPendingBytes:bz,writeTimeoutMs:Rz,signal:L.signal,sizeOf:(X)=>Buffer.byteLength(JSON.stringify(X)),write:async(X)=>{await L.sessionUpdate(X)},onFailure:(X)=>this.handleUpdateEgressFailure(X)})}async refreshPersistedMessages(){let[z,H]=await Promise.all([this.loadPersistedMessages(),this.loadPersistedModelContext()]);if(z.length>0)this.messages=z;if(H.length>0)this.contextMessages=H}async loadModelContextOr(z){let H=await this.loadPersistedModelContext();return H.length>0?H:[...z]}loadPersistedMessages(){return this.roots.kind==="acp-remote"?F.loadRemoteSession(this.id,this.roots.hostStateRoot,this.roots.descriptor):F.loadSession(this.id,this.roots.hostStateRoot)}loadPersistedModelContext(){return this.roots.kind==="acp-remote"?F.loadRemoteSessionModelContext(this.id,this.roots.hostStateRoot,this.roots.descriptor):F.loadSessionModelContext(this.id,this.roots.hostStateRoot)}async persistMetadataUpdate(z,H=z){if(this.roots.kind==="acp-remote"){await F.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,z);return}try{await F.updateSessionMetadata(this.id,this.roots.hostStateRoot,z)}catch(L){if(!(L instanceof Fz)&&L.code!=="ENOENT")throw L;await F.createSessionMetadata(this.id,this.roots.hostStateRoot,{taskStatus:"completed",...H})}}async persistPermissionMode(z){if(this.roots.kind==="acp-remote"){await F.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,{permissionMode:z});return}await F.setSessionPermissionMode(this.id,this.roots.hostStateRoot,z)}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return Pz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){G.debug(`[AcpSession ${this.id}] Initializing...`),await this.persistPermissionMode(this.mapModeToPermissionMode()??"default");let z=R.initializeSession(this.connection,this.id,this.clientCapabilities,this.roots.executionRoot,async(Z)=>{await this.sendUpdateAndWait(Z)},this.roots.kind==="acp-remote"?this.roots.profile:void 0);if(z)this.serviceRegistration=z;if(G.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.roots.kind==="local"?await l.resolvePendingWithHandler(this.roots.hostStateRoot,this.id,{requestConfirmation:(Z)=>this.requestPermission(Z)}):!1)await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let L=this.options.mcpServers?$H(this.options.mcpServers):void 0,Y=R.getInstance().getTerminalService(this.id),$=this.roots.kind==="acp-remote"?{kind:"acp-remote",executionRoot:this.roots.executionRoot,resourceRoot:this.roots.hostResourceRoot,readTextFile:this.clientCapabilities?.fs?.readTextFile===!0,writeTextFile:this.clientCapabilities?.fs?.writeTextFile===!0,terminal:this.clientCapabilities?.terminal===!0,descriptor:this.roots.descriptor}:void 0;if(this.runtime=await Ez.create({sessionId:this.id,workspaceRoot:this.roots.hostStateRoot,...$?{workspace:$}:{},permissionMode:this.mapModeToPermissionMode(),...L?{mcpServers:L}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(Z,_)=>{let U=await Y.execute(Z,{cwd:_.cwd,env:_.env,timeout:_.timeoutMs,signal:_.signal,allowLocalFallback:!1,onOutput:(V)=>_.onOutput?.("stdout",V)});return{exitCode:U.exitCode,stdout:U.stdout,stderr:U.stderr,...U.error?{error:U.error}:{},timedOut:U.failureKind==="timeout",aborted:U.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),this.roots.kind==="local"?await S.recoverInterrupted(this.roots.hostStateRoot,this.id,this.runtime):!1)await this.refreshPersistedMessages();if(this.agent=await this.createAgent(),this.roots.kind==="local")await yz(this.roots.hostStateRoot);G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=Kz.subscribe((Z)=>{if(Z.sessionId!==this.id||Z.projectPath!==this.roots.hostStateRoot)return;if(Z.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":Z.properties}}),this.requestPendingResume();return}if(Z.type==="follow_up.queue.changed"){let _=i.safeParse(Z.properties.queue);if(_.success)this.sendFollowUpQueueSnapshot(_.data);return}if(Z.type==="provider.recovery"){let _=m.safeParse(Z.properties.recovery);if(!_.success)return;this.sendProviderRecoveryProjection(_.data);return}if(Z.type==="turn.activity"){let _=a.safeParse(Z.properties.activity);if(!_.success)return;this.sendTurnActivityProjection(_.data);return}if(Z.type==="task.delivery"){if(!Z.properties.taskDelivery||typeof Z.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof Z.properties.updatedAt==="string"?Z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":Z.properties.taskDelivery,...Z.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(Z.type.startsWith("team.")){let{teamName:_,messageId:U,content:V}=Z.properties,T=Z.properties.metadata;if(Z.type==="team.message.received"&&typeof _==="string"&&typeof U==="string"&&typeof V==="string"&&Oz(T,{messageId:U,teamName:_}))(async()=>{let E=await this.runtime?.enqueueSteering(V,{allowBeforeTurn:!0,messageId:U,origin:"team_message",metadata:T});if(!E?.accepted)return;if(E.queue)this.sendFollowUpQueueSnapshot(E.queue);if(await new Az(_,$z()).markDelivered([U]),E.delivery==="next_turn")this.requestPendingResume()})().catch((E)=>{G.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,E)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:Z.type,...Z.properties}}});return}if(Z.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof Z.properties.updatedAt==="string"?Z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":Z.properties.taskStatus,...typeof Z.properties.taskStatusReason==="string"?{"blade/taskStatusReason":Z.properties.taskStatusReason}:{},...Z.properties.taskFailure&&typeof Z.properties.taskFailure==="object"?{"blade/taskFailure":Z.properties.taskFailure}:{},...typeof Z.properties.taskStartedAt==="string"?{"blade/taskStartedAt":Z.properties.taskStartedAt}:{},...typeof Z.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":Z.properties.taskCompletedAt}:{},...Z.properties.taskDiffStat&&typeof Z.properties.taskDiffStat==="object"?{"blade/taskDiffStat":Z.properties.taskDiffStat}:{},...typeof Z.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":Z.properties.taskQueuePosition}:{},...typeof Z.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":Z.properties.taskQueueDepth}:{},...typeof Z.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":Z.properties.taskConcurrencyLimit}:{},...typeof Z.properties.taskInFlight==="number"?{"blade/taskInFlight":Z.properties.taskInFlight}:{}}})});let Q=await this.runtime.getGoal(),W=this.runtime.getPendingSteeringCount()>0,B=Q?.status==="active"||Q?.status==="verifying";if(W||B)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let Z=this.runtime.getTurnRecoveryAssessment();if(Z.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Z}})}}async replayHistory(){for(let H of this.messages){if(!this.canSendUpdates())return;if(!_z(H))continue;let L=H.role==="user"?"user_message_chunk":H.role==="assistant"?"agent_message_chunk":void 0;if(!L)continue;for(let Y of XH(H)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:L,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.ensurePendingResumeScheduled()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendInitialSessionUpdates()},500)}async sendInitialSessionUpdates(){try{let z=this.runtime;if(z)this.sendFollowUpQueueSnapshot(await z.getFollowUpQueueSnapshot()),this.sendProviderRecoveryProjection(z.getProviderRecoveryProjection()),this.sendTurnActivityProjection(z.getTurnActivityProjection())}catch{G.warn("[AcpSession "+this.id+"] Initial follow-up queue unavailable")}await this.sendAvailableCommands()}async handleSlashCommand(z,H){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let L={cwd:this.roots.hostStateRoot,workspaceKind:this.roots.kind,surface:"acp",workspaceRoot:this.roots.hostStateRoot,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let W=await this.runtime.rewindSession(Q);return this.messages=[...W.messages],this.contextMessages=await this.loadModelContextOr(W.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),W}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Q)=>{if(await this.setReasoningEffort(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Q)=>{if(await this.setServiceTier(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Q)=>{if(await this.setResponseVerbosity(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},...this.roots.kind==="local"?{subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=!1,Z,_=(V)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:V.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:V.result?.message||V.result?.error||`Subagent ${V.status}`}}]})},U=this.runtime.resumeSubagent({agentId:Q,prompt:W,onCompleted:(V)=>{if(B)_(V);else Z=V}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.session.id,status:"in_progress",title:`Resuming ${U.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${U.source.id} at depth ${U.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),B=!0,Z)_(Z);return U}}}:{},...this.roots.kind==="local"?{mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,W,B)},complete:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,W,B)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,W)},getLogs:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,W)},setLoggingLevel:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,W)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}}}:{},sideConversation:{ask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:W})}},...this.roots.kind==="local"?{codeReview:{run:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=await S.start({sessionId:this.id,projectPath:this.roots.hostStateRoot,runtime:this.runtime,request:Q,signal:W,onEvent:(U)=>{if(U.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.toolCall.id,status:"in_progress",title:`Review: ${U.toolCall.function.name}`,content:[],kind:this.mapToolKind(U.toolKind)});else if(U.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.toolCall.id,status:U.result.success?"completed":"failed",content:[]})}}),Z=await B.completion,_=(await S.list(this.roots.hostStateRoot,this.id)).find((U)=>U.start.reviewId===B.reviewId);if(!_)throw Error(`Review not found: ${B.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:B.reviewId,status:Z.status,findings:Z.findings.length,content:Bz(_.start,Z)}}}}:{},signal:H,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,W,B)=>{let Z=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,_=this.mapToolKind(B);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(W,null,2)}}],kind:_})},sendToolResult:(Q,W)=>{if(W.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.summary}})}}},Y=await hz(z,L),$=Y.data?.action;if($==="start_goal"||$==="resume_goal")this.requestPendingResume();if($==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let Q=await this.loadPersistedMessages();if(Q.length>0)this.messages=Q}let X=Y.content||Y.message;if(X)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(L){if(H.aborted||L instanceof Error&&L.name==="AbortError")return{stopReason:"cancelled"};return G.error(`[AcpSession ${this.id}] Slash command error:`,L),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${L instanceof Error?L.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let H=new AbortController,L,Y=new Promise(($)=>{L=$});this.pendingSideConversation=H,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,H.signal)}catch($){if(H.signal.aborted||$ instanceof Error&&$.name==="AbortError")return{stopReason:"cancelled"};throw $}finally{if(L(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===H){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=kz(this.roots.hostStateRoot,this.runtime?.getAgentResources(),this.roots.kind),H=["model","permissions","theme","config","exit","ide"],Y=z.filter(($)=>!H.includes($.name)&&($.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map(($)=>{let X;if($.usage){let Q=$.usage.replace(/^\/\w+\s*/,"").trim();if(Q)X=Q}if($.aliases?.length){let Q=`Aliases: ${$.aliases.join(", ")}`;X=X?`${X} | ${Q}`:Q}return{name:$.name,description:$.description,input:X?{hint:X}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map(($)=>$.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),G.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,H={}){if(R.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let L=this.resolvePrompt(z.prompt),Y=L.content,$=L.displayText,X=z._meta?.outputSchema??(H.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((j)=>j.outputSchema)?.outputSchema:void 0),Q;if(X!==void 0)Q=Dz(X).schema;if($.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand($)}let W=Nz($);if(W){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((j)=>j.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(W.question?`/btw ${W.question}`:"/btw")}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test($.trim()))return this.handleSlashCommand($,this.pendingPrompt.signal);let j=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!j.accepted)throw Error(j.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${j.queued})`),this.sendFollowUpQueueSnapshot(j.queue??await this.runtime.getFollowUpQueueSnapshot()),j.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let B=new AbortController,Z=()=>{B.abort(H.abortSignal?.reason)};if(H.abortSignal?.aborted)Z();else H.abortSignal?.addEventListener("abort",Z,{once:!0});let _=!1,U=!1,V=!1,T,E=new Promise((j)=>{T=j});this.pendingPrompt=B,this.pendingPromptCompletion=E;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${$.slice(0,100)}...`),Iz($)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand($,B.signal)}let j={sessionId:this.id,userId:"acp-user",workspaceRoot:this.roots.hostStateRoot,executionRoot:this.roots.executionRoot,workspaceKind:this.roots.kind,messages:[...this.contextMessages],signal:B.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(J)=>{this.mode=this.mapPermissionModeToMode(J),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(J)=>{return this.requestPermission(J)}}},N=await wz(this.agent.chatStream(Y,j,{pendingInputOnly:H.pendingInputOnly,goalContinuationOnly:H.goalContinuationOnly,outputSchema:Q}),async(J)=>{switch(J.kind){case"content_delta":if(Q)break;if(J.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J.delta}});break;case"thinking_delta":if(J.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:J.delta}});break;case"tool_start":{V=!0;let D=J.toolCall,A=D.function.name;if(A===M)break;let q=this.mapToolKind(J.toolKind),K=`Executing ${A}`;if(A==="Task"&&"function"in D)try{let b=JSON.parse(D.function.arguments),w=b.resume_from??b.resume;if(typeof w==="string")K=`Resuming ${String(b.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D.id,status:"in_progress",title:K,content:[],kind:q});break}case"tool_progress":{V=!0;let D=J.toolCall;if(D.function.name===M)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:J.update.message}}]});break}case"tool_result":{V=!0;let D=J.toolCall;if(D.function.name===M)break;let A=J.result,q=[],K=A.metadata;if(K?.kind==="patch"&&Array.isArray(K.changes))for(let w of K.changes){if(!w||typeof w!=="object"||!("path"in w)||typeof w.path!=="string")continue;q.push({type:"diff",path:w.path,oldText:"oldContent"in w&&typeof w.oldContent==="string"?w.oldContent:null,newText:"newContent"in w&&typeof w.newContent==="string"?w.newContent:null})}else if(K?.kind==="edit"&&typeof K.file_path==="string"&&typeof K.oldContent==="string"&&(typeof K.newContent==="string"||K.newContent===void 0))q.push({type:"diff",path:K.file_path,oldText:K.oldContent,newText:K.newContent??null});else{let w=D.function.name,QH=Tz(jz(qz(w,A),Vz));q.push({type:"content",content:{type:"text",text:QH}})}if(D.function.name==="Task"&&(K?.verificationVerdict==="pass"||K?.verificationVerdict==="fail"||K?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${K.verificationVerdict.toUpperCase()}`}});let b=A.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:b,content:q});break}case"structured_output":U=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(J.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${J.revision} (${J.serverName}): +${J.added.length} -${J.removed.length} ~${J.updated.length}
3
3
  `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${J.contentKind} r${J.revision} (${J.serverName}): +${J.added.length} -${J.removed.length} ~${J.updated.length}
4
4
  `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${J.revision} (${J.serverName}): ${J.uri}
@@ -9,7 +9,7 @@ import{v as HH,w as JH}from"./chunk-56py3ryh.js";import{A as S,x as Cz,y as fz,z
9
9
  `}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${J.files.length}${J.blockedWrite?" (write retry required)":""}
10
10
  `}});break;case"provider_admission":_=J.phase!=="admitted",this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":J.phase!=="admitted"?{phase:J.phase,requestClass:J.requestClass,resource:J.resource,scope:J.scope,...J.reason!==void 0?{reason:J.reason}:{},queuePosition:J.queuePosition,queueDepth:J.queueDepth,inFlight:J.inFlight,limit:J.limit,waitMs:J.waitMs,maxWaitMs:J.maxWaitMs,...J.recoveryRemainingMs!==void 0?{recoveryRemainingMs:J.recoveryRemainingMs}:{}}:null}});break;case"provider_circuit":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerCircuit":{phase:J.phase,reason:J.reason,...J.statusCode!==void 0?{statusCode:J.statusCode}:{},...J.retryAfterMs!==void 0?{retryAfterMs:J.retryAfterMs}:{},...J.nextProbeAt!==void 0?{nextProbeAt:J.nextProbeAt}:{},openDurationMs:J.openDurationMs,...J.sampleCount!==void 0?{sampleCount:J.sampleCount}:{},...J.failureCount!==void 0?{failureCount:J.failureCount}:{},...J.recoveryRemainingMs!==void 0?{recoveryRemainingMs:J.recoveryRemainingMs}:{}}}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:J.phase,attempt:J.attempt,maxRetries:J.maxRetries,reason:J.reason,...J.statusCode!==void 0?{statusCode:J.statusCode}:{},...J.delayMs!==void 0?{delayMs:J.delayMs}:{},...J.nextRetryAt!==void 0?{nextRetryAt:J.nextRetryAt}:{},...J.mode!==void 0?{mode:J.mode}:{},...J.recoveryBudgetMs!==void 0?{recoveryBudgetMs:J.recoveryBudgetMs}:{},...J.recoveryElapsedMs!==void 0?{recoveryElapsedMs:J.recoveryElapsedMs}:{},...J.recoveryRemainingMs!==void 0?{recoveryRemainingMs:J.recoveryRemainingMs}:{},...J.exhaustedBy!==void 0?{exhaustedBy:J.exhaustedBy}:{}}}});break;case"turn_recovery":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":J.assessment}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:J.phase,stallCount:J.stallCount,durationMs:J.durationMs,warningAfterMs:J.warningAfterMs,timeoutMs:J.timeoutMs,outputStarted:J.outputStarted}}});break;case"provider_recovery":break;case"turn_activity":break;case"model_fallback":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/modelFallback":{from:J.from,to:J.to,candidate:J.candidate,candidateCount:J.candidateCount,trigger:J.trigger}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:J.phase,toolName:J.toolName,runLength:J.runLength,nudgeThreshold:J.nudgeThreshold,haltThreshold:J.haltThreshold,progressAware:J.progressAware}}});break;case"task_update":this.sendPlanUpdate(J.tasks);break;case"goal_frontier_updated":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:J.frontier.observedAt,_meta:{"blade/goalFrontier":{goalId:J.goal.goalId,status:J.goal.status,taskListId:J.frontier.taskListId,total:J.frontier.total,completed:J.frontier.completed,inProgress:J.frontier.inProgress,pending:J.frontier.pending,blocked:J.frontier.blocked,nextTask:J.frontier.nextTask,digestSha256:J.frontier.digestSha256,...J.goal.frontierStall?{stall:{category:J.goal.frontierStall.category,consecutiveCount:J.goal.frontierStall.consecutiveCount}}:{}}}}),this.sendPlanUpdate(J.tasks);break;case"steering_applied":this.sendFollowUpQueueSnapshot(J.queue);break;case"follow_up_queue_changed":this.sendFollowUpQueueSnapshot(J.queue);break;case"follow_up_started":{this.sendFollowUpQueueSnapshot(J.queue);let D=0;for(let A of J.messages){if(!A.recovered||A.persisted)continue;if(H.projectedRecoveredInputIds?.has(A.id))continue;for(let q of cz(A.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:q});H.projectedRecoveredInputIds?.add(A.id),D++}if(D>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${D} queued instruction${D===1?"":"s"} recovered after restart]
11
11
  `}});break}case"goal_updated":if(J.goal)this.sendUpdate(this.goalSessionUpdate(J.goal));if(J.goal&&J.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${J.goal.status}: ${J.goal.objective}]
12
- `}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:J.goal.goalId,continuation:J.continuation,...J.prematureStopPattern?{prematureStopPattern:J.prematureStopPattern}:{},...J.prematureStopCount!==void 0?{prematureStopCount:J.prematureStopCount}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:J.phase,...J.reason?{reason:J.reason}:{},...J.strategy?{strategy:J.strategy}:{},...J.outcome?{outcome:J.outcome}:{},...J.preTokens!==void 0?{preTokens:J.preTokens}:{},...J.preTokenSource?{preTokenSource:J.preTokenSource}:{},...J.estimatedPendingTokens!==void 0?{estimatedPendingTokens:J.estimatedPendingTokens}:{},...J.postTokens!==void 0?{postTokens:J.postTokens}:{},...J.sampleAttempts!==void 0?{sampleAttempts:J.sampleAttempts}:{},...J.inputReductions!==void 0?{inputReductions:J.inputReductions}:{},...J.messagesOmitted!==void 0?{messagesOmitted:J.messagesOmitted}:{},...J.filesOmitted!==void 0?{filesOmitted:J.filesOmitted}:{},...J.imagesOmitted!==void 0?{imagesOmitted:J.imagesOmitted}:{},...J.fallbackTargetTokens!==void 0?{fallbackTargetTokens:J.fallbackTargetTokens}:{},...J.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:J.fallbackMessagesOmitted}:{},...J.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:J.fallbackMessagesTruncated}:{},...J.failureReason?{failureReason:J.failureReason}:{}}}});break;default:break}if(!await this.flushUpdates())B.abort("acp-egress-failed")});if(!await this.flushUpdates())B.abort("acp-egress-failed");this.contextMessages=[...j.messages];let Qz=await this.loadPersistedMessages();if(this.messages=Qz.length>0?Qz:[...j.messages],!N.success){let J=N.error?.type??"unknown",D=N.error?.details??N.error?.message??"Agent execution failed",A=BH(D)??v(D);throw gz.internalError({failureType:J,modelId:this.runtime.getCurrentModelId(),taskFailure:A,outputStarted:U,toolExecutionStarted:V,...Number.isInteger(N.metadata?.toolCallsCount)?{toolCallsCount:N.metadata.toolCallsCount}:{}},`Agent turn failed (${J})`)}if(B.signal.aborted)return{stopReason:"cancelled"};let Yz={...N.metadata?.structuredOutput?{structuredOutput:N.metadata.structuredOutput,outputSchemaDigest:N.metadata.structuredOutputSchemaDigest}:{},...N.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:N.metadata.goalVerificationVerdict,...N.metadata.goalVerifierSessionId?{verifierSessionId:N.metadata.goalVerifierSessionId}:{},...N.metadata.goalVerificationEvidenceSha256?{evidenceSha256:N.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(Yz).length>0?{_meta:Yz}:{}}}catch(j){if(B.signal.aborted||j instanceof Error&&j.name==="AbortError")return{stopReason:"cancelled"};throw G.error(`[AcpSession ${this.id}] Prompt error:`,j),j}finally{if(H.abortSignal?.removeEventListener("abort",Z),_&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(T(),this.pendingPromptCompletion===E)this.pendingPromptCompletion=null;if(this.pendingPrompt===B){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let H=z.trimStart().slice(1).trim();if(!H)throw Error("User shell command cannot be empty");let L=new AbortController,Y,$=new Promise((W)=>{Y=W});this.pendingUserShell=L,this.pendingUserShellCompletion=$;let X,Q="";try{let W=await this.runtime.executeUserShellCommand(H,{signal:L.signal,onEvent:async(Z)=>{if(X=Z.executionId,Z.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z.executionId,status:"in_progress",title:`! ${Z.command}`,content:[],kind:"execute"});return}if(Z.type==="output"){Q+=Z.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Z.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:Z.chunk}}]});return}let _=r(Z.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Z.executionId,status:Z.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Q?WH(Z.record):_}}]})}}),B={role:"user",content:W.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(W.record))}};if(this.messages.push(B),this.contextMessages.push(B),W.queue)this.sendFollowUpQueueSnapshot(W.queue);if(W.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return L.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:W.record.status==="aborted"?"cancelled":"end_turn"}}catch(W){if(X)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:X,status:"failed",content:[{type:"content",content:{type:"text",text:W instanceof Error?W.message:String(W)}}]});if(L.signal.aborted)return{stopReason:"cancelled"};throw W}finally{if(Y(),this.pendingUserShellCompletion===$)this.pendingUserShellCompletion=null;if(this.pendingUserShell===L){if(this.pendingUserShell=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}requestPendingResume(z={}){if(!this.canSendUpdates())return;if(!this.pendingResumeRequested){if(this.pendingResumeRequested=!0,!this.pendingResumeInFlight)this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}if(!z.defer)this.ensurePendingResumeScheduled()}ensurePendingResumeScheduled(z=0){if(!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeCompletion!==null)return;this.pendingResumeScheduled=!0;let H=this.pendingResumeGeneration,L=()=>{if(H!==this.pendingResumeGeneration)return;this.startPendingResumeRun(H)};if(z>0)this.pendingResumeTimer=setTimeout(L,z),this.pendingResumeTimer.unref?.();else queueMicrotask(L)}startPendingResumeRun(z){if(z!==this.pendingResumeGeneration)return;if(this.pendingResumeScheduled=!1,this.pendingResumeTimer=null,!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeInFlight||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;let H=this.resumePendingIfIdle();this.pendingResumeCompletion=H,H.then(()=>{if(this.pendingResumeCompletion===H){this.pendingResumeCompletion=null;let L=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,L!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(L)}},()=>{if(this.pendingResumeCompletion===H){this.pendingResumeCompletion=null;let L=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,L!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(L)}})}clearPendingResumeRequest(){let z=this.pendingResumeRequested||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeTimer!==null||this.pendingResumeCompletion!==null;if(this.pendingResumeRequested=!1,this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,this.pendingResumeGeneration++,this.pendingResumeNextDelayMs=null,this.pendingResumeScheduled=!1,this.pendingResumeTimer!==null)clearTimeout(this.pendingResumeTimer),this.pendingResumeTimer=null;return z}preserveNewPendingInput(z){if(z==="pending_input"||!this.pendingResumeRequested||!this.runtime||this.runtime.getPendingSteeringCount()===0)return!1;return this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,!0}pendingResumeSessionUpdate(z,H){return{sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/pendingResume":{phase:z,kind:H.kind,attempt:H.attempt,maxAttempts:Cz,...H.delayMs!==void 0?{delayMs:H.delayMs,nextRetryAt:Date.now()+H.delayMs}:{},...H.taskFailure?{failure:{code:H.taskFailure.code,retryable:H.taskFailure.retryable,...H.taskFailure.resource?{resource:H.taskFailure.resource}:{}}}:{}}}}}async resumePendingIfIdle(){if(!this.pendingResumeRequested)return;if(!this.canSendUpdates()){this.clearPendingResumeRequest();return}if(this.pendingResumeInFlight||this.pendingResumeCompletion!==null||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;this.pendingResumeInFlight=!0,this.pendingResumeRequested=!1;let z=this.pendingResumeGeneration,H=this.pendingResumeAttempt+1;if(this.pendingResumeAttempt=H,this.pendingResumeRecoveryStartedAt===0)this.pendingResumeRecoveryStartedAt=Date.now();let L="preflight",Y=!1,$,X=null;try{let Q=this.runtime.getPendingSteeringCount()>0,W=Q?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let B=W?.status==="active"||W?.status==="verifying",Z=this.runtime.getTurnRecoveryAssessment();if(Z.state!=="none"&&(Z.state==="requires_attention"||!Q&&!B))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Z}});if(!Q&&!B){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if(Z.state==="requires_attention"){this.clearPendingResumeRequest();return}L=Q?"pending_input":"goal",Y=!0;let _=fz-(Date.now()-this.pendingResumeRecoveryStartedAt);if(_<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:H,kind:L,taskFailure:I("timeout")})),!this.preserveNewPendingInput(L))this.clearPendingResumeRequest();return}let U=new AbortController;X=setTimeout(()=>{U.abort("acp-pending-resume-budget-exhausted")},_),X.unref?.();let V=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Q,goalContinuationOnly:B,projectedRecoveredInputIds:L==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:U.signal});if(z!==this.pendingResumeGeneration)return;if(U.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:H,kind:L,taskFailure:I("timeout")})),!this.preserveNewPendingInput(L))this.clearPendingResumeRequest();return}if(V.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(H>1){if(!await this.sendUpdateAndWait(this.pendingResumeSessionUpdate("recovered",{attempt:H,kind:L})))return;if(z!==this.pendingResumeGeneration)return}this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}catch(Q){if(z!==this.pendingResumeGeneration)return;let W=Y?_H(Q):{taskFailure:v(Q),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},B=L==="preflight"||L==="pending_input"&&this.runtime.getPendingSteeringCount()>0,Z=uz({sessionIdentity:this.id,failedAttempt:H,recoveryStartedAt:this.pendingResumeRecoveryStartedAt,workStillPending:B,evidence:W});if(Z.phase==="retry_scheduled")this.pendingResumeRequested=!0,$=Z.delayMs,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:H+1,kind:L,taskFailure:W?.taskFailure,delayMs:Z.delayMs})),G.warn(`[AcpSession ${this.id}] Pending resume attempt ${H} failed; retrying in ${Z.delayMs}ms`);else{let _=Z.phase;if(this.sendUpdate(this.pendingResumeSessionUpdate(_,{attempt:H,kind:L,taskFailure:W?.taskFailure})),G.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${H}, retryable=${Z.retryable}, phase=${_})`,Q),!this.preserveNewPendingInput(L))this.clearPendingResumeRequest()}}finally{if(X!==null)clearTimeout(X);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.pendingResumeNextDelayMs=$??0}}cancel(){G.info(`[AcpSession ${this.id}] Cancel requested`);let z=this.clearPendingResumeRequest();if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,z=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,z=!0;if(this.pendingSideConversation)this.pendingSideConversation.abort(),this.pendingSideConversation=null,z=!0;if(!z)G.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let L=["default","auto-edit","yolo","plan"].includes(z)?z:"default",Y=this.mapModeIdToPermissionMode(L);await this.persistPermissionMode(Y),this.mode=L,G.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(z){switch(z){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(G.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{await this.persistMetadataUpdate({selectedModelId:z})}catch(L){if(H&&H!==z)await this.agent.switchModel(H).catch((Y)=>{G.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});throw L}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(L){throw Error(L instanceof Error?L.message:"Invalid reasoning effort")}if(H.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{await this.persistMetadataUpdate({reasoningEffort:z},{selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}catch(L){throw await this.runtime.refresh({reasoningEffort:H.selection}),L}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(L){throw Error(L instanceof Error?L.message:"Invalid service tier")}if(H.selection===z)return;await this.runtime.refresh({serviceTier:z});try{await this.persistMetadataUpdate({serviceTier:z},{selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}catch(L){throw await this.runtime.refresh({serviceTier:H.selection}),L}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(L){throw Error(L instanceof Error?L.message:"Invalid response verbosity")}if(H.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{await this.persistMetadataUpdate({responseVerbosity:z},{selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}catch(L){throw await this.runtime.refresh({responseVerbosity:H.selection}),L}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getCommunicationStyleConfiguration(),L=this.runtime.resolveCommunicationStyleConfiguration(z);if(L.source!=="built-in"&&!L.contentSha256)throw Error("Custom communication style has no provenance");if(H.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{await this.persistMetadataUpdate({communicationStyle:z,communicationStyleDigest:L.source==="built-in"?null:L.contentSha256},{selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...L.source!=="built-in"&&L.contentSha256?{communicationStyleDigest:L.contentSha256}:{}})}catch(Y){throw await this.runtime.refresh({communicationStyle:H.selection}),Y}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((H)=>structuredClone(H)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&this.pendingSideConversation===null&&!this.pendingResumeRequested&&!this.pendingResumeScheduled&&!this.pendingResumeInFlight&&this.pendingResumeTimer===null&&this.pendingResumeCompletion===null&&(this.runtime?.isIdleForResidency()??!1)}destroy(z={}){if(this.destroyPromise)return this.destroyFinished?Promise.resolve():this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(z.discardPendingInput===!0).finally(()=>{this.destroyFinished=!0}),this.destroyPromise}async destroyOwnedResources(z){if(this.destroyed=!0,this.clearPendingResumeRequest(),this.updateEgress.close(new Sz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let H=this.agent,L=this.runtime,Y=this.pendingPromptCompletion,$=this.pendingUserShellCompletion,X=this.pendingSideConversationCompletion,Q=this.pendingResumeCompletion;this.agent=null,this.runtime=null;let W,B=async(Z)=>{try{await Z()}catch(_){W??=_}};if(await B(()=>this.cancel()),Y)await B(()=>Y);if($)await B(()=>$);if(X)await B(()=>X);if(Q)await B(()=>Q);if(z&&Y&&L)await B(()=>L.discardPendingInput());if(H)await B(()=>H.destroy());if(L)await B(()=>L.dispose());if(await B(()=>R.destroyRegisteredSession(this.serviceRegistration)),this.serviceRegistration=void 0,G.debug(`[AcpSession ${this.id}] Destroyed`),W!==void 0)throw W}resolvePrompt(z){let H=[],L=[],Y=0,$=0,X=0,Q=(Z)=>{if(L.length>0)L.push({type:"text",text:`
12
+ `}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:J.goal.goalId,continuation:J.continuation,...J.prematureStopPattern?{prematureStopPattern:J.prematureStopPattern}:{},...J.prematureStopCount!==void 0?{prematureStopCount:J.prematureStopCount}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:J.phase,...J.reason?{reason:J.reason}:{},...J.strategy?{strategy:J.strategy}:{},...J.outcome?{outcome:J.outcome}:{},...J.preTokens!==void 0?{preTokens:J.preTokens}:{},...J.preTokenSource?{preTokenSource:J.preTokenSource}:{},...J.estimatedPendingTokens!==void 0?{estimatedPendingTokens:J.estimatedPendingTokens}:{},...J.postTokens!==void 0?{postTokens:J.postTokens}:{},...J.sampleAttempts!==void 0?{sampleAttempts:J.sampleAttempts}:{},...J.inputReductions!==void 0?{inputReductions:J.inputReductions}:{},...J.messagesOmitted!==void 0?{messagesOmitted:J.messagesOmitted}:{},...J.filesOmitted!==void 0?{filesOmitted:J.filesOmitted}:{},...J.imagesOmitted!==void 0?{imagesOmitted:J.imagesOmitted}:{},...J.fallbackTargetTokens!==void 0?{fallbackTargetTokens:J.fallbackTargetTokens}:{},...J.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:J.fallbackMessagesOmitted}:{},...J.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:J.fallbackMessagesTruncated}:{},...J.failureReason?{failureReason:J.failureReason}:{},...J.memory?{memory:J.memory}:{}}}});break;default:break}if(!await this.flushUpdates())B.abort("acp-egress-failed")});if(!await this.flushUpdates())B.abort("acp-egress-failed");this.contextMessages=[...j.messages];let Qz=await this.loadPersistedMessages();if(this.messages=Qz.length>0?Qz:[...j.messages],!N.success){let J=N.error?.type??"unknown",D=N.error?.details??N.error?.message??"Agent execution failed",A=BH(D)??v(D);throw gz.internalError({failureType:J,modelId:this.runtime.getCurrentModelId(),taskFailure:A,outputStarted:U,toolExecutionStarted:V,...Number.isInteger(N.metadata?.toolCallsCount)?{toolCallsCount:N.metadata.toolCallsCount}:{}},`Agent turn failed (${J})`)}if(B.signal.aborted)return{stopReason:"cancelled"};let Yz={...N.metadata?.structuredOutput?{structuredOutput:N.metadata.structuredOutput,outputSchemaDigest:N.metadata.structuredOutputSchemaDigest}:{},...N.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:N.metadata.goalVerificationVerdict,...N.metadata.goalVerifierSessionId?{verifierSessionId:N.metadata.goalVerifierSessionId}:{},...N.metadata.goalVerificationEvidenceSha256?{evidenceSha256:N.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(Yz).length>0?{_meta:Yz}:{}}}catch(j){if(B.signal.aborted||j instanceof Error&&j.name==="AbortError")return{stopReason:"cancelled"};throw G.error(`[AcpSession ${this.id}] Prompt error:`,j),j}finally{if(H.abortSignal?.removeEventListener("abort",Z),_&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(T(),this.pendingPromptCompletion===E)this.pendingPromptCompletion=null;if(this.pendingPrompt===B){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let H=z.trimStart().slice(1).trim();if(!H)throw Error("User shell command cannot be empty");let L=new AbortController,Y,$=new Promise((W)=>{Y=W});this.pendingUserShell=L,this.pendingUserShellCompletion=$;let X,Q="";try{let W=await this.runtime.executeUserShellCommand(H,{signal:L.signal,onEvent:async(Z)=>{if(X=Z.executionId,Z.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z.executionId,status:"in_progress",title:`! ${Z.command}`,content:[],kind:"execute"});return}if(Z.type==="output"){Q+=Z.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Z.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:Z.chunk}}]});return}let _=r(Z.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Z.executionId,status:Z.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Q?WH(Z.record):_}}]})}}),B={role:"user",content:W.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(W.record))}};if(this.messages.push(B),this.contextMessages.push(B),W.queue)this.sendFollowUpQueueSnapshot(W.queue);if(W.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return L.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:W.record.status==="aborted"?"cancelled":"end_turn"}}catch(W){if(X)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:X,status:"failed",content:[{type:"content",content:{type:"text",text:W instanceof Error?W.message:String(W)}}]});if(L.signal.aborted)return{stopReason:"cancelled"};throw W}finally{if(Y(),this.pendingUserShellCompletion===$)this.pendingUserShellCompletion=null;if(this.pendingUserShell===L){if(this.pendingUserShell=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}requestPendingResume(z={}){if(!this.canSendUpdates())return;if(!this.pendingResumeRequested){if(this.pendingResumeRequested=!0,!this.pendingResumeInFlight)this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}if(!z.defer)this.ensurePendingResumeScheduled()}ensurePendingResumeScheduled(z=0){if(!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeCompletion!==null)return;this.pendingResumeScheduled=!0;let H=this.pendingResumeGeneration,L=()=>{if(H!==this.pendingResumeGeneration)return;this.startPendingResumeRun(H)};if(z>0)this.pendingResumeTimer=setTimeout(L,z),this.pendingResumeTimer.unref?.();else queueMicrotask(L)}startPendingResumeRun(z){if(z!==this.pendingResumeGeneration)return;if(this.pendingResumeScheduled=!1,this.pendingResumeTimer=null,!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeInFlight||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;let H=this.resumePendingIfIdle();this.pendingResumeCompletion=H,H.then(()=>{if(this.pendingResumeCompletion===H){this.pendingResumeCompletion=null;let L=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,L!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(L)}},()=>{if(this.pendingResumeCompletion===H){this.pendingResumeCompletion=null;let L=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,L!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(L)}})}clearPendingResumeRequest(){let z=this.pendingResumeRequested||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeTimer!==null||this.pendingResumeCompletion!==null;if(this.pendingResumeRequested=!1,this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,this.pendingResumeGeneration++,this.pendingResumeNextDelayMs=null,this.pendingResumeScheduled=!1,this.pendingResumeTimer!==null)clearTimeout(this.pendingResumeTimer),this.pendingResumeTimer=null;return z}preserveNewPendingInput(z){if(z==="pending_input"||!this.pendingResumeRequested||!this.runtime||this.runtime.getPendingSteeringCount()===0)return!1;return this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,!0}pendingResumeSessionUpdate(z,H){return{sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/pendingResume":{phase:z,kind:H.kind,attempt:H.attempt,maxAttempts:Cz,...H.delayMs!==void 0?{delayMs:H.delayMs,nextRetryAt:Date.now()+H.delayMs}:{},...H.taskFailure?{failure:{code:H.taskFailure.code,retryable:H.taskFailure.retryable,...H.taskFailure.resource?{resource:H.taskFailure.resource}:{}}}:{}}}}}async resumePendingIfIdle(){if(!this.pendingResumeRequested)return;if(!this.canSendUpdates()){this.clearPendingResumeRequest();return}if(this.pendingResumeInFlight||this.pendingResumeCompletion!==null||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;this.pendingResumeInFlight=!0,this.pendingResumeRequested=!1;let z=this.pendingResumeGeneration,H=this.pendingResumeAttempt+1;if(this.pendingResumeAttempt=H,this.pendingResumeRecoveryStartedAt===0)this.pendingResumeRecoveryStartedAt=Date.now();let L="preflight",Y=!1,$,X=null;try{let Q=this.runtime.getPendingSteeringCount()>0,W=Q?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let B=W?.status==="active"||W?.status==="verifying",Z=this.runtime.getTurnRecoveryAssessment();if(Z.state!=="none"&&(Z.state==="requires_attention"||!Q&&!B))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Z}});if(!Q&&!B){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if(Z.state==="requires_attention"){this.clearPendingResumeRequest();return}L=Q?"pending_input":"goal",Y=!0;let _=fz-(Date.now()-this.pendingResumeRecoveryStartedAt);if(_<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:H,kind:L,taskFailure:I("timeout")})),!this.preserveNewPendingInput(L))this.clearPendingResumeRequest();return}let U=new AbortController;X=setTimeout(()=>{U.abort("acp-pending-resume-budget-exhausted")},_),X.unref?.();let V=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Q,goalContinuationOnly:B,projectedRecoveredInputIds:L==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:U.signal});if(z!==this.pendingResumeGeneration)return;if(U.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:H,kind:L,taskFailure:I("timeout")})),!this.preserveNewPendingInput(L))this.clearPendingResumeRequest();return}if(V.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(H>1){if(!await this.sendUpdateAndWait(this.pendingResumeSessionUpdate("recovered",{attempt:H,kind:L})))return;if(z!==this.pendingResumeGeneration)return}this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}catch(Q){if(z!==this.pendingResumeGeneration)return;let W=Y?_H(Q):{taskFailure:v(Q),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},B=L==="preflight"||L==="pending_input"&&this.runtime.getPendingSteeringCount()>0,Z=uz({sessionIdentity:this.id,failedAttempt:H,recoveryStartedAt:this.pendingResumeRecoveryStartedAt,workStillPending:B,evidence:W});if(Z.phase==="retry_scheduled")this.pendingResumeRequested=!0,$=Z.delayMs,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:H+1,kind:L,taskFailure:W?.taskFailure,delayMs:Z.delayMs})),G.warn(`[AcpSession ${this.id}] Pending resume attempt ${H} failed; retrying in ${Z.delayMs}ms`);else{let _=Z.phase;if(this.sendUpdate(this.pendingResumeSessionUpdate(_,{attempt:H,kind:L,taskFailure:W?.taskFailure})),G.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${H}, retryable=${Z.retryable}, phase=${_})`,Q),!this.preserveNewPendingInput(L))this.clearPendingResumeRequest()}}finally{if(X!==null)clearTimeout(X);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.pendingResumeNextDelayMs=$??0}}cancel(){G.info(`[AcpSession ${this.id}] Cancel requested`);let z=this.clearPendingResumeRequest();if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,z=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,z=!0;if(this.pendingSideConversation)this.pendingSideConversation.abort(),this.pendingSideConversation=null,z=!0;if(!z)G.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let L=["default","auto-edit","yolo","plan"].includes(z)?z:"default",Y=this.mapModeIdToPermissionMode(L);await this.persistPermissionMode(Y),this.mode=L,G.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(z){switch(z){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(G.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{await this.persistMetadataUpdate({selectedModelId:z})}catch(L){if(H&&H!==z)await this.agent.switchModel(H).catch((Y)=>{G.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});throw L}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(L){throw Error(L instanceof Error?L.message:"Invalid reasoning effort")}if(H.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{await this.persistMetadataUpdate({reasoningEffort:z},{selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}catch(L){throw await this.runtime.refresh({reasoningEffort:H.selection}),L}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(L){throw Error(L instanceof Error?L.message:"Invalid service tier")}if(H.selection===z)return;await this.runtime.refresh({serviceTier:z});try{await this.persistMetadataUpdate({serviceTier:z},{selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}catch(L){throw await this.runtime.refresh({serviceTier:H.selection}),L}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(L){throw Error(L instanceof Error?L.message:"Invalid response verbosity")}if(H.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{await this.persistMetadataUpdate({responseVerbosity:z},{selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}catch(L){throw await this.runtime.refresh({responseVerbosity:H.selection}),L}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getCommunicationStyleConfiguration(),L=this.runtime.resolveCommunicationStyleConfiguration(z);if(L.source!=="built-in"&&!L.contentSha256)throw Error("Custom communication style has no provenance");if(H.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{await this.persistMetadataUpdate({communicationStyle:z,communicationStyleDigest:L.source==="built-in"?null:L.contentSha256},{selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...L.source!=="built-in"&&L.contentSha256?{communicationStyleDigest:L.contentSha256}:{}})}catch(Y){throw await this.runtime.refresh({communicationStyle:H.selection}),Y}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((H)=>structuredClone(H)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&this.pendingSideConversation===null&&!this.pendingResumeRequested&&!this.pendingResumeScheduled&&!this.pendingResumeInFlight&&this.pendingResumeTimer===null&&this.pendingResumeCompletion===null&&(this.runtime?.isIdleForResidency()??!1)}destroy(z={}){if(this.destroyPromise)return this.destroyFinished?Promise.resolve():this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(z.discardPendingInput===!0).finally(()=>{this.destroyFinished=!0}),this.destroyPromise}async destroyOwnedResources(z){if(this.destroyed=!0,this.clearPendingResumeRequest(),this.updateEgress.close(new Sz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let H=this.agent,L=this.runtime,Y=this.pendingPromptCompletion,$=this.pendingUserShellCompletion,X=this.pendingSideConversationCompletion,Q=this.pendingResumeCompletion;this.agent=null,this.runtime=null;let W,B=async(Z)=>{try{await Z()}catch(_){W??=_}};if(await B(()=>this.cancel()),Y)await B(()=>Y);if($)await B(()=>$);if(X)await B(()=>X);if(Q)await B(()=>Q);if(z&&Y&&L)await B(()=>L.discardPendingInput());if(H)await B(()=>H.destroy());if(L)await B(()=>L.dispose());if(await B(()=>R.destroyRegisteredSession(this.serviceRegistration)),this.serviceRegistration=void 0,G.debug(`[AcpSession ${this.id}] Destroyed`),W!==void 0)throw W}resolvePrompt(z){let H=[],L=[],Y=0,$=0,X=0,Q=(Z)=>{if(L.length>0)L.push({type:"text",text:`
13
13
  `}),X+=1;if(L.push(Z),Z.type==="text")X+=Z.text.length};for(let Z of z)if(Z.type==="text")H.push(Z.text),Q({type:"text",text:Z.text});else if(Z.type==="image"){let _=`data:${Z.mimeType};base64,${Z.data}`;Y+=1,$+=_.length,H.push(`[Image: ${Z.mimeType}]`),Q({type:"image_url",image_url:{url:_}})}else if(Z.type==="resource"){let _=Z.resource;if("text"in _){let U=`<file path="${_.uri}">
14
14
  ${_.text}
15
15
  </file>`;H.push(U),Q({type:"text",text:U})}}else if(Z.type==="resource_link"){let _=`[Resource: ${Z.uri}]`;H.push(_),Q({type:"text",text:_})}if(Y>g)throw Error(`ACP prompt contains more than ${g} images`);if($>Xz)throw Error("ACP prompt images exceed the 5 MiB limit");if(X>c)throw Error(`ACP prompt text exceeds ${c} characters`);if(Buffer.byteLength(H.join(`
@@ -0,0 +1 @@
1
+ import{$b as k,Nb as a,Ob as b,Qb as c,Ub as d,Vb as e,Wb as f,Xb as g,Yb as h,Zb as i,_b as j,hc as l,ic as m,jc as n,kc as o,mc as p,nc as q,oc as r}from"./chunk-we13xwds.js";import"./chunk-0sx7ak0b.js";import"./chunk-n6tvswa8.js";import"./chunk-kmg8ad2j.js";import"./chunk-es0cbtx1.js";import"./chunk-zfaenqqx.js";import"./chunk-c562kd2m.js";import"./chunk-pw9axk0e.js";import"./chunk-cww9pp1q.js";import"./chunk-hvmrcd84.js";import"./chunk-ascjys4e.js";import"./chunk-r4q06wbs.js";import"./chunk-2ff55pvt.js";import"./chunk-nxsarfy6.js";import"./chunk-w2m4yczv.js";import"./chunk-zp5097qk.js";import"./chunk-g38d2ezm.js";import"./chunk-n8qg68y2.js";import"./chunk-pg7cgvs8.js";import"./chunk-svsgtj41.js";import"./chunk-2g8avyq6.js";import"./chunk-19zsecpx.js";import"./chunk-5cw3bevx.js";import"./chunk-mnk0b4nz.js";import"./chunk-tecbx0ek.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
@@ -15,4 +15,4 @@ More specific user instructions about presentation take precedence for that resp
15
15
  <communication_style>
16
16
  ${h.prompt}
17
17
  </communication_style>`}
18
- export{R as jh,z as kh,H as lh,W as mh,Z as nh};
18
+ export{R as mh,z as nh,H as oh,W as ph,Z as qh};
@@ -0,0 +1 @@
1
+ import{Xj as a,Yj as b,Zj as c}from"./chunk-85b3kacc.js";import"./chunk-5cw3bevx.js";import"./chunk-mnk0b4nz.js";import"./chunk-tecbx0ek.js";export{b as isWorkspaceTrusted,c as WorkspaceTrustService,a as MAX_RESIDENT_WORKSPACE_TRUST_STATUSES};
@@ -1,2 +1,2 @@
1
- import{Pj as d,Rj as h}from"./chunk-2t0wp7gm.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is evicted",group:"AI Options:",default:void 0},"max-resident-session-projections":{alias:["maxResidentSessionProjections"],type:"number",describe:"Maximum resident Session projections retained in this process",group:"AI Options:",default:void 0},"session-projection-idle-ms":{alias:["sessionProjectionIdleMs"],type:"number",describe:"Idle time before an evictable Session projection is evicted",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
2
- export{q as lf,w as mf};
1
+ import{Sj as d,Uj as h}from"./chunk-19zsecpx.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is evicted",group:"AI Options:",default:void 0},"max-resident-session-projections":{alias:["maxResidentSessionProjections"],type:"number",describe:"Maximum resident Session projections retained in this process",group:"AI Options:",default:void 0},"session-projection-idle-ms":{alias:["sessionProjectionIdleMs"],type:"number",describe:"Idle time before an evictable Session projection is evicted",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
2
+ export{q as of,w as pf};
@@ -1,3 +1,3 @@
1
- import{Jj as N,Mj as M}from"./chunk-65c3vjwm.js";import{Zj as H}from"./chunk-t88sfhjj.js";import{createModels as _,createProvider as Y,envApiKeyAuth as x,getSupportedThinkingLevels as E}from"@earendil-works/pi-ai";import{anthropicMessagesApi as F}from"@earendil-works/pi-ai/api/anthropic-messages.lazy";import{openAICompletionsApi as U}from"@earendil-works/pi-ai/api/openai-completions.lazy";import{builtinProviders as P}from"@earendil-works/pi-ai/providers/all";var K=/^[a-z][a-z0-9._-]{0,63}$/,z=/^[A-Z_][A-Z0-9_]*$/,s=new Set(["openai-completions","anthropic-messages"]);function B(u){return typeof u==="string"&&s.has(u)}function X(u,$){let h=`modelProviders.${u}`,b=[];if(!K.test(u))b.push(`${h}: id must match ${K.source}`);if(!$.name?.trim())b.push(`${h}: name must not be empty`);if(!B($.wireApi))b.push(`${h}: wireApi must be openai-completions or anthropic-messages`);try{let w=new URL($.baseUrl);if(!["http:","https:"].includes(w.protocol))b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}catch{b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}if($.apiKeyEnv!==void 0&&!z.test($.apiKeyEnv))b.push(`${h}: apiKeyEnv must be a valid environment variable name`);if("apiKey"in $)b.push(`${h}: API keys must be stored separately in auth.json`);return b}function J(u,$){let h=$.trim().replace(/\/+$/,"");if(u==="anthropic-messages"&&/\/v1$/i.test(h))return h.slice(0,-3);return h}import{promises as Z}from"node:fs";import j from"node:path";import{Mutex as R}from"async-mutex";import T from"write-file-atomic";class Q{filePath;mutex=new R;constructor(u=j.join(H(),"auth.json")){this.filePath=u}async read(u){return(await this.readAll())[u]}async list(){let u=await this.readAll();return Object.entries(u).map(([$,h])=>({providerId:$,type:h.type}))}async modify(u,$){return this.mutex.runExclusive(async()=>{let h=await this.readAll(),b=h[u],w=await $(b);if(w===void 0)return b;return h[u]=w,await this.writeAll(h),w})}async delete(u){await this.mutex.runExclusive(async()=>{let $=await this.readAll();if(!(u in $))return;delete $[u],await this.writeAll($)})}async readAll(){try{let u=await Z.readFile(this.filePath,"utf8"),$=JSON.parse(u);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch(u){if(u.code==="ENOENT")return{};throw u}}async writeAll(u){let $=j.dirname(this.filePath);await Z.mkdir($,{recursive:!0,mode:448}),await Z.chmod($,448),await T(this.filePath,`${JSON.stringify(u,null,2)}
1
+ import{Mj as N,Pj as M}from"./chunk-2g8avyq6.js";import{ak as H}from"./chunk-mnk0b4nz.js";import{createModels as _,createProvider as Y,envApiKeyAuth as x,getSupportedThinkingLevels as E}from"@earendil-works/pi-ai";import{anthropicMessagesApi as F}from"@earendil-works/pi-ai/api/anthropic-messages.lazy";import{openAICompletionsApi as U}from"@earendil-works/pi-ai/api/openai-completions.lazy";import{builtinProviders as P}from"@earendil-works/pi-ai/providers/all";var K=/^[a-z][a-z0-9._-]{0,63}$/,z=/^[A-Z_][A-Z0-9_]*$/,s=new Set(["openai-completions","anthropic-messages"]);function B(u){return typeof u==="string"&&s.has(u)}function X(u,$){let h=`modelProviders.${u}`,b=[];if(!K.test(u))b.push(`${h}: id must match ${K.source}`);if(!$.name?.trim())b.push(`${h}: name must not be empty`);if(!B($.wireApi))b.push(`${h}: wireApi must be openai-completions or anthropic-messages`);try{let w=new URL($.baseUrl);if(!["http:","https:"].includes(w.protocol))b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}catch{b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}if($.apiKeyEnv!==void 0&&!z.test($.apiKeyEnv))b.push(`${h}: apiKeyEnv must be a valid environment variable name`);if("apiKey"in $)b.push(`${h}: API keys must be stored separately in auth.json`);return b}function J(u,$){let h=$.trim().replace(/\/+$/,"");if(u==="anthropic-messages"&&/\/v1$/i.test(h))return h.slice(0,-3);return h}import{promises as Z}from"node:fs";import j from"node:path";import{Mutex as R}from"async-mutex";import T from"write-file-atomic";class Q{filePath;mutex=new R;constructor(u=j.join(H(),"auth.json")){this.filePath=u}async read(u){return(await this.readAll())[u]}async list(){let u=await this.readAll();return Object.entries(u).map(([$,h])=>({providerId:$,type:h.type}))}async modify(u,$){return this.mutex.runExclusive(async()=>{let h=await this.readAll(),b=h[u],w=await $(b);if(w===void 0)return b;return h[u]=w,await this.writeAll(h),w})}async delete(u){await this.mutex.runExclusive(async()=>{let $=await this.readAll();if(!(u in $))return;delete $[u],await this.writeAll($)})}async readAll(){try{let u=await Z.readFile(this.filePath,"utf8"),$=JSON.parse(u);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch(u){if(u.code==="ENOENT")return{};throw u}}async writeAll(u){let $=j.dirname(this.filePath);await Z.mkdir($,{recursive:!0,mode:448}),await Z.chmod($,448),await T(this.filePath,`${JSON.stringify(u,null,2)}
2
2
  `,{mode:384}),await Z.chmod(this.filePath,384)}}var q="openai-compatible",G="anthropic-compatible",D="https://api.openai.com/v1",V="https://api.anthropic.com",A=128000,C=32768,t={input:0,output:0,cacheRead:0,cacheWrite:0},f=["openai","anthropic","deepseek","google","moonshotai","moonshotai-cn","zai","zai-coding-cn"];class L{credentials;models;compatibleModels=new Map;anthropicCompatibleModels=new Map;customProviderConfigs=new Map;customProviderModels=new Map;reservedProviderIds=new Set;constructor(u=new Q){this.credentials=u,this.models=_({credentials:u});for(let $ of P())this.models.setProvider($);this.installOpenAICompatibleProvider(),this.installAnthropicCompatibleProvider();for(let $ of this.models.getProviders())this.reservedProviderIds.add($.id)}async listProviders(){return Promise.all(this.models.getProviders().map(async(u)=>{let $=u.getModels(),h=this.customProviderConfigs.get(u.id),b=this.getFactoryWireApi(u.id);return{id:u.id,name:u.name,modelCount:$.length,defaultBaseUrl:u.baseUrl??$[0]?.baseUrl,supportsApiKey:Boolean(u.auth.apiKey),supportsOAuth:Boolean(u.auth.oauth),configured:b?!1:Boolean(await this.models.checkAuth(u.id)),custom:Boolean(h),factoryWireApi:b,wireApi:h?.wireApi,apiKeyEnv:h?.apiKeyEnv}}))}listModels(u){return this.models.getModels(u).map(($)=>this.toCatalogEntry($))}getModel(u,$){let h=this.models.getModel(u,$);if(!h&&u===q)this.registerOpenAICompatibleModel($),h=this.models.getModel(u,$);if(!h&&u===G)this.registerAnthropicCompatibleModel($),h=this.models.getModel(u,$);if(!h&&this.customProviderConfigs.has(u))this.registerCustomProviderModel(u,$),h=this.models.getModel(u,$);if(!h)throw Error(`Unknown pi-ai model: ${u}/${$}`);return h}resolveConfig(u){let $=this.getModel(u.provider,u.model),h=u.overrides;return{...$,...h?.baseUrl?{baseUrl:J($.api,h.baseUrl)}:{},...h?.maxOutputTokens?{maxTokens:h.maxOutputTokens}:{}}}async setApiKey(u,$){this.requireProvider(u),await this.credentials.modify(u,async()=>({type:"api_key",key:$}))}async clearCredential(u){this.requireProvider(u),await this.credentials.delete(u)}async isConfigured(u){return this.requireProvider(u),Boolean(await this.models.checkAuth(u))}isReservedProviderId(u){return this.reservedProviderIds.has(u)}configureModelProviders(u,$){for(let h of this.customProviderConfigs.keys())this.models.deleteProvider(h);this.customProviderConfigs.clear(),this.customProviderModels.clear();for(let[h,b]of Object.entries(u)){let w=$.filter((k)=>k.provider===h).map((k)=>k.model);this.registerModelProvider(h,b,w)}}registerModelProvider(u,$,h=[]){if(this.isReservedProviderId(u))throw Error(`modelProviders.${u}: built-in provider ids cannot be overridden`);let b=X(u,$);if(b.length>0)throw Error(b.join("; "));let w={...$,name:$.name.trim(),baseUrl:J($.wireApi,$.baseUrl),...$.apiKeyEnv?{apiKeyEnv:$.apiKeyEnv.trim()}:{}};this.customProviderConfigs.set(u,w);let k=new Map;for(let y of new Set(h)){let W=y.trim();if(!W)continue;k.set(W,this.createCompatibleModel(u,W,w.wireApi,w.baseUrl))}this.customProviderModels.set(u,k),this.installCustomProvider(u)}unregisterModelProvider(u){if(!this.customProviderConfigs.has(u))return;this.customProviderConfigs.delete(u),this.customProviderModels.delete(u),this.models.deleteProvider(u)}requireProvider(u){if(!this.models.getProvider(u))throw Error(`Unknown pi-ai provider: ${u}`)}registerOpenAICompatibleModel(u){let $=u.trim();if(!$)throw Error("OpenAI-compatible model ID must not be empty");if(this.compatibleModels.has($))return;let h=this.createCompatibleModel(q,$,"openai-completions",D);this.compatibleModels.set($,h),this.installOpenAICompatibleProvider()}registerAnthropicCompatibleModel(u){let $=u.trim();if(!$)throw Error("Anthropic-compatible model ID must not be empty");if(this.anthropicCompatibleModels.has($))return;let h=this.createCompatibleModel(G,$,"anthropic-messages",V);this.anthropicCompatibleModels.set($,h),this.installAnthropicCompatibleProvider()}registerCustomProviderModel(u,$){let h=$.trim();if(!h)throw Error("Custom provider model ID must not be empty");let b=this.customProviderConfigs.get(u),w=this.customProviderModels.get(u);if(!b||!w||w.has(h))return;w.set(h,this.createCompatibleModel(u,h,b.wireApi,b.baseUrl)),this.installCustomProvider(u)}createCompatibleModel(u,$,h,b){let w=this.models.getModels().filter((y)=>y.provider!==u&&!this.customProviderConfigs.has(y.provider)&&y.id===$),k=f.flatMap((y)=>w.filter((W)=>W.provider===y))[0]??w[0];return{id:$,name:k?.name??$,api:h,provider:u,baseUrl:b,reasoning:k?.reasoning??!1,input:k?[...k.input]:["text"],cost:{...t},contextWindow:k?.contextWindow??A,maxTokens:k?.maxTokens??C,...k?.thinkingLevelMap?{thinkingLevelMap:{...k.thinkingLevelMap}}:{}}}installOpenAICompatibleProvider(){this.models.setProvider(Y({id:q,name:"Custom OpenAI Endpoint",baseUrl:D,auth:{apiKey:x("OpenAI-compatible API key",["OPENAI_COMPATIBLE_API_KEY","BLADE_API_KEY"])},models:[...this.compatibleModels.values()],api:U()}))}installAnthropicCompatibleProvider(){this.models.setProvider(Y({id:G,name:"Custom Anthropic Endpoint",baseUrl:V,auth:{apiKey:x("Anthropic-compatible API key",["ANTHROPIC_API_KEY","BLADE_API_KEY"])},models:[...this.anthropicCompatibleModels.values()],api:F()}))}installCustomProvider(u){let $=this.customProviderConfigs.get(u),h=this.customProviderModels.get(u);if(!$||!h)return;let b=$.apiKeyEnv?[$.apiKeyEnv]:[];this.models.setProvider(Y({id:u,name:$.name,baseUrl:$.baseUrl,auth:{apiKey:x(`${$.name} API key`,b)},models:[...h.values()],api:$.wireApi==="anthropic-messages"?F():U()}))}getFactoryWireApi(u){if(u===q)return"openai-completions";if(u===G)return"anthropic-messages";return}toCatalogEntry(u){return{id:u.id,name:u.name,provider:u.provider,api:u.api,baseUrl:u.baseUrl,reasoning:u.reasoning,supportedReasoningEfforts:E(u),supportedServiceTiers:M(u),supportedResponseVerbosities:N(u),input:[...u.input],contextWindow:u.contextWindow,maxTokens:u.maxTokens,cost:{...u.cost}}}}var S;function hu(){return S??=new L,S}
3
- export{K as Dj,X as Ej,J as Fj,L as Gj,hu as Hj};
3
+ export{K as Gj,X as Hj,J as Ij,L as Jj,hu as Kj};