blade-code 0.10.131 → 0.10.133
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-7n268v68.js → chunk-00zazdct.js} +2 -2
- package/dist/chunk-04yas0t8.js +1 -0
- package/dist/{chunk-a7gyy1wb.js → chunk-0ap8b3sw.js} +1 -1
- package/dist/{chunk-tkydv9k8.js → chunk-0d440hhe.js} +1 -1
- package/dist/{chunk-hrjjhm84.js → chunk-0xph7bhe.js} +2 -2
- package/dist/{chunk-aaxc81jc.js → chunk-1tfjaazq.js} +1 -1
- package/dist/{chunk-v52wc8yg.js → chunk-2242dshn.js} +1 -1
- package/dist/{chunk-p00f53yq.js → chunk-2nv0kg12.js} +1 -1
- package/dist/chunk-2nxev7f2.js +1 -0
- package/dist/{chunk-6p6ts4kv.js → chunk-2qyh6qhb.js} +1 -1
- package/dist/{chunk-jkfkyedn.js → chunk-3csj18f1.js} +1 -1
- package/dist/{chunk-z03dtyh6.js → chunk-3ndwbb7h.js} +1 -1
- package/dist/chunk-43a0n5rw.js +1 -0
- package/dist/{chunk-853cgxwv.js → chunk-4xhawy0e.js} +1 -1
- package/dist/{chunk-c1w7e6c2.js → chunk-555ffyze.js} +1 -1
- package/dist/{chunk-sfe4810k.js → chunk-5x3h9ak8.js} +1 -1
- package/dist/{chunk-sj1dzeta.js → chunk-679b7s58.js} +1 -1
- package/dist/chunk-78wwep9f.js +1 -0
- package/dist/{chunk-7wbah1y5.js → chunk-7hxyxv4x.js} +2 -2
- package/dist/{chunk-edtxcqxa.js → chunk-7j628q12.js} +1 -1
- package/dist/chunk-7zvwfz85.js +2 -0
- package/dist/{chunk-mvm1rzc4.js → chunk-87ycd3f8.js} +2 -2
- package/dist/{chunk-9ph0t3h8.js → chunk-88jmtcv7.js} +2 -2
- package/dist/{chunk-2y1qngw7.js → chunk-8xem2mzy.js} +1 -1
- package/dist/{chunk-zwjrensv.js → chunk-961nemng.js} +1 -1
- package/dist/{chunk-ar5np5h5.js → chunk-ar3sdj0w.js} +2 -2
- package/dist/chunk-avf9spct.js +1 -0
- package/dist/chunk-azv25dg2.js +10 -0
- package/dist/chunk-b8c1vj8c.js +1 -0
- package/dist/chunk-bbw6s542.js +1 -0
- package/dist/{chunk-44jtpg8y.js → chunk-be2csw9m.js} +1 -1
- package/dist/{chunk-tndrbmk1.js → chunk-bj8cgfbr.js} +1 -1
- package/dist/{chunk-c3qmbrjj.js → chunk-bzp08nf6.js} +1 -1
- package/dist/{chunk-a60cmnmz.js → chunk-cfamqqgv.js} +2 -2
- package/dist/{chunk-637yvyry.js → chunk-cz9mqkn2.js} +1 -1
- package/dist/{chunk-gmqpfm52.js → chunk-d881py5y.js} +2 -2
- package/dist/chunk-dnt4c3gy.js +2 -0
- package/dist/{chunk-g59kv3v3.js → chunk-e1q1hvty.js} +1 -1
- package/dist/chunk-eetva9y8.js +1 -0
- package/dist/{chunk-dnsb80qt.js → chunk-f1wnva76.js} +3 -3
- package/dist/{chunk-g0ra6hge.js → chunk-f4pn5tmr.js} +1 -1
- package/dist/{chunk-pj69j4zp.js → chunk-fjvt9mwv.js} +1 -1
- package/dist/{chunk-dw22ns89.js → chunk-gv24cgpb.js} +3 -3
- package/dist/{chunk-gfbkrk60.js → chunk-h123tjsg.js} +35 -35
- package/dist/{chunk-grhsv55v.js → chunk-h6tr3zz7.js} +1 -1
- package/dist/{chunk-rwnfvbdh.js → chunk-jy61b0v8.js} +2 -2
- package/dist/chunk-kjjpn49y.js +1 -0
- package/dist/{chunk-h9wzvtmy.js → chunk-ks67gd2j.js} +1 -1
- package/dist/chunk-kx61g7xw.js +1 -0
- package/dist/chunk-m30sbsnw.js +1 -0
- package/dist/{chunk-wj44fpe7.js → chunk-mkvqtawj.js} +2 -2
- package/dist/{chunk-5nssnxbd.js → chunk-ms360ds6.js} +2 -2
- package/dist/chunk-n589jxsm.js +1 -0
- package/dist/{chunk-dbddc52r.js → chunk-n7pydthh.js} +2 -2
- package/dist/{chunk-9gs4eqt8.js → chunk-ndgdf5jx.js} +1 -1
- package/dist/{chunk-93x9xbew.js → chunk-nfdfthhb.js} +1 -1
- package/dist/chunk-nry7d26k.js +2 -0
- package/dist/{chunk-25wwj0qb.js → chunk-nyk5q71k.js} +1 -1
- package/dist/{chunk-580dwa0h.js → chunk-p8y5kk56.js} +1 -1
- package/dist/{chunk-xdf4m44y.js → chunk-py92cy57.js} +1 -1
- package/dist/{chunk-mdew58v9.js → chunk-r4bgsfj6.js} +1 -1
- package/dist/{chunk-dfjmvj3d.js → chunk-rcthrb7h.js} +2 -2
- package/dist/{chunk-ajsw4te2.js → chunk-rkjrft19.js} +2 -2
- package/dist/{chunk-qcvxff27.js → chunk-rmm7n9n3.js} +2 -2
- package/dist/chunk-sr9gqacp.js +1 -0
- package/dist/{chunk-2bnpn8be.js → chunk-sxqydew5.js} +1 -1
- package/dist/{chunk-39d95twk.js → chunk-t52v91dy.js} +1 -1
- package/dist/chunk-v7zt3pft.js +171 -0
- package/dist/{chunk-zkzhm39s.js → chunk-w3y69e4e.js} +1 -1
- package/dist/{chunk-j15db2db.js → chunk-x1w3fvhr.js} +2 -2
- package/dist/{chunk-k2e4yjsk.js → chunk-xgz1yanb.js} +1 -1
- package/dist/{chunk-g4xny949.js → chunk-yvk8w63g.js} +1 -1
- package/dist/{chunk-sx77dpxw.js → chunk-z5mm9g1y.js} +1 -1
- package/dist/web/assets/{ChatView-CkmlibKO.js → ChatView-hYd9mmJ6.js} +4 -4
- package/dist/web/assets/{CodeBlockHighlighter-DR5RLA1_.js → CodeBlockHighlighter-D0yM8QTf.js} +1 -1
- package/dist/web/assets/{FilePreview-C4tqzUOM.js → FilePreview-CaTCjV5i.js} +1 -1
- package/dist/web/assets/{KanbanBoard-D7HJQXE2.js → KanbanBoard-BY0SXCol.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-Ct8vtONO.js → MarkdownRenderer-zKto-Pty.js} +3 -3
- package/dist/web/assets/{ScrollArea-CMSE6nO4.js → ScrollArea-1qPJ8lcT.js} +1 -1
- package/dist/web/assets/{SessionHistorySurface-BPwnF9ND.js → SessionHistorySurface-Ce9xX62q.js} +1 -1
- package/dist/web/assets/{SettingsModal-KW5WYAov.js → SettingsModal-BxKOMuIm.js} +1 -1
- package/dist/web/assets/{Sidebar-8BUNEHHQ.js → Sidebar-CEF6lGps.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-CZfkp2L_.js → TaskSwitcher-C-EY0nVG.js} +1 -1
- package/dist/web/assets/{TerminalPanel-DBBMaU_6.js → TerminalPanel-C3PVDyAr.js} +1 -1
- package/dist/web/assets/{archive-tBd5snSF.js → archive-D5Nuw__Q.js} +1 -1
- package/dist/web/assets/{arrow-left-Cs_sFMp-.js → arrow-left-DaOpfgEz.js} +1 -1
- package/dist/web/assets/{calendar-clock-C0ue6XTy.js → calendar-clock-DA_D4ppV.js} +1 -1
- package/dist/web/assets/{chevron-right-DZHCUfAH.js → chevron-right-COQAoZf3.js} +1 -1
- package/dist/web/assets/{chevrons-up-down-BSa16Scz.js → chevrons-up-down-B_WSFixv.js} +1 -1
- package/dist/web/assets/{clock-3-DstAM2AR.js → clock-3-DJ-pSj3t.js} +1 -1
- package/dist/web/assets/{copy-BfnFXTgG.js → copy-5c0ESKoo.js} +1 -1
- package/dist/web/assets/{download-XKyNtMnj.js → download-VkaTciEH.js} +1 -1
- package/dist/web/assets/{external-link-3bcWFMya.js → external-link-BypdqupZ.js} +1 -1
- package/dist/web/assets/{folder-D7hQLvy7.js → folder-B8znObPL.js} +1 -1
- package/dist/web/assets/{index-CCdnLriX.js → index-DorkRCqS.js} +12 -12
- package/dist/web/assets/{pause-CBR55GXy.js → pause-BWbHHYG6.js} +1 -1
- package/dist/web/assets/{pencil-8yqeFHC4.js → pencil-BPyvvR59.js} +1 -1
- package/dist/web/assets/{play-F_Spkp4p.js → play-CLJgUH4S.js} +1 -1
- package/dist/web/assets/{plus-CJCqq3rG.js → plus-D1VVvu-z.js} +1 -1
- package/dist/web/assets/{settings-G6riyt4S.js → settings-CGCgC_NX.js} +1 -1
- package/dist/web/assets/{teamService-Cixkq48S.js → teamService-DsYRmp6u.js} +1 -1
- package/dist/web/assets/{terminal-_Nebc2yj.js → terminal-pA96HZrI.js} +1 -1
- package/dist/web/index.html +1 -1
- package/package.json +2 -2
- package/dist/chunk-0z9nqbd0.js +0 -2
- package/dist/chunk-5nv95djf.js +0 -10
- package/dist/chunk-92fmzgzv.js +0 -1
- package/dist/chunk-9s8saznq.js +0 -1
- package/dist/chunk-af3qm97y.js +0 -1
- package/dist/chunk-cz0n951t.js +0 -1
- package/dist/chunk-f8gb685p.js +0 -2
- package/dist/chunk-kd3k1q9z.js +0 -1
- package/dist/chunk-m9mw8ppy.js +0 -1
- package/dist/chunk-ntdwkenx.js +0 -170
- package/dist/chunk-p9fs659w.js +0 -1
- package/dist/chunk-rd7b9tye.js +0 -1
- package/dist/chunk-rspcywmd.js +0 -2
- package/dist/chunk-s3f85gtm.js +0 -1
- package/dist/chunk-svkdrxk9.js +0 -1
- package/dist/chunk-v9qf59dy.js +0 -1
- package/dist/chunk-xrheg6xr.js +0 -1
- package/dist/chunk-ybwfm7yp.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{
|
|
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
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
3
|
|
|
4
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
|
|
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};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{Kj as C,Lj as I}from"./chunk-zwjrensv.js";import{Mj as _}from"./chunk-pj69j4zp.js";import{createHash as S}from"node:crypto";import{constants as A,promises as B}from"node:fs";import N from"node:os";import F from"node:path";import{Mutex as w}from"async-mutex";import{LRUCache as k}from"lru-cache";import E from"write-file-atomic";var X=1,j=65536,T=1048576,z=100,R=64;function t(q){return q.state==="trusted"||q.state==="not_required"}function K(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)}function V(q,Q=2048){return q.length<=Q?q:`${q.slice(0,Q-1)}…`}function M(q){if(typeof q!=="string"||!q.trim())return;try{let Q=new URL(q);return V(`${Q.origin}${Q.pathname}`)}catch{return V(q)}}function D(q){return Array.isArray(q)?q.filter((Q)=>typeof Q==="string"):[]}function m(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.type==="string"?$.type:"unknown",G=typeof $.command==="string"?$.command:void 0,J=D($.args),L=H==="stdio"?V([G,...J].filter(Boolean).join(" ")):M($.url);return{kind:"mcp",name:`${Q} (${H})`,...L?{target:L}:{}}})}function g(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.command==="string"?V($.command):void 0,G=K($.extensionToLanguage)?Object.keys($.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${Q} (${G})`,...H?{target:H}:{}}})}function P(q){if(!Array.isArray(q))return[];return q.slice(0,z).flatMap((Q)=>{if(!K(Q))return[];let Z=typeof Q.id==="string"?Q.id:"unnamed",$=typeof Q.provider==="string"?Q.provider:"unknown",H=typeof Q.model==="string"?Q.model:"unknown",G=K(Q.overrides)?Q.overrides:{},J=M(G.baseUrl);return[{kind:"model",name:`${Z}: ${$}/${H}`,...J?{target:J}:{}}]})}function y(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.wireApi==="string"?$.wireApi:"unknown",G=M($.baseUrl);return{kind:"model",name:`${Q} (${H})`,...G?{target:G}:{}}})}function f(q){if(!K(q))return[];let Q=[];for(let Z of["allow","ask","deny"])for(let $ of D(q[Z]).slice(0,z))Q.push({kind:"permission",name:`${Z}: ${V($,512)}`});return Q}function h(q){let Q=[...m(q.mcpServers),...g(q.lspServers),...P(q.models),...y(q.modelProviders),...f(q.permissions)];if(K(q.env))for(let Z of Object.keys(q.env).slice(0,z))Q.push({kind:"environment",name:Z});if(typeof q.permissionMode==="string")Q.push({kind:"permission",name:`permissionMode: ${q.permissionMode}`});return Q}function v(q){return q!=="hooks"&&q!=="disableAllHooks"}function l(q){return S("sha256").update(q).digest("hex")}function p(q,Q){let Z=F.relative(q,Q);return Z===""||!Z.startsWith(`..${F.sep}`)&&Z!==".."&&!F.isAbsolute(Z)}class x{storeDir;static instance=null;mutex=new w;statusCache=new k({max:R});constructor(q=F.join(_(),"workspace-trust")){this.storeDir=q}static getInstance(){if(!x.instance)x.instance=new x;return x.instance}static resetInstance(){x.instance=null}async getStatus(q){let Q=await C(q),Z;try{Z=await this.discoverSensitiveSources(Q.projectPath)}catch(Y){let O={...Q,state:"error",sensitiveSources:0,sources:[],decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust review failed"};return this.cacheStatus(q,O),O}if(Z.length===0){let Y={...Q,state:"not_required",sensitiveSources:0,sources:Z,decision:"undecided"};return this.cacheStatus(q,Y),Y}let $;try{$=await this.readDecisions()}catch(Y){let O={...Q,state:"error",sensitiveSources:Z.length,sources:Z,decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust store is unavailable"};return this.cacheStatus(q,O),O}let H=$.filter((Y)=>p(Y.path,Q.trustRoot)),G=Math.max(-1,...H.map((Y)=>Y.path.split(F.sep).length)),J=H.filter((Y)=>Y.path.split(F.sep).length===G),L=J.length>0&&J.every((Y)=>Y.trusted),U=J[0],b=U?.path===Q.trustRoot,W={...Q,state:L?"trusted":"untrusted",sensitiveSources:Z.length,sources:Z,decision:U?b?U.trusted?"trusted":"untrusted":"inherited":"undecided",...U?.decidedAt?{decidedAt:U.decidedAt}:{},...!b&&U?.path?{inheritedFrom:U.path}:{}};return this.cacheStatus(q,W),W}cacheStatus(q,Q){this.statusCache.set(F.resolve(q),Q),this.statusCache.set(Q.projectPath,Q)}getCachedStatus(q){return this.statusCache.get(F.resolve(q))}isTrustedCached(q){return this.getCachedStatus(q)?.state==="trusted"}getCacheStats(){return{capacity:R,entries:this.statusCache.size}}async trust(q){return this.recordDecision(q,!0)}async revoke(q){return this.recordDecision(q,!1)}async recordDecision(q,Q){return this.mutex.runExclusive(async()=>{await I(q);let Z=await C(q);await this.assertSafeTrustRoot(Z);let $={version:X,path:Z.trustRoot,trusted:Q,decidedAt:new Date().toISOString()};return await this.writeDecision($),this.statusCache.clear(),this.getStatus(q)})}async assertSafeTrustRoot(q){let Q=F.parse(q.trustRoot).root,Z=await B.realpath(N.homedir()).catch(()=>F.resolve(N.homedir()));if(!F.isAbsolute(q.trustRoot)||q.trustRoot===Q||q.trustRoot===Z)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(q){let Q=[],Z=await this.reviewPackageScripts(q);if(Z)Q.push(Z);for(let[$,H]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let G=await this.reviewConfigFile(q,$,H);if(G)Q.push(G)}for(let $ of[".blade/plugins",".claude/plugins"]){let H=await this.reviewResourceDirectory(q,$,"plugins","plugin");if(H)Q.push(H)}for(let $ of[".blade/commands",".claude/commands"]){let H=await this.reviewResourceDirectory(q,$,"commands","command");if(H)Q.push(H)}for(let[$,H,G]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let J=await this.reviewResourceDirectory(q,$,H,G);if(J)Q.push(J)}for(let $ of["CLAUDE.md","AGENTS.md","BLADE.md"]){let H=await this.reviewInstructionFile(q,$);if(H)Q.push(H)}return Q}async reviewPackageScripts(q){let Q=F.join(q,"package.json"),Z;try{Z=await B.stat(Q)}catch(J){if(J.code==="ENOENT")return;throw J}if(!Z.isFile())return;if(Z.size>T)throw Error("package.json exceeds the 1 MiB workspace review limit");let $;try{$=JSON.parse(await B.readFile(Q,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!K($)||!K($.scripts))return;let H=$.scripts,G=Object.keys(H).filter((J)=>typeof H[J]==="string").sort().slice(0,z);if(G.length===0)return;return{path:"package.json",kind:"package",keys:G,effects:G.map((J)=>({kind:"command",name:`package script: ${J}`}))}}async reviewInstructionFile(q,Q){try{if(!(await B.stat(F.join(q,Q))).isFile())return}catch(Z){if(Z.code==="ENOENT")return;throw Z}return{path:Q,kind:"instructions",keys:[Q],effects:[{kind:"instruction",name:Q}]}}async reviewConfigFile(q,Q,Z){let $=F.join(q,Q),H;try{H=await B.stat($)}catch(b){if(b.code==="ENOENT")return;throw b}if(!H.isFile())return;if(H.size>T)throw Error(`${Q} exceeds the 1 MiB workspace review limit`);let G;try{G=JSON.parse(await B.readFile($,"utf8"))}catch{return{path:Q,kind:Z,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!K(G))return{path:Q,kind:Z,keys:[],effects:[],warning:"Configuration root is not an object"};let J=Object.keys(G).filter(v).sort();if(J.length===0)return;let L=h(G),U=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let b of J)if(!U.has(b))L.push({kind:"configuration",name:b});return{path:Q,kind:Z,keys:J,effects:L}}async reviewResourceDirectory(q,Q,Z,$){let H=F.join(q,Q),G;try{G=await B.readdir(H,{withFileTypes:!0})}catch(L){if(L.code==="ENOENT")return;throw L}let J=G.filter((L)=>Z==="plugins"||Z==="skills"?L.isDirectory()||L.isSymbolicLink():L.isFile()||L.isDirectory()||L.isSymbolicLink()).slice(0,z);if(J.length===0)return;return{path:Q,kind:Z,keys:J.map((L)=>L.name),effects:J.map((L)=>({kind:$,name:L.name}))}}async readDecisions(){let q;try{q=await B.lstat(this.storeDir)}catch($){if($.code==="ENOENT")return[];throw $}if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let Q=await B.readdir(this.storeDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.name.endsWith(".json"))continue;if(!$.isFile())throw Error("Workspace trust store entries must be regular files");Z.push(await this.readDecision(F.join(this.storeDir,$.name)))}return Z}async readDecision(q){let Q;try{Q=await B.open(q,A.O_RDONLY|A.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let Z=await Q.stat();if(!Z.isFile()||Z.size>j)throw Error("Workspace trust decision is invalid");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let $=JSON.parse(await Q.readFile("utf8"));if(!K($)||$.version!==X||typeof $.path!=="string"||!F.isAbsolute($.path)||typeof $.trusted!=="boolean"||typeof $.decidedAt!=="string"||!Number.isFinite(Date.parse($.decidedAt))||Object.keys($).some((H)=>H!=="version"&&H!=="path"&&H!=="trusted"&&H!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:X,path:$.path,trusted:$.trusted,decidedAt:$.decidedAt}}finally{await Q.close()}}async writeDecision(q){await this.ensureStoreDirectoryForWrite();let Q=F.join(this.storeDir,`${l(q.path)}.json`);try{let Z=await B.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(Z){if(Z.code!=="ENOENT")throw Z}await E(Q,`${JSON.stringify(q,null,2)}
|
|
1
|
+
import{Lj as C,Mj as I}from"./chunk-961nemng.js";import{Nj as _}from"./chunk-fjvt9mwv.js";import{createHash as S}from"node:crypto";import{constants as A,promises as B}from"node:fs";import N from"node:os";import F from"node:path";import{Mutex as w}from"async-mutex";import{LRUCache as k}from"lru-cache";import E from"write-file-atomic";var X=1,j=65536,T=1048576,z=100,R=64;function t(q){return q.state==="trusted"||q.state==="not_required"}function K(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)}function V(q,Q=2048){return q.length<=Q?q:`${q.slice(0,Q-1)}…`}function M(q){if(typeof q!=="string"||!q.trim())return;try{let Q=new URL(q);return V(`${Q.origin}${Q.pathname}`)}catch{return V(q)}}function D(q){return Array.isArray(q)?q.filter((Q)=>typeof Q==="string"):[]}function m(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.type==="string"?$.type:"unknown",G=typeof $.command==="string"?$.command:void 0,J=D($.args),L=H==="stdio"?V([G,...J].filter(Boolean).join(" ")):M($.url);return{kind:"mcp",name:`${Q} (${H})`,...L?{target:L}:{}}})}function g(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.command==="string"?V($.command):void 0,G=K($.extensionToLanguage)?Object.keys($.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${Q} (${G})`,...H?{target:H}:{}}})}function P(q){if(!Array.isArray(q))return[];return q.slice(0,z).flatMap((Q)=>{if(!K(Q))return[];let Z=typeof Q.id==="string"?Q.id:"unnamed",$=typeof Q.provider==="string"?Q.provider:"unknown",H=typeof Q.model==="string"?Q.model:"unknown",G=K(Q.overrides)?Q.overrides:{},J=M(G.baseUrl);return[{kind:"model",name:`${Z}: ${$}/${H}`,...J?{target:J}:{}}]})}function y(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.wireApi==="string"?$.wireApi:"unknown",G=M($.baseUrl);return{kind:"model",name:`${Q} (${H})`,...G?{target:G}:{}}})}function f(q){if(!K(q))return[];let Q=[];for(let Z of["allow","ask","deny"])for(let $ of D(q[Z]).slice(0,z))Q.push({kind:"permission",name:`${Z}: ${V($,512)}`});return Q}function h(q){let Q=[...m(q.mcpServers),...g(q.lspServers),...P(q.models),...y(q.modelProviders),...f(q.permissions)];if(K(q.env))for(let Z of Object.keys(q.env).slice(0,z))Q.push({kind:"environment",name:Z});if(typeof q.permissionMode==="string")Q.push({kind:"permission",name:`permissionMode: ${q.permissionMode}`});return Q}function v(q){return q!=="hooks"&&q!=="disableAllHooks"}function l(q){return S("sha256").update(q).digest("hex")}function p(q,Q){let Z=F.relative(q,Q);return Z===""||!Z.startsWith(`..${F.sep}`)&&Z!==".."&&!F.isAbsolute(Z)}class x{storeDir;static instance=null;mutex=new w;statusCache=new k({max:R});constructor(q=F.join(_(),"workspace-trust")){this.storeDir=q}static getInstance(){if(!x.instance)x.instance=new x;return x.instance}static resetInstance(){x.instance=null}async getStatus(q){let Q=await C(q),Z;try{Z=await this.discoverSensitiveSources(Q.projectPath)}catch(Y){let O={...Q,state:"error",sensitiveSources:0,sources:[],decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust review failed"};return this.cacheStatus(q,O),O}if(Z.length===0){let Y={...Q,state:"not_required",sensitiveSources:0,sources:Z,decision:"undecided"};return this.cacheStatus(q,Y),Y}let $;try{$=await this.readDecisions()}catch(Y){let O={...Q,state:"error",sensitiveSources:Z.length,sources:Z,decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust store is unavailable"};return this.cacheStatus(q,O),O}let H=$.filter((Y)=>p(Y.path,Q.trustRoot)),G=Math.max(-1,...H.map((Y)=>Y.path.split(F.sep).length)),J=H.filter((Y)=>Y.path.split(F.sep).length===G),L=J.length>0&&J.every((Y)=>Y.trusted),U=J[0],b=U?.path===Q.trustRoot,W={...Q,state:L?"trusted":"untrusted",sensitiveSources:Z.length,sources:Z,decision:U?b?U.trusted?"trusted":"untrusted":"inherited":"undecided",...U?.decidedAt?{decidedAt:U.decidedAt}:{},...!b&&U?.path?{inheritedFrom:U.path}:{}};return this.cacheStatus(q,W),W}cacheStatus(q,Q){this.statusCache.set(F.resolve(q),Q),this.statusCache.set(Q.projectPath,Q)}getCachedStatus(q){return this.statusCache.get(F.resolve(q))}isTrustedCached(q){return this.getCachedStatus(q)?.state==="trusted"}getCacheStats(){return{capacity:R,entries:this.statusCache.size}}async trust(q){return this.recordDecision(q,!0)}async revoke(q){return this.recordDecision(q,!1)}async recordDecision(q,Q){return this.mutex.runExclusive(async()=>{await I(q);let Z=await C(q);await this.assertSafeTrustRoot(Z);let $={version:X,path:Z.trustRoot,trusted:Q,decidedAt:new Date().toISOString()};return await this.writeDecision($),this.statusCache.clear(),this.getStatus(q)})}async assertSafeTrustRoot(q){let Q=F.parse(q.trustRoot).root,Z=await B.realpath(N.homedir()).catch(()=>F.resolve(N.homedir()));if(!F.isAbsolute(q.trustRoot)||q.trustRoot===Q||q.trustRoot===Z)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(q){let Q=[],Z=await this.reviewPackageScripts(q);if(Z)Q.push(Z);for(let[$,H]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let G=await this.reviewConfigFile(q,$,H);if(G)Q.push(G)}for(let $ of[".blade/plugins",".claude/plugins"]){let H=await this.reviewResourceDirectory(q,$,"plugins","plugin");if(H)Q.push(H)}for(let $ of[".blade/commands",".claude/commands"]){let H=await this.reviewResourceDirectory(q,$,"commands","command");if(H)Q.push(H)}for(let[$,H,G]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let J=await this.reviewResourceDirectory(q,$,H,G);if(J)Q.push(J)}for(let $ of["CLAUDE.md","AGENTS.md","BLADE.md"]){let H=await this.reviewInstructionFile(q,$);if(H)Q.push(H)}return Q}async reviewPackageScripts(q){let Q=F.join(q,"package.json"),Z;try{Z=await B.stat(Q)}catch(J){if(J.code==="ENOENT")return;throw J}if(!Z.isFile())return;if(Z.size>T)throw Error("package.json exceeds the 1 MiB workspace review limit");let $;try{$=JSON.parse(await B.readFile(Q,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!K($)||!K($.scripts))return;let H=$.scripts,G=Object.keys(H).filter((J)=>typeof H[J]==="string").sort().slice(0,z);if(G.length===0)return;return{path:"package.json",kind:"package",keys:G,effects:G.map((J)=>({kind:"command",name:`package script: ${J}`}))}}async reviewInstructionFile(q,Q){try{if(!(await B.stat(F.join(q,Q))).isFile())return}catch(Z){if(Z.code==="ENOENT")return;throw Z}return{path:Q,kind:"instructions",keys:[Q],effects:[{kind:"instruction",name:Q}]}}async reviewConfigFile(q,Q,Z){let $=F.join(q,Q),H;try{H=await B.stat($)}catch(b){if(b.code==="ENOENT")return;throw b}if(!H.isFile())return;if(H.size>T)throw Error(`${Q} exceeds the 1 MiB workspace review limit`);let G;try{G=JSON.parse(await B.readFile($,"utf8"))}catch{return{path:Q,kind:Z,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!K(G))return{path:Q,kind:Z,keys:[],effects:[],warning:"Configuration root is not an object"};let J=Object.keys(G).filter(v).sort();if(J.length===0)return;let L=h(G),U=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let b of J)if(!U.has(b))L.push({kind:"configuration",name:b});return{path:Q,kind:Z,keys:J,effects:L}}async reviewResourceDirectory(q,Q,Z,$){let H=F.join(q,Q),G;try{G=await B.readdir(H,{withFileTypes:!0})}catch(L){if(L.code==="ENOENT")return;throw L}let J=G.filter((L)=>Z==="plugins"||Z==="skills"?L.isDirectory()||L.isSymbolicLink():L.isFile()||L.isDirectory()||L.isSymbolicLink()).slice(0,z);if(J.length===0)return;return{path:Q,kind:Z,keys:J.map((L)=>L.name),effects:J.map((L)=>({kind:$,name:L.name}))}}async readDecisions(){let q;try{q=await B.lstat(this.storeDir)}catch($){if($.code==="ENOENT")return[];throw $}if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let Q=await B.readdir(this.storeDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.name.endsWith(".json"))continue;if(!$.isFile())throw Error("Workspace trust store entries must be regular files");Z.push(await this.readDecision(F.join(this.storeDir,$.name)))}return Z}async readDecision(q){let Q;try{Q=await B.open(q,A.O_RDONLY|A.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let Z=await Q.stat();if(!Z.isFile()||Z.size>j)throw Error("Workspace trust decision is invalid");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let $=JSON.parse(await Q.readFile("utf8"));if(!K($)||$.version!==X||typeof $.path!=="string"||!F.isAbsolute($.path)||typeof $.trusted!=="boolean"||typeof $.decidedAt!=="string"||!Number.isFinite(Date.parse($.decidedAt))||Object.keys($).some((H)=>H!=="version"&&H!=="path"&&H!=="trusted"&&H!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:X,path:$.path,trusted:$.trusted,decidedAt:$.decidedAt}}finally{await Q.close()}}async writeDecision(q){await this.ensureStoreDirectoryForWrite();let Q=F.join(this.storeDir,`${l(q.path)}.json`);try{let Z=await B.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(Z){if(Z.code!=="ENOENT")throw Z}await E(Q,`${JSON.stringify(q,null,2)}
|
|
2
2
|
`,{mode:384}),await B.chmod(Q,384)}async ensureStoreDirectoryForWrite(){try{let q=await B.lstat(this.storeDir);if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700")}catch(q){if(q.code!=="ENOENT")throw q;await B.mkdir(this.storeDir,{recursive:!0,mode:448}),await B.chmod(this.storeDir,448)}}}
|
|
3
|
-
export{R as
|
|
3
|
+
export{R as Ij,t as Jj,x as Kj};
|
|
@@ -0,0 +1 @@
|
|
|
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};
|
|
@@ -1 +1 @@
|
|
|
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-
|
|
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};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{v as tz,w as ez}from"./chunk-
|
|
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
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
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
4
|
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
|