blade-code 0.10.133 → 0.10.137
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/{chunk-h6tr3zz7.js → chunk-0c82q1sz.js} +1 -1
- package/dist/chunk-0ccm29qy.js +2 -0
- package/dist/{chunk-fjvt9mwv.js → chunk-0k2x2ae6.js} +1 -1
- package/dist/{chunk-7hxyxv4x.js → chunk-1evc05gr.js} +2 -2
- package/dist/chunk-35668hyn.js +1 -0
- package/dist/{chunk-d881py5y.js → chunk-39de5k03.js} +2 -2
- package/dist/chunk-3gmcvd0c.js +1 -0
- package/dist/{chunk-7j628q12.js → chunk-4jqw75ce.js} +1 -1
- package/dist/chunk-5774a669.js +1 -0
- package/dist/chunk-5btfnf2r.js +14 -0
- package/dist/{chunk-bj8cgfbr.js → chunk-5dwmhsrx.js} +1 -1
- package/dist/chunk-5sf2rc1z.js +171 -0
- package/dist/{chunk-nfdfthhb.js → chunk-69nwa6bn.js} +1 -1
- package/dist/{chunk-2nv0kg12.js → chunk-69rjav47.js} +1 -1
- package/dist/{chunk-w3y69e4e.js → chunk-6e3mh79j.js} +1 -1
- package/dist/{chunk-3csj18f1.js → chunk-6xvrrypm.js} +1 -1
- package/dist/{chunk-87ycd3f8.js → chunk-74bswv4z.js} +2 -2
- package/dist/{chunk-ndgdf5jx.js → chunk-75yy9yre.js} +1 -1
- package/dist/chunk-7n035mhg.js +1 -0
- package/dist/{chunk-e1q1hvty.js → chunk-7ykqvsph.js} +2 -2
- package/dist/chunk-9a7bppj7.js +2 -0
- package/dist/{chunk-cfamqqgv.js → chunk-9frd4fpk.js} +2 -2
- package/dist/chunk-a26vtcv5.js +5 -0
- package/dist/{chunk-0ap8b3sw.js → chunk-affzv7f1.js} +1 -1
- package/dist/chunk-b08thknq.js +1 -0
- package/dist/{chunk-f1wnva76.js → chunk-bx75fd0d.js} +396 -394
- package/dist/chunk-bzqbmz6t.js +171 -0
- package/dist/{chunk-yvk8w63g.js → chunk-c2mx5zg0.js} +1 -1
- package/dist/chunk-chspy9f8.js +23 -0
- package/dist/chunk-d6tbr25k.js +1 -0
- package/dist/chunk-dt9n4f4e.js +1 -0
- package/dist/{chunk-ms360ds6.js → chunk-e76gej4y.js} +2 -2
- package/dist/{chunk-bzp08nf6.js → chunk-e8pfbb6c.js} +1 -1
- package/dist/chunk-ermypm1x.js +2 -0
- package/dist/chunk-esp69w6w.js +1 -0
- package/dist/{chunk-z5mm9g1y.js → chunk-etf3e9kt.js} +1 -1
- package/dist/{chunk-x1w3fvhr.js → chunk-f2b9cyj5.js} +2 -2
- package/dist/chunk-g1y60ey9.js +1 -0
- package/dist/{chunk-be2csw9m.js → chunk-g799czsy.js} +1 -1
- package/dist/{chunk-dnt4c3gy.js → chunk-g9vdmvk2.js} +2 -2
- package/dist/chunk-gf5v8aff.js +1 -0
- package/dist/chunk-gpj7k3er.js +6 -0
- package/dist/{chunk-mkvqtawj.js → chunk-h05qhgrb.js} +2 -2
- package/dist/{chunk-2qyh6qhb.js → chunk-h74p51hg.js} +2 -2
- package/dist/{chunk-1tfjaazq.js → chunk-karq4wfd.js} +1 -1
- package/dist/{chunk-cz9mqkn2.js → chunk-ky9br0z8.js} +1 -1
- package/dist/chunk-m9kh7djg.js +6 -0
- package/dist/{chunk-gv24cgpb.js → chunk-mavranwn.js} +3 -3
- package/dist/{chunk-0xph7bhe.js → chunk-mthf5akx.js} +2 -2
- package/dist/{chunk-8xem2mzy.js → chunk-mzye1ah2.js} +1 -1
- package/dist/chunk-na4wzne8.js +1 -0
- package/dist/chunk-ntmkzrs8.js +1 -0
- package/dist/{chunk-961nemng.js → chunk-nxnmqk4s.js} +1 -1
- package/dist/{chunk-h123tjsg.js → chunk-p0gbxaqz.js} +2 -2
- package/dist/chunk-pj15kt5b.js +10 -0
- package/dist/chunk-pv1vwasz.js +1 -0
- package/dist/{chunk-r4bgsfj6.js → chunk-q0s3gcjm.js} +1 -1
- package/dist/{chunk-jy61b0v8.js → chunk-ramana2t.js} +2 -2
- package/dist/{chunk-ks67gd2j.js → chunk-rgjr7jsd.js} +1 -1
- package/dist/chunk-v5503t2t.js +25 -0
- package/dist/chunk-vda03kxj.js +1 -0
- package/dist/{chunk-4xhawy0e.js → chunk-vg3zwv4g.js} +1 -1
- package/dist/chunk-vp6d1fqp.js +3 -0
- package/dist/{chunk-nyk5q71k.js → chunk-w9z34f27.js} +1 -1
- package/dist/{chunk-5x3h9ak8.js → chunk-wa71vstt.js} +1 -1
- package/dist/{chunk-f4pn5tmr.js → chunk-wc9wsyrc.js} +1 -1
- package/dist/{chunk-0d440hhe.js → chunk-wxtj6gqb.js} +1 -1
- package/dist/{chunk-rmm7n9n3.js → chunk-wxypv01z.js} +2 -2
- package/dist/{chunk-77efqpdc.js → chunk-wzkh3e6a.js} +1 -1
- package/dist/{chunk-rcthrb7h.js → chunk-xg9fyvw0.js} +2 -2
- package/dist/{chunk-7zvwfz85.js → chunk-xt0ktytp.js} +2 -2
- package/dist/{chunk-xgz1yanb.js → chunk-y6jee9w7.js} +1 -1
- package/dist/{chunk-3ndwbb7h.js → chunk-ybc5myz7.js} +1 -1
- package/dist/{chunk-53h87fmt.js → chunk-z3hpstky.js} +1 -1
- package/dist/{chunk-555ffyze.js → chunk-zk9rf1d7.js} +2 -2
- package/dist/web/assets/ChatView-DpvPjAh7.js +63 -0
- package/dist/web/assets/{CodeBlockHighlighter-D0yM8QTf.js → CodeBlockHighlighter-Czp4VZIg.js} +1 -1
- package/dist/web/assets/{FilePreview-CaTCjV5i.js → FilePreview-BJWuYfyF.js} +15 -20
- package/dist/web/assets/{KanbanBoard-BY0SXCol.js → KanbanBoard-DrYzt5Kh.js} +4 -4
- package/dist/web/assets/{MarkdownRenderer-zKto-Pty.js → MarkdownRenderer-DxkR5r7t.js} +3 -3
- package/dist/web/assets/{ScrollArea-1qPJ8lcT.js → ScrollArea-D71pJjgW.js} +1 -1
- package/dist/web/assets/{SessionHistorySurface-Ce9xX62q.js → SessionHistorySurface-2y9bnndm.js} +2 -2
- package/dist/web/assets/{SettingsModal-BxKOMuIm.js → SettingsModal-BbaTL5Rk.js} +1 -1
- package/dist/web/assets/{Sidebar-CEF6lGps.js → Sidebar-COZltpL9.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-C-EY0nVG.js → TaskSwitcher-3giB7l1P.js} +2 -2
- package/dist/web/assets/{TerminalPanel-C3PVDyAr.js → TerminalPanel-gvTTiTgX.js} +2 -2
- package/dist/web/assets/{archive-D5Nuw__Q.js → archive-DndqAA2q.js} +1 -1
- package/dist/web/assets/{arrow-left-DaOpfgEz.js → arrow-left-XNYfpUAb.js} +1 -1
- package/dist/web/assets/{calendar-clock-DA_D4ppV.js → calendar-clock-BQOfNcCK.js} +1 -1
- package/dist/web/assets/{chevron-right-COQAoZf3.js → chevron-right-Cvq3LzHK.js} +1 -1
- package/dist/web/assets/chevrons-up-down-Dia1U9Sz.js +16 -0
- package/dist/web/assets/{clock-3-DJ-pSj3t.js → clock-3-CnxLS8cv.js} +1 -1
- package/dist/web/assets/{copy-5c0ESKoo.js → copy-CWCS3Lql.js} +1 -1
- package/dist/web/assets/{download-VkaTciEH.js → download-DXdsM18t.js} +1 -1
- package/dist/web/assets/{external-link-BypdqupZ.js → external-link-1IN2ZfaO.js} +1 -1
- package/dist/web/assets/{folder-B8znObPL.js → folder-Bpq602dI.js} +1 -1
- package/dist/web/assets/index-57UZsfTt.css +1 -0
- package/dist/web/assets/index-DEOQizD2.js +203 -0
- package/dist/web/assets/{pause-BWbHHYG6.js → pause-BYhoGDZq.js} +1 -1
- package/dist/web/assets/{pencil-BPyvvR59.js → pencil-pRZQVHFU.js} +1 -1
- package/dist/web/assets/{play-CLJgUH4S.js → play-DGZdCyPk.js} +1 -1
- package/dist/web/assets/{plus-D1VVvu-z.js → plus-CAQ3qlUJ.js} +1 -1
- package/dist/web/assets/session-events-C5_Q0kZV.js +29 -0
- package/dist/web/assets/{settings-CGCgC_NX.js → settings-BPfzj_Vf.js} +1 -1
- package/dist/web/assets/teamService-BScT9o9A.js +1 -0
- package/dist/web/assets/{terminal-pA96HZrI.js → terminal-CldJbdMr.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-00zazdct.js +0 -25
- package/dist/chunk-04yas0t8.js +0 -1
- package/dist/chunk-2242dshn.js +0 -2
- package/dist/chunk-2nxev7f2.js +0 -1
- package/dist/chunk-43a0n5rw.js +0 -1
- package/dist/chunk-679b7s58.js +0 -2
- package/dist/chunk-78wwep9f.js +0 -1
- package/dist/chunk-88jmtcv7.js +0 -171
- package/dist/chunk-ar3sdj0w.js +0 -3
- package/dist/chunk-avf9spct.js +0 -1
- package/dist/chunk-azv25dg2.js +0 -10
- package/dist/chunk-b8c1vj8c.js +0 -1
- package/dist/chunk-bbw6s542.js +0 -1
- package/dist/chunk-eetva9y8.js +0 -1
- package/dist/chunk-kjjpn49y.js +0 -1
- package/dist/chunk-kx61g7xw.js +0 -1
- package/dist/chunk-m30sbsnw.js +0 -1
- package/dist/chunk-n589jxsm.js +0 -1
- package/dist/chunk-n7pydthh.js +0 -6
- package/dist/chunk-nry7d26k.js +0 -2
- package/dist/chunk-p8y5kk56.js +0 -6
- package/dist/chunk-py92cy57.js +0 -14
- package/dist/chunk-rkjrft19.js +0 -5
- package/dist/chunk-sr9gqacp.js +0 -1
- package/dist/chunk-sxqydew5.js +0 -1
- package/dist/chunk-t52v91dy.js +0 -23
- package/dist/chunk-v7zt3pft.js +0 -171
- package/dist/web/assets/ChatView-hYd9mmJ6.js +0 -53
- package/dist/web/assets/chevrons-up-down-B_WSFixv.js +0 -11
- package/dist/web/assets/index-B4186fIT.css +0 -1
- package/dist/web/assets/index-DorkRCqS.js +0 -210
- package/dist/web/assets/session-events-C6fPz20c.js +0 -22
- package/dist/web/assets/teamService-DsYRmp6u.js +0 -1
package/dist/chunk-rkjrft19.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{$i as If,Ti as __,Ui as mf,Vi as qf,Wi as T_,Xi as Jf,Zi as Wf,bj as q,cj as Qf,ej as Df,fj as Kf,hj as s}from"./chunk-8xem2mzy.js";import{pj as l}from"./chunk-ar3sdj0w.js";import{tj as SE,vj as jf}from"./chunk-rcthrb7h.js";import{yj as aE}from"./chunk-0d440hhe.js";var D_={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},TE=(f)=>D_[f]||{};var H_=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function Vf(f){return typeof f==="string"&&H_.has(f)}function zT(f){if(!f.aborted)return;if(Vf(f.reason))return f.reason;return"user-cancel"}function $T(f){if(Vf(f))return!0;if(!(f instanceof Error))return!1;if(f.name==="AbortError")return!0;if(f instanceof DOMException&&f.name==="AbortError")return!0;if(f.message.includes("aborted"))return!0;return!1}function hE(...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,S]of h)P.removeEventListener("abort",S)};h.set(x,N)}for(let[x,N]of h)x.addEventListener("abort",N,{once:!0});return T.signal}function ff(f,E,_){let T=_?.throwOnAbort??!1;if(E?.aborted){if(T)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((h,x)=>{let 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 U_=l("Chat"),Y_={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function xE(f){if(typeof f==="string")return f;return f.filter((E)=>E.type==="text").map((E)=>E.text).join(`
|
|
2
|
-
`)}function b_(f){if(!f)return{};try{let E=JSON.parse(f);return E&&typeof E==="object"&&!Array.isArray(E)?E:{}}catch{return U_.warn("[PiAIChatService] Invalid historical tool arguments",{value:f}),{}}}function B_(f){let E=f.match(/^data:([^;,]+);base64,(.+)$/s);return E?{mimeType:E[1],data:E[2]}:void 0}async function c_(f,E){let _=B_(f);if(_)return{type:"image",..._};if(!/^https?:\/\//i.test(f))return{type:"text",text:`[Unsupported image source: ${f}]`};let T=await fetch(f,{signal:E});if(!T.ok)throw Error(`Failed to load image ${f}: HTTP ${T.status}`);return{type:"image",mimeType:T.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await T.arrayBuffer()).toString("base64")}}async function tE(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 PE(f,E,_,T,h){let x=f.filter((A)=>A.role==="system").map((A)=>xE(A.content)).filter(Boolean).join(`
|
|
3
|
-
|
|
4
|
-
`),N=[],P=E.input.includes("image");for(let A of f){if(A.role==="system")continue;if(A.role==="user"){let t=typeof A.content==="string"?A.content:await tE(A.content,P,T);N.push({role:"user",content:t,timestamp:Date.now()});continue}if(A.role==="assistant"){let t=[];if(A.reasoningContent?.trim())t.push({type:"thinking",thinking:A.reasoningContent});let M=xE(A.content);if(M)t.push({type:"text",text:M});for(let I of A.tool_calls??[]){if(!("function"in I))continue;t.push({type:"toolCall",id:I.id,name:I.function.name,arguments:b_(I.function.arguments)})}N.push({role:"assistant",content:t,api:E.api,provider:E.provider,model:E.id,usage:Y_,stopReason:A.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}N.push({role:"toolResult",toolCallId:A.tool_call_id??"",toolName:A.name??"unknown",content:typeof A.content==="string"?[{type:"text",text:A.content}]:await tE(A.content,P,T),isError:!1,timestamp:Date.now()})}let S=_?.filter((A)=>!h||A.name===h).map((A)=>({name:A.name,description:A.description,parameters:A.parameters,constrainedSampling:A.constrainedSampling})).sort((A,t)=>A.name<t.name?-1:A.name>t.name?1:0);return{...x?{systemPrompt:x}:{},messages:N,...S?.length?{tools:S}:{}}}function ME(f){let E=[];for(let _=0;_<f.length;_++){let T=f[_];if(T.role==="tool")continue;let h=T.role==="assistant"&&T.tool_calls?.length?T.tool_calls:void 0;if(!h){E.push(T);continue}let x=[],N=_+1;while(N<f.length&&f[N].role==="tool")x.push(f[N++]);let P=new Set(h.map((t)=>t.id)),S=x.filter((t)=>t.tool_call_id&&P.has(t.tool_call_id)),A=new Set(S.map((t)=>t.tool_call_id));if(P.size===h.length&&S.length===P.size&&A.size===P.size)E.push(T,...S);_=N-1}return E}function AE(f){return f.some((E)=>E.role==="assistant"&&Boolean(E.tool_calls?.length)&&!E.reasoningContent?.trim())}function NE(f,E){return{...f,...E.baseUrl?{baseUrl:SE(f.api,E.baseUrl)}:{},...E.maxOutputTokens?{maxTokens:E.maxOutputTokens}:{}}}function Xf(f){let E=f.modelCatalog??jf();return{models:E.models,model:NE(E.getModel(f.provider,f.model),f)}}function uE(f,E){let _=f.modelCatalog??jf();return NE(_.getModel(E.provider,E.model),f)}import{createHash as O_}from"node:crypto";var V_=32,j_=1000,X_=512,z_=2000,J_=0.1,W_=0.05,$_=0.9,k_=300000,L_=3600000;class zf{sessions=new Map;observe(f){if(f.retention==="none"){this.sessions.delete(f.sessionId);return}let E=f.now??Date.now(),_=G_(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<j_)return;let h=T.cacheReadTokens-_.cacheReadTokens,x=Math.min(z_,Math.max(X_,T.cacheReadTokens*J_));if(h<x||_.cacheReadTokens>=T.cacheReadTokens*(1-W_))return;let N=_.modelIdentity!==T.modelIdentity,P=_.systemHash!==T.systemHash,S=_.toolsHash!==T.toolsHash,A=_.policyHash!==T.policyHash;if(!(N||P||S||A)&&_.promptTokens<T.promptTokens*$_)return;let M=Math.max(0,E-T.recordedAt),I=T.retention==="long"?L_:k_,Y=N?"model_changed":P?"system_prompt_changed":S?"tools_changed":A?"request_policy_changed":M>=I?"ttl_expired":"server_side",$=Z_(T,_);return{reason:Y,previousCacheReadTokens:T.cacheReadTokens,cacheReadTokens:_.cacheReadTokens,cacheWriteTokens:Math.max(0,f.usage.cacheCreationInputTokens??0),tokenDrop:h,elapsedMs:M,callNumber:_.callCount,systemPromptChanged:P,systemCharDelta:_.systemChars-T.systemChars,toolsChanged:S,addedToolCount:$.added,removedToolCount:$.removed,changedToolCount:$.changed,modelChanged:N,requestPolicyChanged:A}}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>V_){let _=this.sessions.keys().next().value;if(_===void 0)break;this.sessions.delete(_)}}}function G_(f,E){let _=[...f.tools??f.context.tools??[]].map((T)=>({identityHash:Ef(T.name),contractHash:Ef(_f(T))})).sort((T,h)=>T.identityHash<h.identityHash?-1:T.identityHash>h.identityHash?1:0);return{modelIdentity:f.modelIdentity,systemHash:Ef(f.context.systemPrompt??""),systemChars:f.context.systemPrompt?.length??0,toolsHash:Ef(_f(_)),toolFingerprints:_,policyHash:Ef(_f(f.policy)),contextEpoch:f.contextEpoch??"",retention:f.retention,promptTokens:Number.isFinite(f.usage.promptTokens)?Math.max(0,f.usage.promptTokens):0,cacheReadTokens:Math.max(0,f.usage.cacheReadInputTokens??0),recordedAt:E,callCount:1}}function Z_(f,E){let _=new Map(f.toolFingerprints.map((h)=>[h.identityHash,h.contractHash])),T=new Map(E.toolFingerprints.map((h)=>[h.identityHash,h.contractHash]));return{added:[...T.keys()].filter((h)=>!_.has(h)).length,removed:[..._.keys()].filter((h)=>!T.has(h)).length,changed:[...T].filter(([h,x])=>_.has(h)&&_.get(h)!==x).length}}function _f(f){if(f===null||typeof f!=="object")return JSON.stringify(f)??"undefined";if(Array.isArray(f))return`[${f.map(_f).join(",")}]`;let E=f;return`{${Object.keys(E).sort().map((_)=>`${JSON.stringify(_)}:${_f(E[_])}`).join(",")}}`}function Ef(f){return O_("sha256").update(f).digest("hex")}import{randomBytes as F_}from"node:crypto";import{createHmac as Q_}from"node:crypto";function K_(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 C_(f){if(!f)return[];return Object.entries(f).map(([E,_])=>[E.trim().toLowerCase(),_.trim()]).sort(([E],[_])=>E.localeCompare(_))}function Sf(f,E,_){let T=JSON.stringify([f.provider.trim(),String(f.api).trim(),K_(f.baseUrl),f.model.trim(),f.serviceTier?.trim()??"",f.apiVersion?.trim()??"",f.apiKey??"",C_(f.customHeaders),_]);return Q_("sha256",Buffer.from(E)).update(T).digest("hex")}var o_=60000,s_=4,v_=0.8;var uf=300000,$f=600000;var IE=128,DE=256,w_=1800000,Nf=50;class hf extends Error{circuit;code="PROVIDER_CIRCUIT_OPEN";constructor(f){super(`Provider circuit open; retry after ${f.retryAfterMs??0}ms`);this.circuit=f;this.name="ProviderCircuitOpenError"}}function kf(f){return f instanceof hf||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_CIRCUIT_OPEN"}function a(f,E){return f!==void 0&&Number.isSafeInteger(f)&&f>0?f:E}function p_(f,E){return f!==void 0&&Number.isFinite(f)&&f>0&&f<=1?f:E}function m_(f,E){return Sf(f,E,{providerCircuitOpenDurationMs:f.openDurationMs})}function Tf(f){let E=0;for(let _ of f)if(_.failure)E++;return E}function HE(f){return f!==void 0&&Number.isInteger(f)&&f>=100&&f<=599?f:void 0}function UE(f){if(f===void 0||!Number.isFinite(f)||f<0)return;return Math.min(Math.ceil(f),Wf)}class bE{#x=new Map;#t=new WeakMap;#f;#_;#h;#T;constructor(f={}){this.#f=f.processSecret?new Uint8Array(f.processSecret):F_(32),this.#_=f.now??(()=>performance.now()),this.#h=f.wallNow??f.now??Date.now,this.#T={maxEntries:Math.min(a(f.maxEntries,IE),IE),maxWindowEntries:Math.min(a(f.maxWindowEntries,DE),DE),windowMs:a(f.windowMs,o_),minSamples:a(f.minSamples,s_),errorRateThreshold:p_(f.errorRateThreshold,v_),idleTtlMs:a(f.idleTtlMs,w_)}}get size(){return this.#x.size}get(f){if(f.openDurationMs===0)return this.#P();let E=this.#_();this.#b(E);let _=m_(f,this.#f),T=this.#x.get(_);if(T)return T.lastTouchedAt=E,this.#E(T,f.probeLeaseMs);if(this.#x.size>=this.#T.maxEntries)this.#D();if(this.#x.size>=this.#T.maxEntries)return this.#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(uf,Math.min(a(E,uf),$f));return{preflight:()=>_.#M(f),check:()=>_.#B(f,T),recordSuccess:(h)=>_.#R(h,"success"),recordFailure:(h,x)=>_.#R(h,"failure",x),recordNeutral:(h)=>_.#R(h,"neutral"),abandon:(h)=>_.#N(h),snapshot:()=>_.#j(f)}}#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.#S(E),recordFailure:(E)=>f.#S(E),recordNeutral:(E)=>f.#S(E),abandon:(E)=>f.#N(E),snapshot:()=>({state:"closed",sampleCount:0,failureCount:0,noop:!0,detached:!1})}}#S(f){let E=this.#t.get(f);if(E?.kind==="noop")E.settled=!0;return}#M(f){let E=this.#_();if(f.detached)return{eligible:!0};if(f.lastTouchedAt=E,this.#u(f,E),f.state==="closed")return{eligible:!0};if(f.state==="open"){let T=f.nextProbeAt??E;return E<T?this.#U(f,T-E):{eligible:!0}}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&E>=f.probeLeaseExpiresAt)return{eligible:!0};let _=Math.max(1,(f.probeLeaseExpiresAt??E+Nf)-E);return this.#U(f,Math.min(Nf,_))}#U(f,E){let{allowed:_,...T}=this.#A(f,E);return{eligible:!1,...T}}#B(f,E){let _=this.#_();if(f.detached)return this.#P().check();if(f.lastTouchedAt=_,this.#u(f,_),f.state==="closed")return this.#Y(f,"regular");if(f.state==="open"){let h=f.nextProbeAt??_;if(_<h)return this.#A(f,h-_);f.state="half_open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&_>=f.probeLeaseExpiresAt)return this.#c(f,_,E);let T=Math.max(1,(f.probeLeaseExpiresAt??_+Nf)-_);return this.#A(f,Math.min(Nf,T))}#Y(f,E,_){let T=Object.freeze({kind:E});return this.#t.set(T,{entry:f,generation:f.generation,attemptId:f.nextAttemptId++,kind:E,..._!==void 0?{probeLeaseId:_}:{},settled:!1}),{allowed:!0,probe:E==="probe",token:T}}#c(f,E,_){let T=f.nextProbeLeaseId++;f.probeLeaseId=T,f.probeLeaseExpiresAt=E+_,f.lastTouchedAt=E;let h=this.#Y(f,"probe",T),x=f.lastFailure??{reason:"server_error"};return{...h,reason:x.reason,...x.statusCode!==void 0?{statusCode:x.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:Tf(f.samples)}}#A(f,E){let _=f.lastFailure??{reason:"server_error"};return{allowed:!1,state:f.state==="open"?"open":"half_open",reason:_.reason,..._.statusCode!==void 0?{statusCode:_.statusCode}:{},retryAfterMs:Math.max(0,Math.ceil(E)),nextProbeAt:this.#h()+Math.max(0,Math.ceil(E)),openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:Tf(f.samples)}}#R(f,E,_){let T=this.#t.get(f);if(!T||T.settled)return;if(T.settled=!0,T.kind==="noop"||!T.entry)return;let h=T.entry;if(h.detached||T.generation!==h.generation||T.kind==="regular"&&h.state!=="closed"||T.kind==="probe"&&(h.state!=="half_open"||T.probeLeaseId!==h.probeLeaseId))return;let x=this.#_();if(h.lastTouchedAt=x,T.kind==="probe"){if(E==="failure"&&_)return this.#I(h,_,x,"reopened");return this.#O(h)}if(E==="neutral")return;if(this.#V(h,E==="failure",x),E!=="failure"||!_)return;let N=Tf(h.samples),P=h.samples.length===0?0:N/h.samples.length;if(h.samples.length>=this.#T.minSamples&&P>=this.#T.errorRateThreshold)return this.#I(h,_,x,"opened");return}#I(f,E,_,T){let h={reason:E.reason,...HE(E.statusCode)!==void 0?{statusCode:HE(E.statusCode)}:{},...UE(E.retryAfterMs)!==void 0?{retryAfterMs:UE(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:Tf(f.samples)}}#O(f){let E=f.lastFailure??{reason:"server_error"};return f.state="closed",f.generation++,f.samples=[],f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.nextProbeAt=void 0,f.effectiveOpenDurationMs=f.configuredOpenDurationMs,{phase:"closed",reason:E.reason,...E.statusCode!==void 0?{statusCode:E.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:0,failureCount:0}}#N(f){let E=this.#t.get(f);if(!E||E.settled)return!1;if(E.settled=!0,E.kind==="noop")return!0;let _=E.entry;if(!_||_.detached||E.kind!=="probe"||E.generation!==_.generation||E.probeLeaseId!==_.probeLeaseId)return!1;return _.probeLeaseId=void 0,_.probeLeaseExpiresAt=void 0,_.lastTouchedAt=this.#_(),!0}#V(f,E,_){if(this.#u(f,_),f.samples.length>=this.#T.maxWindowEntries)f.samples.shift();f.samples.push({at:_,failure:E})}#u(f,E){let _=E-this.#T.windowMs,T=0;while(T<f.samples.length&&f.samples[T].at<_)T++;if(T>0)f.samples.splice(0,T)}#j(f){if(!f.detached)this.#u(f,this.#_());return{state:f.state,sampleCount:f.samples.length,failureCount:Tf(f.samples),...f.nextProbeAt!==void 0?{nextProbeAt:f.nextProbeAt}:{},noop:!1,detached:f.detached}}#b(f){for(let[E,_]of this.#x)if(_.state==="closed"&&f-_.lastTouchedAt>this.#T.idleTtlMs)this.#H(E,_)}#D(){let f;for(let E of this.#x.values())if(E.state==="closed"&&(!f||E.lastTouchedAt<f.lastTouchedAt))f=E;if(f)this.#H(f.key,f)}#H(f,E){E.detached=!0,this.#x.delete(f)}}var YE;function BE(){return YE??=new bE,YE}import{randomBytes as q_}from"node:crypto";var g_=16,cE=128,OE=32,l_=3,VE=16,jE=96,XE=24,zE=12,JE=16,WE=4,$E=4,kE=67108864,LE=33554432,a_=12,y_=2,GE=2,ZE=1,oE=15000,QE=30000;function Lf(){return{foreground:0,background:0,internal:0}}function Gf(){return{inFlight:Lf(),queued:Lf(),pendingBytes:Lf()}}function U(f){return f.foreground+f.background+f.internal}function W(f){return f.background+f.internal}function KE(f){return f.inFlight.foreground===0&&f.inFlight.background===0&&f.inFlight.internal===0&&f.queued.foreground===0&&f.queued.background===0&&f.queued.internal===0&&f.pendingBytes.foreground===0&&f.pendingBytes.background===0&&f.pendingBytes.internal===0}class xf extends Error{reason;scope;requestClass;resource;inFlight;limit;queued;maxWaitMs;code="PROVIDER_ADMISSION_BUSY";retryable;constructor(f,E,_,T,h,x,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 tf(f){return f instanceof xf||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_ADMISSION_BUSY"}function z(f,E,_){if(f===void 0||!Number.isSafeInteger(f)||f<=0)return E;return Math.min(f,_)}function e_(f){let E=z(f.globalMaxInFlight,g_,Number.MAX_SAFE_INTEGER),_=z(f.globalMaxPending,cE,cE),T=z(f.domainMaxPending,OE,OE),h=Math.min(z(f.ownerMaxInFlight,l_,Number.MAX_SAFE_INTEGER),E),x=Math.min(z(f.ownerMaxPending,VE,VE),_),N=Math.min(z(f.nonForegroundGlobalMaxPending,Math.min(jE,Math.max(1,Math.floor(_*3/4))),jE),_),P=Math.min(z(f.nonForegroundDomainMaxPending,Math.min(XE,Math.max(1,Math.floor(T*3/4))),XE),T),S=Math.min(z(f.nonForegroundOwnerMaxPending,Math.min(zE,Math.max(1,Math.floor(x*3/4))),zE),x),A=Math.min(z(f.internalGlobalMaxPending,Math.min(JE,Math.max(1,Math.floor(_/8))),JE),N),t=Math.min(z(f.internalDomainMaxPending,Math.min(WE,Math.max(1,Math.floor(T/8))),WE),P),M=Math.min(z(f.internalOwnerMaxPending,Math.min($E,Math.max(1,Math.floor(x/4))),$E),S),I=z(f.globalMaxPendingBytes,s,s),Y=Math.min(z(f.domainMaxPendingBytes,kE,kE),I),$=Math.min(z(f.ownerMaxPendingBytes,LE,LE),I),Q=Math.min(z(f.nonForegroundGlobalMaxInFlight,Math.min(a_,E),E),E),K=Math.min(z(f.nonForegroundOwnerMaxInFlight,Math.min(y_,h),h),h),o=Math.min(z(f.internalGlobalMaxInFlight,Math.min(GE,E),GE),E),Uf=z(f.internalDomainMaxInFlight,ZE,ZE),Rf=z(f.agingMs,QE,QE);return{globalMaxInFlight:E,globalMaxPending:_,domainMaxPending:T,ownerMaxInFlight:h,ownerMaxPending:x,nonForegroundGlobalMaxPending:N,nonForegroundDomainMaxPending:P,nonForegroundOwnerMaxPending:S,internalGlobalMaxPending:A,internalDomainMaxPending:t,internalOwnerMaxPending:M,globalMaxPendingBytes:I,domainMaxPendingBytes:Y,ownerMaxPendingBytes:$,nonForegroundGlobalMaxInFlight:Q,nonForegroundOwnerMaxInFlight:K,internalGlobalMaxInFlight:o,internalDomainMaxInFlight:Uf,agingMs:Rf,classLimitsEnabled:f.classLimitsEnabled!==!1}}function CE(f,E){if(!f.trim())throw Error(`${E} must not be blank`)}function d_(f){if(CE(f.sessionId,"sessionId"),CE(f.ownerId,"ownerId"),!Number.isSafeInteger(f.scope.maxConcurrent)||f.scope.maxConcurrent<If||f.scope.maxConcurrent>q)throw Error(`maxConcurrent must be between ${If} and ${q}`);if(!Number.isSafeInteger(f.scope.maxPendingBytes)||f.scope.maxPendingBytes<=0||f.scope.maxPendingBytes>s)throw Error(`maxPendingBytes must be between 1 and ${s}`);if(!Number.isSafeInteger(f.pendingBytes)||f.pendingBytes<=0||f.pendingBytes>s+1)throw Error(`pendingBytes must be between 1 and ${s+1}`);if(!Number.isSafeInteger(f.maxWaitMs)||f.maxWaitMs<0||f.maxWaitMs>Df)throw Error(`maxWaitMs must be 0-${Df}`)}function Zf(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 n_(f,E){return Sf(f,E,{providerRequestConcurrency:f.maxConcurrent,providerRequestPendingBytes:f.maxPendingBytes})}class sE{#x;#t;#f;#_=[];#h=new Map;#T=new Map;#E=Gf();#P=1;#S=0;#M=!1;constructor(f={}){this.#x=f.processSecret?new Uint8Array(f.processSecret):q_(32),this.#t=f.now??(()=>performance.now()),this.#f=e_(f)}admit(f){if(d_(f),this.#M)throw this.#X("closed",f,{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight},this.#_.length);if(f.signal?.aborted)throw Zf(f.signal);let E=n_(f.scope,this.#x),_=this.#h.get(E),T=this.#T.get(f.ownerId),h=_??this.#Y(f.scope.maxConcurrent),x=T??this.#c();if(this.#_.length===0&&this.#A(h,x,f.requestClass)){if(!_)this.#h.set(E,h);if(!T)this.#T.set(f.ownerId,x),this.#P++;let I=this.#I(E,f.ownerId,f.requestClass),Y=this.#k(f,0);return{ready:Promise.resolve(I),getSnapshot:()=>({...Y}),cancel:()=>{Y={...Y}}}}let N=this.#U(f,h,x);if(N)throw this.#X("queue_full",f,N,this.#_.length);let P=this.#R(h,x,f.requestClass);if(f.maxWaitMs===0)throw this.#X("wait_timeout",f,P,this.#_.length);if(!_)this.#h.set(E,h);if(!T)this.#T.set(f.ownerId,x),this.#P++;let S,A,t=new Promise((I,Y)=>{S=I,A=Y});t.catch(()=>{return});let M={domainKey:E,sessionId:f.sessionId,ownerId:f.ownerId,requestClass:f.requestClass,maxWaitMs:f.maxWaitMs,pendingBytes:f.pendingBytes,enqueuedAt:this.#t(),signal:f.signal,resolve:S,reject:A,settled:!1,admitted:!1};if(f.signal)M.abortListener=()=>this.#b(M,Zf(f.signal)),f.signal.addEventListener("abort",M.abortListener,{once:!0});return M.timer=setTimeout(()=>this.#j(M),f.maxWaitMs),M.timer.unref?.(),this.#_.push(M),this.#B(h,x,M),this.#N(),{ready:t,getSnapshot:()=>this.#$(M),cancel:(I)=>this.#b(M,Zf(f.signal,I))}}close(){if(this.#M)return;this.#M=!0;for(let f of[...this.#_]){let E=this.#h.get(f.domainKey),_=this.#T.get(f.ownerId),T=E&&_?this.#R(E,_,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};this.#D(f,new xf("closed",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}}getStats(){return{inFlight:U(this.#E.inFlight),queued:this.#_.length,pendingBytes:U(this.#E.pendingBytes),nonForegroundInFlight:W(this.#E.inFlight),internalInFlight:this.#E.inFlight.internal,nonForegroundQueued:W(this.#E.queued),internalQueued:this.#E.queued.internal,nonForegroundPendingBytes:W(this.#E.pendingBytes),internalPendingBytes:this.#E.pendingBytes.internal,domainCount:this.#h.size,ownerCount:this.#T.size,closed:this.#M}}#U(f,E,_){let T=(t,M,I)=>M>=I?{scope:t,resource:"pending_count",inFlight:M,limit:I}:void 0;if(this.#f.classLimitsEnabled&&f.requestClass==="internal"){let t=T("class",this.#E.queued.internal,this.#f.internalGlobalMaxPending)??T("class",_.counters.queued.internal,this.#f.internalOwnerMaxPending)??T("class",E.counters.queued.internal,this.#f.internalDomainMaxPending);if(t)return t}if(this.#f.classLimitsEnabled&&f.requestClass!=="foreground"){let t=T("class",W(this.#E.queued),this.#f.nonForegroundGlobalMaxPending)??T("class",W(_.counters.queued),this.#f.nonForegroundOwnerMaxPending)??T("class",W(E.counters.queued),this.#f.nonForegroundDomainMaxPending);if(t)return t}let h=T("global",this.#_.length,this.#f.globalMaxPending)??T("owner",U(_.counters.queued),this.#f.ownerMaxPending)??T("domain",U(E.counters.queued),this.#f.domainMaxPending);if(h)return h;let x=Math.min(f.scope.maxPendingBytes,this.#f.globalMaxPendingBytes),N=Math.min(x,this.#f.domainMaxPendingBytes),P=Math.min(x,this.#f.ownerMaxPendingBytes),S=(t,M)=>f.pendingBytes>M-t,A=(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)),M=Math.max(1,Math.floor(N/4)),I=Math.max(1,Math.floor(P/4));if(S(this.#E.pendingBytes.internal,t)||S(_.counters.pendingBytes.internal,I)||S(E.counters.pendingBytes.internal,M))return A("class")}if(f.requestClass!=="foreground"){let t=Math.max(1,Math.floor(x*3/4)),M=Math.max(1,Math.floor(N*3/4)),I=Math.max(1,Math.floor(P/2));if(S(W(this.#E.pendingBytes),t)||S(W(_.counters.pendingBytes),I)||S(W(E.counters.pendingBytes),M))return A("class")}if(S(U(this.#E.pendingBytes),x))return A("global");if(S(U(_.counters.pendingBytes),P))return A("owner");if(S(U(E.counters.pendingBytes),N))return A("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:Gf()}}#c(){return{order:this.#P,counters:Gf()}}#A(f,E,_){if(U(this.#E.inFlight)>=this.#f.globalMaxInFlight)return!1;if(U(f.counters.inFlight)>=f.maxConcurrent)return!1;if(U(E.counters.inFlight)>=this.#f.ownerMaxInFlight)return!1;if(_==="foreground"||!this.#f.classLimitsEnabled)return!0;if(W(this.#E.inFlight)>=this.#f.nonForegroundGlobalMaxInFlight)return!1;if(W(E.counters.inFlight)>=this.#f.nonForegroundOwnerMaxInFlight)return!1;let T=Math.max(1,f.maxConcurrent-1);if(W(f.counters.inFlight)>=T)return!1;if(_!=="internal")return!0;return this.#E.inFlight.internal<this.#f.internalGlobalMaxInFlight&&f.counters.inFlight.internal<this.#f.internalDomainMaxInFlight}#R(f,E,_){if(U(E.counters.inFlight)>=this.#f.ownerMaxInFlight)return{scope:"owner",resource:"stream",inFlight:U(E.counters.inFlight),limit:this.#f.ownerMaxInFlight};if(this.#f.classLimitsEnabled&&_!=="foreground"&&W(E.counters.inFlight)>=this.#f.nonForegroundOwnerMaxInFlight)return{scope:"class",resource:"stream",inFlight:W(E.counters.inFlight),limit:this.#f.nonForegroundOwnerMaxInFlight};if(U(f.counters.inFlight)>=f.maxConcurrent)return{scope:"domain",resource:"stream",inFlight:U(f.counters.inFlight),limit:f.maxConcurrent};if(this.#f.classLimitsEnabled&&_!=="foreground"){let T=Math.max(1,f.maxConcurrent-1);if(W(f.counters.inFlight)>=T)return{scope:"class",resource:"stream",inFlight:W(f.counters.inFlight),limit:T}}if(this.#f.classLimitsEnabled&&_==="internal"&&f.counters.inFlight.internal>=this.#f.internalDomainMaxInFlight)return{scope:"class",resource:"stream",inFlight:f.counters.inFlight.internal,limit:this.#f.internalDomainMaxInFlight};if(U(this.#E.inFlight)>=this.#f.globalMaxInFlight)return{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};if(this.#f.classLimitsEnabled&&_!=="foreground"&&W(this.#E.inFlight)>=this.#f.nonForegroundGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:W(this.#E.inFlight),limit:this.#f.nonForegroundGlobalMaxInFlight};if(this.#f.classLimitsEnabled&&_==="internal"&&this.#E.inFlight.internal>=this.#f.internalGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#E.inFlight.internal,limit:this.#f.internalGlobalMaxInFlight};return{scope:"domain",resource:"stream",inFlight:U(f.counters.inFlight),limit:f.maxConcurrent}}#I(f,E,_){let T=this.#h.get(f),h=this.#T.get(E);if(!T||!h)throw Error("Provider admission accounting state is unavailable");this.#E.inFlight[_]++,T.counters.inFlight[_]++,h.counters.inFlight[_]++;let x=!1;return{release:()=>{if(x)return;x=!0,this.#O(f,E,_)}}}#O(f,E,_){let T=this.#h.get(f),h=this.#T.get(E);if(this.#E.inFlight[_]--,T)T.counters.inFlight[_]--;if(h)h.counters.inFlight[_]--;this.#z(f,E),this.#N()}#N(){if(this.#M)return;while(this.#_.length>0){let f=this.#t(),E=new Map;for(let[P,S]of this.#_.entries()){let A=this.#h.get(S.domainKey),t=this.#T.get(S.ownerId);if(A===void 0||t===void 0||!this.#A(A,t,S.requestClass))continue;let M=this.#V(S,f),I=E.get(S.ownerId);if(!I||M<I.rank||M===I.rank&&P<I.index)E.set(S.ownerId,{pending:S,rank:M,index:P})}let _=[...E.values()].filter(({pending:P})=>{let S=this.#h.get(P.domainKey),A=this.#T.get(P.ownerId);return S!==void 0&&A!==void 0&&this.#A(S,A,P.requestClass)}).map(({pending:P,rank:S})=>({pending:P,rank:S,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.#S).sort((P,S)=>P.order-S.order)[0]??h.sort((P,S)=>P.order-S.order)[0];this.#u(N.pending,N.order)}}#V(f,E){let _=f.requestClass==="foreground"?0:f.requestClass==="background"?1:2,T=Math.floor(Math.max(0,E-f.enqueuedAt)/this.#f.agingMs);return Math.max(0,_-T)}#u(f,E){if(!this.#H(f,!1))return;f.settled=!0,f.admitted=!0,this.#S=E;let _=this.#I(f.domainKey,f.ownerId,f.requestClass);f.permit=_,f.resolve(_)}#j(f){let E=this.#h.get(f.domainKey),_=this.#T.get(f.ownerId),T=E&&_?this.#R(E,_,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};this.#D(f,new xf("wait_timeout",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}#b(f,E){this.#D(f,E)}#D(f,E){if(!this.#H(f))return;f.settled=!0,f.reject(E),this.#N()}#H(f,E=!0){if(f.settled||f.admitted)return!1;let _=this.#_.indexOf(f);if(_<0)return!1;this.#_.splice(_,1);let T=this.#h.get(f.domainKey),h=this.#T.get(f.ownerId);if(T&&h)this.#J(T,h,f);if(this.#W(f),E)this.#z(f.domainKey,f.ownerId);return!0}#J(f,E,_){let{requestClass:T,pendingBytes:h}=_;this.#E.queued[T]--,f.counters.queued[T]--,E.counters.queued[T]--,this.#E.pendingBytes[T]-=h,f.counters.pendingBytes[T]-=h,E.counters.pendingBytes[T]-=h}#W(f){if(f.timer)clearTimeout(f.timer);if(f.timer=void 0,f.signal&&f.abortListener)f.signal.removeEventListener("abort",f.abortListener);f.abortListener=void 0,f.signal=void 0}#z(f,E){let _=this.#h.get(f);if(_&&KE(_.counters))this.#h.delete(f);let T=this.#T.get(E);if(T&&KE(T.counters))this.#T.delete(E)}#$(f){let E=Math.max(0,Math.floor(this.#t()-f.enqueuedAt));if(f.admitted)return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight,waitMs:E,maxWaitMs:f.maxWaitMs};let _=this.#h.get(f.domainKey),T=this.#T.get(f.ownerId),h=_&&T?this.#R(_,T,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};return{state:"queued",requestClass:f.requestClass,resource:h.resource,scope:h.scope,reason:"capacity",queuePosition:this.#L(f,h.scope),queueDepth:this.#_.length,inFlight:h.inFlight,limit:h.limit,waitMs:E,maxWaitMs:f.maxWaitMs}}#k(f,E){return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight,waitMs:E,maxWaitMs:f.maxWaitMs}}#L(f,E){let _=this.#_.filter((T)=>{switch(E){case"owner":return T.ownerId===f.ownerId;case"domain":return T.domainKey===f.domainKey;case"class":return T.requestClass===f.requestClass;case"global":return!0}});return Math.max(1,_.indexOf(f)+1)}#X(f,E,_,T){return new xf(f,_.scope,E.requestClass,_.resource,_.inFlight,_.limit,T,E.maxWaitMs)}}var FE;function vE(f={}){return FE??=new sE(f),FE}function wE(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,S=(t)=>{if(P||t<=0)return;if(!Number.isSafeInteger(t)||t>_-x){x=_+1,P=!0;return}x+=t},A=(t)=>{if(P)return;if(N+=1,N>T){S(_+1);return}if(t===null){S(4);return}switch(typeof t){case"string":S(Buffer.byteLength(t,"utf8"));return;case"number":case"bigint":S(8);return;case"boolean":S(4);return;case"undefined":case"function":case"symbol":return;case"object":break}if(h.has(t))return;if(h.add(t),ArrayBuffer.isView(t)){S(32+t.byteLength);return}if(t instanceof ArrayBuffer){S(32+t.byteLength);return}if(t instanceof Date){S(40);return}if(t instanceof RegExp){S(32+Buffer.byteLength(t.source,"utf8"));return}if(t instanceof Map){S(32);for(let[M,I]of t)if(A(M),A(I),P)return;return}if(t instanceof Set){S(32);for(let M of t)if(A(M),P)return;return}if(t instanceof WeakMap||t instanceof WeakSet){S(32);return}if(Array.isArray(t)){S(16);for(let M of t)if(A(M),P)return;return}S(32);for(let M of Reflect.ownKeys(t)){if(typeof M!=="string")continue;let I=Object.getOwnPropertyDescriptor(t,M);if(!I?.enumerable||!("value"in I))continue;if(S(8+Buffer.byteLength(M,"utf8")),A(I.value),P)return}};return A(f),x}function pE(f){return wE([f.messages,f.context,f.tools,f.requestOptions],{maxBytes:s})}var mE=new WeakSet;class y extends Error{budgetMs;elapsedMs;code="PROVIDER_RECOVERY_BUDGET_EXCEEDED";constructor(f,E){super(`Provider recovery budget exhausted after ${f}ms`);this.budgetMs=f;this.elapsedMs=E;this.name="ProviderRecoveryBudgetExceededError"}}class Cf 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 r_=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],i_=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],fT=["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 qE(f){return(f instanceof Error?f.message:String(f)).toLowerCase()}function ET(f){let E=qE(f);return i_.some((_)=>E.includes(_))}function Ff(f){if(f!==null&&typeof f==="object")mE.add(f)}function Ph(f){return f!==null&&typeof f==="object"&&mE.has(f)}function _T(f){return f!==null&&typeof f==="object"&&"code"in f?f.code:void 0}function TT(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 hT(f){let E=f.match(/^(?:error:\s*)?(\d{3})\b/),_=f.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),T=Number(E?.[1]??_?.[1]);return Number.isInteger(T)?T:void 0}function e(f,E){let _=qE(f),T=_T(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(r_.some((x)=>_.includes(x))||ET(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??TT(f)??hT(_);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(fT.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 of(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 gE(f,E,_={}){let T=_.now??Date.now(),h=_.maxDelayMs??60000,x=of(E,T);if(x!==void 0)return Math.min(Math.ceil(x),h);let N=Math.max(0,f-1),P=_.maxExponentialDelayMs??8000,S=Math.min(500*2**N,P),A=Math.max(0,Math.min(1,_.random??Math.random())),t=S*(0.75+A*0.25);return Math.min(Math.round(t),h)}function yE(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 xT(f){if(!f.reasoningEnabled)return;return f.reasoningEffort??f.reasoningLevel??"high"}function sf(f,E,_){if(!f.enablePromptCaching)return"none";if(_&&E.api==="openai-completions"&&!E.baseUrl.includes("api.openai.com"))return"long";return"short"}function tT(f){switch(f){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function RT(f,E,_,T){let h=T?void 0:xT(_);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:tT(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 PT(f,E,_){if(!_)return;switch(E){case"anthropic-messages":case"bedrock-converse-stream":f.toolChoice={type:"tool",name:_};break;case"openai-completions":case"mistral-conversations":case"pi-messages":f.toolChoice={type:"function",function:{name:_}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":f.toolChoice={type:"function",name:_};break;case"google-generative-ai":case"google-vertex":f.toolChoice="any";break}}function MT(f,E,_){let T=_.serviceTier;if(!T)return;if(E.api==="openai-responses"||E.api==="openai-codex-responses"||E.api==="azure-openai-responses"){f.serviceTier=T;return}if(E.api!=="openai-completions"&&!(E.api==="anthropic-messages"&&T==="fast"))return;yE(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 AT(f,E,_){let T=_.responseVerbosity;if(!T)return;if(aE(E,T),E.api==="openai-codex-responses"){f.textVerbosity=T;return}yE(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 eE(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:sf(f,E,T?.providerSessionId),sessionId:T?.providerSessionId};if(RT(x,E,f,h),PT(x,E.api,T?.toolChoice?.toolName),MT(x,E,f),AT(x,E,f),E.api==="azure-openai-responses")x.azureBaseUrl=f.baseUrl,x.azureApiVersion=f.apiVersion,x.azureDeploymentName=E.id;return x}function lE(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 ST=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function dE(f,E,_){let T=f.onResponse;if(f.onResponse=async(x,N)=>{let P=new Headers(x.headers);_(lE(x.status,P)),await T?.(x,N)},!ST.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 _(lE(P.status,P.headers)),P}}function nE(f){return{promptTokens:f.input+f.cacheRead+f.cacheWrite,completionTokens:f.output,totalTokens:f.totalTokens,costUsd:f.cost.total,...f.reasoning!==void 0?{reasoningTokens:f.reasoning}:{},...f.cacheWrite>0?{cacheCreationInputTokens:f.cacheWrite}:{},...f.cacheRead>0?{cacheReadInputTokens:f.cacheRead}:{}}}var Hf=300000,NT=30000;class rE 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 iE extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function vf(f){return f.reason instanceof Error?f.reason:new DOMException("Aborted","AbortError")}function uT(f){return f.idleTimeoutMs&&f.idleTimeoutMs>0?f.idleTimeoutMs:Hf}function IT(f,E){if(E===0)return;let _=E!==void 0&&E>0?E:NT;return Math.max(1,Math.min(_,Math.floor(f/2)))}function DT(f,E,_){if(_?.aborted)return Promise.reject(vf(_));return new Promise((T,h)=>{let x=!1,N=()=>{clearTimeout(t),_?.removeEventListener("abort",A)},P=(M)=>{if(x)return;x=!0,N(),T(M)},S=(M)=>{if(x)return;x=!0,N(),h(M instanceof Error?M:Error(String(M)))},A=()=>{if(_)S(vf(_))},t=setTimeout(()=>P({kind:"timer"}),Math.max(0,E));if(_?.addEventListener("abort",A,{once:!0}),_?.aborted){A();return}f.then((M)=>P({kind:"next",result:M}),S)})}async function*HT(f,E,_){let T=uT(E),h=IT(T,E.stallWarningMs);if(E.signal?.aborted)throw vf(E.signal);let x=Date.now(),N=Promise.resolve().then(()=>f.next()),P;for(;;){let A=await DT(N,(P?T:h??T)-(Date.now()-x),E.signal);if(A.kind==="next"){if(P)yield{...P,phase:"recovered",durationMs:Math.max(P.durationMs,Date.now()-x)};return A.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 rE(T);throw E.abort?.(t),t}}async function*f_(f,E,_,T,h={}){let N=f.stream(E,_,T)[Symbol.asyncIterator](),P=0,S=!1,A={stallCount:0,outputStarted:!1};try{while(!0){let t=HT(N,h,A),M=await t.next();while(!M.done)yield{providerStall:M.value},M=await t.next();let I=M.value;if(I.done)throw new iE;let Y=I.value;switch(Y.type){case"text_delta":A.outputStarted=!0,yield{content:Y.delta};break;case"thinking_delta":A.outputStarted=!0,yield{reasoningContent:Y.delta};break;case"toolcall_end":A.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":S=!0,yield{finishReason:Y.reason,usage:nE(Y.message.usage)};return;case"error":throw Error(Y.error.errorMessage??`Request ${Y.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!S)Promise.resolve(N.return?.()).catch(()=>{return})}}var wf=l("Chat"),UT=1;function YT(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 bT(f){return Boolean(f&&f.role==="user"&&Array.isArray(f.content)&&f.content.some((E)=>E.type==="image_url"))}function BT(f){let _=f.findLast((T)=>{let h=T.metadata;return h!==null&&typeof h==="object"&&!Array.isArray(h)&&h.isCompactSummary===!0})?.metadata;return _!==null&&typeof _==="object"&&!Array.isArray(_)&&typeof _.parentId==="string"?_.parentId:""}function cT(f,E){let _=e(f,E);if(!_.retryable||!_.reason)return;let T=_.statusCode;switch(_.reason){case"rate_limit":if(T!==429)return;break;case"server_error":if(T===void 0||T<500||T>599)return;break;case"transport":case"stream_closed":break;case"timeout":return}let h=of(E,Date.now());return{reason:_.reason,...T!==void 0?{statusCode:T}:{},...h!==void 0?{retryAfterMs:h}:{}}}function pf(f){return f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT"}class gf{config;models;model;promptCacheBreakMonitor=new zf;providerAdmissionScheduler;admissionFallbackOwnerId=`pi-service-${process.pid}-${UT++}`;constructor(f){let E=Xf(f);this.config={...f,maxContextTokens:E.model.contextWindow,maxOutputTokens:f.maxOutputTokens??E.model.maxTokens},this.models=E.models,this.model=E.model,this.providerAdmissionScheduler=E_(this.config),wf.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,S;for await(let A of this.streamChat(f,E,_,T)){h+=A.content??"",x+=A.reasoningContent??"";for(let t of A.toolCalls??[])if(t.id&&t.type==="function"&&t.function?.name)N.push(t);P=A.usage??P,S=A.finishReason??S}return{content:h,...x?{reasoningContent:x}:{},...N.length>0?{toolCalls:N}:{},usage:P,finishReason:S}}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=ME(f);if(x.some((R)=>bT(R))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let N=Boolean(h)||AE(x),P=await PE(x,this.model,E,_,h),S=(R,u)=>{let O=T?.providerSessionId;if(!O||!R.usage)return R;if(!this.config.enablePromptCaching)return this.promptCacheBreakMonitor.clear(O),R;let b=sf(this.config,u,O),H=this.promptCacheBreakMonitor.observe({sessionId:O,modelIdentity:`${u.provider}\x00${u.api}\x00${u.id}`,context:P,retention:b,contextEpoch:BT(x),policy:{baseUrl:u.baseUrl??this.config.baseUrl??"",retention:b,requiredTool:h??"",reasoningEnabled:this.config.reasoningEnabled??!1,reasoningEffort:this.config.reasoningEffort??this.config.reasoningLevel??"",serviceTier:this.config.serviceTier??"",responseVerbosity:this.config.responseVerbosity??"",temperature:T?.temperature??this.config.temperature??0,maxOutputTokens:T?.maxOutputTokens??this.config.maxOutputTokens??0,customHeaders:this.config.customHeaders??{}},usage:R.usage});if(!H)return R;return wf.warn("[PiAIChatService] Prompt cache break detected",{reason:H.reason,previousCacheReadTokens:H.previousCacheReadTokens,cacheReadTokens:H.cacheReadTokens,tokenDrop:H.tokenDrop,callNumber:H.callNumber}),{...R,usage:{...R.usage,promptCacheBreak:H}}},A=pE({messages:x,context:P,tools:E,requestOptions:T}),t=T?.providerRecovery;if(t&&!T_(t.budgetMs))throw Error("Invalid bounded foreground Provider recovery budget");let M=t?.mode==="bounded_foreground"&&t.budgetMs>0?{budgetMs:t.budgetMs,startedAt:void 0}:void 0,I=M?"bounded_foreground":"standard",Y=this.config.maxRetries??2,$=this.config.maxRetries??(M?__:2),Q=M!==void 0&&this.config.maxRetries===void 0,K=0,o,Uf=this.config.providerCircuitRegistry??BE(),Rf=this.config.providerCircuitBreakerOpenMs??Jf,h_=Math.max(uf,Math.min(this.config.streamIdleTimeout??Hf,$f)),lf=this.providerAdmissionScheduler,x_=this.config.providerRequestConcurrency??q,af=this.config.providerRequestAdmissionMs??Qf,t_=this.config.providerRequestPendingBytes??Kf,Yf=T?.providerAdmission??{sessionId:this.admissionFallbackOwnerId,ownerId:this.admissionFallbackOwnerId,requestClass:"internal"},R_=(R,u)=>Uf.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:Rf,probeLeaseMs:h_}),P_=(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:x_,maxPendingBytes:t_}),j=(R=Date.now())=>{if(!M)return;let u=M.startedAt===void 0?0:Math.min(M.budgetMs,Math.max(0,R-M.startedAt));return{recoveryBudgetMs:M.budgetMs,recoveryElapsedMs:u,recoveryRemainingMs:Math.max(0,M.budgetMs-u)}},v=()=>({mode:I,...j()??{}}),yf=()=>{if(M&&M.startedAt===void 0)M.startedAt=Date.now()},w=()=>{let R=j();return new y(M?.budgetMs??0,R?.recoveryElapsedMs??0)},d=()=>!Q||K<$+1,bf=(R,u)=>{let{state:O,...b}=u;return{phase:R,...b,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}},ef=(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,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),M_=async function*(R,u){if(!lf)return{release:()=>{return}};let O=j()?.recoveryRemainingMs,b=O!==void 0&&M?.startedAt!==void 0?Math.min(af,O):af,H;try{H=lf.admit({scope:P_(R,u),sessionId:Yf.sessionId,ownerId:Yf.ownerId,requestClass:Yf.requestClass,maxWaitMs:b,pendingBytes:A,signal:_})}catch(B){if(tf(B)){if(B.reason==="wait_timeout"&&M?.startedAt!==void 0&&(j()?.recoveryRemainingMs??0)<=0)throw w();yield{providerAdmission:ef(B)}}throw B}let L=H.getSnapshot();if(L.state==="admitted")return await H.ready;yield{providerAdmission:bf("queued",L)};let F=H.ready.then((B)=>({kind:"ready",permit:B}),(B)=>({kind:"error",error:B}));while(!0){let B=H.getSnapshot(),c=Math.max(1,Math.min(oE,Math.max(1,b-B.waitMs))),J,X=new Promise((p)=>{J=setTimeout(()=>p({kind:"heartbeat"}),c),J.unref?.()}),G=await Promise.race([F,X]);if(J)clearTimeout(J);if(G.kind==="heartbeat"){yield{providerAdmission:bf("queued",H.getSnapshot())};continue}if(G.kind==="error"){if(tf(G.error)){if(G.error.reason==="wait_timeout"&&M?.startedAt!==void 0&&(j()?.recoveryRemainingMs??0)<=0)throw w();yield{providerAdmission:ef(G.error)}}throw G.error}return yield{providerAdmission:bf("admitted",H.getSnapshot())},G.permit}},A_=(R,u)=>{if(!d())throw w();if(Q)K++;o=void 0;let O=new AbortController,b=_?hE(_,O.signal):O.signal,H=typeof u.timeout==="number"&&Number.isFinite(u.timeout)&&u.timeout>0?Math.max(1,Math.floor(u.timeout)):void 0,L;if(M?.startedAt!==void 0){let c=j()?.recoveryRemainingMs??0;if(c<=0)throw w();L={remainingMs:c,error:new y(M.budgetMs,M.budgetMs)}}let F=eE(u,R,b,T,N);dE(F,R,(c)=>{o=c});let B=f_(this.models,R,P,F,{idleTimeoutMs:u.streamIdleTimeout??Hf,signal:b,abort:(c)=>O.abort(c)});return async function*(){let c,J;try{if(H!==void 0&&(L===void 0||H<L.remainingMs)){let X=new Cf(H);c=setTimeout(()=>O.abort(X),H),c.unref?.()}if(L){let X=L;J=setTimeout(()=>O.abort(X.error),X.remainingMs),J.unref?.()}yield*B}finally{if(c)clearTimeout(c);if(J)clearTimeout(J)}}()},df=this,g=(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,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),nf=(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,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),S_=(R)=>({phase:"probe",reason:R.reason??"server_error",...R.statusCode!==void 0?{statusCode:R.statusCode}:{},openDurationMs:R.openDurationMs??Rf,...R.sampleCount!==void 0?{sampleCount:R.sampleCount}:{},...R.failureCount!==void 0?{failureCount:R.failureCount}:{},...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),Bf=(R,u,O)=>({providerRetry:{phase:"exhausted",attempt:R,maxRetries:$,reason:u,...O!==void 0?{statusCode:O}:{},...v(),exhaustedBy:"recovery_budget"}}),rf=async function*(R,u,O,b,H){let L,F=!1,B,c,J=R_(R,u);for(let X=0;X<=b;X++){if(!d())break;let G,p;while(!G){let D=J.preflight();while(!D.eligible){if(B=D.reason,c=D.statusCode,!M||!H){let C=nf("rejected",D);throw yield{providerCircuit:C},new hf(C)}yf();let V=j()?.recoveryRemainingMs??0;if(V<=0){let C=w();throw yield Bf(Q?Math.max(0,K-1):X,D.reason,D.statusCode),C}yield{providerCircuit:nf("waiting",D)};let m=Math.min(Math.max(1,D.retryAfterMs),mf,V);if(await ff(m,_,{throwOnAbort:!0}),(j()?.recoveryRemainingMs??0)<=0){let C=w();throw yield Bf(Q?Math.max(0,K-1):X,D.reason,D.statusCode),C}D=J.preflight()}try{p=yield*M_(R,u)}catch(Z){if(Z instanceof y)yield Bf(Q?Math.max(0,K-1):X,B??"timeout",c);throw Z}let k=J.check();if(k.allowed)G=k;else p.release(),p=void 0}let n=G.token;if(G.probe)yield{providerCircuit:S_(G)};try{let D=!1,k=!1;for await(let Z of A_(R,u)){if(Z.providerStall){yield Z;continue}let V=Q?K-1:X;if(V>0&&B&&!D)D=!0,yield{providerRetry:{phase:"recovered",attempt:V,maxRetries:$,reason:B,...c!==void 0?{statusCode:c}:{},...v()}};if(!k){k=!0;let m=J.recordSuccess(n);if(m)yield{providerCircuit:g(m)}}F=!0,O(),yield S(Z,R)}if(!k){let Z=J.recordSuccess(n);if(Z)yield{providerCircuit:g(Z)}}return}catch(D){if(p?.release(),L=D,df.logIdleTimeout(D,F,R),await df.handleAbort(_),D instanceof y){if(F)throw Ff(D),D;throw yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):X,maxRetries:$,reason:B??"timeout",...c!==void 0?{statusCode:c}:{},...v(),exhaustedBy:"recovery_budget"}},D}let k=e(D,o);if(F)throw Ff(D),D;let Z=cT(D,o),V=Z?J.recordFailure(n,Z):o&&!pf(D)?J.recordNeutral(n):void 0;if(V)yield{providerCircuit:g(V)};if(!k.retryable||!k.reason){if(X>0&&B)yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):X,maxRetries:$,reason:B,...c!==void 0?{statusCode:c}:{},...v()}};throw D}B=k.reason,c=k.statusCode;let m=X<b&&d();if(V&&V.phase!=="closed"&&m&&(!M||!H)){let C={...g(V),phase:"rejected"};throw yield{providerCircuit:C},new hf(C)}if(m){yf();let C=Q?K:X+1,u_=gE(C,o,M?{maxDelayMs:qf,maxExponentialDelayMs:qf}:void 0),EE=V&&V.phase!=="closed"?V.retryAfterMs??0:0;if(M&&EE>0&&V)yield{providerCircuit:{...g(V),phase:"waiting"}};let I_=j(),Of=Math.max(u_,EE),r=M?Math.min(Of,I_?.recoveryRemainingMs??Of):Of,Mf={attempt:C,maxRetries:$,reason:k.reason,...k.statusCode!==void 0?{statusCode:k.statusCode}:{}};if(yield{providerRetry:{phase:"scheduled",...Mf,delayMs:r,nextRetryAt:Date.now()+r,...v()}},M){let i=r;while(i>0){let _E=Math.min(i,mf);if(await ff(_E,_,{throwOnAbort:!0}),i-=_E,(j()?.recoveryRemainingMs??0)<=0){let Af=w();throw yield{providerRetry:{phase:"exhausted",...Mf,...v(),exhaustedBy:"recovery_budget"}},Af}if(i>0){if(V&&V.phase!=="closed"&&V.nextProbeAt!==void 0){let Af=Math.max(0,V.nextProbeAt-Date.now());if(Af>0)yield{providerCircuit:{...g(V),phase:"waiting",retryAfterMs:Af}}}yield{providerRetry:{phase:"waiting",...Mf,delayMs:r,nextRetryAt:Date.now()+i,...v()}}}}}else await ff(r,_,{throwOnAbort:!0});yield{providerRetry:{phase:"attempt",...Mf,...v()}}}else yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):X,maxRetries:$,reason:k.reason,...k.statusCode!==void 0?{statusCode:k.statusCode}:{},...v(),...M&&(H||!d())?{exhaustedBy:"attempt_limit"}:{}}}}finally{J.abandon(n),p?.release()}}throw L},cf,fE=!1,Pf=this.config.fallbackModels??[],N_=M&&Pf.length>0?Math.min(Y,$):$;try{for await(let R of rf(this.model,this.config,()=>{fE=!0},N_,Pf.length===0))yield R;return}catch(R){if(cf=R,fE||!tf(R)&&!kf(R)&&!pf(R)&&!e(R,o).retryable)throw R}for(let[R,u]of Pf.entries()){if(!d())break;yield{modelFallback:!0};let O=!1;try{let b=YT(this.config,u),H=uE(b,u),L=R===Pf.length-1,F=M&&!L?Math.min(Y,$):$;for await(let B of rf(H,b,()=>{O=!0},F,L))yield B;return}catch(b){if(cf=b,O||!tf(b)&&!kf(b)&&!pf(b)&&!e(b,o).retryable)throw b}}throw cf}async handleAbort(f){if(f?.aborted)await ff(0,f,{throwOnAbort:!0})}logIdleTimeout(f,E,_){if(f===null||typeof f!=="object"||!("code"in f)||f.code!=="STREAM_IDLE_TIMEOUT"||!("timeoutMs"in f)||typeof f.timeoutMs!=="number")return;wf.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},_=Xf(E);this.config={...E,maxContextTokens:_.model.contextWindow,maxOutputTokens:E.maxOutputTokens??_.model.maxTokens},this.models=_.models,this.model=_.model,this.providerAdmissionScheduler=E_(this.config)}}function E_(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 vE({globalMaxInFlight:E,ownerMaxInFlight:_,nonForegroundGlobalMaxInFlight:E,nonForegroundOwnerMaxInFlight:_,internalGlobalMaxInFlight:E,internalDomainMaxInFlight:f.providerRequestConcurrency??q,classLimitsEnabled:!1})}var OT=l("Service");async function Zh(f){let E=f;if(E.provider){let _=TE(E.provider);if(Object.keys(_).length>0)E={...E,customHeaders:{..._,...E.customHeaders}},OT.debug(`Injected ${E.provider} specific headers:`,Object.keys(_))}return VT(E)}function VT(f){return new gf(f)}
|
|
5
|
-
export{zT as Qf,$T as Rf,hE as Sf,ff as Tf,tf as Uf,wE as Vf,ET as Wf,Ph as Xf,e as Yf,gE as Zf,gf as _f,Zh as $f};
|
package/dist/chunk-sr9gqacp.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{bf as a,cf as b}from"./chunk-mkvqtawj.js";import"./chunk-dnt4c3gy.js";import"./chunk-w3y69e4e.js";export{a as globalOptions,b as cliConfig};
|
package/dist/chunk-sxqydew5.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Ae as a,Be as b,Ce as c,De as d,Ee as e,Fe as f,Ge as g,He as h,Ie as i,Je as j,Ke as k,Le as l,Me as m,Ne as n,Oe as o,Pe as p,Qe as q,Re as r}from"./chunk-h123tjsg.js";import"./chunk-7zvwfz85.js";import"./chunk-yvk8w63g.js";import"./chunk-679b7s58.js";import"./chunk-ar3sdj0w.js";import"./chunk-fjvt9mwv.js";import"./chunk-w3y69e4e.js";export{h as syncSession,j as syncAllAcpRemoteScopes,k as syncAll,i as syncAcpRemoteScope,r as searchProjectionText,f as resetProjectionDbCache,l as removeSessionFromProjection,m as rebuildProjectionIndex,q as readSessionSurfaceHistoryPage,o as readSessionSurfaceCatalogRevision,p as readSessionSurfaceCatalogPage,n as readSessionSurfaceCandidates,g as projectSessionSurfaceSummaryFields,c as getSessionSurfaceHistoryByteLimit,e as getProjectionDb,d as getIndexDbPath,a as __setProjectionIOForTesting,b as __resetProjectionIOForTesting};
|
package/dist/chunk-t52v91dy.js
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import{v as tz,w as ez}from"./chunk-cz9mqkn2.js";import{A as S,x as yz,y as Iz,z as kz}from"./chunk-xgz1yanb.js";import{B as sz,C as Pz,D as Ez,E as Tz,F as xz,G as bz}from"./chunk-bzp08nf6.js";import{Aa as Mz,N as R,W as wz,X as Fz,aa as Oz,da as Nz,ea as Az,ha as qz,xa as Rz,ya as Sz,za as hz}from"./chunk-f1wnva76.js";import"./chunk-2qyh6qhb.js";import{Oa as nz}from"./chunk-e1q1hvty.js";import{Qa as Dz}from"./chunk-2242dshn.js";import{Kb as Kz,Tb as d,yb as _z}from"./chunk-88jmtcv7.js";import{cc as m}from"./chunk-77efqpdc.js";import{Dd as Uz,Gd as jz,Id as h,Ld as Gz,Qd as Vz,Td as K,md as Wz,wd as M,xd as v,yd as Bz}from"./chunk-555ffyze.js";import"./chunk-53h87fmt.js";import{pe as Hz,we as l,xe as Xz}from"./chunk-h123tjsg.js";import"./chunk-7zvwfz85.js";import{if as zJ}from"./chunk-7hxyxv4x.js";import"./chunk-cfamqqgv.js";import{Df as iz,Ef as az}from"./chunk-00zazdct.js";import"./chunk-v508x7cg.js";import{Pf as n}from"./chunk-r4bgsfj6.js";import{Uf as Lz}from"./chunk-rkjrft19.js";import"./chunk-87ycd3f8.js";import{dg as rz}from"./chunk-7j628q12.js";import"./chunk-ms360ds6.js";import"./chunk-x1w3fvhr.js";import"./chunk-z5mm9g1y.js";import{Zg as oz}from"./chunk-1tfjaazq.js";import"./chunk-nfdfthhb.js";import"./chunk-gv24cgpb.js";import"./chunk-yvk8w63g.js";import{ai as dz,di as lz}from"./chunk-jy61b0v8.js";import"./chunk-3csj18f1.js";import{Bi as g,Ci as Yz,Ei as c,Fi as p}from"./chunk-nry7d26k.js";import{Ji as o}from"./chunk-be2csw9m.js";import"./chunk-679b7s58.js";import"./chunk-8xem2mzy.js";import{pj as y}from"./chunk-ar3sdj0w.js";import"./chunk-rcthrb7h.js";import{wj as mz,zj as vz}from"./chunk-0d440hhe.js";import"./chunk-dnt4c3gy.js";import"./chunk-rmm7n9n3.js";import"./chunk-961nemng.js";import{Nj as Qz,Oj as cz,Sj as s,Wj as t,Xj as pz,Yj as e}from"./chunk-fjvt9mwv.js";import"./chunk-w3y69e4e.js";import{Readable as VJ,Writable as _J}from"node:stream";import*as f from"@agentclientprotocol/sdk";import i from"node:path";import{PROTOCOL_VERSION as XJ,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as Cz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var V=y("Agent");function T(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function $z(z){if(!z)return{};return Object.fromEntries(z.map((J)=>[J.name,J.value]))}function $J(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:$z(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:$z("headers"in z?z.headers:void 0)};return null}function QJ(z){let J={};for(let Z of z){let Y=$J(Z);if(Y)J[Z.name]=Y}return J}function fz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((J)=>{if(J.type==="text")return J.text?[{type:"text",text:J.text}]:[];let Z=J.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(Z);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function YJ(z){let J=Xz(z.metadata);return J?[{type:"text",text:l(J)}]:fz(z.content)}function LJ(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
|
-
`)}function WJ(z){if(!Lz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...M("capacity"),resource:z.resource}}function HJ(z){if(!(z instanceof Cz)||!z.data||typeof z.data!=="object")return;let J=z.data;if(!Bz(J.taskFailure)||J.toolExecutionStarted!==!1||!Number.isInteger(J.toolCallsCount)||J.toolCallsCount<0||J.outputStarted!==!1)return;return{taskFailure:J.taskFailure,toolExecutionStarted:J.toolExecutionStarted,toolCallsCount:J.toolCallsCount,outputStarted:J.outputStarted}}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;destroyed=!1;destroyFinished=!1;destroyPromise;serviceRegistration;messages;contextMessages;mode;updateEgress;constructor(z,J,Z,Y,W={}){this.id=z;this.roots=J;this.connection=Z;this.clientCapabilities=Y;this.options=W;this.messages=[...W.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(W.permissionMode),this.updateEgress=new bz({maxPendingItems:Pz,maxPendingBytes:Ez,writeTimeoutMs:Tz,signal:Z.signal,sizeOf:(H)=>Buffer.byteLength(JSON.stringify(H)),write:async(H)=>{await Z.sessionUpdate(H)},onFailure:(H)=>this.handleUpdateEgressFailure(H)})}async refreshPersistedMessages(){let[z,J]=await Promise.all([this.loadPersistedMessages(),this.loadPersistedModelContext()]);if(z.length>0)this.messages=z;if(J.length>0)this.contextMessages=J}async loadModelContextOr(z){let J=await this.loadPersistedModelContext();return J.length>0?J:[...z]}loadPersistedMessages(){return this.roots.kind==="acp-remote"?K.loadRemoteSession(this.id,this.roots.hostStateRoot,this.roots.descriptor):K.loadSession(this.id,this.roots.hostStateRoot)}loadPersistedModelContext(){return this.roots.kind==="acp-remote"?K.loadRemoteSessionModelContext(this.id,this.roots.hostStateRoot,this.roots.descriptor):K.loadSessionModelContext(this.id,this.roots.hostStateRoot)}async persistMetadataUpdate(z,J=z){if(this.roots.kind==="acp-remote"){await K.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,z);return}try{await K.updateSessionMetadata(this.id,this.roots.hostStateRoot,z)}catch(Z){if(!(Z instanceof Vz)&&Z.code!=="ENOENT")throw Z;await K.createSessionMetadata(this.id,this.roots.hostStateRoot,{taskStatus:"completed",...J})}}async persistPermissionMode(z){if(this.roots.kind==="acp-remote"){await K.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,{permissionMode:z});return}await K.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 qz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){V.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(L)=>{await this.sendUpdateAndWait(L)},this.roots.kind==="acp-remote"?this.roots.profile:void 0);if(z)this.serviceRegistration=z;if(V.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.roots.kind==="local"?await d.resolvePendingWithHandler(this.roots.hostStateRoot,this.id,{requestConfirmation:(L)=>this.requestPermission(L)}):!1)await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?QJ(this.options.mcpServers):void 0,Y=R.getInstance().getTerminalService(this.id),W=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 Oz.create({sessionId:this.id,workspaceRoot:this.roots.hostStateRoot,...W?{workspace:W}:{},permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(L,U)=>{let j=await Y.execute(L,{cwd:U.cwd,env:U.env,timeout:U.timeoutMs,signal:U.signal,allowLocalFallback:!1,onOutput:(G)=>U.onOutput?.("stdout",G)});return{exitCode:j.exitCode,stdout:j.stdout,stderr:j.stderr,...j.error?{error:j.error}:{},timedOut:j.failureKind==="timeout",aborted:j.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 Sz(this.roots.hostStateRoot);V.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=_z.subscribe((L)=>{if(L.sessionId!==this.id||L.projectPath!==this.roots.hostStateRoot)return;if(L.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":L.properties}}),this.requestPendingResume();return}if(L.type==="task.delivery"){if(!L.properties.taskDelivery||typeof L.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof L.properties.updatedAt==="string"?L.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":L.properties.taskDelivery,...L.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(L.type.startsWith("team.")){let{teamName:U,messageId:j,content:G}=L.properties,P=L.properties.metadata;if(L.type==="team.message.received"&&typeof U==="string"&&typeof j==="string"&&typeof G==="string"&&Fz(P,{messageId:j,teamName:U}))(async()=>{let E=await this.runtime?.enqueueSteering(G,{allowBeforeTurn:!0,messageId:j,origin:"team_message",metadata:P});if(!E?.accepted)return;if(await new wz(U,Qz()).markDelivered([j]),E.delivery==="next_turn")this.requestPendingResume()})().catch((E)=>{V.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,E)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:L.type,...L.properties}}});return}if(L.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof L.properties.updatedAt==="string"?L.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":L.properties.taskStatus,...typeof L.properties.taskStatusReason==="string"?{"blade/taskStatusReason":L.properties.taskStatusReason}:{},...L.properties.taskFailure&&typeof L.properties.taskFailure==="object"?{"blade/taskFailure":L.properties.taskFailure}:{},...typeof L.properties.taskStartedAt==="string"?{"blade/taskStartedAt":L.properties.taskStartedAt}:{},...typeof L.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":L.properties.taskCompletedAt}:{},...L.properties.taskDiffStat&&typeof L.properties.taskDiffStat==="object"?{"blade/taskDiffStat":L.properties.taskDiffStat}:{},...typeof L.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":L.properties.taskQueuePosition}:{},...typeof L.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":L.properties.taskQueueDepth}:{},...typeof L.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":L.properties.taskConcurrencyLimit}:{},...typeof L.properties.taskInFlight==="number"?{"blade/taskInFlight":L.properties.taskInFlight}:{}}})});let Q=await this.runtime.getGoal(),X=this.runtime.getPendingSteeringCount()>0,B=Q?.status==="active"||Q?.status==="verifying";if(X||B)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let L=this.runtime.getTurnRecoveryAssessment();if(L.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":L}})}}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;if(!Hz(J))continue;let Z=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!Z)continue;for(let Y of YJ(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Z,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);V.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,J){try{V.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let Z={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 X=await this.runtime.rewindSession(Q);return this.messages=[...X.messages],this.contextMessages=await this.loadModelContextOr(X.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),X}},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,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=!1,L,U=(G)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:G.id,status:G.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:G.result?.message||G.result?.error||`Subagent ${G.status}`}}]})},j=this.runtime.resumeSubagent({agentId:Q,prompt:X,onCompleted:(G)=>{if(B)U(G);else L=G}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:j.session.id,status:"in_progress",title:`Resuming ${j.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${j.source.id} at depth ${j.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),B=!0,L)U(L);return j}}}:{},...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,X,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,X,B)},complete:async(Q,X,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,X,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,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,X)},getLogs:async(Q,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,X)},setLoggingLevel:async(Q,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,X)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}}}:{},sideConversation:{ask:async(Q,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:X})}},...this.roots.kind==="local"?{codeReview:{run:async(Q,X)=>{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:X,onEvent:(j)=>{if(j.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:j.toolCall.id,status:"in_progress",title:`Review: ${j.toolCall.function.name}`,content:[],kind:this.mapToolKind(j.toolKind)});else if(j.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:j.toolCall.id,status:j.result.success?"completed":"failed",content:[]})}}),L=await B.completion,U=(await S.list(this.roots.hostStateRoot,this.id)).find((j)=>j.start.reviewId===B.reviewId);if(!U)throw Error(`Review not found: ${B.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:B.reviewId,status:L.status,findings:L.findings.length,content:Wz(U.start,L)}}}}:{},signal:J,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,X,B)=>{let L=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,U=this.mapToolKind(B);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(X,null,2)}}],kind:U})},sendToolResult:(Q,X)=>{if(X.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X.summary}})}}},Y=await hz(z,Z),W=Y.data?.action;if(W==="start_goal"||W==="resume_goal")this.requestPendingResume();if(W==="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 H=Y.content||Y.message;if(H)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:H}});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(Z){if(J.aborted||Z instanceof Error&&Z.name==="AbortError")return{stopReason:"cancelled"};return V.error(`[AcpSession ${this.id}] Slash command error:`,Z),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${Z instanceof Error?Z.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let J=new AbortController,Z,Y=new Promise((W)=>{Z=W});this.pendingSideConversation=J,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,J.signal)}catch(W){if(J.signal.aborted||W instanceof Error&&W.name==="AbortError")return{stopReason:"cancelled"};throw W}finally{if(Z(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===J){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=Mz(this.roots.hostStateRoot,this.runtime?.getAgentResources(),this.roots.kind),J=["model","permissions","theme","config","exit","ide"],Y=z.filter((W)=>!J.includes(W.name)&&(W.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((W)=>{let H;if(W.usage){let Q=W.usage.replace(/^\/\w+\s*/,"").trim();if(Q)H=Q}if(W.aliases?.length){let Q=`Aliases: ${W.aliases.join(", ")}`;H=H?`${H} | ${Q}`:Q}return{name:W.name,description:W.description,input:H?{hint:H}:void 0}});V.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((W)=>W.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),V.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){V.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,J={}){if(R.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Z=this.resolvePrompt(z.prompt),Y=Z.content,W=Z.displayText,H=z._meta?.outputSchema??(J.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((D)=>D.outputSchema)?.outputSchema:void 0),Q;if(H!==void 0)Q=Gz(H).schema;if(W.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(W)}let X=Dz(W);if(X){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((D)=>D.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(X.question?`/btw ${X.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(W.trim()))return this.handleSlashCommand(W,this.pendingPrompt.signal);let D=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!D.accepted)throw Error(D.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(V.debug(`[AcpSession ${this.id}] Queued steering for active turn (${D.queued})`),D.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let B=new AbortController,L=()=>{B.abort(J.abortSignal?.reason)};if(J.abortSignal?.aborted)L();else J.abortSignal?.addEventListener("abort",L,{once:!0});let U=!1,j=!1,G=!1,P,E=new Promise((D)=>{P=D});this.pendingPrompt=B,this.pendingPromptCompletion=E;try{if(V.debug(`[AcpSession ${this.id}] Received prompt: ${W.slice(0,100)}...`),Rz(W)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(W,B.signal)}let D={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($)=>{this.mode=this.mapPermissionModeToMode($),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async($)=>{return this.requestPermission($)}}},O=await Kz(this.agent.chatStream(Y,D,{pendingInputOnly:J.pendingInputOnly,goalContinuationOnly:J.goalContinuationOnly,outputSchema:Q}),async($)=>{switch($.kind){case"content_delta":if(Q)break;if($.delta.length>0)j=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":if($.delta.length>0)j=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{G=!0;let _=$.toolCall,N=_.function.name;if(N===h)break;let q=this.mapToolKind($.toolKind),w=`Executing ${N}`;if(N==="Task"&&"function"in _)try{let b=JSON.parse(_.function.arguments),F=b.resume_from??b.resume;if(typeof F==="string")w=`Resuming ${String(b.subagent_type||"subagent")} from ${F}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:_.id,status:"in_progress",title:w,content:[],kind:q});break}case"tool_progress":{G=!0;let _=$.toolCall;if(_.function.name===h)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:_.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{G=!0;let _=$.toolCall;if(_.function.name===h)break;let N=$.result,q=[],w=N.metadata;if(w?.kind==="patch"&&Array.isArray(w.changes))for(let F of w.changes){if(!F||typeof F!=="object"||!("path"in F)||typeof F.path!=="string")continue;q.push({type:"diff",path:F.path,oldText:"oldContent"in F&&typeof F.oldContent==="string"?F.oldContent:null,newText:"newContent"in F&&typeof F.newContent==="string"?F.newContent:null})}else if(w?.kind==="edit"&&typeof w.file_path==="string"&&typeof w.oldContent==="string"&&(typeof w.newContent==="string"||w.newContent===void 0))q.push({type:"diff",path:w.file_path,oldText:w.oldContent,newText:w.newContent??null});else{let F=_.function.name,JJ=Az(jz(Nz(F,N),Uz));q.push({type:"content",content:{type:"text",text:JJ}})}if(_.function.name==="Task"&&(w?.verificationVerdict==="pass"||w?.verificationVerdict==="fail"||w?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${w.verificationVerdict.toUpperCase()}`}});let b=N.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:_.id,status:b,content:q});break}case"structured_output":j=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify($.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
|
|
3
|
-
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${$.contentKind} r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
|
|
4
|
-
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
|
|
5
|
-
`}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${$.revision} (${$.serverName}): ${$.phase} ${$.attempt}/${$.maxAttempts}
|
|
6
|
-
`}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${$.revision} (${$.serverName}) ${$.level}${$.logger?` logger=${$.logger}`:""}: ${$.message}
|
|
7
|
-
`}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${$.revision} (${$.serverName}): ${$.action}${$.detailsOmitted?" details-omitted":""}
|
|
8
|
-
`}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${$.revision} ${$.taskId} (${$.serverName}/${$.toolName}): ${$.status}${$.hasResult?" result-available":""}
|
|
9
|
-
`}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${$.files.length}${$.blockedWrite?" (write retry required)":""}
|
|
10
|
-
`}});break;case"provider_admission":U=$.phase!=="admitted",this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":$.phase!=="admitted"?{phase:$.phase,requestClass:$.requestClass,resource:$.resource,scope:$.scope,...$.reason!==void 0?{reason:$.reason}:{},queuePosition:$.queuePosition,queueDepth:$.queueDepth,inFlight:$.inFlight,limit:$.limit,waitMs:$.waitMs,maxWaitMs:$.maxWaitMs,...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}}:null}});break;case"provider_circuit":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerCircuit":{phase:$.phase,reason:$.reason,...$.statusCode!==void 0?{statusCode:$.statusCode}:{},...$.retryAfterMs!==void 0?{retryAfterMs:$.retryAfterMs}:{},...$.nextProbeAt!==void 0?{nextProbeAt:$.nextProbeAt}:{},openDurationMs:$.openDurationMs,...$.sampleCount!==void 0?{sampleCount:$.sampleCount}:{},...$.failureCount!==void 0?{failureCount:$.failureCount}:{},...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}}}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:$.phase,attempt:$.attempt,maxRetries:$.maxRetries,reason:$.reason,...$.statusCode!==void 0?{statusCode:$.statusCode}:{},...$.delayMs!==void 0?{delayMs:$.delayMs}:{},...$.nextRetryAt!==void 0?{nextRetryAt:$.nextRetryAt}:{},...$.mode!==void 0?{mode:$.mode}:{},...$.recoveryBudgetMs!==void 0?{recoveryBudgetMs:$.recoveryBudgetMs}:{},...$.recoveryElapsedMs!==void 0?{recoveryElapsedMs:$.recoveryElapsedMs}:{},...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{},...$.exhaustedBy!==void 0?{exhaustedBy:$.exhaustedBy}:{}}}});break;case"turn_recovery":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":$.assessment}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:$.phase,stallCount:$.stallCount,durationMs:$.durationMs,warningAfterMs:$.warningAfterMs,timeoutMs:$.timeoutMs,outputStarted:$.outputStarted}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:$.phase,toolName:$.toolName,runLength:$.runLength,nudgeThreshold:$.nudgeThreshold,haltThreshold:$.haltThreshold,progressAware:$.progressAware}}});break;case"task_update":this.sendPlanUpdate($.tasks);break;case"goal_frontier_updated":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:$.frontier.observedAt,_meta:{"blade/goalFrontier":{goalId:$.goal.goalId,status:$.goal.status,taskListId:$.frontier.taskListId,total:$.frontier.total,completed:$.frontier.completed,inProgress:$.frontier.inProgress,pending:$.frontier.pending,blocked:$.frontier.blocked,nextTask:$.frontier.nextTask,digestSha256:$.frontier.digestSha256,...$.goal.frontierStall?{stall:{category:$.goal.frontierStall.category,consecutiveCount:$.goal.frontierStall.consecutiveCount}}:{}}}}),this.sendPlanUpdate($.tasks);break;case"steering_applied":break;case"follow_up_started":{let _=0;for(let N of $.messages){if(!N.recovered||N.persisted)continue;if(J.projectedRecoveredInputIds?.has(N.id))continue;for(let q of fz(N.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:q});J.projectedRecoveredInputIds?.add(N.id),_++}if(_>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${_} queued instruction${_===1?"":"s"} recovered after restart]
|
|
11
|
-
`}});break}case"goal_updated":if($.goal)this.sendUpdate(this.goalSessionUpdate($.goal));if($.goal&&$.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${$.goal.status}: ${$.goal.objective}]
|
|
12
|
-
`}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:$.goal.goalId,continuation:$.continuation,...$.prematureStopPattern?{prematureStopPattern:$.prematureStopPattern}:{},...$.prematureStopCount!==void 0?{prematureStopCount:$.prematureStopCount}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:$.phase,...$.reason?{reason:$.reason}:{},...$.strategy?{strategy:$.strategy}:{},...$.outcome?{outcome:$.outcome}:{},...$.preTokens!==void 0?{preTokens:$.preTokens}:{},...$.preTokenSource?{preTokenSource:$.preTokenSource}:{},...$.estimatedPendingTokens!==void 0?{estimatedPendingTokens:$.estimatedPendingTokens}:{},...$.postTokens!==void 0?{postTokens:$.postTokens}:{},...$.sampleAttempts!==void 0?{sampleAttempts:$.sampleAttempts}:{},...$.inputReductions!==void 0?{inputReductions:$.inputReductions}:{},...$.messagesOmitted!==void 0?{messagesOmitted:$.messagesOmitted}:{},...$.filesOmitted!==void 0?{filesOmitted:$.filesOmitted}:{},...$.imagesOmitted!==void 0?{imagesOmitted:$.imagesOmitted}:{},...$.fallbackTargetTokens!==void 0?{fallbackTargetTokens:$.fallbackTargetTokens}:{},...$.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:$.fallbackMessagesOmitted}:{},...$.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:$.fallbackMessagesTruncated}:{},...$.failureReason?{failureReason:$.failureReason}:{}}}});break;default:break}if(!await this.flushUpdates())B.abort("acp-egress-failed")});if(!await this.flushUpdates())B.abort("acp-egress-failed");this.contextMessages=[...D.messages];let Jz=await this.loadPersistedMessages();if(this.messages=Jz.length>0?Jz:[...D.messages],!O.success){let $=O.error?.type??"unknown",_=O.error?.details??O.error?.message??"Agent execution failed",N=WJ(_)??v(_);throw Cz.internalError({failureType:$,modelId:this.runtime.getCurrentModelId(),taskFailure:N,outputStarted:j,toolExecutionStarted:G,...Number.isInteger(O.metadata?.toolCallsCount)?{toolCallsCount:O.metadata.toolCallsCount}:{}},`Agent turn failed (${$})`)}if(B.signal.aborted)return{stopReason:"cancelled"};let Zz={...O.metadata?.structuredOutput?{structuredOutput:O.metadata.structuredOutput,outputSchemaDigest:O.metadata.structuredOutputSchemaDigest}:{},...O.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:O.metadata.goalVerificationVerdict,...O.metadata.goalVerifierSessionId?{verifierSessionId:O.metadata.goalVerifierSessionId}:{},...O.metadata.goalVerificationEvidenceSha256?{evidenceSha256:O.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(Zz).length>0?{_meta:Zz}:{}}}catch(D){if(B.signal.aborted||D instanceof Error&&D.name==="AbortError")return{stopReason:"cancelled"};throw V.error(`[AcpSession ${this.id}] Prompt error:`,D),D}finally{if(J.abortSignal?.removeEventListener("abort",L),U&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(P(),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 J=z.trimStart().slice(1).trim();if(!J)throw Error("User shell command cannot be empty");let Z=new AbortController,Y,W=new Promise((X)=>{Y=X});this.pendingUserShell=Z,this.pendingUserShellCompletion=W;let H,Q="";try{let X=await this.runtime.executeUserShellCommand(J,{signal:Z.signal,onEvent:async(L)=>{if(H=L.executionId,L.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.executionId,status:"in_progress",title:`! ${L.command}`,content:[],kind:"execute"});return}if(L.type==="output"){Q+=L.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:L.chunk}}]});return}let U=l(L.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.executionId,status:L.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Q?LJ(L.record):U}}]})}}),B={role:"user",content:X.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(X.record))}};if(this.messages.push(B),this.contextMessages.push(B),X.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return Z.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:X.record.status==="aborted"?"cancelled":"end_turn"}}catch(X){if(H)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:H,status:"failed",content:[{type:"content",content:{type:"text",text:X instanceof Error?X.message:String(X)}}]});if(Z.signal.aborted)return{stopReason:"cancelled"};throw X}finally{if(Y(),this.pendingUserShellCompletion===W)this.pendingUserShellCompletion=null;if(this.pendingUserShell===Z){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 J=this.pendingResumeGeneration,Z=()=>{if(J!==this.pendingResumeGeneration)return;this.startPendingResumeRun(J)};if(z>0)this.pendingResumeTimer=setTimeout(Z,z),this.pendingResumeTimer.unref?.();else queueMicrotask(Z)}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 J=this.resumePendingIfIdle();this.pendingResumeCompletion=J,J.then(()=>{if(this.pendingResumeCompletion===J){this.pendingResumeCompletion=null;let Z=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,Z!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(Z)}},()=>{if(this.pendingResumeCompletion===J){this.pendingResumeCompletion=null;let Z=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,Z!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(Z)}})}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,J){return{sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/pendingResume":{phase:z,kind:J.kind,attempt:J.attempt,maxAttempts:yz,...J.delayMs!==void 0?{delayMs:J.delayMs,nextRetryAt:Date.now()+J.delayMs}:{},...J.taskFailure?{failure:{code:J.taskFailure.code,retryable:J.taskFailure.retryable,...J.taskFailure.resource?{resource:J.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,J=this.pendingResumeAttempt+1;if(this.pendingResumeAttempt=J,this.pendingResumeRecoveryStartedAt===0)this.pendingResumeRecoveryStartedAt=Date.now();let Z="preflight",Y=!1,W,H=null;try{let Q=this.runtime.getPendingSteeringCount()>0,X=Q?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let B=X?.status==="active"||X?.status==="verifying",L=this.runtime.getTurnRecoveryAssessment();if(L.state!=="none"&&(L.state==="requires_attention"||!Q&&!B))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":L}});if(!Q&&!B){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if(L.state==="requires_attention"){this.clearPendingResumeRequest();return}Z=Q?"pending_input":"goal",Y=!0;let U=Iz-(Date.now()-this.pendingResumeRecoveryStartedAt);if(U<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:Z,taskFailure:M("timeout")})),!this.preserveNewPendingInput(Z))this.clearPendingResumeRequest();return}let j=new AbortController;H=setTimeout(()=>{j.abort("acp-pending-resume-budget-exhausted")},U),H.unref?.();let G=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Q,goalContinuationOnly:B,projectedRecoveredInputIds:Z==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:j.signal});if(z!==this.pendingResumeGeneration)return;if(j.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:Z,taskFailure:M("timeout")})),!this.preserveNewPendingInput(Z))this.clearPendingResumeRequest();return}if(G.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(J>1){if(!await this.sendUpdateAndWait(this.pendingResumeSessionUpdate("recovered",{attempt:J,kind:Z})))return;if(z!==this.pendingResumeGeneration)return}this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}catch(Q){if(z!==this.pendingResumeGeneration)return;let X=Y?HJ(Q):{taskFailure:v(Q),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},B=Z==="preflight"||Z==="pending_input"&&this.runtime.getPendingSteeringCount()>0,L=kz({sessionIdentity:this.id,failedAttempt:J,recoveryStartedAt:this.pendingResumeRecoveryStartedAt,workStillPending:B,evidence:X});if(L.phase==="retry_scheduled")this.pendingResumeRequested=!0,W=L.delayMs,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:J+1,kind:Z,taskFailure:X?.taskFailure,delayMs:L.delayMs})),V.warn(`[AcpSession ${this.id}] Pending resume attempt ${J} failed; retrying in ${L.delayMs}ms`);else{let U=L.phase;if(this.sendUpdate(this.pendingResumeSessionUpdate(U,{attempt:J,kind:Z,taskFailure:X?.taskFailure})),V.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${J}, retryable=${L.retryable}, phase=${U})`,Q),!this.preserveNewPendingInput(Z))this.clearPendingResumeRequest()}}finally{if(H!==null)clearTimeout(H);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.pendingResumeNextDelayMs=W??0}}cancel(){V.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)V.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let Z=["default","auto-edit","yolo","plan"].includes(z)?z:"default",Y=this.mapModeIdToPermissionMode(Z);await this.persistPermissionMode(Y),this.mode=Z,V.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(V.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 J=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{await this.persistMetadataUpdate({selectedModelId:z})}catch(Z){if(J&&J!==z)await this.agent.switchModel(J).catch((Y)=>{V.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});throw Z}}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 J=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(Z){throw Error(Z instanceof Error?Z.message:"Invalid reasoning effort")}if(J.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{await this.persistMetadataUpdate({reasoningEffort:z},{selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}catch(Z){throw await this.runtime.refresh({reasoningEffort:J.selection}),Z}}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 J=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(Z){throw Error(Z instanceof Error?Z.message:"Invalid service tier")}if(J.selection===z)return;await this.runtime.refresh({serviceTier:z});try{await this.persistMetadataUpdate({serviceTier:z},{selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}catch(Z){throw await this.runtime.refresh({serviceTier:J.selection}),Z}}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 J=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(Z){throw Error(Z instanceof Error?Z.message:"Invalid response verbosity")}if(J.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{await this.persistMetadataUpdate({responseVerbosity:z},{selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}catch(Z){throw await this.runtime.refresh({responseVerbosity:J.selection}),Z}}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 J=this.runtime.getCommunicationStyleConfiguration(),Z=this.runtime.resolveCommunicationStyleConfiguration(z);if(Z.source!=="built-in"&&!Z.contentSha256)throw Error("Custom communication style has no provenance");if(J.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{await this.persistMetadataUpdate({communicationStyle:z,communicationStyleDigest:Z.source==="built-in"?null:Z.contentSha256},{selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...Z.source!=="built-in"&&Z.contentSha256?{communicationStyleDigest:Z.contentSha256}:{}})}catch(Y){throw await this.runtime.refresh({communicationStyle:J.selection}),Y}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((J)=>structuredClone(J)),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 xz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,Z=this.runtime,Y=this.pendingPromptCompletion,W=this.pendingUserShellCompletion,H=this.pendingSideConversationCompletion,Q=this.pendingResumeCompletion;this.agent=null,this.runtime=null;let X,B=async(L)=>{try{await L()}catch(U){X??=U}};if(await B(()=>this.cancel()),Y)await B(()=>Y);if(W)await B(()=>W);if(H)await B(()=>H);if(Q)await B(()=>Q);if(z&&Y&&Z)await B(()=>Z.discardPendingInput());if(J)await B(()=>J.destroy());if(Z)await B(()=>Z.dispose());if(await B(()=>R.destroyRegisteredSession(this.serviceRegistration)),this.serviceRegistration=void 0,V.debug(`[AcpSession ${this.id}] Destroyed`),X!==void 0)throw X}resolvePrompt(z){let J=[],Z=[],Y=0,W=0,H=0,Q=(L)=>{if(Z.length>0)Z.push({type:"text",text:`
|
|
13
|
-
`}),H+=1;if(Z.push(L),L.type==="text")H+=L.text.length};for(let L of z)if(L.type==="text")J.push(L.text),Q({type:"text",text:L.text});else if(L.type==="image"){let U=`data:${L.mimeType};base64,${L.data}`;Y+=1,W+=U.length,J.push(`[Image: ${L.mimeType}]`),Q({type:"image_url",image_url:{url:U}})}else if(L.type==="resource"){let U=L.resource;if("text"in U){let j=`<file path="${U.uri}">
|
|
14
|
-
${U.text}
|
|
15
|
-
</file>`;J.push(j),Q({type:"text",text:j})}}else if(L.type==="resource_link"){let U=`[Resource: ${L.uri}]`;J.push(U),Q({type:"text",text:U})}if(Y>g)throw Error(`ACP prompt contains more than ${g} images`);if(W>Yz)throw Error("ACP prompt images exceed the 5 MiB limit");if(H>c)throw Error(`ACP prompt text exceeds ${c} characters`);if(Buffer.byteLength(J.join(`
|
|
16
|
-
`),"utf8")>p)throw Error(`ACP prompt text exceeds ${p} bytes`);let B=J.join(`
|
|
17
|
-
`);return{content:Y>0?Z:B,displayText:B}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted&&!this.updateEgress.stats().closed}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;let J=this.updateEgress.offer({sessionId:this.id,update:z});if(!J.accepted)return!1;try{return await J.completion,this.canSendUpdates()}catch{return!1}}goalSessionUpdate(z){return{sessionUpdate:"session_info_update",updatedAt:z.updatedAt,_meta:{"blade/goal":{goalId:z.goalId,status:z.status,verificationAttempt:z.completionVerification?.attempt,verificationStatus:z.completionVerification?.status,verifierSessionId:z.completionVerification?.verifierSessionId,verificationEvidenceSha256:z.completionVerification?.evidenceSha256,verificationSummary:z.completionVerification?.summary,verificationStallCount:z.verificationStall?.consecutiveCount}}}}sendUpdate(z){if(!this.canSendUpdates())return;this.updateEgress.offer({sessionId:this.id,update:z})}async flushUpdates(){if(!this.canSendUpdates())return!1;try{return await this.updateEgress.flush(),this.canSendUpdates()}catch{return!1}}handleUpdateEgressFailure(z){if(this.destroyed)return;V.warn(`[AcpSession ${this.id}] Update egress closed: kind=${z.kind}`),this.clearPendingResumeRequest(),this.pendingPrompt?.abort("acp-egress-failed"),this.pendingUserShell?.abort("acp-egress-failed"),this.pendingSideConversation?.abort("acp-egress-failed")}sendPlanUpdate(z){let J=z.map((Z)=>({content:Z.subject,priority:Z.priority,status:Z.status}));V.debug(`[AcpSession ${this.id}] Sending plan update with ${J.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:J})}async requestPermission(z){let J=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,J);if(z.type==="mcpElicitation")return this.requestMcpElicitation(z,J);let Z=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(Z))return V.debug(`[AcpSession ${this.id}] Auto-approving ${Z} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(Z==="write"||Z==="execute"))return V.debug(`[AcpSession ${this.id}] Rejecting ${Z} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Y=u(),W=[];if(z.message)W.push({type:"content",content:{type:"text",text:z.message}});if(z.details)W.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)W.push({type:"content",content:{type:"text",text:`Risks:
|
|
18
|
-
- ${z.risks.join(`
|
|
19
|
-
- `)}`}});let H=this.mapToolKind(Z),Q={sessionId:this.id,options:z.type==="mcpSampling"?[{optionId:"allow_once",name:"Allow this sampling request",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}]:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:Y,status:"pending",title:z.title||"Permission Required",content:W,kind:H}},X=await this.waitForClientInteraction(this.connection.requestPermission(Q),J);if(!X)return{approved:!1,reason:m};let B=X.outcome;if(B.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let L=B.optionId;if(L==="allow_always")return{approved:!0,scope:"project"};if(L==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let U=L==="allow_once";return{approved:U,scope:"once",reason:U?void 0:"User denied the operation"}}catch(Y){return V.warn(`[AcpSession ${this.id}] Permission request failed:`,Y),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,J){let Z=z.questions??[];if(Z.length===0)return{approved:!1,reason:"No structured questions were provided"};if(Z.some((W)=>W.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let Y={};try{for(let[W,H]of Z.entries()){let Q=H.options.map((U,j)=>`answer:${W}:${j}`),X=`answer:${W}:cancel`,B=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...H.options.map((U,j)=>({optionId:Q[j],name:U.label,kind:"allow_once"})),{optionId:X,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:u(),status:"pending",title:H.header,kind:"think",content:[{type:"content",content:{type:"text",text:[H.question,...H.options.map((U)=>`${U.label}: ${U.description}`)].join(`
|
|
20
|
-
`)}}]}}),J);if(!B)return{approved:!1,reason:m};if(B.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let L=Q.indexOf(B.outcome.optionId);if(L<0)return{approved:!1,reason:"User cancelled the question prompt"};Y[H.header]=H.options[L].label}return{approved:!0,answers:Y}}catch(W){return V.warn(`[AcpSession ${this.id}] Question request failed:`,W),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(z,J){let Z=z.mcpElicitation;if(!Z)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(Z.mode==="url"){let W=await this.requestElicitationChoice("MCP external authorization",[Z.message,`Server: ${Z.serverName}`,`Domain: ${Z.domain??"unknown"}`,`URL: ${Z.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
|
|
21
|
-
`),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],J);if(W==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:W==="decline"?"User declined URL":"User cancelled",elicitation:{action:W==="decline"?"decline":"cancel"}}}let Y=Object.create(null);for(let W of Z.fields??[]){let H=await this.collectAcpElicitationField(W,J);if(H.cancelled)return{approved:!1,reason:H.reason,elicitation:{action:"cancel"}};if(H.value!==void 0)Y[W.name]=H.value}return{approved:!0,elicitation:{action:"accept",content:Y}}}catch(Y){return V.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,Y),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(z,J){if(z.type==="select"||z.type==="boolean"){let Z=z.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(z.options??[]).map((H,Q)=>({id:`option:${Q}`,label:H.label,value:H.value})),Y=await this.requestElicitationChoice(z.title,[z.description,z.required?"Required":"Optional"].filter(Boolean).join(`
|
|
22
|
-
`),[...Z.map((H)=>({id:H.id,label:H.label})),...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(Y==="skip")return{cancelled:!1};let W=Z.find((H)=>H.id===Y);if(!W)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:W.value}}if(z.defaultValue!==void 0){let Z=await this.requestElicitationChoice(z.title,[z.description,`ACP cannot collect ${z.type} input. Use the server default: ${String(z.defaultValue)}?`].filter(Boolean).join(`
|
|
23
|
-
`),[{id:"default",label:"Use default"},...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(Z==="default")return{cancelled:!1,value:z.defaultValue};if(Z==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!z.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${z.type} field "${z.name}"`}}async requestElicitationChoice(z,J,Z,Y){let W=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Z.map((H)=>({optionId:H.id,name:H.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:u(),status:"pending",title:z,kind:"think",content:[{type:"content",content:{type:"text",text:J}}]}}),Y);return W?.outcome.outcome==="selected"?W.outcome.optionId:void 0}async waitForClientInteraction(z,J){if(!J)return z;if(J.aborted)return;return new Promise((Z,Y)=>{let W=!1,H=(X)=>{if(W)return;W=!0,J.removeEventListener("abort",Q),X()},Q=()=>H(()=>Z(void 0));if(J.addEventListener("abort",Q,{once:!0}),J.aborted)Q();z.then((X)=>H(()=>Z(X)),(X)=>H(()=>Y(X)))})}mapToolKind(z){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[z||""]||"other"}}var A=y("Agent"),BJ="remote task isolation is not supported";function I(z){return z?.fs?.readTextFile===!0||z?.fs?.writeTextFile===!0}function UJ(z){return C.invalidParams({code:z.code,reason:z.reason})}function jJ(){return C.invalidParams({code:"acp_remote_task_isolation_unsupported",reason:BJ})}function uz(){return C.invalidParams({code:"acp_remote_workspace_mismatch",reason:"exact-identity-mismatch"})}function gz(z){return z instanceof Error&&"code"in z&&z.code==="acp_remote_workspace_mismatch"&&"reason"in z&&z.reason==="exact-identity-mismatch"}function k(z){try{return s(z)}catch(J){if(J instanceof cz)throw UJ(J);throw J}}function a(z,J){let Z=t(z);return Object.freeze({kind:"acp-remote",hostStateRoot:e(Z.collisionIdentity),executionRoot:Z.wirePath,hostResourceRoot:J,profile:z,descriptor:Z})}function r(z,J){let Z=pz(z.remoteWorkspace),Y=e(Z.collisionIdentity);if(z.projectPath!==Y)throw Error("ACP remote workspace durable state is invalid");let W=s(Z.wirePath);return Object.freeze({kind:"acp-remote",hostStateRoot:Y,executionRoot:Z.wirePath,hostResourceRoot:J,profile:W,descriptor:Z})}function GJ(z){if(!z.remoteWorkspace)throw Error("ACP remote workspace durable state is invalid");return z.remoteWorkspace.wirePath}class zz{connection;sessions=new Map;sessionLoadQueues=new Map;runtimeResidencyValue;clientCapabilities;destroyed=!1;destroyPromise;hostResourceRoot;constructor(z){this.connection=z;this.hostResourceRoot=i.resolve(o())}get runtimeResidency(){if(!this.runtimeResidencyValue){let z=iz();this.runtimeResidencyValue=new ez({maxResident:z?.maxResidentSessionRuntimes??dz,idleMs:z?.sessionRuntimeIdleMs??lz})}return this.runtimeResidencyValue}async reserveSessionRuntime(z){try{return await this.runtimeResidency.reserve(z,{surface:"acp",allowEviction:!1})}catch(J){if(J instanceof tz)throw C.internalError({resource:J.resource,limit:J.limit,retryable:J.retryable},J.message);throw J}}async initialize(z){return A.info("[BladeAgent] Initializing ACP connection"),A.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,await az(),{protocolVersion:XJ,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{},close:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let J=n("acp"),Z=z.cwd||o(),Y=I(this.clientCapabilities),W=Y?k(Z):void 0,H=z._meta?.["blade/taskIsolation"],Q=H==="local"||H==="worktree"?H:void 0;if(Y&&Q)throw jJ();let X=z._meta?.["blade/taskPrompt"],B=await this.reserveSessionRuntime(J),L;try{let U,j;if(W){let P=a(W,this.hostResourceRoot);U=await K.createRemoteSessionMetadata(J,P.hostStateRoot,P.descriptor,{}),j=r(U,this.hostResourceRoot)}else j=T(Z);let G=!Y&&Q?await sz.createSessionTask({sessionId:J,prompt:typeof X==="string"&&X.trim()?X:"ACP task session",sourceProjectPath:Z,isolation:Q}):void 0;if(G)j=T(G.metadata.projectPath);return A.info(`[BladeAgent] Creating new session: ${J}`),A.debug(`[BladeAgent] Session kind: ${j.kind}`),L=new x(J,j,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...G?.taskWorktree?{taskWorktree:G.taskWorktree}:{},...G?.metadata.taskIsolation?{taskIsolation:G.metadata.taskIsolation}:{}}),await L.initialize(),this.assertNotDestroyed(),this.commitSession(J,L,B),A.info(`[BladeAgent] Session ${J} created, scheduling available commands update`),L.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(J,G?.metadata,L.getModelConfiguration())}catch(U){throw B.cancel(),await L?.destroy().catch(()=>{return}),U}}async listSessions(z){let J=I(this.clientCapabilities);if(!J&&z.cwd!=null&&!i.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let Z=J?await K.listRemoteSessionPage({...z.cwd!=null?{descriptor:t(k(z.cwd))}:{},cursor:z.cursor??void 0,limit:50,includeSubagents:!1}):await K.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:Z.sessions.map((Y)=>({sessionId:Y.sessionId,cwd:J?GJ(Y):Y.projectPath,title:Y.title??null,updatedAt:Y.lastMessageTime,_meta:{"blade/taskStatus":Y.taskStatus,...Y.taskStatusReason?{"blade/taskStatusReason":Y.taskStatusReason}:{},...Y.taskFailure?{"blade/taskFailure":Y.taskFailure}:{},...Y.taskStartedAt?{"blade/taskStartedAt":Y.taskStartedAt}:{},...Y.taskCompletedAt?{"blade/taskCompletedAt":Y.taskCompletedAt}:{},...Y.taskModelId?{"blade/taskModelId":Y.taskModelId}:{},...Y.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Y.taskRetriedFrom?{"blade/taskRetriedFrom":Y.taskRetriedFrom}:{},...Y.taskDelivery?{"blade/taskDelivery":Y.taskDelivery}:{},...Y.taskIsolation?{"blade/taskIsolation":Y.taskIsolation}:{},...Y.taskSourceProjectPath?{"blade/taskSourceProjectPath":Y.taskSourceProjectPath}:{},...Y.taskWorktreeBranch?{"blade/taskWorktreeBranch":Y.taskWorktreeBranch}:{},...Y.taskBaseCommit?{"blade/taskBaseCommit":Y.taskBaseCommit}:{},...Y.taskDiffStat?{"blade/taskDiffStat":Y.taskDiffStat}:{},...Y.taskQueuePosition?{"blade/taskQueuePosition":Y.taskQueuePosition}:{},...Y.taskQueueDepth!==void 0?{"blade/taskQueueDepth":Y.taskQueueDepth}:{},...Y.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":Y.taskConcurrencyLimit}:{}}})),nextCursor:Z.nextCursor}}async unstable_forkSession(z){this.assertNotDestroyed();let J=I(this.clientCapabilities),Z=J?a(k(z.cwd),this.hostResourceRoot):void 0;if(!J&&!i.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let Y=n("fork"),W=await this.reserveSessionRuntime(Y),H;try{let Q;try{Q=await K.forkSession(z.sessionId,{sourceProjectPath:Z?.hostStateRoot??z.cwd,targetProjectPath:Z?.hostStateRoot??z.cwd,newSessionId:Y,...Z?{remote:{expectedDescriptor:Z.descriptor}}:{}})}catch(B){if(gz(B))throw uz();throw B}this.assertNotDestroyed();let X=J?r(Q.metadata,this.hostResourceRoot):T(Q.projectPath??z.cwd);return H=new x(Q.sessionId,X,this.connection,this.clientCapabilities,{initialMessages:Q.messages,permissionMode:Q.metadata.permissionMode,mcpServers:z.mcpServers}),await H.initialize(),this.assertNotDestroyed(),this.commitSession(Q.sessionId,H,W),H.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Q.sessionId,J?void 0:Q.metadata,H.getModelConfiguration())}catch(Q){throw W.cancel(),await H?.destroy().catch(()=>{return}),Q}}async loadSession(z){this.assertNotDestroyed(),A.info(`[BladeAgent] Loading session: ${z.sessionId}`);let Z=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),Y=Z.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{return await Z}finally{if(this.sessionLoadQueues.get(z.sessionId)===Y)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){if(this.assertNotDestroyed(),!I(this.clientCapabilities)){await K.assertSessionWritable(z.sessionId,z.cwd),await this.closeResidentSession(z.sessionId);let X=await this.reserveSessionRuntime(z.sessionId),B;try{let[L,U]=await Promise.all([K.loadSession(z.sessionId,z.cwd),K.findSessionMetadata(z.sessionId,z.cwd)]);if(!U)throw Error(`Session not found: ${z.sessionId}`);return B=new x(z.sessionId,T(z.cwd),this.connection,this.clientCapabilities,{initialMessages:L,permissionMode:U.permissionMode,mcpServers:z.mcpServers}),await B.initialize(),await B.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,B,X),B.sendAvailableCommandsDelayed(),this.buildSessionSetup(B.getModelConfiguration(),B.getMode())}catch(L){throw X.cancel(),await B?.destroy().catch(()=>{return}),L}}let Z=a(k(z.cwd),this.hostResourceRoot),Y;try{Y=await K.assertRemoteSessionWritable(z.sessionId,Z.hostStateRoot,Z.descriptor)}catch(X){if(gz(X))throw uz();throw X}let W=r(Y,this.hostResourceRoot);await this.closeResidentSession(z.sessionId);let H=await this.reserveSessionRuntime(z.sessionId),Q;try{let X=await K.loadRemoteSession(z.sessionId,W.hostStateRoot,W.descriptor);return Q=new x(z.sessionId,W,this.connection,this.clientCapabilities,{initialMessages:X,permissionMode:Y.permissionMode,mcpServers:z.mcpServers}),await Q.initialize(),await Q.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,Q,H),Q.sendAvailableCommandsDelayed(),this.buildSessionSetup(Q.getModelConfiguration(),Q.getMode())}catch(X){throw H.cancel(),await Q?.destroy().catch(()=>{return}),X}}commitSession(z,J,Z){let Y=Z.commit({key:z,surface:"acp",value:J,canEvict:()=>J.isIdleForResidency(),dispose:async()=>{if(this.sessions.get(z)===J)this.sessions.delete(z);await J.destroy()}});this.sessions.set(z,J),Y.release()}async closeResidentSession(z,J={}){let Z=this.sessions.get(z);if(!Z)return;let Y=this.runtimeResidency.owns(z,Z),W;try{await Z.destroy(J)}catch(Q){W=Q}let H=await this.runtimeResidency.forget(z,Z);if(this.sessions.get(z)===Z)this.sessions.delete(z);if(Y&&!H&&W===void 0)throw Error(`ACP Session is still active: ${z}`);if(W!==void 0)throw W}buildChildSessionResponse(z,J,Z){return{sessionId:z,...this.buildSessionSetup(Z,J?.permissionMode==="autoEdit"?"auto-edit":J?.permissionMode),...J?{_meta:{"blade/taskIsolation":J.taskIsolation,"blade/taskSourceProjectPath":J.taskSourceProjectPath,"blade/taskProjectPath":J.projectPath,...J.taskModelId?{"blade/taskModelId":J.taskModelId}:{},...J.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...J.taskRetriedFrom?{"blade/taskRetriedFrom":J.taskRetriedFrom}:{},...J.taskDelivery?{"blade/taskDelivery":J.taskDelivery}:{},...J.taskWorktreeBranch?{"blade/taskWorktreeBranch":J.taskWorktreeBranch}:{},...J.taskBaseCommit?{"blade/taskBaseCommit":J.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}getRuntimeResidencyStats(){return this.runtimeResidency.getStats()}buildSessionSetup(z,J="default"){let Z=z?.models??[],Y=(z?.currentModelId&&Z.some((Q)=>Q.id===z.currentModelId)?z.currentModelId:void 0)??Z[0]?.id,W=[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],H=[];if(Z.length>0)H.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:Y,options:Z.map((Q)=>({value:Q.id,name:Q.displayName??Q.model,description:`${z?.modelProviders[Q.provider]?.name??Q.provider} · ${Q.model}`}))});if(z?.reasoning)H.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:z.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${z.reasoning.effective})`},...z.reasoning.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:Q==="off"?"Disable model reasoning":`Use ${Q} reasoning effort`}))]});if(z?.serviceTier)H.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:z.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...z.serviceTier.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:Q==="fast"?"Use the provider priority tier":Q==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(z?.responseVerbosity)H.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:z.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...z.responseVerbosity.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:`Use ${Q} response verbosity`}))]});if(z?.communicationStyle)H.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:z.communicationStyle.selection,options:z.communicationStyle.supported.map((Q)=>({value:Q.id,name:Q.name,description:`${Q.description} · ${Q.source}`}))});return{modes:{availableModes:W,currentModeId:J},configOptions:H.length>0?H:void 0}}async closeSession(z){this.assertNotDestroyed();let Z=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.closeResidentSession(z.sessionId,{discardPendingInput:!0})),Y=Z.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{await Z}finally{if(this.sessionLoadQueues.get(z.sessionId)===Y)this.sessionLoadQueues.delete(z.sessionId)}}async prompt(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{return await J.value.prompt(z)}finally{J.release()}}async cancel(z){A.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J){A.info("[BladeAgent] Found session, calling session.cancel()");try{J.value.cancel()}finally{J.release()}}else A.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){A.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J)try{await J.value.setMode(z.modeId)}finally{J.release()}return{}}async setSessionConfigOption(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{let Z=J.value;if(z.configId==="model"&&"value"in z&&typeof z.value==="string")A.info(`[BladeAgent] Setting session model: ${z.value}`),await Z.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&rz(z.value))A.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await Z.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&vz(z.value))A.info(`[BladeAgent] Setting service tier: ${z.value}`),await Z.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&mz(z.value))A.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await Z.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&oz(z.value))A.info(`[BladeAgent] Setting communication style: ${z.value}`),await Z.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(Z.getModelConfiguration(),Z.getMode()).configOptions??[]}}finally{J.release()}}destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(),this.destroyPromise}async destroyOwnedResources(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let J of[...this.sessions.keys()])try{await this.closeResidentSession(J)}catch(Z){z??=Z}try{await this.runtimeResidency.disposeAll()}catch(J){z??=J}this.sessions.clear();try{await nz.getInstance().disconnectAll()}catch(J){z??=J}if(z!==void 0)throw z}}async function GZ(){let z=_J.toWeb(process.stdout),J=VJ.toWeb(process.stdin),Z=f.ndJsonStream(z,J),Y,W=new f.AgentSideConnection((Q)=>{return Y=new zz(Q),Y},Z),H=zJ(async()=>{await Y?.destroy()});try{await W.closed}finally{H(),await Y?.destroy()}}export{GZ as runAcpIntegration,T as createLocalAcpSessionRoots};
|