blade-code 0.10.124 → 0.10.125
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-wvq95qx6.js → chunk-0gmzs677.js} +1 -1
- package/dist/{chunk-fneerm4v.js → chunk-15va76vr.js} +1 -1
- package/dist/{chunk-3jqd18d8.js → chunk-1b2dkwpv.js} +1 -1
- package/dist/{chunk-ncqagb27.js → chunk-1g0d9yw0.js} +2 -2
- package/dist/chunk-2j2mnzdg.js +2 -0
- package/dist/{chunk-nz4a0mep.js → chunk-2naedw9h.js} +1 -1
- package/dist/{chunk-nq0w1j1a.js → chunk-2xezz3nt.js} +1 -1
- package/dist/{chunk-tg54jbta.js → chunk-359xeryx.js} +1 -1
- package/dist/{chunk-rgqxy1j1.js → chunk-37hmsd3h.js} +1 -1
- package/dist/chunk-48btnfa3.js +1 -0
- package/dist/{chunk-62c3707d.js → chunk-4s1eaeek.js} +1 -1
- package/dist/{chunk-2zewxt27.js → chunk-4vvpbrrf.js} +1 -1
- package/dist/chunk-54f7t2g3.js +1 -0
- package/dist/{chunk-p89wgwn0.js → chunk-5cqr7d6w.js} +2 -2
- package/dist/{chunk-w4xqaw4h.js → chunk-68sf54n4.js} +2 -2
- package/dist/{chunk-207s8tns.js → chunk-6kwg4hcv.js} +1 -1
- package/dist/{chunk-kpqdfn9z.js → chunk-7n7swtwg.js} +1 -1
- package/dist/chunk-7sfhnmkv.js +1 -0
- package/dist/chunk-7td3f2hm.js +1 -0
- package/dist/{chunk-5kg2kvbw.js → chunk-827422x9.js} +2 -2
- package/dist/{chunk-anjpwev3.js → chunk-8zftskf2.js} +1 -1
- package/dist/chunk-90fwjr48.js +1 -0
- package/dist/{chunk-dcy8s8rz.js → chunk-9hm3hy8d.js} +1 -1
- package/dist/chunk-9rj1may5.js +1 -0
- package/dist/{chunk-spxb931p.js → chunk-9xzw649r.js} +2 -2
- package/dist/chunk-afadq5w7.js +1 -0
- package/dist/chunk-ax0q681y.js +1 -0
- package/dist/{chunk-sn0cv7vd.js → chunk-bey4af86.js} +1 -1
- package/dist/{chunk-9fgkg1vr.js → chunk-cw2b3383.js} +1 -1
- package/dist/{chunk-b41den40.js → chunk-dh03cybw.js} +1 -1
- package/dist/chunk-dm1yxsdx.js +44 -0
- package/dist/{chunk-07gqhhfd.js → chunk-dwnysndf.js} +1 -1
- package/dist/{chunk-8nsv9gpn.js → chunk-dxhga3ag.js} +1 -1
- package/dist/chunk-fyhks83r.js +1 -0
- package/dist/{chunk-hgrdsef7.js → chunk-g2jx4y8f.js} +1 -1
- package/dist/{chunk-e7va75fw.js → chunk-g391y5wf.js} +1 -1
- package/dist/{chunk-9jtjq50j.js → chunk-hbafhk9y.js} +1 -1
- package/dist/{chunk-c4aeejq1.js → chunk-hhnfd5xm.js} +1 -1
- package/dist/{chunk-m7b779kd.js → chunk-hmwz31tc.js} +1 -1
- package/dist/chunk-k0d7eqd9.js +6 -0
- package/dist/chunk-k952hgkh.js +1 -0
- package/dist/{chunk-ne9dyvcc.js → chunk-m6pnnjq4.js} +2 -2
- package/dist/{chunk-9fntcgem.js → chunk-mqm3mbmv.js} +1 -1
- package/dist/chunk-mzxwhhnc.js +1 -0
- package/dist/{chunk-4a79dppv.js → chunk-n3km6ncq.js} +1 -1
- package/dist/chunk-nrz53vjn.js +1 -0
- package/dist/chunk-nym7zz07.js +8 -0
- package/dist/{chunk-twdfyk78.js → chunk-pezzyyyk.js} +1 -1
- package/dist/{chunk-1eq5phqv.js → chunk-qprvj0mv.js} +1 -1
- package/dist/{chunk-1kbx9es5.js → chunk-rcstr6sb.js} +2 -2
- package/dist/{chunk-32z8gkex.js → chunk-rvg14b78.js} +1 -1
- package/dist/{chunk-kzzty3v5.js → chunk-s6562rsq.js} +1 -1
- package/dist/{chunk-r6svhe3w.js → chunk-sv833k2e.js} +2 -2
- package/dist/{chunk-6bvc4z1c.js → chunk-sw0g5xy1.js} +3 -3
- package/dist/{chunk-v1cmz2bw.js → chunk-tqjrt537.js} +1 -1
- package/dist/{chunk-a4dmw23t.js → chunk-w7n73ag8.js} +1 -1
- package/dist/{chunk-apssk1cy.js → chunk-xdvn6yrd.js} +1 -1
- package/dist/{chunk-4x0xm63t.js → chunk-xf47kpaq.js} +1 -1
- package/dist/{chunk-7dykmcjj.js → chunk-xnbzrh8b.js} +1 -1
- package/dist/{chunk-3jdt8kqf.js → chunk-xvn80fge.js} +1 -1
- package/dist/{chunk-0hf6dd5w.js → chunk-xz5s5ayj.js} +1 -1
- package/dist/{chunk-kz15jy62.js → chunk-y94239bb.js} +1 -1
- package/dist/{chunk-fpjhg6ce.js → chunk-z1zr4wts.js} +1 -1
- package/dist/chunk-zfm5e5h2.js +10 -0
- package/dist/{chunk-dabq8kdx.js → chunk-zm2bbagg.js} +1 -1
- package/dist/{chunk-m2ak1nky.js → chunk-zyj91sa5.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-0t5hvj49.js +0 -1
- package/dist/chunk-2824tzwn.js +0 -44
- package/dist/chunk-43dg28ph.js +0 -1
- package/dist/chunk-5nban6rq.js +0 -1
- package/dist/chunk-90v9qj85.js +0 -8
- package/dist/chunk-a6nz99qf.js +0 -1
- package/dist/chunk-javj7p2j.js +0 -1
- package/dist/chunk-jdjmr823.js +0 -1
- package/dist/chunk-me93hkqv.js +0 -10
- package/dist/chunk-mtmg3cxy.js +0 -1
- package/dist/chunk-p7k7hqtb.js +0 -1
- package/dist/chunk-pykxe413.js +0 -2
- package/dist/chunk-rkk31kq5.js +0 -1
- package/dist/chunk-sy0x18rq.js +0 -1
- package/dist/chunk-v6sfs4qf.js +0 -1
- package/dist/chunk-vjenmz1x.js +0 -1
- package/dist/chunk-w6cg2fnz.js +0 -6
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{gi as __,hi as mf,ii as qf,ji as T_,ki as Jf,mi as Wf,oi as If,qi as q,ri as Qf,ti as Df,ui as Kf,wi as s}from"./chunk-hbafhk9y.js";import{Ei as l}from"./chunk-68sf54n4.js";import{Ii as SE,Ki as jf}from"./chunk-sv833k2e.js";import{Ni as aE}from"./chunk-w7n73ag8.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)}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Bb as c,Fb as d,Gb as e,Hb as f,Ib as g,Jb as h,Kb as i,Lb as j,Mb as k,Tb as l,Ub as m,Vb as n,Wb as o,Yb as p,Zb as q,_b as r,yb as a,zb as b}from"./chunk-rcstr6sb.js";import"./chunk-sca5q3tt.js";import"./chunk-g391y5wf.js";import"./chunk-q265drks.js";import"./chunk-xnbzrh8b.js";import"./chunk-ye4wyq1k.js";import"./chunk-7n7swtwg.js";import"./chunk-8qp8v96d.js";import"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-m6pnnjq4.js";import"./chunk-2t6b962t.js";import"./chunk-y94239bb.js";import"./chunk-cw2b3383.js";import"./chunk-2j2mnzdg.js";import"./chunk-s6562rsq.js";import"./chunk-hbafhk9y.js";import"./chunk-68sf54n4.js";import"./chunk-sv833k2e.js";import"./chunk-w7n73ag8.js";import"./chunk-827422x9.js";import"./chunk-6kwg4hcv.js";import"./chunk-9xzw649r.js";import"./chunk-hmwz31tc.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{$e as m,Pe as a,Qe as b,Re as c,Se as d,Te as e,Ue as f,Ve as g,We as h,Xe as i,Ye as j,Ze as k,_e as l,af as n,bf as o,cf as p,df as q}from"./chunk-rvg14b78.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-dm1yxsdx.js";import"./chunk-y94239bb.js";import"./chunk-cw2b3383.js";import"./chunk-2j2mnzdg.js";import"./chunk-s6562rsq.js";import"./chunk-hbafhk9y.js";import"./chunk-68sf54n4.js";import"./chunk-sv833k2e.js";import"./chunk-w7n73ag8.js";import"./chunk-827422x9.js";import"./chunk-1g0d9yw0.js";import"./chunk-6kwg4hcv.js";import"./chunk-9xzw649r.js";import"./chunk-hmwz31tc.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.
|
|
2
|
-
export{y as
|
|
1
|
+
import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.125",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",playwright:"1.62.1","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(a(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(u(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function g(){return r().description}function f(){return`v${p()}`}function w(){return`v${p()} © 2025 Blade Code`}
|
|
2
|
+
export{y as Ri,p as Si,v as Ti,g as Ui,f as Vi,w as Wi};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ki as o}from"./chunk-sv833k2e.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
|
|
2
2
|
export{e,i as f};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b as i,c as l,d as m}from"./chunk-nym7zz07.js";import"./chunk-8zftskf2.js";import"./chunk-2xezz3nt.js";import"./chunk-bey4af86.js";import"./chunk-qprvj0mv.js";import"./chunk-359xeryx.js";import"./chunk-sw0g5xy1.js";import"./chunk-zm2bbagg.js";import"./chunk-15va76vr.js";import"./chunk-z1zr4wts.js";import"./chunk-rcstr6sb.js";import"./chunk-sca5q3tt.js";import"./chunk-g391y5wf.js";import"./chunk-q265drks.js";import"./chunk-xnbzrh8b.js";import{ze as n}from"./chunk-2naedw9h.js";import"./chunk-pezzyyyk.js";import{Ve as s}from"./chunk-rvg14b78.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-7n7swtwg.js";import"./chunk-dh03cybw.js";import"./chunk-8qp8v96d.js";import"./chunk-mqm3mbmv.js";import"./chunk-0gmzs677.js";import"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import"./chunk-m6pnnjq4.js";import"./chunk-2t6b962t.js";import"./chunk-dm1yxsdx.js";import"./chunk-y94239bb.js";import"./chunk-cw2b3383.js";import"./chunk-2j2mnzdg.js";import"./chunk-s6562rsq.js";import"./chunk-hbafhk9y.js";import"./chunk-68sf54n4.js";import"./chunk-sv833k2e.js";import"./chunk-w7n73ag8.js";import"./chunk-827422x9.js";import"./chunk-1g0d9yw0.js";import"./chunk-6kwg4hcv.js";import"./chunk-9xzw649r.js";import"./chunk-hmwz31tc.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Oa as V,Qa as W,Ra as O,hb as J}from"./chunk-
|
|
1
|
+
import{Oa as V,Qa as W,Ra as O,hb as J}from"./chunk-z1zr4wts.js";import"./chunk-cw2b3383.js";import"./chunk-2j2mnzdg.js";import{ci as Q}from"./chunk-s6562rsq.js";import"./chunk-68sf54n4.js";import"./chunk-9xzw649r.js";import"./chunk-hmwz31tc.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{qf as a}from"./chunk-7n7swtwg.js";import"./chunk-hbafhk9y.js";import"./chunk-68sf54n4.js";import"./chunk-sv833k2e.js";import"./chunk-w7n73ag8.js";import"./chunk-9xzw649r.js";import"./chunk-hmwz31tc.js";export{a as createChatServiceAsync};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{M as
|
|
1
|
+
import{kj as F}from"./chunk-hmwz31tc.js";import{execSync as G}from"node:child_process";import*as C from"node:os";import*as v from"node:path";function H(k){return v.resolve(k).replace(/[/\\]/g,"-").replace(/:/g,"_")}function M(k){let q=k.replace(/_/g,":");if(q.startsWith("-"))q="/"+q.slice(1);return q.replace(/-/g,"/")}function z(k){let q=H(k);return v.join(E(),"projects",q)}function J(k){return typeof k==="string"&&k!=="."&&k!==".."&&/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/.test(k)}function A(k){if(!J(k))throw Error(`Invalid session ID: ${k}`)}function N(k,q){return A(q),v.join(z(k),`${q}.jsonl`)}function O(k,q){return A(q),v.join(z(k),`${q}.inbox.json`)}function Q(k,q){return A(q),v.join(z(k),`${q}.goal.json`)}function T(k){try{return G("git rev-parse --abbrev-ref HEAD",{cwd:k,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function E(){return process.env.BLADE_STORAGE_ROOT||v.join(C.homedir(),".blade")}async function U(){let{readdir:k}=await import("node:fs/promises");try{let q=v.join(E(),"projects");return(await k(q,{withFileTypes:!0})).filter((w)=>w.isDirectory()).map((w)=>w.name)}catch{return[]}}
|
|
2
|
+
export{M as aj,z as bj,J as cj,A as dj,N as ej,O as fj,Q as gj,T as hj,E as ij,U as jj};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ue as a,ve as b,we as c}from"./chunk-k0d7eqd9.js";import"./chunk-1b2dkwpv.js";import"./chunk-rvg14b78.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-85bamng3.js";import"./chunk-dm1yxsdx.js";import"./chunk-y94239bb.js";import"./chunk-cw2b3383.js";import"./chunk-2j2mnzdg.js";import"./chunk-s6562rsq.js";import"./chunk-hbafhk9y.js";import"./chunk-68sf54n4.js";import"./chunk-sv833k2e.js";import"./chunk-w7n73ag8.js";import"./chunk-827422x9.js";import"./chunk-1g0d9yw0.js";import"./chunk-6kwg4hcv.js";import"./chunk-9xzw649r.js";import"./chunk-hmwz31tc.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ri as a,Si as b,Ti as c,Ui as d,Vi as e,Wi as f}from"./chunk-827422x9.js";import"./chunk-hmwz31tc.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{vh as H,wh as I}from"./chunk-dm1yxsdx.js";import{Mutex as J}from"async-mutex";class B extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(b){super("Session runtime capacity is full");this.limit=b;this.name="SessionRuntimeCapacityError"}}class D extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class A extends Error{constructor(b){super(`Session runtime residency already owns key: ${b}`);this.name="SessionRuntimeResidencyConflictError"}}class K{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new J;nextGeneration=1;closed=!1;constructor(b){if(!H(b.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!I(b.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=b.maxResident,this.idleMs=b.idleMs,this.now=b.now??Date.now}acquire(b){let j=this.residents.get(b);if(!j||j.poisoned)return;return j.pins++,j.lastUsedAt=this.now(),this.createLease(j)}owns(b,j){let q=this.residents.get(b);return Boolean(q&&(j===void 0||q.value===j))}async reserve(b,j){if(!b.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new D;if(this.residents.has(b)||this.reservations.has(b))throw new A(b);while(this.retainedCount()>=this.maxResident){if(!j.allowEviction)throw new B(this.maxResident);let z=this.oldestEvictableWebResident();if(!z)throw new B(this.maxResident);await this.disposeResident(z,!0)}let q={generation:this.allocateGeneration(),surface:j.surface};return this.reservations.set(b,q),this.createReservation(b,q)})}async remove(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j)return!1;if(q.pins>0)return!1;return await this.disposeResident(q,!0),!0})}async forget(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j||q.pins>0)return!1;return this.residents.delete(b),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let b=0;while(!0){let j=this.oldestIdleWebResident();if(!j)return b;await this.disposeResident(j,!0),b++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let b;for(let j of[...this.residents.values()])try{await this.disposeResident(j,!1)}catch(q){b??=q}if(this.residents.clear(),b!==void 0)throw b})}getStats(){let b=0;for(let j of this.residents.values())if(j.pins>0)b++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:b,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let b=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,b}createReservation(b,j){let q=!1;return{commit:(z)=>{if(q)throw new A(b);if(z.key!==b||z.surface!==j.surface||this.reservations.get(b)!==j||this.closed)throw this.reservations.delete(b),q=!0,this.closed?new D:new A(b);this.reservations.delete(b);let G={...z,generation:j.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(b,G),q=!0,this.createLease(G)},cancel:()=>{if(q)return;if(this.reservations.get(b)===j)this.reservations.delete(b);q=!0}}}createLease(b){let j=!1;return{value:b.value,release:()=>{if(j)return;j=!0;let q=this.residents.get(b.key);if(q!==b||q.generation!==b.generation)return;q.pins=Math.max(0,q.pins-1),q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((b)=>this.canEvict(b))}oldestIdleWebResident(){let b=this.now();return this.sortedWebResidents().find((j)=>b-j.lastUsedAt>=this.idleMs&&this.canEvict(j))}sortedWebResidents(){return[...this.residents.values()].filter((b)=>b.surface==="web").sort((b,j)=>b.lastUsedAt-j.lastUsedAt||b.generation-j.generation)}canEvict(b){if(b.pins>0||b.poisoned)return!1;try{return b.canEvict()}catch{return!1}}async disposeResident(b,j){if(this.residents.get(b.key)!==b)return;this.residents.delete(b.key);try{await b.dispose()}catch(q){if(j&&!this.closed&&!this.residents.has(b.key))b.lastUsedAt=this.now(),b.poisoned=!0,this.residents.set(b.key,b);throw q}}}
|
|
2
2
|
export{B as s,K as t};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import d from"typebox/schema";import o from"typebox/value";class u extends Error{issues;constructor(r){super(r.map((t)=>{return`${t.path.length>0?t.path.join("."):"root"}: ${t.message}`}).join("; "));this.issues=r;this.name="SchemaValidationError"}}function p(r){if(!r)return[];return r.split("/").slice(1).map((t)=>t.replace(/~1/g,"/").replace(/~0/g,"~")).map((t)=>/^(0|[1-9]\d*)$/.test(t)?Number(t):t)}function g(r,t){let n=r;for(let e of t){if(n===null||typeof n!=="object")return;n=n[e]}return n}function i(r,t){let[,n]=d.Errors(r,t);return n.map((e)=>{let s=p(e.instancePath);return{code:e.keyword,path:s,message:e.message,value:g(t,s)}})}function a(r,t){let n=o.Default(r,o.Clone(t)),e=i(r,n);if(e.length>0)return{success:!1,error:new u(e)};let s=o.Clean(r,n),c=i(r,s);if(c.length>0)return{success:!1,error:new u(c)};return{success:!0,data:s}}function f(r,t){let n=a(r,t);if(!n.success)throw n.error;return n.data}import l from"typebox";function x(r){return Object.defineProperties(r,{parse:{value:(t)=>f(r,t),enumerable:!1},safeParse:{value:(t)=>a(r,t),enumerable:!1}}),r}function b(r,t){return l.Optional({...r,default:t})}function V(r,t={}){return l.Unsafe({type:"string",enum:[...r],...t})}
|
|
2
|
-
export{a as
|
|
2
|
+
export{a as Qh,f as Rh,l as Sh,x as Th,b as Uh,V as Vh};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{vf as B}from"./chunk-8qp8v96d.js";import{
|
|
1
|
+
import{vf as B}from"./chunk-8qp8v96d.js";import{Ki as Y}from"./chunk-sv833k2e.js";import{Ni as Z,Qi as $}from"./chunk-w7n73ag8.js";import{createHash as H}from"node:crypto";var N="fast-mode-2026-02-01";function R(q,x,z){if(x.api!=="anthropic-messages"||z.providerValue!=="fast")return q;let J={...q},w=Object.keys(J).find((G)=>G.toLowerCase()==="anthropic-beta")??"anthropic-beta",Q=new Set((J[w]??"").split(",").map((G)=>G.trim()).filter(Boolean));return Q.add(N),J[w]=[...Q].join(","),J}function D(q){return`BLADE_MODEL_API_KEY_${H("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function F(q,x){if(!q.fallbackModels?.length)return;return q.fallbackModels.map((z)=>{let J=(x.models??[]).filter((G)=>G.provider===z.provider&&G.model===z.model),w=z.configId?(x.models??[]).find((G)=>G.id===z.configId):J.length===1?J[0]:void 0;if(z.configId&&!w)throw Error(`Unknown fallback model config ID: ${z.configId}`);if(w&&(w.provider!==z.provider||w.model!==z.model))throw Error(`Fallback model config ${w.id} does not match ${z.provider}/${z.model}`);if(!z.configId&&J.length>1)throw Error(`Fallback model ${z.provider}/${z.model} is ambiguous; set configId`);if(!w)return z;let Q=w.provider===q.provider;return{...z,configId:w.id,channel:{apiKey:process.env[D(w.id)]??(Q?process.env.BLADE_API_KEY:void 0),baseUrl:w.overrides?.baseUrl??(Q?process.env.BLADE_BASE_URL:void 0),temperature:w.overrides?.temperature??x.temperature,maxOutputTokens:w.overrides?.maxOutputTokens,timeout:w.overrides?.timeout??x.timeout,streamIdleTimeout:w.overrides?.streamIdleTimeout,apiVersion:w.overrides?.apiVersion,customHeaders:w.overrides?.customHeaders,enablePromptCaching:w.overrides?.enablePromptCaching}}})}function h(q,x,z,J=Y(),w="auto",Q="auto"){let G=J.resolveConfig(q),U=B(G,z),W=$(G,w),X=Z(G,Q),L=q.overrides;return{config:q,model:G,displayName:q.displayName??G.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[D(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??L?.baseUrl,temperature:L?.temperature??x.temperature,maxContextTokens:G.contextWindow,maxOutputTokens:L?.maxOutputTokens,timeout:L?.timeout??x.timeout,streamIdleTimeout:L?.streamIdleTimeout,reasoningEnabled:U.effective!=="off",...U.effective==="off"?{}:{reasoningEffort:U.effective},...W.providerValue?{serviceTier:W.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:F(q,x),enablePromptCaching:L?.enablePromptCaching,customHeaders:R(L?.customHeaders,G,W),apiVersion:L?.apiVersion,maxRetries:L?.maxRetries,providerCircuitBreakerOpenMs:x.providerCircuitBreakerOpenMs,providerRequestConcurrency:x.providerRequestConcurrency,providerGlobalConcurrency:x.providerGlobalConcurrency,providerOwnerConcurrency:x.providerOwnerConcurrency,providerRequestAdmissionMs:x.providerRequestAdmissionMs,providerRequestPendingBytes:x.providerRequestPendingBytes,modelCatalog:J},reasoning:U,serviceTier:W,responseVerbosity:X}}function j(q,x=Y()){try{return q.displayName??x.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
|
|
2
2
|
export{D as rf,h as sf,j as tf};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import{Ph as K}from"./chunk-y94239bb.js";import{Qh as bn,Rh as _n,Sh as T}from"./chunk-cw2b3383.js";import{Wh as wt,Xh as ft}from"./chunk-2j2mnzdg.js";import{ci as I}from"./chunk-s6562rsq.js";import{Ai as yt,di as tt,ei as Dt,fi as Bt,ji as Gt,ki as et,li as Kt,mi as Ht,ni as Yt,oi as cn,pi as Ft,qi as qt,ri as Mt,si as Vt,ti as Jt,ui as _t,vi as Qt,wi as jt,xi as Wt,yi as Zt,zi as kt}from"./chunk-hbafhk9y.js";import{Ei as Un}from"./chunk-68sf54n4.js";import{Hi as zt,Ki as v}from"./chunk-sv833k2e.js";import{Si as xn,Ti as Cn}from"./chunk-827422x9.js";import{Zi as a}from"./chunk-1g0d9yw0.js";import{ij as Ln}from"./chunk-9xzw649r.js";var lt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function vt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function p(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&vt(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{p(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function nn(n){let t=n.oauth;if(!t)return;let e=t;for(let E of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[E]!==void 0)throw Error(`MCP OAuth "${E}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(p(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((E)=>E.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((E)=>E.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((E)=>!E||E.length>128||!lt.test(E)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as Sn}from"node:crypto";import Te from"node:http";import{auth as dn}from"@modelcontextprotocol/sdk/client/auth.js";import se from"open";import{createHash as ne,randomUUID as te}from"node:crypto";import{constants as tn,promises as b}from"node:fs";import en from"node:path";import ee from"write-file-atomic";var Nn=1,Me=1048576,_e=5000,re=50,Se=/^[a-f0-9]{64}$/,Ee=T.Object({client_id:T.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),ue=T.Object({access_token:T.String({minLength:1,maxLength:65536}),token_type:T.String({minLength:1,maxLength:64}),expires_in:T.Optional(T.Number({minimum:0})),refresh_token:T.Optional(T.String({minLength:1,maxLength:65536})),scope:T.Optional(T.String({maxLength:16384})),id_token:T.Optional(T.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),oe=T.Unsafe({type:"object",properties:{authorizationServerUrl:T.String({format:"uri"}),resourceMetadataUrl:T.Optional(T.String({format:"uri"})),resourceMetadata:T.Optional(T.Unknown()),authorizationServerMetadata:T.Optional(T.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),an=T.Object({serverUrl:T.String({format:"uri"}),clientId:T.Optional(T.String({minLength:1,maxLength:4096})),clientInformation:T.Optional(Ee),tokens:T.Optional(ue),tokenExpiresAt:T.Optional(T.Number({minimum:0})),discoveryState:T.Optional(oe),updatedAt:T.String({format:"date-time"})},{additionalProperties:!1}),gn=T.Object({version:T.Literal(Nn),credentials:T.Record(T.String(),an)},{additionalProperties:!1});function G(n,t){return n instanceof Error&&"code"in n&&n.code===t}function me(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return G(t,"EPERM")}}function Mn(n){return structuredClone(n)}function In(n){if(Object.keys(n.credentials).some((t)=>!Se.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function H(n){let t=new URL(n);return t.hash="",t.toString()}function rn(n,t,e=[]){return ne("sha256").update(JSON.stringify({serverUrl:H(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class f{static locks=new K;stateRoot;tokenFilePath;constructor(n=Ln()){this.stateRoot=en.join(n,"mcp"),this.tokenFilePath=en.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let e=(await this.readStore()).credentials[n];return e?Mn(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let M=e.credentials[n],_=await t(M?Mn(M):null);if(_)e.credentials[n]=_n(an,_);else delete e.credentials[n];return _?Mn(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return f.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),M=await n(e);return await this.writeStore(e),M}finally{await t()}})}async ensureStateRoot(){await b.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await b.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await b.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Me)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await b.readFile(this.tokenFilePath,"utf8")),e=bn(gn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return In(e.data),e.data}catch(n){if(G(n,"ENOENT"))return{version:Nn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=_n(gn,n);In(t),await ee(this.tokenFilePath,`${JSON.stringify(t,null,2)}
|
|
2
|
+
`,{mode:384,encoding:"utf8"}),await b.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=en.join(this.stateRoot,".oauth-credentials.lock"),t=te(),e=Date.now()+_e;while(Date.now()<e)try{let M=await b.open(n,tn.O_CREAT|tn.O_EXCL|tn.O_WRONLY,384);return await M.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
|
|
3
|
+
`,"utf8"),await M.close(),async()=>{try{if(JSON.parse(await b.readFile(n,"utf8")).token===t)await b.unlink(n)}catch(_){if(!G(_,"ENOENT"))throw _}}}catch(M){if(!G(M,"EEXIST"))throw M;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,re))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await b.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let e=JSON.parse(await b.readFile(n,"utf8"));if(typeof e.pid!=="number"||!Number.isInteger(e.pid)||e.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!me(e.pid))await b.unlink(n)}}var wn="127.0.0.1",fn=7777,Pn="/oauth/callback",Ae=300000;class En extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class hn extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function ce(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
|
|
4
|
+
<html lang="en">
|
|
5
|
+
<head>
|
|
6
|
+
<meta charset="utf-8">
|
|
7
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
8
|
+
<title>${t}</title>
|
|
9
|
+
</head>
|
|
10
|
+
<body>
|
|
11
|
+
<main>
|
|
12
|
+
<h1>${t}</h1>
|
|
13
|
+
<p>${n?"You can close this window and return to Blade.":"Return to Blade and retry the OAuth login."}</p>
|
|
14
|
+
</main>
|
|
15
|
+
</body>
|
|
16
|
+
</html>`}function U(n,t,e){n.writeHead(t,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Content-Security-Policy":"default-src 'none'; style-src 'unsafe-inline'","X-Content-Type-Options":"nosniff","Referrer-Policy":"no-referrer"}),n.end(ce(e))}class C{serverName;config;static activeFlowIdentity;tokenStorage;serverUrl;identity;callbackUrl;openAuthorizationUrl;codeVerifierValue;activeFlow;lastError;constructor(n,t,e,M={}){this.serverName=n;this.config=e;this.serverUrl=H(t),this.identity=rn(this.serverUrl,e.clientId,e.scopes),this.tokenStorage=M.tokenStorage??new f;let _=e.callbackPort??fn;this.callbackUrl=`http://${wn}:${_}${Pn}`,this.openAuthorizationUrl=M.openAuthorizationUrl??(async(S)=>{await se(S,{wait:!1})})}get redirectUrl(){return this.callbackUrl}get clientMetadata(){return{redirect_uris:[this.callbackUrl],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:`${Cn()} ${xn()}`,...this.config.scopes?.length?{scope:this.config.scopes.join(" ")}:{}}}async state(){return this.activeFlow?.state??Sn()}async clientInformation(){if(this.config.clientId)return{client_id:this.config.clientId};return(await this.readCredential())?.clientInformation}async saveClientInformation(n){await this.updateCredential((t)=>({...this.baseCredential(t),clientInformation:n}))}async tokens(){let n=await this.readCredential();if(!n?.tokens)return;if(n.tokenExpiresAt!==void 0&&n.tokenExpiresAt<=Date.now()&&!n.tokens.refresh_token)return;return structuredClone(n.tokens)}async saveTokens(n){let t=n.expires_in===void 0?void 0:Date.now()+n.expires_in*1000;await this.updateCredential((e)=>({...this.baseCredential(e),tokens:structuredClone(n),...t===void 0?{}:{tokenExpiresAt:t}})),this.lastError=void 0}async redirectToAuthorization(n){let t=this.activeFlow;if(!t)throw new En(this.serverName);t.authorizationUrl=p(n,"MCP OAuth authorization URL").toString()}async saveCodeVerifier(n){this.codeVerifierValue=n}async codeVerifier(){if(!this.codeVerifierValue)throw Error("MCP OAuth PKCE verifier is unavailable");return this.codeVerifierValue}async saveDiscoveryState(n){await this.updateCredential((t)=>({...this.baseCredential(t),discoveryState:structuredClone(n)}))}async discoveryState(){let n=(await this.readCredential())?.discoveryState;return n?structuredClone(n):void 0}async invalidateCredentials(n){if(n==="verifier"){this.codeVerifierValue=void 0;return}if(n==="all"){await this.tokenStorage.deleteCredential(this.identity),this.codeVerifierValue=void 0;return}await this.updateCredential((t)=>{if(!t)return null;let e={...t};if(n==="client")delete e.clientInformation,delete e.tokens,delete e.tokenExpiresAt;else if(n==="tokens")delete e.tokens,delete e.tokenExpiresAt;else if(n==="discovery")delete e.discoveryState;return{...e,updatedAt:new Date().toISOString()}})}async getStatus(){if(this.activeFlow)return"authorizing";if(this.lastError)return"error";return await this.hasUsableCredentials()?"authenticated":"unauthenticated"}async hasUsableCredentials(){let n=await this.readCredential();if(!n?.tokens?.access_token)return!1;if(n.tokenExpiresAt===void 0||n.tokenExpiresAt>Date.now())return!0;return Boolean(n.tokens.refresh_token)}async beginAuthorization(){if(this.activeFlow)return this.toHandle(this.activeFlow);if(await this.hasUsableCredentials())throw Error(`MCP server "${this.serverName}" already has OAuth credentials`);if(C.activeFlowIdentity)throw Error("Another MCP OAuth authorization is already in progress");C.activeFlowIdentity=this.identity,this.lastError=void 0,this.codeVerifierValue=void 0;try{let n=await this.createFlow();if(this.activeFlow=n,await dn(this,{serverUrl:this.serverUrl,fetchFn:B})!=="REDIRECT"||!n.authorizationUrl)throw Error("MCP OAuth server did not start an authorization redirect");return this.toHandle(n)}catch(n){let t=n instanceof Error?n:Error(String(n));throw await this.failActiveFlow(t),t}}async openAuthorization(){let n=await this.beginAuthorization();return await this.openAuthorizationUrl(n.authorizationUrl),n}async logout(){if(this.activeFlow)await this.failActiveFlow(Error("MCP OAuth authorization cancelled"));await this.tokenStorage.deleteCredential(this.identity),this.codeVerifierValue=void 0,this.lastError=void 0}async dispose(){if(this.activeFlow)await this.failActiveFlow(Error("MCP OAuth authorization cancelled"))}async createFlow(){let n,t,e=new Promise((r,E)=>{n=r,t=E});e.catch(()=>{return});let M=Sn(),_=Te.createServer((r,E)=>{this.handleCallback(r,E)});_.on("clientError",(r,E)=>{E.end(`HTTP/1.1 400 Bad Request\r
|
|
17
|
+
Connection: close\r
|
|
18
|
+
\r
|
|
19
|
+
`)}),await new Promise((r,E)=>{let u=(m)=>E(m);_.once("error",u),_.listen(this.config.callbackPort??fn,wn,()=>{_.off("error",u),r()})});let S={flowId:Sn(),state:M,callbackUrl:this.callbackUrl,server:_,timeout:setTimeout(()=>{this.failActiveFlow(Error("MCP OAuth authorization timed out"))},Ae),completion:e,resolve:n,reject:t,settled:!1};return S.timeout.unref(),S}async handleCallback(n,t){let e=this.activeFlow;if(!e){U(t,410,!1);return}try{if(n.method!=="GET"){t.setHeader("Allow","GET"),U(t,405,!1);return}let M=new URL(n.url??"/",e.callbackUrl);if(M.pathname!==Pn){U(t,404,!1);return}let _=M.searchParams.get("state"),S=M.searchParams.get("code");if(M.searchParams.get("error"))throw Error("MCP OAuth authorization was denied");if(!_||_!==e.state)throw Error("MCP OAuth state mismatch");if(!S)throw Error("MCP OAuth callback is missing the authorization code");if(await dn(this,{serverUrl:this.serverUrl,authorizationCode:S,fetchFn:B})!=="AUTHORIZED")throw Error("MCP OAuth token exchange did not complete");U(t,200,!0),await this.completeActiveFlow()}catch(M){U(t,400,!1),await this.failActiveFlow(M instanceof Error?M:Error(String(M)))}}async completeActiveFlow(){let n=this.activeFlow;if(!n||n.settled)return;n.settled=!0,clearTimeout(n.timeout),await new Promise((t)=>n.server.close(()=>t())),this.activeFlow=void 0,C.activeFlowIdentity=void 0,this.codeVerifierValue=void 0,this.lastError=void 0,n.resolve()}async failActiveFlow(n){let t=this.activeFlow;if(this.lastError=n,this.codeVerifierValue=void 0,C.activeFlowIdentity=void 0,!t||t.settled){this.activeFlow=void 0;return}t.settled=!0,clearTimeout(t.timeout),await new Promise((e)=>t.server.close(()=>e())),this.activeFlow=void 0,t.reject(n)}toHandle(n){if(!n.authorizationUrl)throw Error("MCP OAuth authorization URL is unavailable");return{flowId:n.flowId,authorizationUrl:n.authorizationUrl,callbackUrl:n.callbackUrl,completion:n.completion}}readCredential(){return this.tokenStorage.getCredential(this.identity)}updateCredential(n){return this.tokenStorage.updateCredential(this.identity,n)}baseCredential(n){return{...n??{},serverUrl:this.serverUrl,...this.config.clientId?{clientId:this.config.clientId}:{},updatedAt:new Date().toISOString()}}}import{promises as j}from"node:fs";import $n from"node:os";import w from"node:path";import{merge as ie}from"lodash-es";import ge from"write-file-atomic";var Y=1,Rn=256,F=4096,q=30000,Xn=1800000,V=86400000,TM=30000,sM=30000;function J(n){return Number.isSafeInteger(n)&&n>=1&&n<=4096}function Q(n){return Number.isSafeInteger(n)&&n>=30000&&n<=86400000}var pn=Un("Service"),P={models:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},modelProviders:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},currentModelId:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},temperature:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxOutputTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},timeout:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},bashForegroundHandoffMs:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerForegroundRecoveryMs:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerCircuitBreakerOpenMs:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerRequestConcurrency:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerGlobalConcurrency:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerOwnerConcurrency:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerRequestAdmissionMs:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerRequestPendingBytes:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},agentTeamsEnabled:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},codeTheme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},uiTheme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},language:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},debug:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},fontSize:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},autoSaveSessions:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyBuild:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyErrors:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifySounds:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyTelemetry:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyCrash:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},communicationStyle:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},permissionMode:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},permissions:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},hooks:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},enabledPlugins:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},pluginSourcePolicy:{target:"settings",defaultScope:"global",mergeStrategy:"replace",persistable:!0},env:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},disableAllHooks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxTurns:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxConcurrentTasks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxQueuedTasks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxQueuedTaskBytes:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxResidentSessionRuntimes:{target:"settings",defaultScope:"global",mergeStrategy:"replace",persistable:!0},sessionRuntimeIdleMs:{target:"settings",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxResidentSessionProjections:{target:"settings",defaultScope:"global",mergeStrategy:"replace",persistable:!0,allowedScopes:["global"]},sessionProjectionIdleMs:{target:"settings",defaultScope:"global",mergeStrategy:"replace",persistable:!0,allowedScopes:["global"]},mcpServers:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},lspServers:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},stream:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topP:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topK:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},mcpEnabled:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},systemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},appendSystemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},initialMessage:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},resumeSessionId:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},forkSession:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},allowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},disallowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},mcpConfigPaths:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},strictMcpConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},addDirs:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},outputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},inputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},print:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},includePartialMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},replayUserMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},agentsConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},settingSources:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1}},fM=new Set(Object.entries(P).filter(([n,t])=>t.persistable).map(([n])=>n)),PM=new Set(Object.entries(P).filter(([n,t])=>!t.persistable).map(([n])=>n));class h extends Error{code;field;constructor(n,t,e){super(t);this.code=n;this.field=e;this.name="ConfigSaveError"}}class N{static instance=null;pendingUpdates=new Map;timers=new Map;fileLocks=new K;lastSaveError=null;debounceDelay=300;constructor(){}static getInstance(){if(!N.instance)N.instance=new N;return N.instance}static resetInstance(){if(N.instance)for(let n of N.instance.timers.values())clearTimeout(n);N.instance=null}coordinationStatsForTests(){return this.fileLocks.getStats()}async save(n,t={}){this.validatePersistableFields(n),this.validateAllowedScopes(n,t.scope),this.validateFieldValues(n);let e=this.groupUpdatesByTarget(n,t.scope,t.projectDir);if(t.immediate)await Promise.all(Array.from(e.entries()).map(([M,_])=>this.flushTarget(M,_)));else for(let[M,_]of e)this.scheduleSave(M,_)}async flush(){for(let t of this.timers.values())clearTimeout(t);this.timers.clear();let n=Array.from(this.pendingUpdates.entries()).map(([t,e])=>this.flushTarget(t,e));this.pendingUpdates.clear(),await Promise.all(n)}getLastSaveError(){return this.lastSaveError}clearLastSaveError(){this.lastSaveError=null}async appendPermissionRule(n,t={}){await this.appendPermissionRuleForDecision(n,"allow",t)}async appendPermissionDenyRule(n,t={}){await this.appendPermissionRuleForDecision(n,"deny",t)}async appendPermissionRuleForDecision(n,t,e){let M=e.scope??"local",_=this.resolveFilePath("settings",M,e.projectDir);await this.flushTargetWithModifier(_,(S)=>{let r=S.permissions??{allow:[],ask:[],deny:[]},E={allow:t==="allow"?this.dedupeArray([...r.allow||[],n]):r.allow||[],ask:r.ask||[],deny:t==="deny"?this.dedupeArray([...r.deny||[],n]):r.deny||[]};return{...S,permissions:E}})}async appendLocalPermissionRule(n,t={}){await this.appendPermissionRule(n,{...t,scope:"local"})}async appendLocalPermissionDenyRule(n,t={}){await this.appendPermissionDenyRule(n,{...t,scope:"local"})}async removePluginSetting(n,t={}){let e=t.scope??"local",M=this.resolveFilePath("settings",e,t.projectDir);await this.flushTargetWithModifier(M,(_)=>{let S={..._.enabledPlugins??{}};delete S[n];let r={..._};if(Object.keys(S).length>0)r.enabledPlugins=S;else delete r.enabledPlugins;return r})}validatePersistableFields(n){for(let t of Object.keys(n)){let e=P[t];if(!e)throw new h("UNKNOWN_CONFIG_FIELD",`Unknown config field: ${t}`);if(!e.persistable)throw new h("NON_PERSISTABLE_FIELD",`Field "${t}" is non-persistable and cannot be saved to config files. Non-persistable fields are runtime-only and only valid for the current session.`,t)}}validateAllowedScopes(n,t){for(let e of Object.keys(n)){let M=P[e];if(!M?.allowedScopes)continue;let _=t??M.defaultScope;if(!M.allowedScopes.includes(_))throw new h("INVALID_CONFIG_SCOPE",`Field "${e}" only supports scopes: ${M.allowedScopes.join(", ")}`,e)}}validateFieldValues(n){if(n.maxResidentSessionProjections!==void 0&&!J(n.maxResidentSessionProjections))throw new h("INVALID_CONFIG_VALUE",`Field "maxResidentSessionProjections" must be a safe integer between ${Y} and ${F}`,"maxResidentSessionProjections");if(n.sessionProjectionIdleMs!==void 0&&!Q(n.sessionProjectionIdleMs))throw new h("INVALID_CONFIG_VALUE",`Field "sessionProjectionIdleMs" must be a safe integer between ${q} and ${V}`,"sessionProjectionIdleMs")}groupUpdatesByTarget(n,t,e){let M=new Map;for(let[_,S]of Object.entries(n)){let r=P[_];if(!r)continue;let E=t??r.defaultScope,u=this.resolveFilePath(r.target,E,e);if(!M.has(u))M.set(u,{});M.get(u)[_]=S}return M}resolveFilePath(n,t,e){let M=e??I();if(n==="config")return t==="global"?w.join($n.homedir(),".blade","config.json"):w.join(M,".blade","config.json");switch(t){case"local":return w.join(M,".blade","settings.local.json");case"project":return w.join(M,".blade","settings.json");case"global":return w.join($n.homedir(),".blade","settings.json");default:return w.join(M,".blade","settings.local.json")}}scheduleSave(n,t){let e=this.pendingUpdates.get(n)??{},M=this.mergePendingUpdates(e,t);this.pendingUpdates.set(n,M);let _=this.timers.get(n);if(_)clearTimeout(_);let S=setTimeout(async()=>{let r=this.pendingUpdates.get(n);if(r){this.pendingUpdates.delete(n),this.timers.delete(n);try{await this.flushTarget(n,r),this.lastSaveError=null}catch(E){let u=E instanceof Error?E:Error(String(E));this.lastSaveError=u,pn.error(`Failed to save config to ${n}:`,u.message),pn.error("Stack trace:",u.stack)}}},this.debounceDelay);this.timers.set(n,S)}mergePendingUpdates(n,t){let e={...n};for(let[M,_]of Object.entries(t)){let S=P[M];if(!S){e[M]=_;continue}switch(S.mergeStrategy){case"replace":e[M]=_;break;case"append-dedupe":this.applyAppendDedupe(e,M,_);break;case"deep-merge":this.applyDeepMerge(e,M,_);break}}return e}async flushTarget(n,t){await this.fileLocks.runExclusive(n,async()=>{await this.performWrite(n,t)})}async flushTargetWithModifier(n,t){await this.fileLocks.runExclusive(n,async()=>{await j.mkdir(w.dirname(n),{recursive:!0,mode:493});let e={};try{let _=await j.readFile(n,"utf-8");e=JSON.parse(_)}catch{e={}}let M=t(e);await this.atomicWrite(n,M)})}async performWrite(n,t){await j.mkdir(w.dirname(n),{recursive:!0,mode:493});let e={};try{let _=await j.readFile(n,"utf-8");e=JSON.parse(_)}catch{e={}}let M={...e};if(typeof M.theme==="string"&&M.codeTheme===void 0)M.codeTheme=M.theme;delete M.theme;for(let[_,S]of Object.entries(t)){let r=P[_];if(!r){M[_]=S;continue}switch(r.mergeStrategy){case"replace":M[_]=S;break;case"append-dedupe":this.applyAppendDedupe(M,_,S);break;case"deep-merge":this.applyDeepMerge(M,_,S);break}}await this.atomicWrite(n,M)}applyAppendDedupe(n,t,e){if(t==="permissions"&&typeof e==="object"&&e!==null){let M=n[t]??{allow:[],ask:[],deny:[]},_=e;n[t]={allow:this.dedupeArray([...M.allow||[],..._.allow||[]]),ask:this.dedupeArray([...M.ask||[],..._.ask||[]]),deny:this.dedupeArray([...M.deny||[],..._.deny||[]])}}else if(Array.isArray(e)){let M=Array.isArray(n[t])?n[t]:[];n[t]=this.dedupeArray([...M,...e])}else n[t]=e}applyDeepMerge(n,t,e){if(typeof e==="object"&&e!==null&&!Array.isArray(e)){let M=typeof n[t]==="object"&&n[t]!==null?n[t]:{};n[t]=ie({},M,e)}else n[t]=e}dedupeArray(n){return Array.from(new Set(n))}async atomicWrite(n,t){await ge(n,JSON.stringify(t,null,2),{mode:384,encoding:"utf-8"})}}function xM(){return N.getInstance()}var On=15000,zn=1000,Dn=300000;function un(n){return n===0||typeof n==="number"&&Number.isSafeInteger(n)&&n>=1000&&n<=300000}function hM(n,t=15000){return un(n)?n:t}var Bn=1,Gn=32,Kn=256,Hn=30000,Yn=300000,Fn=3600000,XM=30000;function qn(n){return Number.isSafeInteger(n)&&n>=1&&n<=256}function Vn(n){return Number.isSafeInteger(n)&&n>=30000&&n<=3600000}var Jn=1,Qn=64,jn=1,Wn=1e4,Zn=67108864,kn=65536,yn=134217728;function ln(n){return Number.isInteger(n)&&n>=1&&n<=64}function vn(n){return Number.isInteger(n)&&n>=1&&n<=1e4}function nt(n){return Number.isSafeInteger(n)&&n>=65536&&n<=134217728}var s={currentModelId:"",models:[],modelProviders:{},temperature:0,maxOutputTokens:void 0,stream:!0,topP:0.9,topK:50,timeout:180000,bashForegroundHandoffMs:On,providerForegroundRecoveryMs:tt,providerCircuitBreakerOpenMs:et,providerRequestAdmissionMs:Mt,agentTeamsEnabled:!1,providerRequestPendingBytes:_t,codeTheme:"dracula",uiTheme:"system",language:"zh-CN",fontSize:14,autoSaveSessions:!0,notifyBuild:!0,notifyErrors:!1,notifySounds:!1,privacyTelemetry:!1,privacyCrash:!0,debug:!1,mcpEnabled:!1,mcpServers:{},lspServers:{},permissions:{allow:["Bash(pwd)","Bash(which *)","Bash(whoami)","Bash(hostname)","Bash(uname *)","Bash(date)","Bash(echo *)","Bash(ls *)","Bash(tree *)","Bash(git status)","Bash(git status -*)","Bash(git log *)","Bash(git diff *)","Bash(git show *)","Bash(git branch -* *)","Bash(git branch)","Bash(git tag -l *)","Bash(git tag --list *)","Bash(git stash list *)","Bash(git stash show *)","Bash(git rev-parse *)","Bash(git describe *)","Bash(git blame *)","Bash(git ls-files *)","Bash(git config --get *)","Bash(git config --list *)","Bash(git shortlog *)","Bash(git merge-base *)","Bash(git cat-file *)","Bash(git for-each-ref *)","Bash(git grep *)","Bash(git worktree list *)","Bash(git reflog show *)","Bash(git reflog)","Bash(git rev-list *)","Bash(git ls-remote *)","Bash(git remote -v)","Bash(git remote --verbose)","Bash(git remote)","Bash(gh pr view *)","Bash(gh pr list *)","Bash(gh pr diff *)","Bash(gh pr checks *)","Bash(gh pr status *)","Bash(gh issue view *)","Bash(gh issue list *)","Bash(gh issue status *)","Bash(gh run list *)","Bash(gh run view *)","Bash(gh repo view *)","Bash(gh auth status)","Bash(npm list *)","Bash(bun pm ls *)","Bash(npm view *)","Bash(npm outdated *)","Bash(pnpm list *)","Bash(yarn list *)","Bash(pip list *)","Bash(pip show *)"],ask:["Bash(curl *)","Bash(wget *)","Bash(aria2c *)","Bash(axel *)","Bash(rm -rf *)","Bash(rm -r *)","Bash(rm --recursive *)","Bash(nc *)","Bash(netcat *)","Bash(telnet *)","Bash(ncat *)"],deny:["Read(./.env)","Read(./.env.*)","Bash(rm -rf /)","Bash(rm -rf /*)","Bash(sudo *)","Bash(chmod 777 *)","Bash(bash *)","Bash(sh *)","Bash(zsh *)","Bash(fish *)","Bash(dash *)","Bash(eval *)","Bash(source *)","Bash(mkfs *)","Bash(fdisk *)","Bash(dd *)","Bash(format *)","Bash(parted *)","Bash(open http*)","Bash(open https*)","Bash(xdg-open http*)","Bash(xdg-open https*)"]},permissionMode:"default",hooks:{enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionRequest:[],Elicitation:[],ElicitationResult:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]},enabledPlugins:{},pluginSourcePolicy:{restrictToAllowedSources:!1,requireGitCommitSha:!1,allowedGitHosts:[],allowedMarketplaces:[],allowedLocalRoots:[]},env:{},disableAllHooks:!1,maxTurns:-1,maxConcurrentTasks:3,maxQueuedTasks:100,maxQueuedTaskBytes:Zn,maxResidentSessionRuntimes:Gn,sessionRuntimeIdleMs:Yn,maxResidentSessionProjections:Rn,sessionProjectionIdleMs:Xn};var rt=/^[A-Za-z0-9_-]{21}$/;function St(n){return n.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[._-]+|[._-]+$/g,"").slice(0,80)||"model"}function Le(n,t){let e=new Set(t.map((r)=>r.id)),M=St(n.model);if(!e.has(M))return M;let _=`${St(n.provider)}-${M}`.slice(0,120);if(!e.has(_))return _;let S=2;while(e.has(`${_}-${S}`))S++;return`${_}-${S}`}function Et(n,t){let e=n.filter((S)=>!rt.test(S.id)).map((S)=>({id:S.id})),M=new Map;return{models:n.map((S)=>{if(!rt.test(S.id))return{...S};let{id:r,...E}=S,u=Le(E,e);return e.push({id:u}),M.set(r,u),{...S,id:u}}),currentModelId:M.get(t)??t,changed:M.size>0}}import{promises as Ot}from"fs";import{merge as D}from"lodash-es";import i from"os";import o from"path";function ot(n){let t=ut(n.timeout??300000,"MCP timeout"),e=ut(n.idleTimeout??Math.min(60000,t),"MCP idleTimeout");if(e>t)throw Error("MCP idleTimeout must not exceed timeout");return{totalTimeoutMs:t,idleTimeoutMs:e,maxProgressEvents:128}}function VM(n,t,e){if(t.count>=e.maxProgressEvents)return;if(!Number.isFinite(n.progress)||n.progress<0)return;if(n.total!==void 0&&(!Number.isFinite(n.total)||n.total<=0))return;if(t.lastProgress!==void 0&&n.progress<t.lastProgress)return;t.count++,t.lastProgress=n.progress;let M=n.message?.replace(/\0/g,"").trim().slice(0,1000);return{progress:n.progress,...n.total!==void 0?{total:n.total}:{},message:M||be(n.progress,n.total)}}function ut(n,t){if(!Number.isSafeInteger(n)||n<1000||n>1800000)throw Error(`${t} must be an integer between 1000 and 1800000 milliseconds`);return n}function be(n,t){if(t!==void 0)return`MCP progress ${Math.max(0,Math.min(100,n/t*100)).toFixed(0)}%`;return`MCP progress ${n}`}import{createHash as Ne}from"node:crypto";var W=["debug","info","notice","warning","error","critical","alert","emergency"],jM=64,WM=64,ZM=256,ae=8192,At=16384,de=256,we=6,fe=128,mt=64,Tt=64,Pe=128,xe=/authorization|api[-_]?key|cookie|credential|password|secret|token/i;function ct(n){let t=n.logging;if(t!==void 0&&(t===null||typeof t!=="object"||Array.isArray(t)))throw Error("MCP logging configuration must be an object");let e=t?.enabled??!0;if(typeof e!=="boolean")throw Error("MCP logging enabled must be a boolean");let M=t?.level??"warning";if(!Ce(M))throw Error(`MCP logging level must be one of: ${W.join(", ")}`);return{enabled:e,level:M}}function Ce(n){return typeof n==="string"&&W.includes(n)}function kM(n,t){return W.indexOf(n)>=W.indexOf(t)}function he(n,t={}){let e=Re(n.data),M=typeof e.value==="string"?e.value:JSON.stringify(e.value),_=st(M,At),S=_.value,r=Buffer.byteLength(S),E=Ne("sha256").update(S).digest("hex"),u=t.exposeDetails!==!1,m=u?st(S,ae):{value:`[MCP log details omitted; sha256=${E}]`,truncated:!1},A=u&&n.logger?Z(mn(n.logger),de):void 0;return{level:n.level,...A?{logger:A}:{},message:m.value||"[empty MCP log message]",projectedBytes:r,dataSha256:E,truncated:e.truncated||_.truncated||m.truncated,detailsOmitted:!u,timestamp:t.now??Date.now()}}function yM(n,t={}){return{...he({level:"warning",logger:"blade.mcp.logging",data:`MCP log rate exceeded; dropped at least ${Math.max(1,n)} message(s)`},t),synthetic:!0}}function Re(n){let t={nodes:0,remainingStringBytes:At,truncated:!1,seen:new WeakSet};return{value:on(n,0,t),truncated:t.truncated}}function on(n,t,e){if(e.nodes++,e.nodes>fe)return e.truncated=!0,"[node limit reached]";if(n===null||typeof n==="boolean")return n;if(typeof n==="number")return Number.isFinite(n)?n:String(n);if(typeof n==="bigint")return n.toString();if(typeof n==="string"){let M=mn(n),_=Math.max(0,e.remainingStringBytes),S=Z(M,_),r=Buffer.byteLength(S);if(e.remainingStringBytes-=r,r<Buffer.byteLength(M))e.truncated=!0;return S}if(typeof n>"u")return"[undefined]";if(typeof n==="symbol"||typeof n==="function")return`[${typeof n}]`;if(t>=we)return e.truncated=!0,"[depth limit reached]";if(e.seen.has(n))return e.truncated=!0,"[circular]";e.seen.add(n);try{if(Array.isArray(n)){if(n.length>mt)e.truncated=!0;return n.slice(0,mt).map((S)=>on(S,t+1,e))}let M=Object.create(null),_=Object.entries(n);if(_.length>Tt)e.truncated=!0;for(let[S,r]of _.slice(0,Tt)){let E=Z(mn(S),Pe)||"[empty-key]";if(S==="_meta"||xe.test(S))M[E]="[redacted]";else M[E]=on(r,t+1,e)}return M}finally{e.seen.delete(n)}}function mn(n){return[...n.replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]")].filter((e)=>{let M=e.charCodeAt(0);return(M===9||M===10||M===13||M>=32)&&M!==127}).join("")}function Z(n,t){if(t<=0)return"";if(Buffer.byteLength(n)<=t)return n;let e=Buffer.from(n).subarray(0,t).toString("utf8");while(Buffer.byteLength(e)>t)e=e.slice(0,-1);return e}function st(n,t){if(Buffer.byteLength(n)<=t)return{value:n,truncated:!1};let e=`
|
|
20
|
+
...[MCP log truncated]`;return{value:Z(n,t-Buffer.byteLength(e))+e,truncated:!0}}var it=1024,Xe=4096,gt=2,$e=8,It=65536,pe=1048576,Lt=50,bt=16000,Nt=4,Ue=100,at=1048576,Oe=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function Pt(n){if(!n)return{enabled:!1,maxTokens:it,maxRequestsPerToolCall:gt,maxInputBytes:It};if(typeof n.enabled!=="boolean")throw Error("MCP sampling.enabled must be a boolean");return{enabled:n.enabled,maxTokens:k(n.maxTokens??it,1,Xe,"MCP sampling.maxTokens"),maxRequestsPerToolCall:k(n.maxRequestsPerToolCall??gt,1,$e,"MCP sampling.maxRequestsPerToolCall"),maxInputBytes:k(n.maxInputBytes??It,1,pe,"MCP sampling.maxInputBytes")}}function n_(n,t){if(!t.enabled)throw Error("MCP sampling is disabled");if(n.task)throw Error("Task-based MCP sampling is not supported");if(n.tools?.length)throw Error("MCP sampling tools were not negotiated");if(n.includeContext&&n.includeContext!=="none")throw Error("MCP sampling server context was not negotiated");if(n.messages.length===0||n.messages.length>Lt)throw Error(`MCP sampling messages must contain 1-${Lt} entries`);if(n.systemPrompt!==void 0&&n.systemPrompt.length>bt)throw Error(`MCP sampling system prompt exceeds ${bt} characters`);if(n.temperature!==void 0&&(!Number.isFinite(n.temperature)||n.temperature<0||n.temperature>2))throw Error("MCP sampling temperature must be between 0 and 2");let e=n.stopSequences??[];if(e.length>Nt||e.some((m)=>!m||m.length>Ue||m.includes("\x00")))throw Error(`MCP sampling stop sequences must contain at most ${Nt} non-empty bounded values`);let M=[],_=0,S=0,r=0,E=[];if(n.systemPrompt)_+=Buffer.byteLength(n.systemPrompt,"utf8"),M.push({role:"system",content:n.systemPrompt}),E.push(`System: ${dt(n.systemPrompt)}`);for(let m of n.messages){let A=Array.isArray(m.content)?m.content:[m.content],L=[],g=[];for(let c of A){if(c.type==="text"){_+=Buffer.byteLength(c.text,"utf8"),L.push({type:"text",text:c.text}),g.push(dt(c.text));continue}if(c.type==="image"){if(m.role!=="user")throw Error("MCP sampling images are only supported in user messages");if(!Oe.has(c.mimeType))throw Error(`Unsupported MCP sampling image type: ${c.mimeType}`);let $=ze(c.data);S+=$,r++,L.push({type:"image_url",image_url:{url:`data:${c.mimeType};base64,${c.data}`}}),g.push(`[${c.mimeType} image, ${$} bytes]`);continue}throw Error(`Unsupported MCP sampling content type: ${c.type}`)}if(L.length===0)throw Error("MCP sampling message has no supported content");M.push({role:m.role,content:L.length===1&&L[0]?.type==="text"?L[0].text:L}),E.push(`${m.role==="user"?"User":"Assistant"}: ${g.join(" ")}`)}if(_+S>t.maxInputBytes)throw Error(`MCP sampling input exceeds ${t.maxInputBytes} bytes`);if(r>wt||S>ft)throw Error("MCP sampling image input exceeds the shared attachment budget");let u=k(n.maxTokens,1,Number.MAX_SAFE_INTEGER,"MCP sampling maxTokens");return{messages:M,maxTokens:Math.min(u,t.maxTokens),...n.temperature!==void 0?{temperature:n.temperature}:{},stopSequences:[...e],preview:E.join(`
|
|
21
|
+
`).slice(0,8000)}}function t_(n,t,e){if(n.toolCalls?.length)throw Error("Model returned tools for basic MCP sampling");let M=n.content,_=n.finishReason==="length"||n.finishReason==="max_tokens"?"maxTokens":"endTurn",S=-1;for(let r of e.stopSequences){let E=M.indexOf(r);if(E>=0&&(S===-1||E<S))S=E}if(S>=0)M=M.slice(0,S),_="stopSequence";if(Buffer.byteLength(M,"utf8")>at)throw Error(`MCP sampling response exceeds ${at} bytes`);return{model:t,role:"assistant",content:{type:"text",text:M},stopReason:_}}function k(n,t,e,M){if(!Number.isSafeInteger(n)||n<t||n>e)throw Error(`${M} must be an integer between ${t} and ${e}`);return n}function ze(n){if(!n||n.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(n))throw Error("MCP sampling image contains invalid base64 data");return Buffer.from(n,"base64").byteLength}function dt(n){return n.replace(/\s+/g," ").trim().slice(0,1000)}var M_=256,__=1e4,r_=86400000;var De=/[\p{Cf}\p{Co}\p{Cn}]/u;function Ct(n){if(!n)return{enabled:!1,defaultTtlMs:600000,pollIntervalMs:500,maxTasksPerSession:32,maxLifetimeMs:1800000};if(typeof n.enabled!=="boolean")throw Error("MCP tasks.enabled must be a boolean");let t=x(n.defaultTtlMs??600000,1e4,86400000,"MCP tasks.defaultTtlMs"),e=x(n.maxLifetimeMs??1800000,1e4,86400000,"MCP tasks.maxLifetimeMs");if(t>e)throw Error("MCP tasks.defaultTtlMs must not exceed tasks.maxLifetimeMs");return{enabled:n.enabled,defaultTtlMs:t,pollIntervalMs:x(n.pollIntervalMs??500,100,1e4,"MCP tasks.pollIntervalMs"),maxTasksPerSession:x(n.maxTasksPerSession??32,1,32,"MCP tasks.maxTasksPerSession"),maxLifetimeMs:e}}function S_(n,t){return x(n??t.defaultTtlMs,1e4,Math.min(86400000,t.maxLifetimeMs),"MCP task ttl")}function E_(n,t,e){let M=Ge(n.taskId,"task ID",512),_=xt(n.createdAt,"createdAt"),S=xt(n.lastUpdatedAt,"lastUpdatedAt");if(Date.parse(S)<Date.parse(_))throw Error("MCP task lastUpdatedAt precedes createdAt");if(e&&(M!==e.taskId||_!==e.createdAt))throw Error("MCP task identity changed across connection generation");let r=n.ttl===null?null:x(n.ttl,0,86400000,"MCP task ttl"),E=n.pollInterval===void 0?t.pollIntervalMs:x(n.pollInterval,0,Number.MAX_SAFE_INTEGER,"MCP task pollInterval"),u=Math.min(1e4,Math.max(100,E)),m=n.statusMessage?Be(n.statusMessage,M):void 0;return{taskId:M,status:n.status,createdAt:_,lastUpdatedAt:S,ttl:r,pollIntervalMs:u,...m?{statusMessage:m}:{}}}function u_(n){return["completed","failed","cancelled"].includes(n)}function o_(n){let t=n instanceof Error?n.message:String(n);return ht(Tn(t.replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]")),1024)}function Be(n,t){return ht(Tn(n.replaceAll(t,"[redacted-task-id]")),1024)}function Tn(n){return[...n.normalize("NFKC")].filter((t)=>{let e=t.codePointAt(0)??0;if(e===0||e>=1&&e<=8||e===11||e===12||e>=14&&e<=31||e===127)return!1;return!De.test(t)}).join("").trim()}function xt(n,t){let e=Date.parse(n);if(!Number.isFinite(e))throw Error(`MCP task ${t} is invalid`);return new Date(e).toISOString()}function Ge(n,t,e){if(!n||Buffer.byteLength(n)>e||Tn(n)!==n)throw Error(`MCP ${t} is invalid`);return n}function x(n,t,e,M){if(!Number.isSafeInteger(n)||n<t||n>e)throw Error(`${M} must be an integer between ${t} and ${e}`);return n}function ht(n,t){let e=Buffer.from(n);if(e.length<=t)return n;let M=e.subarray(0,t).toString("utf8");while(Buffer.byteLength(M)>t)M=M.slice(0,-1);return M}var Ke={sonnet:"claude-sonnet-4-20250514",opus:"claude-opus-4-20250514",haiku:"claude-3-5-haiku-20241022",claude:"claude-sonnet-4-20250514",gpt4o:"gpt-4o",gpt4:"gpt-4o",o1:"o1",o3:"o3","o4-mini":"o4-mini",deepseek:"deepseek-chat","deepseek-v3":"deepseek-chat","deepseek-r1":"deepseek-reasoner","deepseek-v4":"deepseek-v4-0324",gemini:"gemini-2.5-pro",flash:"gemini-2.5-flash",qwen:"qwen3-235b-a22b","qwen-max":"qwen-max","qwen-plus":"qwen-plus"};function sn(n){let t=n.toLowerCase().trim();return Ke[t]??n}var He=/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/,Ye=/^\.[A-Za-z0-9_+-]{1,32}$/;function y(n){return n!==null&&typeof n==="object"&&!Array.isArray(n)}function R(n,t,e,M,_){if(n===void 0)return _;if(!Number.isInteger(n)||Number(n)<e||Number(n)>M)throw Error(`${t} must be an integer between ${e} and ${M}`);return Number(n)}function Rt(n,t){if(n===void 0)return;let e;try{e=JSON.stringify(n)}catch{throw Error(`${t} must be JSON serializable`)}if(e===void 0||Buffer.byteLength(e)>262144)throw Error(`${t} exceeds the 256 KiB limit`);return structuredClone(n)}function Fe(n,t){if(n===void 0)return{};if(!y(n))throw Error(`${t} must be an object`);let e={};for(let[M,_]of Object.entries(n)){if(!M||typeof _!=="string"||_.includes("\x00"))throw Error(`${t} must contain non-empty string values`);e[M]=_}return e}function d(n){if(n===void 0)return{};if(!y(n))throw Error("lspServers must be an object");let t=Object.entries(n);if(t.length>32)throw Error("lspServers exceeds the 32-server limit");let e={};for(let[M,_]of t){if(!He.test(M))throw Error(`Invalid LSP server name: ${M}`);if(!y(_))throw Error(`lspServers.${M} must be an object`);let S=new Set(["command","args","extensionToLanguage","env","initializationOptions","settings","enabled","priority","startupTimeout","shutdownTimeout","requestTimeout","diagnosticWaitTimeout","maxRestarts"]),r=Object.keys(_).filter((g)=>!S.has(g));if(r.length>0)throw Error(`Unknown LSP server field: ${M}.${r[0]}`);if(typeof _.command!=="string"||!_.command.trim()||_.command.includes("\x00")||_.command.includes(`
|
|
22
|
+
`))throw Error(`lspServers.${M}.command must be a non-empty command`);if(_.args!==void 0&&!Array.isArray(_.args))throw Error(`lspServers.${M}.args must be an array`);let E=(_.args??[]).map((g,c)=>{if(typeof g!=="string"||g.includes("\x00"))throw Error(`lspServers.${M}.args.${c} must be a string`);return g});if(E.length>128)throw Error(`lspServers.${M}.args exceeds the 128-item limit`);if(!y(_.extensionToLanguage))throw Error(`lspServers.${M}.extensionToLanguage must be an object`);let u=Object.entries(_.extensionToLanguage);if(u.length===0||u.length>64)throw Error(`lspServers.${M}.extensionToLanguage must contain 1-64 entries`);let m={};for(let[g,c]of u){let $=g.startsWith(".")?g.toLowerCase():`.${g.toLowerCase()}`;if(!Ye.test($)||typeof c!=="string"||!c.trim())throw Error(`Invalid lspServers.${M}.extensionToLanguage entry: ${g}`);m[$]=c.trim()}if(_.enabled!==void 0&&typeof _.enabled!=="boolean")throw Error(`lspServers.${M}.enabled must be a boolean`);let A=Rt(_.initializationOptions,`lspServers.${M}.initializationOptions`),L=Rt(_.settings,`lspServers.${M}.settings`);e[M]={command:_.command.trim(),...E.length>0?{args:E}:{},extensionToLanguage:m,..._.env!==void 0?{env:Fe(_.env,`lspServers.${M}.env`)}:{},...A!==void 0?{initializationOptions:A}:{},...L!==void 0?{settings:L}:{},..._.enabled!==void 0?{enabled:_.enabled}:{},priority:R(_.priority,`lspServers.${M}.priority`,-1000,1000,0),startupTimeout:R(_.startupTimeout,`lspServers.${M}.startupTimeout`,100,60000,1e4),shutdownTimeout:R(_.shutdownTimeout,`lspServers.${M}.shutdownTimeout`,100,1e4,2000),requestTimeout:R(_.requestTimeout,`lspServers.${M}.requestTimeout`,100,60000,1e4),diagnosticWaitTimeout:R(_.diagnosticWaitTimeout,`lspServers.${M}.diagnosticWaitTimeout`,0,5000,750),maxRestarts:R(_.maxRestarts,`lspServers.${M}.maxRestarts`,0,10,3)}}return e}function Xt(n){return Number.isInteger(n)&&(n===-1||n>=0)}function $t(){return"-1 (unlimited), 0 (disabled), or any positive integer"}import pt from"node:path";var Ut=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,qe=/^(?:\*\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;function O(n){let t=[];for(let[e,M]of Object.entries(n)){if(!Ut.test(e))throw Error(`Invalid plugin name in enabledPlugins: ${e}`);if(typeof M!=="boolean")throw Error(`Invalid enabledPlugins value for ${e}`);t.push([e,M])}return Object.fromEntries(t)}function An(n,t,e){if(!Array.isArray(n))throw Error(`${t} must be an array`);return[...new Set(n.map((M,_)=>{if(typeof M!=="string"||!M.trim())throw Error(`${t}[${_}] must be a non-empty string`);return e(M.trim())}))].sort()}function z(n){let t=new Set(["restrictToAllowedSources","requireGitCommitSha","allowedGitHosts","allowedMarketplaces","allowedLocalRoots"]),e=Object.keys(n).filter((_)=>!t.has(_));if(e.length>0)throw Error(`Unknown pluginSourcePolicy fields: ${e.join(", ")}`);let M={};for(let _ of["restrictToAllowedSources","requireGitCommitSha"]){if(n[_]===void 0)continue;if(typeof n[_]!=="boolean")throw Error(`pluginSourcePolicy.${_} must be boolean`);M[_]=n[_]}if(n.allowedGitHosts!==void 0)M.allowedGitHosts=An(n.allowedGitHosts,"pluginSourcePolicy.allowedGitHosts",(_)=>{let S=_.toLowerCase();if(!qe.test(S))throw Error(`Invalid plugin Git host pattern: ${_}`);return S});if(n.allowedMarketplaces!==void 0)M.allowedMarketplaces=An(n.allowedMarketplaces,"pluginSourcePolicy.allowedMarketplaces",(_)=>{if(!Ut.test(_))throw Error(`Invalid allowed Marketplace name: ${_}`);return _});if(n.allowedLocalRoots!==void 0)M.allowedLocalRoots=An(n.allowedLocalRoots,"pluginSourcePolicy.allowedLocalRoots",(_)=>{if(!pt.isAbsolute(_))throw Error(`Plugin local allowlist root must be absolute: ${_}`);return pt.resolve(_)});return M}function l(n){let t=[];for(let[e,M]of Object.entries(n)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw Error(`Invalid environment variable name: ${e}`);if(typeof M!=="string"||M.includes("\x00"))throw Error(`Invalid environment variable value: ${e}`);t.push([e,M])}return Object.fromEntries(t)}class X{static instance=null;runtimePermissionOverrides;lastAdditionalSettings;warnedGlobalOnlyProjectionResidencyFiles=new Set;constructor(){}static getInstance(){if(!X.instance)X.instance=new X;return X.instance}static resetInstance(){X.instance=null}async initialize(n){try{this.lastAdditionalSettings=n,this.runtimePermissionOverrides=n?.permissions;let e=(await a.getInstance().getStatus(I())).state==="trusted",M=await this.loadConfigFiles(e),_=await this.loadSettingsFiles(e),S={...M,..._,enabledPlugins:{...M.enabledPlugins||{},..._.enabledPlugins||{}}};if(n)S=this.mergeSettings(S,n);let r=this.normalizeConfig(S),E={...s,...r};if(E.enabledPlugins=O(E.enabledPlugins),E.lspServers=d(E.lspServers),E.pluginSourcePolicy={...s.pluginSourcePolicy,...z(E.pluginSourcePolicy)},this.resolveEnvInterpolation(E),process.env.BLADE_MODEL&&E.models?.length>0){let u=sn(process.env.BLADE_MODEL),m=E.models.find((A)=>A.id===u||A.model===u||A.id===process.env.BLADE_MODEL||A.model===process.env.BLADE_MODEL);if(m)E.currentModelId=m.id}if(process.env.BLADE_DEBUG)E.debug=process.env.BLADE_DEBUG==="1"||process.env.BLADE_DEBUG==="true"||process.env.BLADE_DEBUG;if(v().configureModelProviders(E.modelProviders,E.models),E.models.length>0)this.validateConfig(E);if(E.debug)console.log("[ConfigManager] Configuration loaded successfully");return E}catch(t){return console.error("[ConfigManager] Failed to initialize:",t),v().configureModelProviders({},[]),s}}async reload(){return this.initialize(this.lastAdditionalSettings)}async loadConfigFiles(n){let t=o.join(i.homedir(),".blade","config.json"),e=o.join(I(),".blade","config.json"),M={},_=await this.loadJsonFile(t),S=_?await this.migrateLegacyUserConfig(_):null;if(S)M={...M,...S};let r=await this.loadJsonFile(e);if(r&&n){let E={...M.mcpServers||{},...r.mcpServers||{}},u={...M.lspServers||{},...r.lspServers||{}},m={...M.modelProviders||{},...r.modelProviders||{}},A={...M.enabledPlugins||{},...r.enabledPlugins||{}};if(M={...M,...r},Object.keys(E).length>0)M.mcpServers=E;if(Object.keys(u).length>0)M.lspServers=d(u);if(Object.keys(m).length>0)M.modelProviders=m;if(Object.keys(A).length>0)M.enabledPlugins=O(A)}else if(r?.hooks)M.hooks=r.hooks;return M}async migrateLegacyUserConfig(n){let t=n,e={...n},M={};if(e.codeTheme===void 0&&typeof t.theme==="string")e.codeTheme=t.theme,M.codeTheme=t.theme;if(Array.isArray(e.models)){let _=Et(e.models,e.currentModelId??"");if(_.changed)e.models=_.models,e.currentModelId=_.currentModelId,M.models=_.models,M.currentModelId=_.currentModelId}if(delete e.theme,Object.keys(M).length>0)try{await N.getInstance().save(M,{scope:"global",immediate:!0})}catch{console.warn("[ConfigManager] Could not persist legacy config migration")}return e}async loadSettingsFiles(n){let t=o.join(i.homedir(),".blade","settings.json"),e=o.join(I(),".blade","settings.json"),M=o.join(I(),".blade","settings.local.json"),_={},S=await this.loadJsonFile(t);if(S)_=this.mergeSettings(_,S);let r=this.stripGlobalOnlyProjectionResidencyFromLayer(await this.loadJsonFile(e),e,"project");if(r&&n)_=this.mergeSettings(_,r);else if(r?.hooks)_=this.mergeSettings(_,{hooks:r.hooks});let E=this.stripGlobalOnlyProjectionResidencyFromLayer(await this.loadJsonFile(M),M,"local");if(E&&n)_=this.mergeSettings(_,E);else if(E?.hooks)_=this.mergeSettings(_,{hooks:E.hooks});return _}stripGlobalOnlyProjectionResidencyFromLayer(n,t,e){if(!n)return n;let M=n.maxResidentSessionProjections!==void 0,_=n.sessionProjectionIdleMs!==void 0;if(!M&&!_)return n;this.warnGlobalOnlyProjectionResidencyOnce(t,e);let S={...n};return delete S.maxResidentSessionProjections,delete S.sessionProjectionIdleMs,S}warnGlobalOnlyProjectionResidencyOnce(n,t){if(this.warnedGlobalOnlyProjectionResidencyFiles.has(n))return;this.warnedGlobalOnlyProjectionResidencyFiles.add(n),console.warn(`[ConfigManager] Ignoring global-only session projection residency settings in ${t} settings file:`,n)}async loadWorkspacePermissions(n,t){let e={allow:[...t.allow],ask:[...t.ask],deny:[...t.deny]};if(o.resolve(n)!==o.resolve(I())){let _=await this.loadWorkspacePermissionOverrides(I(),{includeUntrusted:!0}),S=await this.loadJsonFile(o.join(i.homedir(),".blade","settings.json")),r={allow:Array.from(new Set([...s.permissions.allow,...S?.permissions?.allow||[],...this.runtimePermissionOverrides?.allow||[]])),ask:Array.from(new Set([...s.permissions.ask,...S?.permissions?.ask||[],...this.runtimePermissionOverrides?.ask||[]])),deny:Array.from(new Set([...s.permissions.deny,...S?.permissions?.deny||[],...this.runtimePermissionOverrides?.deny||[]]))};for(let E of["allow","ask","deny"]){let u=new Set(_[E].filter((m)=>!r[E].includes(m)));e[E]=e[E].filter((m)=>!u.has(m))}}let M=await this.loadWorkspacePermissionOverrides(n);for(let _ of["allow","ask","deny"])e[_]=Array.from(new Set([...e[_],...M[_]]));return e}async loadWorkspaceMcpServers(n,t){if(o.resolve(n)===o.resolve(I()))return{...t};let e=await a.getInstance().getStatus(n),M=e.state==="trusted",_=e.projectPath,S={},r=async(u)=>{let m=await this.loadJsonFile(u);if(m?.mcpServers)S={...S,...m.mcpServers}};if(await r(o.join(i.homedir(),".blade","config.json")),await r(o.join(i.homedir(),".blade","settings.json")),M)await r(o.join(_,".blade","config.json")),await r(o.join(_,".blade","settings.json")),await r(o.join(_,".blade","settings.local.json"));if(this.lastAdditionalSettings?.mcpServers)S={...S,...this.lastAdditionalSettings.mcpServers};let E={mcpServers:S};return this.resolveEnvInterpolation(E),E.mcpServers}async loadWorkspaceLspServers(n,t){if(o.resolve(n)===o.resolve(I()))return d(t);let e=await a.getInstance().getStatus(n),M={},_=async(r)=>{let E=await this.loadJsonFile(r);if(E?.lspServers)M={...M,...d(E.lspServers)}};if(await _(o.join(i.homedir(),".blade","config.json")),await _(o.join(i.homedir(),".blade","settings.json")),e.state==="trusted")for(let r of["config.json","settings.json","settings.local.json"])await _(o.join(e.projectPath,".blade",r));if(this.lastAdditionalSettings?.lspServers)M={...M,...d(this.lastAdditionalSettings.lspServers)};let S={lspServers:M};return this.resolveEnvInterpolation(S),d(S.lspServers)}async loadWorkspaceModelConfig(n,t){if(o.resolve(n)===o.resolve(I()))return{currentModelId:t.currentModelId,models:t.models.map((r)=>structuredClone(r)),modelProviders:structuredClone(t.modelProviders),temperature:t.temperature,...t.maxOutputTokens!==void 0?{maxOutputTokens:t.maxOutputTokens}:{},timeout:t.timeout,...t.providerCircuitBreakerOpenMs!==void 0?{providerCircuitBreakerOpenMs:t.providerCircuitBreakerOpenMs}:{},...t.providerRequestConcurrency!==void 0?{providerRequestConcurrency:t.providerRequestConcurrency}:{},...t.providerGlobalConcurrency!==void 0?{providerGlobalConcurrency:t.providerGlobalConcurrency}:{},...t.providerOwnerConcurrency!==void 0?{providerOwnerConcurrency:t.providerOwnerConcurrency}:{},...t.providerRequestAdmissionMs!==void 0?{providerRequestAdmissionMs:t.providerRequestAdmissionMs}:{},...t.providerRequestPendingBytes!==void 0?{providerRequestPendingBytes:t.providerRequestPendingBytes}:{}};let e=await a.getInstance().getStatus(n),M=e.projectPath,_={currentModelId:s.currentModelId,models:s.models.map((r)=>structuredClone(r)),modelProviders:structuredClone(s.modelProviders),temperature:s.temperature,...s.maxOutputTokens!==void 0?{maxOutputTokens:s.maxOutputTokens}:{},timeout:s.timeout,...s.providerCircuitBreakerOpenMs!==void 0?{providerCircuitBreakerOpenMs:s.providerCircuitBreakerOpenMs}:{},...s.providerRequestConcurrency!==void 0?{providerRequestConcurrency:s.providerRequestConcurrency}:{},...s.providerGlobalConcurrency!==void 0?{providerGlobalConcurrency:s.providerGlobalConcurrency}:{},...s.providerOwnerConcurrency!==void 0?{providerOwnerConcurrency:s.providerOwnerConcurrency}:{},...s.providerRequestAdmissionMs!==void 0?{providerRequestAdmissionMs:s.providerRequestAdmissionMs}:{},...s.providerRequestPendingBytes!==void 0?{providerRequestPendingBytes:s.providerRequestPendingBytes}:{}},S=(r)=>{if(!r)return;if(r.modelProviders)_.modelProviders={..._.modelProviders,...structuredClone(r.modelProviders)};if(r.models)_.models=r.models.map((E)=>structuredClone(E));if(r.currentModelId!==void 0)_.currentModelId=r.currentModelId;if(r.temperature!==void 0)_.temperature=r.temperature;if(r.maxOutputTokens!==void 0)_.maxOutputTokens=r.maxOutputTokens;if(r.timeout!==void 0)_.timeout=r.timeout;if(r.providerCircuitBreakerOpenMs!==void 0)_.providerCircuitBreakerOpenMs=r.providerCircuitBreakerOpenMs;if(r.providerRequestConcurrency!==void 0)_.providerRequestConcurrency=r.providerRequestConcurrency;if(r.providerGlobalConcurrency!==void 0)_.providerGlobalConcurrency=r.providerGlobalConcurrency;if(r.providerOwnerConcurrency!==void 0)_.providerOwnerConcurrency=r.providerOwnerConcurrency;if(r.providerRequestAdmissionMs!==void 0)_.providerRequestAdmissionMs=r.providerRequestAdmissionMs;if(r.providerRequestPendingBytes!==void 0)_.providerRequestPendingBytes=r.providerRequestPendingBytes};if(S(await this.loadJsonFile(o.join(i.homedir(),".blade","config.json"))),S(await this.loadJsonFile(o.join(i.homedir(),".blade","settings.json"))),e.state==="trusted")S(await this.loadJsonFile(o.join(M,".blade","config.json"))),S(await this.loadJsonFile(o.join(M,".blade","settings.json"))),S(await this.loadJsonFile(o.join(M,".blade","settings.local.json")));if(S(this.lastAdditionalSettings),_=this.normalizeConfig(_),this.resolveEnvInterpolation(_),process.env.BLADE_MODEL&&_.models.length>0){let r=process.env.BLADE_MODEL,E=sn(r),u=_.models.find((m)=>m.id===E||m.model===E||m.id===r||m.model===r);if(u)_.currentModelId=u.id}if(!_.models.some((r)=>r.id===_.currentModelId))_.currentModelId=_.models[0]?.id??"";return _}async loadWorkspaceRuntimeSettings(n,t){if(o.resolve(n)===o.resolve(I()))return{env:l(t.env),disableAllHooks:t.disableAllHooks,maxTurns:t.maxTurns,permissionMode:t.permissionMode};let e=await a.getInstance().getStatus(n),M=e.projectPath,_={env:{},disableAllHooks:s.disableAllHooks,maxTurns:s.maxTurns,permissionMode:s.permissionMode},S=(u,m)=>{if(!u)return;if(m.allowExecutionSettings){if(u.env)_.env={..._.env,...l(u.env)};if(u.maxTurns!==void 0)_.maxTurns=u.maxTurns;if(u.permissionMode!==void 0)_.permissionMode=u.permissionMode;if(u.disableAllHooks!==void 0)_.disableAllHooks=u.disableAllHooks}else if(u.disableAllHooks===!0)_.disableAllHooks=!0};S(await this.loadJsonFile(o.join(i.homedir(),".blade","config.json")),{allowExecutionSettings:!0}),S(await this.loadJsonFile(o.join(i.homedir(),".blade","settings.json")),{allowExecutionSettings:!0});let r=await Promise.all([this.loadJsonFile(o.join(M,".blade","config.json")),this.loadJsonFile(o.join(M,".blade","settings.json")),this.loadJsonFile(o.join(M,".blade","settings.local.json"))]);for(let u of r)S(u,{allowExecutionSettings:e.state==="trusted"});S(this.lastAdditionalSettings,{allowExecutionSettings:!0});let E={env:_.env};return this.resolveEnvInterpolation(E),_.env=l(E.env),_}async loadWorkspacePluginSettings(n){return(await this.loadWorkspacePluginSettingsResolution(n)).effective}async loadWorkspacePluginSettingsResolution(n){let t=await a.getInstance().getStatus(n),e={},M={},_=(S,r,E)=>{if(!S?.enabledPlugins)return;let u=O(S.enabledPlugins);for(let[m,A]of Object.entries(u)){if(!E&&A!==!1)continue;let L=M[m];e[m]=A,M[m]={effective:A,effectiveScope:r,layers:{...L?.layers??{},[r]:A}}}};_(await this.loadJsonFile(o.join(i.homedir(),".blade","config.json")),"global",!0),_(await this.loadJsonFile(o.join(i.homedir(),".blade","settings.json")),"global",!0);for(let S of["config.json","settings.json"])_(await this.loadJsonFile(o.join(t.projectPath,".blade",S)),"project",t.state==="trusted");return _(await this.loadJsonFile(o.join(t.projectPath,".blade","settings.local.json")),"local",t.state==="trusted"),_(this.lastAdditionalSettings,"invocation",!0),{effective:e,settings:M,workspaceTrusted:t.state==="trusted"}}async loadWorkspacePluginSourcePolicy(n){let t=await a.getInstance().getStatus(n),e={...s.pluginSourcePolicy,allowedGitHosts:[...s.pluginSourcePolicy.allowedGitHosts],allowedMarketplaces:[...s.pluginSourcePolicy.allowedMarketplaces],allowedLocalRoots:[...s.pluginSourcePolicy.allowedLocalRoots]},M=(r)=>{if(!r?.pluginSourcePolicy)return;Object.assign(e,z(r.pluginSourcePolicy))},_=(r,E)=>{if(!E)return r;if(r.length===0&&!e.restrictToAllowedSources)return E;let u=new Set(E);return r.filter((m)=>u.has(m))},S=(r)=>{if(!r?.pluginSourcePolicy)return;let E=z(r.pluginSourcePolicy);e.allowedGitHosts=_(e.allowedGitHosts,E.allowedGitHosts),e.allowedMarketplaces=_(e.allowedMarketplaces,E.allowedMarketplaces),e.allowedLocalRoots=_(e.allowedLocalRoots,E.allowedLocalRoots),e.restrictToAllowedSources=e.restrictToAllowedSources||E.restrictToAllowedSources===!0,e.requireGitCommitSha=e.requireGitCommitSha||E.requireGitCommitSha===!0};M(await this.loadJsonFile(o.join(i.homedir(),".blade","config.json"))),M(await this.loadJsonFile(o.join(i.homedir(),".blade","settings.json")));for(let r of["config.json","settings.json","settings.local.json"])S(await this.loadJsonFile(o.join(t.projectPath,".blade",r)));if(S(this.lastAdditionalSettings),process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true")e.requireGitCommitSha=!0;return e}async loadWorkspaceHooks(n,t,e={}){if(o.resolve(n)===o.resolve(I())&&e.includeBaseForCurrentWorkspace!==!1)return D({},t);let M=D({},s.hooks),_=[o.join(i.homedir(),".blade","settings.json"),o.join(n,".blade","settings.json"),o.join(n,".blade","settings.local.json")];for(let S of _){let r=await this.loadJsonFile(S);if(r?.hooks)M=D({},M,r.hooks)}return M}async loadWorkspacePermissionOverrides(n,t={}){let e={allow:[],ask:[],deny:[]},M=(await a.getInstance().getStatus(n)).state==="trusted",_=[...M||t.includeUntrusted?[o.join(n,".blade","settings.json")]:[],...M||t.includeUntrusted?[o.join(n,".blade","settings.local.json")]:[]];for(let S of _){let r=await this.loadJsonFile(S);if(!r?.permissions)continue;for(let E of["allow","ask","deny"])e[E]=Array.from(new Set([...e[E],...r.permissions[E]||[]]))}return e}mergeSettings(n,t){let e={...JSON.parse(JSON.stringify(n)),...JSON.parse(JSON.stringify(t))};if(t.permissions)e.permissions={allow:Array.from(new Set([...n.permissions?.allow||[],...t.permissions.allow||[]])),ask:Array.from(new Set([...n.permissions?.ask||[],...t.permissions.ask||[]])),deny:Array.from(new Set([...n.permissions?.deny||[],...t.permissions.deny||[]]))};if(t.hooks)e.hooks=D({},e.hooks,t.hooks);if(t.enabledPlugins)e.enabledPlugins={...n.enabledPlugins||{},...O(t.enabledPlugins)};if(t.pluginSourcePolicy)e.pluginSourcePolicy={...n.pluginSourcePolicy??s.pluginSourcePolicy,...z(t.pluginSourcePolicy)};if(t.env)e.env=D({},e.env,t.env);if(t.mcpServers)e.mcpServers={...e.mcpServers||{},...t.mcpServers};if(t.lspServers)e.lspServers={...e.lspServers||{},...d(t.lspServers)};if(t.disableAllHooks!==void 0)e.disableAllHooks=t.disableAllHooks;if(t.permissionMode!==void 0)e.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)e.maxTurns=t.maxTurns;return e}resolveEnvInterpolation(n){let t=/\$\{?([A-Z_][A-Z0-9_]*)(:-([^}]+))?\}?/g,e=(_)=>{if(typeof _==="string")return _.replace(t,(S,r,E,u)=>{return process.env[r]||u||S});if(Array.isArray(_))return _.map(e);if(typeof _==="object"&&_!==null){let S=_;for(let[r,E]of Object.entries(S))S[r]=e(E);return S}return _},M=n;for(let[_,S]of Object.entries(M))M[_]=e(S)}async loadJsonFile(n){try{if(await this.fileExists(n)){let t=await Ot.readFile(n,"utf-8");return JSON.parse(t)}}catch(t){console.warn(`[ConfigManager] Failed to load ${n}:`,t)}return null}async fileExists(n){try{return await Ot.access(n),!0}catch{return!1}}normalizeConfig(n){let t=JSON.parse(JSON.stringify(n));if(t.codeTheme===void 0&&typeof t.theme==="string")t.codeTheme=t.theme;delete t.theme;let e=(_)=>_.trim().replace(/^`|`$/g,""),M=(_)=>{for(let[S,r]of Object.entries(_))if(typeof r==="string")_[S]=e(r);else if(Array.isArray(r))r.forEach((E,u)=>{if(typeof E==="string")r[u]=e(E);else if(typeof E==="object"&&E!==null)M(E)});else if(typeof r==="object"&&r!==null)M(r)};return M(t),t}validateConfig(n,t=v()){let e=[];try{n.lspServers=d(n.lspServers)}catch(M){e.push(M instanceof Error?M.message:"Invalid LSP server configuration")}for(let[M,_]of Object.entries(n.mcpServers||{}))try{ot(_),_.oauth=nn(_);let S=ct(_);if(_.logging!==void 0)_.logging=S;if(_.sampling)_.sampling=Pt(_.sampling);if(_.tasks)_.tasks=Ct(_.tasks)}catch(S){e.push(`MCP server "${M}": ${S instanceof Error?S.message:"invalid sampling policy"}`)}for(let[M,_]of Object.entries(n.modelProviders||{}))if(e.push(...zt(M,_)),t.isReservedProviderId(M))e.push(`modelProviders.${M}: built-in provider ids cannot be overridden`);if(e.length===0)try{t.configureModelProviders(n.modelProviders||{},n.models)}catch(M){e.push(M instanceof Error?M.message:"Failed to configure custom model providers")}if(!n.models||n.models.length===0)e.push("没有可用的模型配置");if(!Xt(n.maxTurns))e.push(`maxTurns 必须是 ${$t()}`);if(!ln(n.maxConcurrentTasks))e.push(`maxConcurrentTasks 必须是 ${Jn}-${Qn} 之间的整数`);if(!vn(n.maxQueuedTasks))e.push(`maxQueuedTasks 必须是 ${jn}-${Wn} 之间的整数`);if(!nt(n.maxQueuedTaskBytes))e.push(`maxQueuedTaskBytes 必须是 ${kn}-${yn} 之间的整数`);if(!qn(n.maxResidentSessionRuntimes))e.push(`maxResidentSessionRuntimes 必须是 ${Bn}-${Kn} 之间的整数`);if(!Vn(n.sessionRuntimeIdleMs))e.push(`sessionRuntimeIdleMs 必须是 ${Hn}-${Fn} 之间的整数`);if(!J(n.maxResidentSessionProjections))e.push("maxResidentSessionProjections 必须是 "+`${Y}-${F} 之间的整数`);if(!Q(n.sessionProjectionIdleMs))e.push(`sessionProjectionIdleMs 必须是 ${q}-${V} 之间的整数`);if(n.bashForegroundHandoffMs!==void 0&&!un(n.bashForegroundHandoffMs))e.push("bashForegroundHandoffMs 必须是 0,或 "+`${zn}-${Dn} 之间的整数`);if(n.providerForegroundRecoveryMs!==void 0&&!Gt(n.providerForegroundRecoveryMs))e.push("providerForegroundRecoveryMs 必须是 0,或 "+`${Dt}-${Bt} 之间的整数`);if(n.providerCircuitBreakerOpenMs!==void 0&&!Yt(n.providerCircuitBreakerOpenMs))e.push("providerCircuitBreakerOpenMs 必须是 0,或 "+`${Kt}-${Ht} 之间的整数`);if(n.providerRequestConcurrency!==void 0&&!Wt(n.providerRequestConcurrency))e.push("providerRequestConcurrency 必须是 "+`${cn}-${Ft} 之间的整数`);for(let[M,_]of[["providerGlobalConcurrency",n.providerGlobalConcurrency],["providerOwnerConcurrency",n.providerOwnerConcurrency]])if(_!==void 0&&!Zt(_))e.push(`${M} 必须是 ${cn}-${qt} 之间的整数`);if(n.providerRequestAdmissionMs!==void 0&&!kt(n.providerRequestAdmissionMs))e.push("providerRequestAdmissionMs 必须是 0,或 "+`${Vt}-${Jt} 之间的整数`);if(n.providerRequestPendingBytes!==void 0&&!yt(n.providerRequestPendingBytes))e.push("providerRequestPendingBytes 必须是 "+`${Qt}-${jt} 之间的整数`);if(n.models&&n.models.length>0){if(!n.currentModelId)e.push("未设置当前模型 ID");else if(!n.models.find((_)=>_.id===n.currentModelId))e.push(`当前模型 ID "${n.currentModelId}" 在 models 列表中不存在`);for(let M of n.models){let _=`模型 "${M.displayName||M.id}"`,S=["name","apiKey","baseUrl","maxContextTokens","maxOutputTokens","supportsThinking","thinkingBudget","thinkingMode"].filter((E)=>(E in M));if(S.length>0)e.push(`${_}: 不再支持旧字段 ${S.join(", ")};请重新配置模型`);if(!M.model)e.push(`${_}: model 字段必填`);if(!M.provider)e.push(`${_}: provider 字段必填`);if(M.overrides?.baseUrl&&!M.overrides.baseUrl.startsWith("http"))e.push(`${_}: overrides.baseUrl "${M.overrides.baseUrl}" 不是有效的 HTTP URL`);let r=M.overrides?.streamIdleTimeout;if(r!==void 0&&(!Number.isFinite(r)||r<1000))e.push(`${_}: overrides.streamIdleTimeout 必须至少为 1000ms`);try{t.getModel(M.provider,M.model)}catch{e.push(`${_}: 内置 catalog 中不存在 ${M.provider}/${M.model}`)}}}if(e.length>0)throw Error(`配置验证失败:
|
|
23
|
+
${e.map((M)=>` - ${M}`).join(`
|
|
24
|
+
`)}
|
|
25
|
+
|
|
26
|
+
`+`请通过以下方式之一提供配置:
|
|
27
|
+
`+` 1. 首次启动: 运行 blade,系统会自动引导配置
|
|
28
|
+
`+` 2. 添加模型: blade 后输入 /model add
|
|
29
|
+
`+` 3. 初始化向导: 输入 /init
|
|
30
|
+
|
|
31
|
+
`+`配置文件示例 (~/.blade/config.json):
|
|
32
|
+
`+`{
|
|
33
|
+
"currentModelId": "model-id-123",
|
|
34
|
+
"models": [
|
|
35
|
+
{
|
|
36
|
+
"id": "model-id-123",
|
|
37
|
+
`+` "displayName": "默认模型",
|
|
38
|
+
`+` "provider": "deepseek",
|
|
39
|
+
"model": "deepseek-v4-pro"
|
|
40
|
+
}
|
|
41
|
+
]
|
|
42
|
+
}
|
|
43
|
+
`)}}function W_(n,t={}){let e={...n};if(t.debug!==void 0)e.debug=t.debug===""?!0:t.debug;if(t.model){if(!n.models.some((_)=>_.id===t.model))throw Error(`模型配置未找到: ${t.model}`);e.currentModelId=t.model}if(t.yolo===!0)e.permissionMode="yolo";else if(t.permissionMode!==void 0)e.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)e.maxTurns=t.maxTurns;if(t.maxConcurrentTasks!==void 0)e.maxConcurrentTasks=t.maxConcurrentTasks;if(t.maxQueuedTasks!==void 0)e.maxQueuedTasks=t.maxQueuedTasks;if(t.maxQueuedTaskBytes!==void 0)e.maxQueuedTaskBytes=t.maxQueuedTaskBytes;if(t.maxResidentSessionRuntimes!==void 0)e.maxResidentSessionRuntimes=t.maxResidentSessionRuntimes;if(t.sessionRuntimeIdleMs!==void 0)e.sessionRuntimeIdleMs=t.sessionRuntimeIdleMs;if(t.maxResidentSessionProjections!==void 0)e.maxResidentSessionProjections=t.maxResidentSessionProjections;if(t.sessionProjectionIdleMs!==void 0)e.sessionProjectionIdleMs=t.sessionProjectionIdleMs;return e.systemPrompt=t.systemPrompt,e.appendSystemPrompt=t.appendSystemPrompt,e.model=t.model,e.resumeSessionId=t.sessionId,e.forkSession=t.forkSession,e.allowedTools=t.allowedTools,e.disallowedTools=t.disallowedTools,e.mcpConfigPaths=t.mcpConfig,e.strictMcpConfig=t.strictMcpConfig,e.addDirs=t.addDir,e.outputFormat=t.outputFormat,e.inputFormat=t.inputFormat,e.print=t.print,e.includePartialMessages=t.includePartialMessages,e.replayUserMessages=t.replayUserMessages,e.agentsConfig=t.agents,e.settingSources=t.settingSources,e}
|
|
44
|
+
export{B as zg,nn as Ag,f as Bg,En as Cg,hn as Dg,C as Eg,ot as Fg,VM as Gg,W as Hg,jM as Ig,WM as Jg,ZM as Kg,ct as Lg,Ce as Mg,kM as Ng,he as Og,yM as Pg,Pt as Qg,n_ as Rg,t_ as Sg,M_ as Tg,__ as Ug,r_ as Vg,Ct as Wg,S_ as Xg,E_ as Yg,u_ as Zg,o_ as _g,Y as $g,Rn as ah,F as bh,q as ch,Xn as dh,V as eh,TM as fh,sM as gh,J as hh,Q as ih,h as jh,xM as kh,zn as lh,Dn as mh,hM as nh,Bn as oh,Gn as ph,Kn as qh,Hn as rh,Yn as sh,Fn as th,XM as uh,qn as vh,Vn as wh,Jn as xh,Qn as yh,jn as zh,Wn as Ah,Zn as Bh,kn as Ch,yn as Dh,ln as Eh,vn as Fh,nt as Gh,s as Hh,d as Ih,Le as Jh,z as Kh,l as Lh,X as Mh,W_ as Nh};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Rf as a,Sf as b,Tf as c,Uf as d,Vf as e,Wf as f,Xf as g,Yf as h,Zf as i,_f as j}from"./chunk-
|
|
1
|
+
import{Rf as a,Sf as b,Tf as c,Uf as d,Vf as e,Wf as f,Xf as g,Yf as h,Zf as i,_f as j}from"./chunk-0gmzs677.js";import"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import"./chunk-m6pnnjq4.js";import"./chunk-2t6b962t.js";import"./chunk-dm1yxsdx.js";import"./chunk-y94239bb.js";import"./chunk-cw2b3383.js";import"./chunk-2j2mnzdg.js";import"./chunk-s6562rsq.js";import"./chunk-hbafhk9y.js";import"./chunk-68sf54n4.js";import"./chunk-sv833k2e.js";import"./chunk-w7n73ag8.js";import"./chunk-827422x9.js";import"./chunk-1g0d9yw0.js";import"./chunk-6kwg4hcv.js";import"./chunk-9xzw649r.js";import"./chunk-hmwz31tc.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,j as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
|