blade-code 0.10.46 → 0.10.63
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-0d1197b9.js +1 -0
- package/dist/chunk-0ft3egjr.js +710 -0
- package/dist/chunk-0jxh2zq5.js +5 -0
- package/dist/{chunk-4dthhzfe.js → chunk-1hb0rt7n.js} +1 -1
- package/dist/{chunk-26wse17p.js → chunk-1jc7d3nt.js} +2 -2
- package/dist/{chunk-sqd5ge5s.js → chunk-2xbmkyb2.js} +1 -1
- package/dist/chunk-2xsrqsk9.js +44 -0
- package/dist/chunk-2yws8pqt.js +1 -0
- package/dist/{chunk-0qsssahq.js → chunk-2z3xe3rw.js} +1 -1
- package/dist/{chunk-fk4wbmv6.js → chunk-3tednchw.js} +2 -2
- package/dist/chunk-5sk6v1et.js +10 -0
- package/dist/{chunk-qp2z1r7y.js → chunk-69rc9hw6.js} +1 -1
- package/dist/chunk-6fdvffcc.js +2 -0
- package/dist/{chunk-c9s4n31b.js → chunk-6g3qzz9h.js} +1 -1
- package/dist/{chunk-2eddqgnh.js → chunk-6rg6mngq.js} +1 -1
- package/dist/{chunk-8y3skwtt.js → chunk-6x1g554w.js} +1 -1
- package/dist/{chunk-m8ss9rmx.js → chunk-7b467h8k.js} +1 -1
- package/dist/{chunk-8vtyatd6.js → chunk-83wm4akj.js} +1 -1
- package/dist/chunk-86gc2mqb.js +1 -0
- package/dist/{chunk-cxzx7j0p.js → chunk-87jz5600.js} +1 -1
- package/dist/{chunk-1atpfmpe.js → chunk-8an49nbn.js} +53 -53
- package/dist/chunk-8b1ehxzh.js +45 -0
- package/dist/{chunk-yk9pxkc1.js → chunk-8ekk8pa7.js} +1 -1
- package/dist/{chunk-xes0szvj.js → chunk-94d8hhqc.js} +2 -2
- package/dist/{chunk-s5205dnv.js → chunk-95hvy6dn.js} +2 -2
- package/dist/chunk-9c31jemm.js +1 -0
- package/dist/chunk-9kmtcgm6.js +2 -0
- package/dist/{chunk-mrsc4a55.js → chunk-9r0yebs1.js} +1 -1
- package/dist/{chunk-szdcprq7.js → chunk-9rjaem5f.js} +2 -2
- package/dist/{chunk-t4y3h47y.js → chunk-adz2756v.js} +2 -2
- package/dist/{chunk-ssymrsyx.js → chunk-atqnan6x.js} +2 -2
- package/dist/{chunk-hfrcwkc8.js → chunk-av10vmxk.js} +1 -1
- package/dist/{chunk-9rrced3b.js → chunk-b19f55s7.js} +1 -1
- package/dist/{chunk-q78s028m.js → chunk-cm9mph7j.js} +1 -1
- package/dist/chunk-cq77ah56.js +6 -0
- package/dist/{chunk-qmxfkkgn.js → chunk-cr154zrx.js} +2 -2
- package/dist/chunk-cx05we7e.js +1 -0
- package/dist/{chunk-qb0sqh29.js → chunk-cz68x56m.js} +2 -2
- package/dist/{chunk-tpa75y39.js → chunk-d1t91jgz.js} +1 -1
- package/dist/{chunk-2yvte5a7.js → chunk-detkh4dd.js} +1 -1
- package/dist/chunk-dpzx4mgb.js +1 -0
- package/dist/chunk-dq9ya06q.js +1 -0
- package/dist/{chunk-f4sp074f.js → chunk-eeac8teg.js} +1 -1
- package/dist/chunk-ej6h16ae.js +3 -0
- package/dist/{chunk-hcm55r3d.js → chunk-fp1h8wdh.js} +1 -1
- package/dist/{chunk-ecf8dh3c.js → chunk-fp2fh7cn.js} +16 -16
- package/dist/chunk-g0n88mhg.js +1 -0
- package/dist/{chunk-j66r48pz.js → chunk-hpehkz2x.js} +2 -2
- package/dist/{chunk-jmksywff.js → chunk-j8akkmc8.js} +1 -1
- package/dist/{chunk-7fqsgdee.js → chunk-j9snkjpe.js} +2 -2
- package/dist/{chunk-v9tzhe90.js → chunk-jk8bqc5b.js} +2 -2
- package/dist/{chunk-67zpsrst.js → chunk-k4ermznt.js} +1 -1
- package/dist/chunk-khkhsaan.js +2 -0
- package/dist/{chunk-kfpzrmq7.js → chunk-kjvntyr5.js} +1 -1
- package/dist/{chunk-4qvna4m2.js → chunk-kxrss9sv.js} +1 -1
- package/dist/chunk-m0t7g2vg.js +1 -0
- package/dist/{chunk-8kzdhgys.js → chunk-ng0tkmrn.js} +2 -2
- package/dist/chunk-nnbfk60b.js +1 -0
- package/dist/chunk-nnc1abkf.js +1 -0
- package/dist/{chunk-2yjm55cb.js → chunk-pdrqnywp.js} +1 -1
- package/dist/chunk-q7pznpyh.js +1 -0
- package/dist/{chunk-y6tkxqjx.js → chunk-qs4erqd0.js} +2 -2
- package/dist/chunk-rwy763tf.js +160 -0
- package/dist/chunk-tf4p1778.js +1 -0
- package/dist/{chunk-5vbrcvxg.js → chunk-ttkwrqtp.js} +1 -1
- package/dist/chunk-vhckw5e7.js +1 -0
- package/dist/{chunk-yrd794kb.js → chunk-w4sp56dn.js} +1 -1
- package/dist/{chunk-56qew7w0.js → chunk-wwsg165p.js} +2 -2
- package/dist/{chunk-wwvb6znp.js → chunk-wy4pn9sk.js} +1 -1
- package/dist/chunk-xsx1av03.js +1621 -0
- package/dist/{chunk-fhnkyqfb.js → chunk-y8r2knxm.js} +2 -2
- package/dist/chunk-yagna3ws.js +8 -0
- package/dist/web/assets/ChatView-B6IO9U-D.js +18 -0
- package/dist/web/assets/{CodeBlockHighlighter-Bb3gIeQv.js → CodeBlockHighlighter-DVGtFQgX.js} +1 -1
- package/dist/web/assets/{FilePreview-BXg9VaTv.js → FilePreview-C-8_o7yw.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-vxpqGt4L.js → MarkdownRenderer-D04IKQhF.js} +3 -3
- package/dist/web/assets/{SettingsModal-4L1nPkh0.js → SettingsModal-BMoZLVEe.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-DKSqTLK1.js → TaskSwitcher-CIuCEbvU.js} +1 -1
- package/dist/web/assets/{TerminalPanel-Bv9PDclr.js → TerminalPanel-fTk9D5hU.js} +1 -1
- package/dist/web/assets/{index-Bz4W1-8a.js → index-CO5sUiJn.js} +6 -6
- package/dist/web/assets/index-Dxdnbd79.css +1 -0
- package/dist/web/assets/{session-events-DJh6SZcl.js → session-events-BvtUOaNG.js} +8 -8
- package/dist/web/index.html +3 -3
- package/package.json +12 -2
- package/dist/chunk-3y784b9c.js +0 -1
- package/dist/chunk-54d7545y.js +0 -1
- package/dist/chunk-6cx4t8r6.js +0 -1
- package/dist/chunk-6h28xs47.js +0 -8
- package/dist/chunk-7qpbtnsa.js +0 -6
- package/dist/chunk-7sna3js9.js +0 -2
- package/dist/chunk-807x1cw8.js +0 -2
- package/dist/chunk-9mnbnyrc.js +0 -1
- package/dist/chunk-aarwre5y.js +0 -1
- package/dist/chunk-bvf9syb2.js +0 -3
- package/dist/chunk-cyw6cpac.js +0 -44
- package/dist/chunk-egczvfsv.js +0 -5
- package/dist/chunk-fer18bbe.js +0 -1
- package/dist/chunk-fz91aw1w.js +0 -10
- package/dist/chunk-j7edwwg1.js +0 -2
- package/dist/chunk-mqmf40p2.js +0 -1
- package/dist/chunk-n5dkq98k.js +0 -160
- package/dist/chunk-qbvm38ba.js +0 -1
- package/dist/chunk-sh58bey1.js +0 -1
- package/dist/chunk-sjtbp01y.js +0 -710
- package/dist/chunk-sztrmhgd.js +0 -1
- package/dist/chunk-v6ydjg9c.js +0 -1
- package/dist/chunk-vhamhbej.js +0 -1612
- package/dist/chunk-vhxtzacr.js +0 -1
- package/dist/chunk-yha9fpc7.js +0 -1
- package/dist/chunk-yvyqhw5q.js +0 -45
- package/dist/chunk-z1aqe7ms.js +0 -1
- package/dist/web/assets/ChatView-CyxiCTbL.js +0 -18
- package/dist/web/assets/index-7zaeanZL.css +0 -1
package/dist/chunk-cyw6cpac.js
DELETED
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
import{Tf as mn,Uf as j,Vf as o}from"./chunk-m8ss9rmx.js";import{Zf as bt,_f as ct}from"./chunk-j7edwwg1.js";import{dg as a}from"./chunk-kfpzrmq7.js";import{Ag as Gt,eg as Zn,fg as Xt,gg as gt,kg as pt,lg as On,mg as it,ng as Rt,og as Ct,pg as Jn,qg as zt,rg as Bt,sg as kn,tg as Kt,ug as Ut,vg as yn,wg as Ht,xg as Yt,yg as qt,zg as Vt}from"./chunk-yk9pxkc1.js";import{Eg as hn}from"./chunk-fhnkyqfb.js";import{Hg as $t,Kg as Z}from"./chunk-26wse17p.js";import{Sg as wn,Tg as an}from"./chunk-807x1cw8.js";import{Xg as d}from"./chunk-bvf9syb2.js";import{fh as En}from"./chunk-qb0sqh29.js";var Qt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Dt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function R(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&Dt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var U=async(n,t)=>{R(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function O(n){let t=n.oauth;if(!t)return;let M=t;for(let u of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[u]!==void 0)throw Error(`MCP OAuth "${u}" 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(R(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((u)=>u.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let r=t.clientId?.trim();if(r&&r.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((u)=>u.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((u)=>!u||u.length>128||!Qt.test(u)))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 _=t.callbackPort;if(_!==void 0&&(!Number.isInteger(_)||_<1024||_>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...r?{clientId:r}:{},...S?.length?{scopes:S}:{},..._!==void 0?{callbackPort:_}:{}}}import{randomUUID as l}from"node:crypto";import MM from"node:http";import{auth as sn}from"@modelcontextprotocol/sdk/client/auth.js";import eM from"open";import{createHash as Wt,randomUUID as Zt}from"node:crypto";import{constants as J,promises as P}from"node:fs";import k from"node:path";import{Mutex as Ot}from"async-mutex";import Jt from"write-file-atomic";var Tn=1,kt=1048576,yt=5000,jt=50,Ft=/^[a-f0-9]{64}$/,lt=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),vt=o.Object({access_token:o.String({minLength:1,maxLength:65536}),token_type:o.String({minLength:1,maxLength:64}),expires_in:o.Optional(o.Number({minimum:0})),refresh_token:o.Optional(o.String({minLength:1,maxLength:65536})),scope:o.Optional(o.String({maxLength:16384})),id_token:o.Optional(o.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),nM=o.Unsafe({type:"object",properties:{authorizationServerUrl:o.String({format:"uri"}),resourceMetadataUrl:o.Optional(o.String({format:"uri"})),resourceMetadata:o.Optional(o.Unknown()),authorizationServerMetadata:o.Optional(o.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),on=o.Object({serverUrl:o.String({format:"uri"}),clientId:o.Optional(o.String({minLength:1,maxLength:4096})),clientInformation:o.Optional(lt),tokens:o.Optional(vt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(nM),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),Sn=o.Object({version:o.Literal(Tn),credentials:o.Record(o.String(),on)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function tM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function y(n){return structuredClone(n)}function un(n){if(Object.keys(n.credentials).some((t)=>!Ft.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function Y(n){let t=new URL(n);return t.hash="",t.toString()}function F(n,t,M=[]){return Wt("sha256").update(JSON.stringify({serverUrl:Y(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class N{static mutexes=new Map;stateRoot;tokenFilePath;mutex;constructor(n=En()){this.stateRoot=k.join(n,"mcp"),this.tokenFilePath=k.join(this.stateRoot,"oauth-credentials.json");let t=N.mutexes.get(this.tokenFilePath);if(!t)t=new Ot,N.mutexes.set(this.tokenFilePath,t);this.mutex=t}async getCredential(n){return this.mutex.runExclusive(async()=>{let M=(await this.readStore()).credentials[n];return M?y(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],r=await t(e?y(e):null);if(r)M.credentials[n]=j(on,r);else delete M.credentials[n];return r?y(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return this.mutex.runExclusive(async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return this.mutex.runExclusive(async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),e=await n(M);return await this.writeStore(M),e}finally{await t()}})}async ensureStateRoot(){await P.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await P.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 P.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>kt)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await P.readFile(this.tokenFilePath,"utf8")),M=mn(Sn,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return un(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:Tn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=j(Sn,n);un(t),await Jt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
|
|
2
|
-
`,{mode:384,encoding:"utf8"}),await P.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=k.join(this.stateRoot,".oauth-credentials.lock"),t=Zt(),M=Date.now()+yt;while(Date.now()<M)try{let e=await P.open(n,J.O_CREAT|J.O_EXCL|J.O_WRONLY,384);return await e.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
|
|
3
|
-
`,"utf8"),await e.close(),async()=>{try{if(JSON.parse(await P.readFile(n,"utf8")).token===t)await P.unlink(n)}catch(r){if(!H(r,"ENOENT"))throw r}}}catch(e){if(!H(e,"EEXIST"))throw e;await this.removeDeadLock(n),await new Promise((r)=>setTimeout(r,jt))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await P.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 M=JSON.parse(await P.readFile(n,"utf8"));if(typeof M.pid!=="number"||!Number.isInteger(M.pid)||M.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!tM(M.pid))await P.unlink(n)}}var An="127.0.0.1",bn=7777,cn="/oauth/callback",rM=300000;class v 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 Ln extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function _M(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 C(n,t,M){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(_M(M))}class ${serverName;config;static activeFlowIdentity;tokenStorage;serverUrl;identity;callbackUrl;openAuthorizationUrl;codeVerifierValue;activeFlow;lastError;constructor(n,t,M,e={}){this.serverName=n;this.config=M;this.serverUrl=Y(t),this.identity=F(this.serverUrl,M.clientId,M.scopes),this.tokenStorage=e.tokenStorage??new N;let r=M.callbackPort??bn;this.callbackUrl=`http://${An}:${r}${cn}`,this.openAuthorizationUrl=e.openAuthorizationUrl??(async(S)=>{await eM(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:`${an()} ${wn()}`,...this.config.scopes?.length?{scope:this.config.scopes.join(" ")}:{}}}async state(){return this.activeFlow?.state??l()}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((M)=>({...this.baseCredential(M),tokens:structuredClone(n),...t===void 0?{}:{tokenExpiresAt:t}})),this.lastError=void 0}async redirectToAuthorization(n){let t=this.activeFlow;if(!t)throw new v(this.serverName);t.authorizationUrl=R(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 M={...t};if(n==="client")delete M.clientInformation,delete M.tokens,delete M.tokenExpiresAt;else if(n==="tokens")delete M.tokens,delete M.tokenExpiresAt;else if(n==="discovery")delete M.discoveryState;return{...M,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($.activeFlowIdentity)throw Error("Another MCP OAuth authorization is already in progress");$.activeFlowIdentity=this.identity,this.lastError=void 0,this.codeVerifierValue=void 0;try{let n=await this.createFlow();if(this.activeFlow=n,await sn(this,{serverUrl:this.serverUrl,fetchFn:U})!=="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,M=new Promise((_,u)=>{n=_,t=u});M.catch(()=>{return});let e=l(),r=MM.createServer((_,u)=>{this.handleCallback(_,u)});r.on("clientError",(_,u)=>{u.end(`HTTP/1.1 400 Bad Request\r
|
|
17
|
-
Connection: close\r
|
|
18
|
-
\r
|
|
19
|
-
`)}),await new Promise((_,u)=>{let E=(T)=>u(T);r.once("error",E),r.listen(this.config.callbackPort??bn,An,()=>{r.off("error",E),_()})});let S={flowId:l(),state:e,callbackUrl:this.callbackUrl,server:r,timeout:setTimeout(()=>{this.failActiveFlow(Error("MCP OAuth authorization timed out"))},rM),completion:M,resolve:n,reject:t,settled:!1};return S.timeout.unref(),S}async handleCallback(n,t){let M=this.activeFlow;if(!M){C(t,410,!1);return}try{if(n.method!=="GET"){t.setHeader("Allow","GET"),C(t,405,!1);return}let e=new URL(n.url??"/",M.callbackUrl);if(e.pathname!==cn){C(t,404,!1);return}let r=e.searchParams.get("state"),S=e.searchParams.get("code");if(e.searchParams.get("error"))throw Error("MCP OAuth authorization was denied");if(!r||r!==M.state)throw Error("MCP OAuth state mismatch");if(!S)throw Error("MCP OAuth callback is missing the authorization code");if(await sn(this,{serverUrl:this.serverUrl,authorizationCode:S,fetchFn:U})!=="AUTHORIZED")throw Error("MCP OAuth token exchange did not complete");C(t,200,!0),await this.completeActiveFlow()}catch(e){C(t,400,!1),await this.failActiveFlow(e instanceof Error?e:Error(String(e)))}}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,$.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,$.activeFlowIdentity=void 0,!t||t.settled){this.activeFlow=void 0;return}t.settled=!0,clearTimeout(t.timeout),await new Promise((M)=>t.server.close(()=>M())),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 q}from"node:fs";import Pn from"node:os";import I from"node:path";import{Mutex as xn}from"async-mutex";import{merge as SM}from"lodash-es";import uM from"write-file-atomic";var dn=hn("Service"),X={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},providerRequestAdmissionMs:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerRequestPendingBytes:{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},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}},oe=new Set(Object.entries(X).filter(([n,t])=>t.persistable).map(([n])=>n)),se=new Set(Object.entries(X).filter(([n,t])=>!t.persistable).map(([n])=>n));class x{static instance=null;pendingUpdates=new Map;timers=new Map;fileLocks=new Map;lastSaveError=null;debounceDelay=300;constructor(){}static getInstance(){if(!x.instance)x.instance=new x;return x.instance}static resetInstance(){if(x.instance)for(let n of x.instance.timers.values())clearTimeout(n);x.instance=null}async save(n,t={}){this.validatePersistableFields(n);let M=this.groupUpdatesByTarget(n,t.scope,t.projectDir);if(t.immediate)await Promise.all(Array.from(M.entries()).map(([e,r])=>this.flushTarget(e,r)));else for(let[e,r]of M)this.scheduleSave(e,r)}async flush(){for(let t of this.timers.values())clearTimeout(t);this.timers.clear();let n=Array.from(this.pendingUpdates.entries()).map(([t,M])=>this.flushTarget(t,M));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,M){let e=M.scope??"local",r=this.resolveFilePath("settings",e,M.projectDir);await this.flushTargetWithModifier(r,(S)=>{let _=S.permissions??{allow:[],ask:[],deny:[]},u={allow:t==="allow"?this.dedupeArray([..._.allow||[],n]):_.allow||[],ask:_.ask||[],deny:t==="deny"?this.dedupeArray([..._.deny||[],n]):_.deny||[]};return{...S,permissions:u}})}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 M=t.scope??"local",e=this.resolveFilePath("settings",M,t.projectDir);await this.flushTargetWithModifier(e,(r)=>{let S={...r.enabledPlugins??{}};delete S[n];let _={...r};if(Object.keys(S).length>0)_.enabledPlugins=S;else delete _.enabledPlugins;return _})}validatePersistableFields(n){for(let t of Object.keys(n)){let M=X[t];if(!M)throw Error(`Unknown config field: ${t}`);if(!M.persistable)throw Error(`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.`)}}groupUpdatesByTarget(n,t,M){let e=new Map;for(let[r,S]of Object.entries(n)){let _=X[r];if(!_)continue;let u=t??_.defaultScope,E=this.resolveFilePath(_.target,u,M);if(!e.has(E))e.set(E,{});e.get(E)[r]=S}return e}resolveFilePath(n,t,M){let e=M??a();if(n==="config")return t==="global"?I.join(Pn.homedir(),".blade","config.json"):I.join(e,".blade","config.json");switch(t){case"local":return I.join(e,".blade","settings.local.json");case"project":return I.join(e,".blade","settings.json");case"global":return I.join(Pn.homedir(),".blade","settings.json");default:return I.join(e,".blade","settings.local.json")}}scheduleSave(n,t){let M=this.pendingUpdates.get(n)??{},e=this.mergePendingUpdates(M,t);this.pendingUpdates.set(n,e);let r=this.timers.get(n);if(r)clearTimeout(r);let S=setTimeout(async()=>{let _=this.pendingUpdates.get(n);if(_){this.pendingUpdates.delete(n),this.timers.delete(n);try{await this.flushTarget(n,_),this.lastSaveError=null}catch(u){let E=u instanceof Error?u:Error(String(u));this.lastSaveError=E,dn.error(`Failed to save config to ${n}:`,E.message),dn.error("Stack trace:",E.stack)}}},this.debounceDelay);this.timers.set(n,S)}mergePendingUpdates(n,t){let M={...n};for(let[e,r]of Object.entries(t)){let S=X[e];if(!S){M[e]=r;continue}switch(S.mergeStrategy){case"replace":M[e]=r;break;case"append-dedupe":this.applyAppendDedupe(M,e,r);break;case"deep-merge":this.applyDeepMerge(M,e,r);break}}return M}async flushTarget(n,t){let M=this.fileLocks.get(n);if(!M)M=new xn,this.fileLocks.set(n,M);await M.runExclusive(async()=>{await this.performWrite(n,t)})}async flushTargetWithModifier(n,t){let M=this.fileLocks.get(n);if(!M)M=new xn,this.fileLocks.set(n,M);await M.runExclusive(async()=>{await q.mkdir(I.dirname(n),{recursive:!0,mode:493});let e={};try{let S=await q.readFile(n,"utf-8");e=JSON.parse(S)}catch{e={}}let r=t(e);await this.atomicWrite(n,r)})}async performWrite(n,t){await q.mkdir(I.dirname(n),{recursive:!0,mode:493});let M={};try{let r=await q.readFile(n,"utf-8");M=JSON.parse(r)}catch{M={}}let e={...M};if(typeof e.theme==="string"&&e.codeTheme===void 0)e.codeTheme=e.theme;delete e.theme;for(let[r,S]of Object.entries(t)){let _=X[r];if(!_){e[r]=S;continue}switch(_.mergeStrategy){case"replace":e[r]=S;break;case"append-dedupe":this.applyAppendDedupe(e,r,S);break;case"deep-merge":this.applyDeepMerge(e,r,S);break}}await this.atomicWrite(n,e)}applyAppendDedupe(n,t,M){if(t==="permissions"&&typeof M==="object"&&M!==null){let e=n[t]??{allow:[],ask:[],deny:[]},r=M;n[t]={allow:this.dedupeArray([...e.allow||[],...r.allow||[]]),ask:this.dedupeArray([...e.ask||[],...r.ask||[]]),deny:this.dedupeArray([...e.deny||[],...r.deny||[]])}}else if(Array.isArray(M)){let e=Array.isArray(n[t])?n[t]:[];n[t]=this.dedupeArray([...e,...M])}else n[t]=M}applyDeepMerge(n,t,M){if(typeof M==="object"&&M!==null&&!Array.isArray(M)){let e=typeof n[t]==="object"&&n[t]!==null?n[t]:{};n[t]=SM({},e,M)}else n[t]=M}dedupeArray(n){return Array.from(new Set(n))}async atomicWrite(n,t){await uM(n,JSON.stringify(t,null,2),{mode:384,encoding:"utf-8"})}}function Ae(){return x.getInstance()}var In=15000,fn=1000,Nn=300000;function nn(n){return n===0||typeof n==="number"&&Number.isSafeInteger(n)&&n>=1000&&n<=300000}function ce(n,t=15000){return nn(n)?n:t}var $n=1,Xn=32,gn=256,pn=30000,Rn=300000,Cn=3600000,ae=30000;function zn(n){return Number.isSafeInteger(n)&&n>=1&&n<=256}function Bn(n){return Number.isSafeInteger(n)&&n>=30000&&n<=3600000}var Kn=1,Un=64,Hn=1,Yn=1e4,qn=67108864,Vn=65536,Gn=134217728;function Qn(n){return Number.isInteger(n)&&n>=1&&n<=64}function Dn(n){return Number.isInteger(n)&&n>=1&&n<=1e4}function Wn(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:In,providerForegroundRecoveryMs:Zn,providerCircuitBreakerOpenMs:On,providerRequestConcurrency:Jn,providerRequestAdmissionMs:kn,providerRequestPendingBytes:yn,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:qn,maxResidentSessionRuntimes:Xn,sessionRuntimeIdleMs:Rn};var jn=/^[A-Za-z0-9_-]{21}$/;function Fn(n){return n.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[._-]+|[._-]+$/g,"").slice(0,80)||"model"}function mM(n,t){let M=new Set(t.map((_)=>_.id)),e=Fn(n.model);if(!M.has(e))return e;let r=`${Fn(n.provider)}-${e}`.slice(0,120);if(!M.has(r))return r;let S=2;while(M.has(`${r}-${S}`))S++;return`${r}-${S}`}function ln(n,t){let M=n.filter((S)=>!jn.test(S.id)).map((S)=>({id:S.id})),e=new Map;return{models:n.map((S)=>{if(!jn.test(S.id))return{...S};let{id:_,...u}=S,E=mM(u,M);return M.push({id:E}),e.set(_,E),{...S,id:E}}),currentModelId:e.get(t)??t,changed:e.size>0}}import{promises as Nt}from"fs";import{merge as K}from"lodash-es";import c from"os";import m from"path";function nt(n){let t=vn(n.timeout??300000,"MCP timeout"),M=vn(n.idleTimeout??Math.min(60000,t),"MCP idleTimeout");if(M>t)throw Error("MCP idleTimeout must not exceed timeout");return{totalTimeoutMs:t,idleTimeoutMs:M,maxProgressEvents:128}}function ie(n,t,M){if(t.count>=M.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 e=n.message?.replace(/\0/g,"").trim().slice(0,1000);return{progress:n.progress,...n.total!==void 0?{total:n.total}:{},message:e||TM(n.progress,n.total)}}function vn(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 TM(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 oM}from"node:crypto";var V=["debug","info","notice","warning","error","critical","alert","emergency"],ze=64,Be=64,Ke=256,sM=8192,rt=16384,AM=256,bM=6,cM=128,tt=64,Mt=64,wM=128,aM=/authorization|api[-_]?key|cookie|credential|password|secret|token/i;function _t(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 M=t?.enabled??!0;if(typeof M!=="boolean")throw Error("MCP logging enabled must be a boolean");let e=t?.level??"warning";if(!LM(e))throw Error(`MCP logging level must be one of: ${V.join(", ")}`);return{enabled:M,level:e}}function LM(n){return typeof n==="string"&&V.includes(n)}function Ue(n,t){return V.indexOf(n)>=V.indexOf(t)}function PM(n,t={}){let M=xM(n.data),e=typeof M.value==="string"?M.value:JSON.stringify(M.value),r=et(e,rt),S=r.value,_=Buffer.byteLength(S),u=oM("sha256").update(S).digest("hex"),E=t.exposeDetails!==!1,T=E?et(S,sM):{value:`[MCP log details omitted; sha256=${u}]`,truncated:!1},A=E&&n.logger?G(Mn(n.logger),AM):void 0;return{level:n.level,...A?{logger:A}:{},message:T.value||"[empty MCP log message]",projectedBytes:_,dataSha256:u,truncated:M.truncated||r.truncated||T.truncated,detailsOmitted:!E,timestamp:t.now??Date.now()}}function He(n,t={}){return{...PM({level:"warning",logger:"blade.mcp.logging",data:`MCP log rate exceeded; dropped at least ${Math.max(1,n)} message(s)`},t),synthetic:!0}}function xM(n){let t={nodes:0,remainingStringBytes:rt,truncated:!1,seen:new WeakSet};return{value:tn(n,0,t),truncated:t.truncated}}function tn(n,t,M){if(M.nodes++,M.nodes>cM)return M.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 e=Mn(n),r=Math.max(0,M.remainingStringBytes),S=G(e,r),_=Buffer.byteLength(S);if(M.remainingStringBytes-=_,_<Buffer.byteLength(e))M.truncated=!0;return S}if(typeof n>"u")return"[undefined]";if(typeof n==="symbol"||typeof n==="function")return`[${typeof n}]`;if(t>=bM)return M.truncated=!0,"[depth limit reached]";if(M.seen.has(n))return M.truncated=!0,"[circular]";M.seen.add(n);try{if(Array.isArray(n)){if(n.length>tt)M.truncated=!0;return n.slice(0,tt).map((S)=>tn(S,t+1,M))}let e=Object.create(null),r=Object.entries(n);if(r.length>Mt)M.truncated=!0;for(let[S,_]of r.slice(0,Mt)){let u=G(Mn(S),wM)||"[empty-key]";if(S==="_meta"||aM.test(S))e[u]="[redacted]";else e[u]=tn(_,t+1,M)}return e}finally{M.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((M)=>{let e=M.charCodeAt(0);return(e===9||e===10||e===13||e>=32)&&e!==127}).join("")}function G(n,t){if(t<=0)return"";if(Buffer.byteLength(n)<=t)return n;let M=Buffer.from(n).subarray(0,t).toString("utf8");while(Buffer.byteLength(M)>t)M=M.slice(0,-1);return M}function et(n,t){if(Buffer.byteLength(n)<=t)return{value:n,truncated:!1};let M=`
|
|
20
|
-
...[MCP log truncated]`;return{value:G(n,t-Buffer.byteLength(M))+M,truncated:!0}}var St=1024,dM=4096,ut=2,hM=8,Et=65536,IM=1048576,mt=50,Tt=16000,ot=4,fM=100,st=1048576,NM=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function wt(n){if(!n)return{enabled:!1,maxTokens:St,maxRequestsPerToolCall:ut,maxInputBytes:Et};if(typeof n.enabled!=="boolean")throw Error("MCP sampling.enabled must be a boolean");return{enabled:n.enabled,maxTokens:Q(n.maxTokens??St,1,dM,"MCP sampling.maxTokens"),maxRequestsPerToolCall:Q(n.maxRequestsPerToolCall??ut,1,hM,"MCP sampling.maxRequestsPerToolCall"),maxInputBytes:Q(n.maxInputBytes??Et,1,IM,"MCP sampling.maxInputBytes")}}function Ve(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>mt)throw Error(`MCP sampling messages must contain 1-${mt} entries`);if(n.systemPrompt!==void 0&&n.systemPrompt.length>Tt)throw Error(`MCP sampling system prompt exceeds ${Tt} 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 M=n.stopSequences??[];if(M.length>ot||M.some((T)=>!T||T.length>fM||T.includes("\x00")))throw Error(`MCP sampling stop sequences must contain at most ${ot} non-empty bounded values`);let e=[],r=0,S=0,_=0,u=[];if(n.systemPrompt)r+=Buffer.byteLength(n.systemPrompt,"utf8"),e.push({role:"system",content:n.systemPrompt}),u.push(`System: ${At(n.systemPrompt)}`);for(let T of n.messages){let A=Array.isArray(T.content)?T.content:[T.content],L=[],w=[];for(let b of A){if(b.type==="text"){r+=Buffer.byteLength(b.text,"utf8"),L.push({type:"text",text:b.text}),w.push(At(b.text));continue}if(b.type==="image"){if(T.role!=="user")throw Error("MCP sampling images are only supported in user messages");if(!NM.has(b.mimeType))throw Error(`Unsupported MCP sampling image type: ${b.mimeType}`);let i=$M(b.data);S+=i,_++,L.push({type:"image_url",image_url:{url:`data:${b.mimeType};base64,${b.data}`}}),w.push(`[${b.mimeType} image, ${i} bytes]`);continue}throw Error(`Unsupported MCP sampling content type: ${b.type}`)}if(L.length===0)throw Error("MCP sampling message has no supported content");e.push({role:T.role,content:L.length===1&&L[0]?.type==="text"?L[0].text:L}),u.push(`${T.role==="user"?"User":"Assistant"}: ${w.join(" ")}`)}if(r+S>t.maxInputBytes)throw Error(`MCP sampling input exceeds ${t.maxInputBytes} bytes`);if(_>bt||S>ct)throw Error("MCP sampling image input exceeds the shared attachment budget");let E=Q(n.maxTokens,1,Number.MAX_SAFE_INTEGER,"MCP sampling maxTokens");return{messages:e,maxTokens:Math.min(E,t.maxTokens),...n.temperature!==void 0?{temperature:n.temperature}:{},stopSequences:[...M],preview:u.join(`
|
|
21
|
-
`).slice(0,8000)}}function Ge(n,t,M){if(n.toolCalls?.length)throw Error("Model returned tools for basic MCP sampling");let e=n.content,r=n.finishReason==="length"||n.finishReason==="max_tokens"?"maxTokens":"endTurn",S=-1;for(let _ of M.stopSequences){let u=e.indexOf(_);if(u>=0&&(S===-1||u<S))S=u}if(S>=0)e=e.slice(0,S),r="stopSequence";if(Buffer.byteLength(e,"utf8")>st)throw Error(`MCP sampling response exceeds ${st} bytes`);return{model:t,role:"assistant",content:{type:"text",text:e},stopReason:r}}function Q(n,t,M,e){if(!Number.isSafeInteger(n)||n<t||n>M)throw Error(`${e} must be an integer between ${t} and ${M}`);return n}function $M(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 At(n){return n.replace(/\s+/g," ").trim().slice(0,1000)}var De=256,We=1e4,Ze=86400000;var XM=/[\p{Cf}\p{Co}\p{Cn}]/u;function Lt(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=f(n.defaultTtlMs??600000,1e4,86400000,"MCP tasks.defaultTtlMs"),M=f(n.maxLifetimeMs??1800000,1e4,86400000,"MCP tasks.maxLifetimeMs");if(t>M)throw Error("MCP tasks.defaultTtlMs must not exceed tasks.maxLifetimeMs");return{enabled:n.enabled,defaultTtlMs:t,pollIntervalMs:f(n.pollIntervalMs??500,100,1e4,"MCP tasks.pollIntervalMs"),maxTasksPerSession:f(n.maxTasksPerSession??32,1,32,"MCP tasks.maxTasksPerSession"),maxLifetimeMs:M}}function Oe(n,t){return f(n??t.defaultTtlMs,1e4,Math.min(86400000,t.maxLifetimeMs),"MCP task ttl")}function Je(n,t,M){let e=pM(n.taskId,"task ID",512),r=at(n.createdAt,"createdAt"),S=at(n.lastUpdatedAt,"lastUpdatedAt");if(Date.parse(S)<Date.parse(r))throw Error("MCP task lastUpdatedAt precedes createdAt");if(M&&(e!==M.taskId||r!==M.createdAt))throw Error("MCP task identity changed across connection generation");let _=n.ttl===null?null:f(n.ttl,0,86400000,"MCP task ttl"),u=n.pollInterval===void 0?t.pollIntervalMs:f(n.pollInterval,0,Number.MAX_SAFE_INTEGER,"MCP task pollInterval"),E=Math.min(1e4,Math.max(100,u)),T=n.statusMessage?gM(n.statusMessage,e):void 0;return{taskId:e,status:n.status,createdAt:r,lastUpdatedAt:S,ttl:_,pollIntervalMs:E,...T?{statusMessage:T}:{}}}function ke(n){return["completed","failed","cancelled"].includes(n)}function ye(n){let t=n instanceof Error?n.message:String(n);return Pt(en(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 gM(n,t){return Pt(en(n.replaceAll(t,"[redacted-task-id]")),1024)}function en(n){return[...n.normalize("NFKC")].filter((t)=>{let M=t.codePointAt(0)??0;if(M===0||M>=1&&M<=8||M===11||M===12||M>=14&&M<=31||M===127)return!1;return!XM.test(t)}).join("").trim()}function at(n,t){let M=Date.parse(n);if(!Number.isFinite(M))throw Error(`MCP task ${t} is invalid`);return new Date(M).toISOString()}function pM(n,t,M){if(!n||Buffer.byteLength(n)>M||en(n)!==n)throw Error(`MCP ${t} is invalid`);return n}function f(n,t,M,e){if(!Number.isSafeInteger(n)||n<t||n>M)throw Error(`${e} must be an integer between ${t} and ${M}`);return n}function Pt(n,t){let M=Buffer.from(n);if(M.length<=t)return n;let e=M.subarray(0,t).toString("utf8");while(Buffer.byteLength(e)>t)e=e.slice(0,-1);return e}var iM={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 rn(n){let t=n.toLowerCase().trim();return iM[t]??n}var RM=/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/,CM=/^\.[A-Za-z0-9_+-]{1,32}$/;function D(n){return n!==null&&typeof n==="object"&&!Array.isArray(n)}function g(n,t,M,e,r){if(n===void 0)return r;if(!Number.isInteger(n)||Number(n)<M||Number(n)>e)throw Error(`${t} must be an integer between ${M} and ${e}`);return Number(n)}function xt(n,t){if(n===void 0)return;let M;try{M=JSON.stringify(n)}catch{throw Error(`${t} must be JSON serializable`)}if(M===void 0||Buffer.byteLength(M)>262144)throw Error(`${t} exceeds the 256 KiB limit`);return structuredClone(n)}function zM(n,t){if(n===void 0)return{};if(!D(n))throw Error(`${t} must be an object`);let M={};for(let[e,r]of Object.entries(n)){if(!e||typeof r!=="string"||r.includes("\x00"))throw Error(`${t} must contain non-empty string values`);M[e]=r}return M}function h(n){if(n===void 0)return{};if(!D(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 M={};for(let[e,r]of t){if(!RM.test(e))throw Error(`Invalid LSP server name: ${e}`);if(!D(r))throw Error(`lspServers.${e} must be an object`);let S=new Set(["command","args","extensionToLanguage","env","initializationOptions","settings","enabled","priority","startupTimeout","shutdownTimeout","requestTimeout","diagnosticWaitTimeout","maxRestarts"]),_=Object.keys(r).filter((w)=>!S.has(w));if(_.length>0)throw Error(`Unknown LSP server field: ${e}.${_[0]}`);if(typeof r.command!=="string"||!r.command.trim()||r.command.includes("\x00")||r.command.includes(`
|
|
22
|
-
`))throw Error(`lspServers.${e}.command must be a non-empty command`);if(r.args!==void 0&&!Array.isArray(r.args))throw Error(`lspServers.${e}.args must be an array`);let u=(r.args??[]).map((w,b)=>{if(typeof w!=="string"||w.includes("\x00"))throw Error(`lspServers.${e}.args.${b} must be a string`);return w});if(u.length>128)throw Error(`lspServers.${e}.args exceeds the 128-item limit`);if(!D(r.extensionToLanguage))throw Error(`lspServers.${e}.extensionToLanguage must be an object`);let E=Object.entries(r.extensionToLanguage);if(E.length===0||E.length>64)throw Error(`lspServers.${e}.extensionToLanguage must contain 1-64 entries`);let T={};for(let[w,b]of E){let i=w.startsWith(".")?w.toLowerCase():`.${w.toLowerCase()}`;if(!CM.test(i)||typeof b!=="string"||!b.trim())throw Error(`Invalid lspServers.${e}.extensionToLanguage entry: ${w}`);T[i]=b.trim()}if(r.enabled!==void 0&&typeof r.enabled!=="boolean")throw Error(`lspServers.${e}.enabled must be a boolean`);let A=xt(r.initializationOptions,`lspServers.${e}.initializationOptions`),L=xt(r.settings,`lspServers.${e}.settings`);M[e]={command:r.command.trim(),...u.length>0?{args:u}:{},extensionToLanguage:T,...r.env!==void 0?{env:zM(r.env,`lspServers.${e}.env`)}:{},...A!==void 0?{initializationOptions:A}:{},...L!==void 0?{settings:L}:{},...r.enabled!==void 0?{enabled:r.enabled}:{},priority:g(r.priority,`lspServers.${e}.priority`,-1000,1000,0),startupTimeout:g(r.startupTimeout,`lspServers.${e}.startupTimeout`,100,60000,1e4),shutdownTimeout:g(r.shutdownTimeout,`lspServers.${e}.shutdownTimeout`,100,1e4,2000),requestTimeout:g(r.requestTimeout,`lspServers.${e}.requestTimeout`,100,60000,1e4),diagnosticWaitTimeout:g(r.diagnosticWaitTimeout,`lspServers.${e}.diagnosticWaitTimeout`,0,5000,750),maxRestarts:g(r.maxRestarts,`lspServers.${e}.maxRestarts`,0,10,3)}}return M}function dt(n){return Number.isInteger(n)&&(n===-1||n>=0)}function ht(){return"-1 (unlimited), 0 (disabled), or any positive integer"}import It from"node:path";var ft=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,BM=/^(?:\*\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;function z(n){let t=[];for(let[M,e]of Object.entries(n)){if(!ft.test(M))throw Error(`Invalid plugin name in enabledPlugins: ${M}`);if(typeof e!=="boolean")throw Error(`Invalid enabledPlugins value for ${M}`);t.push([M,e])}return Object.fromEntries(t)}function _n(n,t,M){if(!Array.isArray(n))throw Error(`${t} must be an array`);return[...new Set(n.map((e,r)=>{if(typeof e!=="string"||!e.trim())throw Error(`${t}[${r}] must be a non-empty string`);return M(e.trim())}))].sort()}function B(n){let t=new Set(["restrictToAllowedSources","requireGitCommitSha","allowedGitHosts","allowedMarketplaces","allowedLocalRoots"]),M=Object.keys(n).filter((r)=>!t.has(r));if(M.length>0)throw Error(`Unknown pluginSourcePolicy fields: ${M.join(", ")}`);let e={};for(let r of["restrictToAllowedSources","requireGitCommitSha"]){if(n[r]===void 0)continue;if(typeof n[r]!=="boolean")throw Error(`pluginSourcePolicy.${r} must be boolean`);e[r]=n[r]}if(n.allowedGitHosts!==void 0)e.allowedGitHosts=_n(n.allowedGitHosts,"pluginSourcePolicy.allowedGitHosts",(r)=>{let S=r.toLowerCase();if(!BM.test(S))throw Error(`Invalid plugin Git host pattern: ${r}`);return S});if(n.allowedMarketplaces!==void 0)e.allowedMarketplaces=_n(n.allowedMarketplaces,"pluginSourcePolicy.allowedMarketplaces",(r)=>{if(!ft.test(r))throw Error(`Invalid allowed Marketplace name: ${r}`);return r});if(n.allowedLocalRoots!==void 0)e.allowedLocalRoots=_n(n.allowedLocalRoots,"pluginSourcePolicy.allowedLocalRoots",(r)=>{if(!It.isAbsolute(r))throw Error(`Plugin local allowlist root must be absolute: ${r}`);return It.resolve(r)});return e}function W(n){let t=[];for(let[M,e]of Object.entries(n)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(M))throw Error(`Invalid environment variable name: ${M}`);if(typeof e!=="string"||e.includes("\x00"))throw Error(`Invalid environment variable value: ${M}`);t.push([M,e])}return Object.fromEntries(t)}class p{static instance=null;runtimePermissionOverrides;lastAdditionalSettings;constructor(){}static getInstance(){if(!p.instance)p.instance=new p;return p.instance}static resetInstance(){p.instance=null}async initialize(n){try{this.lastAdditionalSettings=n,this.runtimePermissionOverrides=n?.permissions;let M=(await d.getInstance().getStatus(a())).state==="trusted",e=await this.loadConfigFiles(M),r=await this.loadSettingsFiles(M),S={...e,...r,enabledPlugins:{...e.enabledPlugins||{},...r.enabledPlugins||{}}};if(n)S=this.mergeSettings(S,n);let _=this.normalizeConfig(S),u={...s,..._};if(u.enabledPlugins=z(u.enabledPlugins),u.lspServers=h(u.lspServers),u.pluginSourcePolicy={...s.pluginSourcePolicy,...B(u.pluginSourcePolicy)},this.resolveEnvInterpolation(u),process.env.BLADE_MODEL&&u.models?.length>0){let E=rn(process.env.BLADE_MODEL),T=u.models.find((A)=>A.id===E||A.model===E||A.id===process.env.BLADE_MODEL||A.model===process.env.BLADE_MODEL);if(T)u.currentModelId=T.id}if(process.env.BLADE_DEBUG)u.debug=process.env.BLADE_DEBUG==="1"||process.env.BLADE_DEBUG==="true"||process.env.BLADE_DEBUG;if(Z().configureModelProviders(u.modelProviders,u.models),u.models.length>0)this.validateConfig(u);if(u.debug)console.log("[ConfigManager] Configuration loaded successfully");return u}catch(t){return console.error("[ConfigManager] Failed to initialize:",t),Z().configureModelProviders({},[]),s}}async reload(){return this.initialize(this.lastAdditionalSettings)}async loadConfigFiles(n){let t=m.join(c.homedir(),".blade","config.json"),M=m.join(a(),".blade","config.json"),e={},r=await this.loadJsonFile(t),S=r?await this.migrateLegacyUserConfig(r):null;if(S)e={...e,...S};let _=await this.loadJsonFile(M);if(_&&n){let u={...e.mcpServers||{},..._.mcpServers||{}},E={...e.lspServers||{},..._.lspServers||{}},T={...e.modelProviders||{},..._.modelProviders||{}},A={...e.enabledPlugins||{},..._.enabledPlugins||{}};if(e={...e,..._},Object.keys(u).length>0)e.mcpServers=u;if(Object.keys(E).length>0)e.lspServers=h(E);if(Object.keys(T).length>0)e.modelProviders=T;if(Object.keys(A).length>0)e.enabledPlugins=z(A)}else if(_?.hooks)e.hooks=_.hooks;return e}async migrateLegacyUserConfig(n){let t=n,M={...n},e={};if(M.codeTheme===void 0&&typeof t.theme==="string")M.codeTheme=t.theme,e.codeTheme=t.theme;if(Array.isArray(M.models)){let r=ln(M.models,M.currentModelId??"");if(r.changed)M.models=r.models,M.currentModelId=r.currentModelId,e.models=r.models,e.currentModelId=r.currentModelId}if(delete M.theme,Object.keys(e).length>0)try{await x.getInstance().save(e,{scope:"global",immediate:!0})}catch{console.warn("[ConfigManager] Could not persist legacy config migration")}return M}async loadSettingsFiles(n){let t=m.join(c.homedir(),".blade","settings.json"),M=m.join(a(),".blade","settings.json"),e=m.join(a(),".blade","settings.local.json"),r={},S=await this.loadJsonFile(t);if(S)r=this.mergeSettings(r,S);let _=await this.loadJsonFile(M);if(_&&n)r=this.mergeSettings(r,_);else if(_?.hooks)r=this.mergeSettings(r,{hooks:_.hooks});let u=await this.loadJsonFile(e);if(u&&n)r=this.mergeSettings(r,u);else if(u?.hooks)r=this.mergeSettings(r,{hooks:u.hooks});return r}async loadWorkspacePermissions(n,t){let M={allow:[...t.allow],ask:[...t.ask],deny:[...t.deny]};if(m.resolve(n)!==m.resolve(a())){let r=await this.loadWorkspacePermissionOverrides(a(),{includeUntrusted:!0}),S=await this.loadJsonFile(m.join(c.homedir(),".blade","settings.json")),_={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 u of["allow","ask","deny"]){let E=new Set(r[u].filter((T)=>!_[u].includes(T)));M[u]=M[u].filter((T)=>!E.has(T))}}let e=await this.loadWorkspacePermissionOverrides(n);for(let r of["allow","ask","deny"])M[r]=Array.from(new Set([...M[r],...e[r]]));return M}async loadWorkspaceMcpServers(n,t){if(m.resolve(n)===m.resolve(a()))return{...t};let M=await d.getInstance().getStatus(n),e=M.state==="trusted",r=M.projectPath,S={},_=async(E)=>{let T=await this.loadJsonFile(E);if(T?.mcpServers)S={...S,...T.mcpServers}};if(await _(m.join(c.homedir(),".blade","config.json")),await _(m.join(c.homedir(),".blade","settings.json")),e)await _(m.join(r,".blade","config.json")),await _(m.join(r,".blade","settings.json")),await _(m.join(r,".blade","settings.local.json"));if(this.lastAdditionalSettings?.mcpServers)S={...S,...this.lastAdditionalSettings.mcpServers};let u={mcpServers:S};return this.resolveEnvInterpolation(u),u.mcpServers}async loadWorkspaceLspServers(n,t){if(m.resolve(n)===m.resolve(a()))return h(t);let M=await d.getInstance().getStatus(n),e={},r=async(_)=>{let u=await this.loadJsonFile(_);if(u?.lspServers)e={...e,...h(u.lspServers)}};if(await r(m.join(c.homedir(),".blade","config.json")),await r(m.join(c.homedir(),".blade","settings.json")),M.state==="trusted")for(let _ of["config.json","settings.json","settings.local.json"])await r(m.join(M.projectPath,".blade",_));if(this.lastAdditionalSettings?.lspServers)e={...e,...h(this.lastAdditionalSettings.lspServers)};let S={lspServers:e};return this.resolveEnvInterpolation(S),h(S.lspServers)}async loadWorkspaceModelConfig(n,t){if(m.resolve(n)===m.resolve(a()))return{currentModelId:t.currentModelId,models:t.models.map((_)=>structuredClone(_)),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.providerRequestAdmissionMs!==void 0?{providerRequestAdmissionMs:t.providerRequestAdmissionMs}:{},...t.providerRequestPendingBytes!==void 0?{providerRequestPendingBytes:t.providerRequestPendingBytes}:{}};let M=await d.getInstance().getStatus(n),e=M.projectPath,r={currentModelId:s.currentModelId,models:s.models.map((_)=>structuredClone(_)),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.providerRequestAdmissionMs!==void 0?{providerRequestAdmissionMs:s.providerRequestAdmissionMs}:{},...s.providerRequestPendingBytes!==void 0?{providerRequestPendingBytes:s.providerRequestPendingBytes}:{}},S=(_)=>{if(!_)return;if(_.modelProviders)r.modelProviders={...r.modelProviders,...structuredClone(_.modelProviders)};if(_.models)r.models=_.models.map((u)=>structuredClone(u));if(_.currentModelId!==void 0)r.currentModelId=_.currentModelId;if(_.temperature!==void 0)r.temperature=_.temperature;if(_.maxOutputTokens!==void 0)r.maxOutputTokens=_.maxOutputTokens;if(_.timeout!==void 0)r.timeout=_.timeout;if(_.providerCircuitBreakerOpenMs!==void 0)r.providerCircuitBreakerOpenMs=_.providerCircuitBreakerOpenMs;if(_.providerRequestConcurrency!==void 0)r.providerRequestConcurrency=_.providerRequestConcurrency;if(_.providerRequestAdmissionMs!==void 0)r.providerRequestAdmissionMs=_.providerRequestAdmissionMs;if(_.providerRequestPendingBytes!==void 0)r.providerRequestPendingBytes=_.providerRequestPendingBytes};if(S(await this.loadJsonFile(m.join(c.homedir(),".blade","config.json"))),S(await this.loadJsonFile(m.join(c.homedir(),".blade","settings.json"))),M.state==="trusted")S(await this.loadJsonFile(m.join(e,".blade","config.json"))),S(await this.loadJsonFile(m.join(e,".blade","settings.json"))),S(await this.loadJsonFile(m.join(e,".blade","settings.local.json")));if(S(this.lastAdditionalSettings),r=this.normalizeConfig(r),this.resolveEnvInterpolation(r),process.env.BLADE_MODEL&&r.models.length>0){let _=process.env.BLADE_MODEL,u=rn(_),E=r.models.find((T)=>T.id===u||T.model===u||T.id===_||T.model===_);if(E)r.currentModelId=E.id}if(!r.models.some((_)=>_.id===r.currentModelId))r.currentModelId=r.models[0]?.id??"";return r}async loadWorkspaceRuntimeSettings(n,t){if(m.resolve(n)===m.resolve(a()))return{env:W(t.env),disableAllHooks:t.disableAllHooks,maxTurns:t.maxTurns,permissionMode:t.permissionMode};let M=await d.getInstance().getStatus(n),e=M.projectPath,r={env:{},disableAllHooks:s.disableAllHooks,maxTurns:s.maxTurns,permissionMode:s.permissionMode},S=(E,T)=>{if(!E)return;if(T.allowExecutionSettings){if(E.env)r.env={...r.env,...W(E.env)};if(E.maxTurns!==void 0)r.maxTurns=E.maxTurns;if(E.permissionMode!==void 0)r.permissionMode=E.permissionMode;if(E.disableAllHooks!==void 0)r.disableAllHooks=E.disableAllHooks}else if(E.disableAllHooks===!0)r.disableAllHooks=!0};S(await this.loadJsonFile(m.join(c.homedir(),".blade","config.json")),{allowExecutionSettings:!0}),S(await this.loadJsonFile(m.join(c.homedir(),".blade","settings.json")),{allowExecutionSettings:!0});let _=await Promise.all([this.loadJsonFile(m.join(e,".blade","config.json")),this.loadJsonFile(m.join(e,".blade","settings.json")),this.loadJsonFile(m.join(e,".blade","settings.local.json"))]);for(let E of _)S(E,{allowExecutionSettings:M.state==="trusted"});S(this.lastAdditionalSettings,{allowExecutionSettings:!0});let u={env:r.env};return this.resolveEnvInterpolation(u),r.env=W(u.env),r}async loadWorkspacePluginSettings(n){return(await this.loadWorkspacePluginSettingsResolution(n)).effective}async loadWorkspacePluginSettingsResolution(n){let t=await d.getInstance().getStatus(n),M={},e={},r=(S,_,u)=>{if(!S?.enabledPlugins)return;let E=z(S.enabledPlugins);for(let[T,A]of Object.entries(E)){if(!u&&A!==!1)continue;let L=e[T];M[T]=A,e[T]={effective:A,effectiveScope:_,layers:{...L?.layers??{},[_]:A}}}};r(await this.loadJsonFile(m.join(c.homedir(),".blade","config.json")),"global",!0),r(await this.loadJsonFile(m.join(c.homedir(),".blade","settings.json")),"global",!0);for(let S of["config.json","settings.json"])r(await this.loadJsonFile(m.join(t.projectPath,".blade",S)),"project",t.state==="trusted");return r(await this.loadJsonFile(m.join(t.projectPath,".blade","settings.local.json")),"local",t.state==="trusted"),r(this.lastAdditionalSettings,"invocation",!0),{effective:M,settings:e,workspaceTrusted:t.state==="trusted"}}async loadWorkspacePluginSourcePolicy(n){let t=await d.getInstance().getStatus(n),M={...s.pluginSourcePolicy,allowedGitHosts:[...s.pluginSourcePolicy.allowedGitHosts],allowedMarketplaces:[...s.pluginSourcePolicy.allowedMarketplaces],allowedLocalRoots:[...s.pluginSourcePolicy.allowedLocalRoots]},e=(_)=>{if(!_?.pluginSourcePolicy)return;Object.assign(M,B(_.pluginSourcePolicy))},r=(_,u)=>{if(!u)return _;if(_.length===0&&!M.restrictToAllowedSources)return u;let E=new Set(u);return _.filter((T)=>E.has(T))},S=(_)=>{if(!_?.pluginSourcePolicy)return;let u=B(_.pluginSourcePolicy);M.allowedGitHosts=r(M.allowedGitHosts,u.allowedGitHosts),M.allowedMarketplaces=r(M.allowedMarketplaces,u.allowedMarketplaces),M.allowedLocalRoots=r(M.allowedLocalRoots,u.allowedLocalRoots),M.restrictToAllowedSources=M.restrictToAllowedSources||u.restrictToAllowedSources===!0,M.requireGitCommitSha=M.requireGitCommitSha||u.requireGitCommitSha===!0};e(await this.loadJsonFile(m.join(c.homedir(),".blade","config.json"))),e(await this.loadJsonFile(m.join(c.homedir(),".blade","settings.json")));for(let _ of["config.json","settings.json","settings.local.json"])S(await this.loadJsonFile(m.join(t.projectPath,".blade",_)));if(S(this.lastAdditionalSettings),process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true")M.requireGitCommitSha=!0;return M}async loadWorkspaceHooks(n,t,M={}){if(m.resolve(n)===m.resolve(a())&&M.includeBaseForCurrentWorkspace!==!1)return K({},t);let e=K({},s.hooks),r=[m.join(c.homedir(),".blade","settings.json"),m.join(n,".blade","settings.json"),m.join(n,".blade","settings.local.json")];for(let S of r){let _=await this.loadJsonFile(S);if(_?.hooks)e=K({},e,_.hooks)}return e}async loadWorkspacePermissionOverrides(n,t={}){let M={allow:[],ask:[],deny:[]},e=(await d.getInstance().getStatus(n)).state==="trusted",r=[...e||t.includeUntrusted?[m.join(n,".blade","settings.json")]:[],...e||t.includeUntrusted?[m.join(n,".blade","settings.local.json")]:[]];for(let S of r){let _=await this.loadJsonFile(S);if(!_?.permissions)continue;for(let u of["allow","ask","deny"])M[u]=Array.from(new Set([...M[u],..._.permissions[u]||[]]))}return M}mergeSettings(n,t){let M={...JSON.parse(JSON.stringify(n)),...JSON.parse(JSON.stringify(t))};if(t.permissions)M.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)M.hooks=K({},M.hooks,t.hooks);if(t.enabledPlugins)M.enabledPlugins={...n.enabledPlugins||{},...z(t.enabledPlugins)};if(t.pluginSourcePolicy)M.pluginSourcePolicy={...n.pluginSourcePolicy??s.pluginSourcePolicy,...B(t.pluginSourcePolicy)};if(t.env)M.env=K({},M.env,t.env);if(t.mcpServers)M.mcpServers={...M.mcpServers||{},...t.mcpServers};if(t.lspServers)M.lspServers={...M.lspServers||{},...h(t.lspServers)};if(t.disableAllHooks!==void 0)M.disableAllHooks=t.disableAllHooks;if(t.permissionMode!==void 0)M.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)M.maxTurns=t.maxTurns;return M}resolveEnvInterpolation(n){let t=/\$\{?([A-Z_][A-Z0-9_]*)(:-([^}]+))?\}?/g,M=(r)=>{if(typeof r==="string")return r.replace(t,(S,_,u,E)=>{return process.env[_]||E||S});if(Array.isArray(r))return r.map(M);if(typeof r==="object"&&r!==null){let S=r;for(let[_,u]of Object.entries(S))S[_]=M(u);return S}return r},e=n;for(let[r,S]of Object.entries(e))e[r]=M(S)}async loadJsonFile(n){try{if(await this.fileExists(n)){let t=await Nt.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 Nt.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 M=(r)=>r.trim().replace(/^`|`$/g,""),e=(r)=>{for(let[S,_]of Object.entries(r))if(typeof _==="string")r[S]=M(_);else if(Array.isArray(_))_.forEach((u,E)=>{if(typeof u==="string")_[E]=M(u);else if(typeof u==="object"&&u!==null)e(u)});else if(typeof _==="object"&&_!==null)e(_)};return e(t),t}validateConfig(n,t=Z()){let M=[];try{n.lspServers=h(n.lspServers)}catch(e){M.push(e instanceof Error?e.message:"Invalid LSP server configuration")}for(let[e,r]of Object.entries(n.mcpServers||{}))try{nt(r),r.oauth=O(r);let S=_t(r);if(r.logging!==void 0)r.logging=S;if(r.sampling)r.sampling=wt(r.sampling);if(r.tasks)r.tasks=Lt(r.tasks)}catch(S){M.push(`MCP server "${e}": ${S instanceof Error?S.message:"invalid sampling policy"}`)}for(let[e,r]of Object.entries(n.modelProviders||{}))if(M.push(...$t(e,r)),t.isReservedProviderId(e))M.push(`modelProviders.${e}: built-in provider ids cannot be overridden`);if(M.length===0)try{t.configureModelProviders(n.modelProviders||{},n.models)}catch(e){M.push(e instanceof Error?e.message:"Failed to configure custom model providers")}if(!n.models||n.models.length===0)M.push("没有可用的模型配置");if(!dt(n.maxTurns))M.push(`maxTurns 必须是 ${ht()}`);if(!Qn(n.maxConcurrentTasks))M.push(`maxConcurrentTasks 必须是 ${Kn}-${Un} 之间的整数`);if(!Dn(n.maxQueuedTasks))M.push(`maxQueuedTasks 必须是 ${Hn}-${Yn} 之间的整数`);if(!Wn(n.maxQueuedTaskBytes))M.push(`maxQueuedTaskBytes 必须是 ${Vn}-${Gn} 之间的整数`);if(!zn(n.maxResidentSessionRuntimes))M.push(`maxResidentSessionRuntimes 必须是 ${$n}-${gn} 之间的整数`);if(!Bn(n.sessionRuntimeIdleMs))M.push(`sessionRuntimeIdleMs 必须是 ${pn}-${Cn} 之间的整数`);if(n.bashForegroundHandoffMs!==void 0&&!nn(n.bashForegroundHandoffMs))M.push("bashForegroundHandoffMs 必须是 0,或 "+`${fn}-${Nn} 之间的整数`);if(n.providerForegroundRecoveryMs!==void 0&&!pt(n.providerForegroundRecoveryMs))M.push("providerForegroundRecoveryMs 必须是 0,或 "+`${Xt}-${gt} 之间的整数`);if(n.providerCircuitBreakerOpenMs!==void 0&&!Ct(n.providerCircuitBreakerOpenMs))M.push("providerCircuitBreakerOpenMs 必须是 0,或 "+`${it}-${Rt} 之间的整数`);if(n.providerRequestConcurrency!==void 0&&!qt(n.providerRequestConcurrency))M.push("providerRequestConcurrency 必须是 "+`${zt}-${Bt} 之间的整数`);if(n.providerRequestAdmissionMs!==void 0&&!Vt(n.providerRequestAdmissionMs))M.push("providerRequestAdmissionMs 必须是 0,或 "+`${Kt}-${Ut} 之间的整数`);if(n.providerRequestPendingBytes!==void 0&&!Gt(n.providerRequestPendingBytes))M.push("providerRequestPendingBytes 必须是 "+`${Ht}-${Yt} 之间的整数`);if(n.models&&n.models.length>0){if(!n.currentModelId)M.push("未设置当前模型 ID");else if(!n.models.find((r)=>r.id===n.currentModelId))M.push(`当前模型 ID "${n.currentModelId}" 在 models 列表中不存在`);for(let e of n.models){let r=`模型 "${e.displayName||e.id}"`,S=["name","apiKey","baseUrl","maxContextTokens","maxOutputTokens","supportsThinking","thinkingBudget","thinkingMode"].filter((u)=>(u in e));if(S.length>0)M.push(`${r}: 不再支持旧字段 ${S.join(", ")};请重新配置模型`);if(!e.model)M.push(`${r}: model 字段必填`);if(!e.provider)M.push(`${r}: provider 字段必填`);if(e.overrides?.baseUrl&&!e.overrides.baseUrl.startsWith("http"))M.push(`${r}: overrides.baseUrl "${e.overrides.baseUrl}" 不是有效的 HTTP URL`);let _=e.overrides?.streamIdleTimeout;if(_!==void 0&&(!Number.isFinite(_)||_<1000))M.push(`${r}: overrides.streamIdleTimeout 必须至少为 1000ms`);try{t.getModel(e.provider,e.model)}catch{M.push(`${r}: 内置 catalog 中不存在 ${e.provider}/${e.model}`)}}}if(M.length>0)throw Error(`配置验证失败:
|
|
23
|
-
${M.map((e)=>` - ${e}`).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 zr(n,t={}){let M={...n};if(t.debug!==void 0)M.debug=t.debug===""?!0:t.debug;if(t.model){if(!n.models.some((r)=>r.id===t.model))throw Error(`模型配置未找到: ${t.model}`);M.currentModelId=t.model}if(t.yolo===!0)M.permissionMode="yolo";else if(t.permissionMode!==void 0)M.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)M.maxTurns=t.maxTurns;if(t.maxConcurrentTasks!==void 0)M.maxConcurrentTasks=t.maxConcurrentTasks;if(t.maxQueuedTasks!==void 0)M.maxQueuedTasks=t.maxQueuedTasks;if(t.maxQueuedTaskBytes!==void 0)M.maxQueuedTaskBytes=t.maxQueuedTaskBytes;if(t.maxResidentSessionRuntimes!==void 0)M.maxResidentSessionRuntimes=t.maxResidentSessionRuntimes;if(t.sessionRuntimeIdleMs!==void 0)M.sessionRuntimeIdleMs=t.sessionRuntimeIdleMs;return M.systemPrompt=t.systemPrompt,M.appendSystemPrompt=t.appendSystemPrompt,M.model=t.model,M.resumeSessionId=t.sessionId,M.forkSession=t.forkSession,M.allowedTools=t.allowedTools,M.disallowedTools=t.disallowedTools,M.mcpConfigPaths=t.mcpConfig,M.strictMcpConfig=t.strictMcpConfig,M.addDirs=t.addDir,M.outputFormat=t.outputFormat,M.inputFormat=t.inputFormat,M.print=t.print,M.includePartialMessages=t.includePartialMessages,M.replayUserMessages=t.replayUserMessages,M.agentsConfig=t.agents,M.settingSources=t.settingSources,M}
|
|
44
|
-
export{U as Oe,O as Pe,N as Qe,v as Re,Ln as Se,$ as Te,nt as Ue,ie as Ve,V as We,ze as Xe,Be as Ye,Ke as Ze,_t as _e,LM as $e,Ue as af,PM as bf,He as cf,wt as df,Ve as ef,Ge as ff,De as gf,We as hf,Ze as if,Lt as jf,Oe as kf,Je as lf,ke as mf,ye as nf,Ae as of,fn as pf,Nn as qf,ce as rf,$n as sf,Xn as tf,gn as uf,pn as vf,Rn as wf,Cn as xf,ae as yf,zn as zf,Bn as Af,Kn as Bf,Un as Cf,Hn as Df,Yn as Ef,qn as Ff,Vn as Gf,Gn as Hf,Qn as If,Dn as Jf,Wn as Kf,s as Lf,h as Mf,mM as Nf,B as Of,W as Pf,p as Qf,zr as Rf};
|
package/dist/chunk-egczvfsv.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{hg as y_,ig as Qf,jg as Kf,kg as g_,lg as zf,ng as Wf,pg as Hf,qg as hf,rg as Rf,sg as $f,ug as Sf,vg as Gf,xg as I}from"./chunk-yk9pxkc1.js";import{Eg as q}from"./chunk-fhnkyqfb.js";import{Ig as ef,Kg as Cf}from"./chunk-26wse17p.js";import{Ng as v_}from"./chunk-hcm55r3d.js";var ME={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},af=(f)=>ME[f]||{};var AE=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function Vf(f){return typeof f==="string"&&AE.has(f)}function nE(f){if(!f.aborted)return;if(Vf(f.reason))return f.reason;return"user-cancel"}function ET(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 yf(...f){let _=f.filter(Boolean);if(_.length===0)return new AbortController().signal;if(_.length===1)return _[0];let E=AbortSignal;if(typeof E.any==="function")return E.any(_);for(let A of _)if(A.aborted)return A;let T=new AbortController,x=new Map;for(let A of _){let Y=()=>{T.abort(A.reason);for(let[R,h]of x)R.removeEventListener("abort",h)};x.set(A,Y)}for(let[A,Y]of x)A.addEventListener("abort",Y,{once:!0});return T.signal}function d(f,_,E){let T=E?.throwOnAbort??!1;if(_?.aborted){if(T)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((x,A)=>{let Y,R=setTimeout(()=>{if(_&&Y)_.removeEventListener("abort",Y);x()},f);if(_)Y=()=>{if(clearTimeout(R),T)A(new DOMException("Aborted","AbortError"));else x()},_.addEventListener("abort",Y,{once:!0})})}var hE=q("Chat"),RE={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function bf(f){if(typeof f==="string")return f;return f.filter((_)=>_.type==="text").map((_)=>_.text).join(`
|
|
2
|
-
`)}function SE(f){if(!f)return{};try{let _=JSON.parse(f);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return hE.warn("[PiAIChatService] Invalid historical tool arguments",{value:f}),{}}}function YE(f){let _=f.match(/^data:([^;,]+);base64,(.+)$/s);return _?{mimeType:_[1],data:_[2]}:void 0}async function PE(f,_){let E=YE(f);if(E)return{type:"image",...E};if(!/^https?:\/\//i.test(f))return{type:"text",text:`[Unsupported image source: ${f}]`};let T=await fetch(f,{signal:_});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 of(f,_,E,T,x){let A=f.filter((h)=>h.role==="system").map((h)=>bf(h.content)).filter(Boolean).join(`
|
|
3
|
-
|
|
4
|
-
`),Y=[];for(let h of f){if(h.role==="system")continue;if(h.role==="user"){let U=_.input.includes("image"),M=typeof h.content==="string"?h.content:await Promise.all(h.content.map((P)=>P.type==="text"?Promise.resolve({type:"text",text:P.text}):U?PE(P.image_url.url,T):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})));Y.push({role:"user",content:M,timestamp:Date.now()});continue}if(h.role==="assistant"){let U=[];if(h.reasoningContent?.trim())U.push({type:"thinking",thinking:h.reasoningContent});let M=bf(h.content);if(M)U.push({type:"text",text:M});for(let P of h.tool_calls??[]){if(!("function"in P))continue;U.push({type:"toolCall",id:P.id,name:P.function.name,arguments:SE(P.function.arguments)})}Y.push({role:"assistant",content:U,api:_.api,provider:_.provider,model:_.id,usage:RE,stopReason:h.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}Y.push({role:"toolResult",toolCallId:h.tool_call_id??"",toolName:h.name??"unknown",content:[{type:"text",text:bf(h.content)}],isError:!1,timestamp:Date.now()})}let R=E?.filter((h)=>!x||h.name===x).map((h)=>({name:h.name,description:h.description,parameters:h.parameters,constrainedSampling:h.constrainedSampling}));return{...A?{systemPrompt:A}:{},messages:Y,...R?.length?{tools:R}:{}}}function df(f){let _=[];for(let E=0;E<f.length;E++){let T=f[E];if(T.role==="tool")continue;let x=T.role==="assistant"&&T.tool_calls?.length?T.tool_calls:void 0;if(!x){_.push(T);continue}let A=[],Y=E+1;while(Y<f.length&&f[Y].role==="tool")A.push(f[Y++]);let R=new Set(x.map((M)=>M.id)),h=A.filter((M)=>M.tool_call_id&&R.has(M.tool_call_id)),U=new Set(h.map((M)=>M.tool_call_id));if(R.size===x.length&&h.length===R.size&&U.size===R.size)_.push(T,...h);E=Y-1}return _}function rf(f){return f.some((_)=>_.role==="assistant"&&Boolean(_.tool_calls?.length)&&!_.reasoningContent?.trim())}function nf(f,_){return{...f,..._.baseUrl?{baseUrl:ef(f.api,_.baseUrl)}:{},..._.maxOutputTokens?{maxTokens:_.maxOutputTokens}:{}}}function jf(f){let _=f.modelCatalog??Cf();return{models:_.models,model:nf(_.getModel(f.provider,f.model),f)}}function f_(f,_){let E=f.modelCatalog??Cf();return nf(E.getModel(_.provider,_.model),f)}import{randomBytes as OE}from"node:crypto";import{createHmac as UE}from"node:crypto";function uE(f){try{let _=new URL(f);if(_.hash="",_.hostname=_.hostname.toLowerCase(),_.searchParams.sort(),_.pathname!=="/")_.pathname=_.pathname.replace(/\/+$/,"");return _.toString()}catch{return f.trim().replace(/\/+$/,"")}}function DE(f){if(!f)return[];return Object.entries(f).map(([_,E])=>[_.trim().toLowerCase(),E.trim()]).sort(([_],[E])=>_.localeCompare(E))}function xf(f,_,E){let T=JSON.stringify([f.provider.trim(),String(f.api).trim(),uE(f.baseUrl),f.model.trim(),f.serviceTier?.trim()??"",f.apiVersion?.trim()??"",f.apiKey??"",DE(f.customHeaders),E]);return UE("sha256",Buffer.from(_)).update(T).digest("hex")}var NE=60000,BE=4,VE=0.8;var Af=300000,Xf=600000;var __=128,E_=256,bE=1800000,Mf=50;class e 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 Jf(f){return f instanceof e||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_CIRCUIT_OPEN"}function m(f,_){return f!==void 0&&Number.isSafeInteger(f)&&f>0?f:_}function CE(f,_){return f!==void 0&&Number.isFinite(f)&&f>0&&f<=1?f:_}function jE(f,_){return xf(f,_,{providerCircuitOpenDurationMs:f.openDurationMs})}function r(f){let _=0;for(let E of f)if(E.failure)_++;return _}function T_(f){return f!==void 0&&Number.isInteger(f)&&f>=100&&f<=599?f:void 0}function x_(f){if(f===void 0||!Number.isFinite(f)||f<0)return;return Math.min(Math.ceil(f),Wf)}class A_{#M=new Map;#R=new WeakMap;#f;#_;#T;#E;constructor(f={}){this.#f=f.processSecret?new Uint8Array(f.processSecret):OE(32),this.#_=f.now??(()=>performance.now()),this.#T=f.wallNow??f.now??Date.now,this.#E={maxEntries:Math.min(m(f.maxEntries,__),__),maxWindowEntries:Math.min(m(f.maxWindowEntries,E_),E_),windowMs:m(f.windowMs,NE),minSamples:m(f.minSamples,BE),errorRateThreshold:CE(f.errorRateThreshold,VE),idleTtlMs:m(f.idleTtlMs,bE)}}get size(){return this.#M.size}get(f){if(f.openDurationMs===0)return this.#A();let _=this.#_();this.#V(_);let E=jE(f,this.#f),T=this.#M.get(E);if(T)return T.lastTouchedAt=_,this.#x(T,f.probeLeaseMs);if(this.#M.size>=this.#E.maxEntries)this.#j();if(this.#M.size>=this.#E.maxEntries)return this.#A();let x={key:E,state:"closed",samples:[],generation:0,nextAttemptId:1,nextProbeLeaseId:1,configuredOpenDurationMs:f.openDurationMs,effectiveOpenDurationMs:f.openDurationMs,lastTouchedAt:_,detached:!1};return this.#M.set(E,x),this.#x(x,f.probeLeaseMs)}#x(f,_){let E=this,T=Math.max(Af,Math.min(m(_,Af),Xf));return{preflight:()=>E.#U(f),check:()=>E.#u(f,T),recordSuccess:(x)=>E.#N(x,"success"),recordFailure:(x,A)=>E.#N(x,"failure",A),recordNeutral:(x)=>E.#N(x,"neutral"),abandon:(x)=>E.#C(x),snapshot:()=>E.#b(f)}}#A(){let f=this;return{preflight:()=>({eligible:!0}),check:()=>{let _=Object.freeze({kind:"noop"});return f.#R.set(_,{generation:0,attemptId:0,kind:"noop",settled:!1}),{allowed:!0,probe:!1,token:_}},recordSuccess:(_)=>f.#h(_),recordFailure:(_)=>f.#h(_),recordNeutral:(_)=>f.#h(_),abandon:(_)=>f.#C(_),snapshot:()=>({state:"closed",sampleCount:0,failureCount:0,noop:!0,detached:!1})}}#h(f){let _=this.#R.get(f);if(_?.kind==="noop")_.settled=!0;return}#U(f){let _=this.#_();if(f.detached)return{eligible:!0};if(f.lastTouchedAt=_,this.#B(f,_),f.state==="closed")return{eligible:!0};if(f.state==="open"){let T=f.nextProbeAt??_;return _<T?this.#S(f,T-_):{eligible:!0}}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&_>=f.probeLeaseExpiresAt)return{eligible:!0};let E=Math.max(1,(f.probeLeaseExpiresAt??_+Mf)-_);return this.#S(f,Math.min(Mf,E))}#S(f,_){let{allowed:E,...T}=this.#O(f,_);return{eligible:!1,...T}}#u(f,_){let E=this.#_();if(f.detached)return this.#A().check();if(f.lastTouchedAt=E,this.#B(f,E),f.state==="closed")return this.#Y(f,"regular");if(f.state==="open"){let x=f.nextProbeAt??E;if(E<x)return this.#O(f,x-E);f.state="half_open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&E>=f.probeLeaseExpiresAt)return this.#D(f,E,_);let T=Math.max(1,(f.probeLeaseExpiresAt??E+Mf)-E);return this.#O(f,Math.min(Mf,T))}#Y(f,_,E){let T=Object.freeze({kind:_});return this.#R.set(T,{entry:f,generation:f.generation,attemptId:f.nextAttemptId++,kind:_,...E!==void 0?{probeLeaseId:E}:{},settled:!1}),{allowed:!0,probe:_==="probe",token:T}}#D(f,_,E){let T=f.nextProbeLeaseId++;f.probeLeaseId=T,f.probeLeaseExpiresAt=_+E,f.lastTouchedAt=_;let x=this.#Y(f,"probe",T),A=f.lastFailure??{reason:"server_error"};return{...x,reason:A.reason,...A.statusCode!==void 0?{statusCode:A.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:r(f.samples)}}#O(f,_){let E=f.lastFailure??{reason:"server_error"};return{allowed:!1,state:f.state==="open"?"open":"half_open",reason:E.reason,...E.statusCode!==void 0?{statusCode:E.statusCode}:{},retryAfterMs:Math.max(0,Math.ceil(_)),nextProbeAt:this.#T()+Math.max(0,Math.ceil(_)),openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:r(f.samples)}}#N(f,_,E){let T=this.#R.get(f);if(!T||T.settled)return;if(T.settled=!0,T.kind==="noop"||!T.entry)return;let x=T.entry;if(x.detached||T.generation!==x.generation||T.kind==="regular"&&x.state!=="closed"||T.kind==="probe"&&(x.state!=="half_open"||T.probeLeaseId!==x.probeLeaseId))return;let A=this.#_();if(x.lastTouchedAt=A,T.kind==="probe"){if(_==="failure"&&E)return this.#P(x,E,A,"reopened");return this.#W(x)}if(_==="neutral")return;if(this.#X(x,_==="failure",A),_!=="failure"||!E)return;let Y=r(x.samples),R=x.samples.length===0?0:Y/x.samples.length;if(x.samples.length>=this.#E.minSamples&&R>=this.#E.errorRateThreshold)return this.#P(x,E,A,"opened");return}#P(f,_,E,T){let x={reason:_.reason,...T_(_.statusCode)!==void 0?{statusCode:T_(_.statusCode)}:{},...x_(_.retryAfterMs)!==void 0?{retryAfterMs:x_(_.retryAfterMs)}:{}},A=x.retryAfterMs??0,Y=Math.max(f.configuredOpenDurationMs,A);return f.state="open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.effectiveOpenDurationMs=Y,f.nextProbeAt=E+Y,f.lastFailure=x,{phase:T,reason:x.reason,...x.statusCode!==void 0?{statusCode:x.statusCode}:{},retryAfterMs:Y,nextProbeAt:this.#T()+Y,openDurationMs:Y,sampleCount:f.samples.length,failureCount:r(f.samples)}}#W(f){let _=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:_.reason,..._.statusCode!==void 0?{statusCode:_.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:0,failureCount:0}}#C(f){let _=this.#R.get(f);if(!_||_.settled)return!1;if(_.settled=!0,_.kind==="noop")return!0;let E=_.entry;if(!E||E.detached||_.kind!=="probe"||_.generation!==E.generation||_.probeLeaseId!==E.probeLeaseId)return!1;return E.probeLeaseId=void 0,E.probeLeaseExpiresAt=void 0,E.lastTouchedAt=this.#_(),!0}#X(f,_,E){if(this.#B(f,E),f.samples.length>=this.#E.maxWindowEntries)f.samples.shift();f.samples.push({at:E,failure:_})}#B(f,_){let E=_-this.#E.windowMs,T=0;while(T<f.samples.length&&f.samples[T].at<E)T++;if(T>0)f.samples.splice(0,T)}#b(f){if(!f.detached)this.#B(f,this.#_());return{state:f.state,sampleCount:f.samples.length,failureCount:r(f.samples),...f.nextProbeAt!==void 0?{nextProbeAt:f.nextProbeAt}:{},noop:!1,detached:f.detached}}#V(f){for(let[_,E]of this.#M)if(E.state==="closed"&&f-E.lastTouchedAt>this.#E.idleTtlMs)this.#z(_,E)}#j(){let f;for(let _ of this.#M.values())if(_.state==="closed"&&(!f||_.lastTouchedAt<f.lastTouchedAt))f=_;if(f)this.#z(f.key,f)}#z(f,_){_.detached=!0,this.#M.delete(f)}}var M_;function h_(){return M_??=new A_,M_}import{randomBytes as zE}from"node:crypto";var R_=16,S_=128,Y_=32,P_=3,U_=16,u_=96,D_=24,O_=12,N_=16,B_=4,V_=4,b_=67108864,C_=33554432,j_=12,z_=2,W_=2,X_=1,$_=15000,J_=30000;class i extends Error{reason;scope;requestClass;resource;inFlight;limit;queued;maxWaitMs;code="PROVIDER_ADMISSION_BUSY";retryable;constructor(f,_,E,T,x,A,Y,R){super(f==="queue_full"?`Provider request admission ${_} ${T} queue is full`:f==="wait_timeout"?`Provider request admission timed out waiting for ${_} capacity`:"Provider request admission scheduler is closed");this.reason=f;this.scope=_;this.requestClass=E;this.resource=T;this.inFlight=x;this.limit=A;this.queued=Y;this.maxWaitMs=R;this.name="ProviderAdmissionError",this.retryable=f!=="closed"}}function n(f){return f instanceof i||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_ADMISSION_BUSY"}function j(f,_,E){if(f===void 0||!Number.isSafeInteger(f)||f<=0)return _;return Math.min(f,E)}function WE(f){let _=j(f.globalMaxInFlight,R_,R_),E=j(f.globalMaxPending,S_,S_),T=j(f.domainMaxPending,Y_,Y_),x=Math.min(j(f.ownerMaxInFlight,P_,P_),_),A=Math.min(j(f.ownerMaxPending,U_,U_),E),Y=Math.min(j(f.nonForegroundGlobalMaxPending,Math.min(u_,Math.max(1,Math.floor(E*3/4))),u_),E),R=Math.min(j(f.nonForegroundDomainMaxPending,Math.min(D_,Math.max(1,Math.floor(T*3/4))),D_),T),h=Math.min(j(f.nonForegroundOwnerMaxPending,Math.min(O_,Math.max(1,Math.floor(A*3/4))),O_),A),U=Math.min(j(f.internalGlobalMaxPending,Math.min(N_,Math.max(1,Math.floor(E/8))),N_),Y),M=Math.min(j(f.internalDomainMaxPending,Math.min(B_,Math.max(1,Math.floor(T/8))),B_),R),P=Math.min(j(f.internalOwnerMaxPending,Math.min(V_,Math.max(1,Math.floor(A/4))),V_),h),u=j(f.globalMaxPendingBytes,I,I),D=Math.min(j(f.domainMaxPendingBytes,b_,b_),u),G=Math.min(j(f.ownerMaxPendingBytes,C_,C_),u),L=Math.min(j(f.nonForegroundGlobalMaxInFlight,Math.min(j_,_),j_),_),Q=Math.min(j(f.nonForegroundOwnerMaxInFlight,Math.min(z_,x),z_),x),Pf=Math.min(j(f.internalGlobalMaxInFlight,Math.min(W_,_),W_),_),ff=j(f.internalDomainMaxInFlight,X_,X_),Uf=j(f.agingMs,J_,J_);return{globalMaxInFlight:_,globalMaxPending:E,domainMaxPending:T,ownerMaxInFlight:x,ownerMaxPending:A,nonForegroundGlobalMaxPending:Y,nonForegroundDomainMaxPending:R,nonForegroundOwnerMaxPending:h,internalGlobalMaxPending:U,internalDomainMaxPending:M,internalOwnerMaxPending:P,globalMaxPendingBytes:u,domainMaxPendingBytes:D,ownerMaxPendingBytes:G,nonForegroundGlobalMaxInFlight:L,nonForegroundOwnerMaxInFlight:Q,internalGlobalMaxInFlight:Pf,internalDomainMaxInFlight:ff,agingMs:Uf}}function k_(f,_){if(!f.trim())throw Error(`${_} must not be blank`)}function XE(f){if(k_(f.sessionId,"sessionId"),k_(f.ownerId,"ownerId"),!Number.isSafeInteger(f.scope.maxConcurrent)||f.scope.maxConcurrent<hf||f.scope.maxConcurrent>Rf)throw Error(`maxConcurrent must be between ${hf} and ${Rf}`);if(!Number.isSafeInteger(f.scope.maxPendingBytes)||f.scope.maxPendingBytes<=0||f.scope.maxPendingBytes>I)throw Error(`maxPendingBytes must be between 1 and ${I}`);if(!Number.isSafeInteger(f.pendingBytes)||f.pendingBytes<=0||f.pendingBytes>I+1)throw Error(`pendingBytes must be between 1 and ${I+1}`);if(!Number.isSafeInteger(f.maxWaitMs)||f.maxWaitMs<0||f.maxWaitMs>Sf)throw Error(`maxWaitMs must be 0-${Sf}`)}function kf(f,_){if(_!==void 0)return _;if(f?.reason!==void 0)return f.reason;return new DOMException("Provider request admission cancelled","AbortError")}function JE(f,_){return xf(f,_,{providerRequestConcurrency:f.maxConcurrent,providerRequestPendingBytes:f.maxPendingBytes})}class G_{#M;#R;#f;#_=[];#T=new Map;#E=new Map;#x=0;#A=0;#h=0;#U=0;#S=0;#u=0;#Y=0;#D=0;#O=1;#N=0;#P=!1;constructor(f={}){this.#M=f.processSecret?new Uint8Array(f.processSecret):zE(32),this.#R=f.now??(()=>performance.now()),this.#f=WE(f)}admit(f){if(XE(f),this.#P)throw this.#H("closed",f,{scope:"global",resource:"stream",inFlight:this.#x,limit:this.#f.globalMaxInFlight},this.#_.length);if(f.signal?.aborted)throw kf(f.signal);let _=JE(f.scope,this.#M),E=this.#T.get(_),T=this.#E.get(f.ownerId),x=E??this.#X(f.scope.maxConcurrent),A=T??this.#B();if(this.#_.length===0&&this.#b(x,A,f.requestClass)){if(!E)this.#T.set(_,x);if(!T)this.#E.set(f.ownerId,A),this.#O++;let u=this.#j(_,f.ownerId,f.requestClass),D=this.#v(f,0);return{ready:Promise.resolve(u),getSnapshot:()=>({...D}),cancel:()=>{D={...D}}}}let Y=this.#W(f,x,A);if(Y)throw this.#H("queue_full",f,Y,this.#_.length);let R=this.#V(x,A,f.requestClass);if(f.maxWaitMs===0)throw this.#H("wait_timeout",f,R,this.#_.length);if(!E)this.#T.set(_,x);if(!T)this.#E.set(f.ownerId,A),this.#O++;let h,U,M=new Promise((u,D)=>{h=u,U=D});M.catch(()=>{return});let P={domainKey:_,sessionId:f.sessionId,ownerId:f.ownerId,requestClass:f.requestClass,maxWaitMs:f.maxWaitMs,pendingBytes:f.pendingBytes,enqueuedAt:this.#R(),signal:f.signal,resolve:h,reject:U,settled:!1,admitted:!1};if(f.signal)P.abortListener=()=>this.#$(P,kf(f.signal)),f.signal.addEventListener("abort",P.abortListener,{once:!0});return P.timer=setTimeout(()=>this.#Q(P),f.maxWaitMs),P.timer.unref?.(),this.#_.push(P),this.#C(x,A,P),this.#J(),{ready:M,getSnapshot:()=>this.#F(P),cancel:(u)=>this.#$(P,kf(f.signal,u))}}close(){if(this.#P)return;this.#P=!0;for(let f of[...this.#_]){let _=this.#T.get(f.domainKey),E=this.#E.get(f.ownerId),T=_&&E?this.#V(_,E,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#x,limit:this.#f.globalMaxInFlight};this.#k(f,new i("closed",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}}getStats(){return{inFlight:this.#x,queued:this.#_.length,pendingBytes:this.#u,nonForegroundInFlight:this.#A,internalInFlight:this.#h,nonForegroundQueued:this.#U,internalQueued:this.#S,nonForegroundPendingBytes:this.#Y,internalPendingBytes:this.#D,domainCount:this.#T.size,ownerCount:this.#E.size,closed:this.#P}}#W(f,_,E){let T=(M,P,u)=>P>=u?{scope:M,resource:"pending_count",inFlight:P,limit:u}:void 0;if(f.requestClass==="internal"){let M=T("class",this.#S,this.#f.internalGlobalMaxPending)??T("class",E.internalQueued,this.#f.internalOwnerMaxPending)??T("class",_.internalQueued,this.#f.internalDomainMaxPending);if(M)return M}if(f.requestClass!=="foreground"){let M=T("class",this.#U,this.#f.nonForegroundGlobalMaxPending)??T("class",E.nonForegroundQueued,this.#f.nonForegroundOwnerMaxPending)??T("class",_.nonForegroundQueued,this.#f.nonForegroundDomainMaxPending);if(M)return M}let x=T("global",this.#_.length,this.#f.globalMaxPending)??T("owner",E.queued,this.#f.ownerMaxPending)??T("domain",_.queued,this.#f.domainMaxPending);if(x)return x;let A=Math.min(f.scope.maxPendingBytes,this.#f.globalMaxPendingBytes),Y=Math.min(A,this.#f.domainMaxPendingBytes),R=Math.min(A,this.#f.ownerMaxPendingBytes),h=(M,P)=>f.pendingBytes>P-M,U=(M)=>{if(M==="owner")return{scope:M,resource:"pending_bytes",inFlight:E.inFlight,limit:this.#f.ownerMaxInFlight};if(M==="domain")return{scope:M,resource:"pending_bytes",inFlight:_.inFlight,limit:_.maxConcurrent};return{scope:M,resource:"pending_bytes",inFlight:this.#x,limit:this.#f.globalMaxInFlight}};if(f.requestClass==="internal"){let M=Math.max(1,Math.floor(A/8)),P=Math.max(1,Math.floor(Y/4)),u=Math.max(1,Math.floor(R/4));if(h(this.#D,M)||h(E.internalPendingBytes,u)||h(_.internalPendingBytes,P))return U("class")}if(f.requestClass!=="foreground"){let M=Math.max(1,Math.floor(A*3/4)),P=Math.max(1,Math.floor(Y*3/4)),u=Math.max(1,Math.floor(R/2));if(h(this.#Y,M)||h(E.nonForegroundPendingBytes,u)||h(_.nonForegroundPendingBytes,P))return U("class")}if(h(this.#u,A))return U("global");if(h(E.pendingBytes,R))return U("owner");if(h(_.pendingBytes,Y))return U("domain");return}#C(f,_,E){if(f.queued++,_.queued++,this.#u+=E.pendingBytes,f.pendingBytes+=E.pendingBytes,_.pendingBytes+=E.pendingBytes,E.requestClass!=="foreground")this.#U++,f.nonForegroundQueued++,_.nonForegroundQueued++,this.#Y+=E.pendingBytes,f.nonForegroundPendingBytes+=E.pendingBytes,_.nonForegroundPendingBytes+=E.pendingBytes;if(E.requestClass==="internal")this.#S++,f.internalQueued++,_.internalQueued++,this.#D+=E.pendingBytes,f.internalPendingBytes+=E.pendingBytes,_.internalPendingBytes+=E.pendingBytes}#X(f){return{maxConcurrent:f,inFlight:0,nonForegroundInFlight:0,internalInFlight:0,queued:0,nonForegroundQueued:0,internalQueued:0,pendingBytes:0,nonForegroundPendingBytes:0,internalPendingBytes:0}}#B(){return{order:this.#O,inFlight:0,nonForegroundInFlight:0,internalInFlight:0,queued:0,nonForegroundQueued:0,internalQueued:0,pendingBytes:0,nonForegroundPendingBytes:0,internalPendingBytes:0}}#b(f,_,E){if(this.#x>=this.#f.globalMaxInFlight)return!1;if(f.inFlight>=f.maxConcurrent)return!1;if(_.inFlight>=this.#f.ownerMaxInFlight)return!1;if(E==="foreground")return!0;if(this.#A>=this.#f.nonForegroundGlobalMaxInFlight)return!1;if(_.nonForegroundInFlight>=this.#f.nonForegroundOwnerMaxInFlight)return!1;let T=Math.max(1,f.maxConcurrent-1);if(f.nonForegroundInFlight>=T)return!1;if(E!=="internal")return!0;return this.#h<this.#f.internalGlobalMaxInFlight&&f.internalInFlight<this.#f.internalDomainMaxInFlight}#V(f,_,E){if(_.inFlight>=this.#f.ownerMaxInFlight)return{scope:"owner",resource:"stream",inFlight:_.inFlight,limit:this.#f.ownerMaxInFlight};if(E!=="foreground"&&_.nonForegroundInFlight>=this.#f.nonForegroundOwnerMaxInFlight)return{scope:"class",resource:"stream",inFlight:_.nonForegroundInFlight,limit:this.#f.nonForegroundOwnerMaxInFlight};if(f.inFlight>=f.maxConcurrent)return{scope:"domain",resource:"stream",inFlight:f.inFlight,limit:f.maxConcurrent};if(E!=="foreground"){let T=Math.max(1,f.maxConcurrent-1);if(f.nonForegroundInFlight>=T)return{scope:"class",resource:"stream",inFlight:f.nonForegroundInFlight,limit:T}}if(E==="internal"&&f.internalInFlight>=this.#f.internalDomainMaxInFlight)return{scope:"class",resource:"stream",inFlight:f.internalInFlight,limit:this.#f.internalDomainMaxInFlight};if(this.#x>=this.#f.globalMaxInFlight)return{scope:"global",resource:"stream",inFlight:this.#x,limit:this.#f.globalMaxInFlight};if(E!=="foreground"&&this.#A>=this.#f.nonForegroundGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#A,limit:this.#f.nonForegroundGlobalMaxInFlight};if(E==="internal"&&this.#h>=this.#f.internalGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#h,limit:this.#f.internalGlobalMaxInFlight};return{scope:"domain",resource:"stream",inFlight:f.inFlight,limit:f.maxConcurrent}}#j(f,_,E){let T=this.#T.get(f),x=this.#E.get(_);if(!T||!x)throw Error("Provider admission accounting state is unavailable");if(this.#x++,T.inFlight++,x.inFlight++,E!=="foreground")this.#A++,T.nonForegroundInFlight++,x.nonForegroundInFlight++;if(E==="internal")this.#h++,T.internalInFlight++,x.internalInFlight++;let A=!1;return{release:()=>{if(A)return;A=!0,this.#z(f,_,E)}}}#z(f,_,E){let T=this.#T.get(f),x=this.#E.get(_);if(this.#x=Math.max(0,this.#x-1),T)T.inFlight=Math.max(0,T.inFlight-1);if(x)x.inFlight=Math.max(0,x.inFlight-1);if(E!=="foreground"){if(this.#A=Math.max(0,this.#A-1),T)T.nonForegroundInFlight=Math.max(0,T.nonForegroundInFlight-1);if(x)x.nonForegroundInFlight=Math.max(0,x.nonForegroundInFlight-1)}if(E==="internal"){if(this.#h=Math.max(0,this.#h-1),T)T.internalInFlight=Math.max(0,T.internalInFlight-1);if(x)x.internalInFlight=Math.max(0,x.internalInFlight-1)}this.#L(f,_),this.#J()}#J(){if(this.#P)return;while(this.#_.length>0){let f=this.#R(),_=new Map;for(let[R,h]of this.#_.entries()){let U=this.#T.get(h.domainKey),M=this.#E.get(h.ownerId);if(U===void 0||M===void 0||!this.#b(U,M,h.requestClass))continue;let P=this.#Z(h,f),u=_.get(h.ownerId);if(!u||P<u.rank||P===u.rank&&R<u.index)_.set(h.ownerId,{pending:h,rank:P,index:R})}let E=[..._.values()].filter(({pending:R})=>{let h=this.#T.get(R.domainKey),U=this.#E.get(R.ownerId);return h!==void 0&&U!==void 0&&this.#b(h,U,R.requestClass)}).map(({pending:R,rank:h})=>({pending:R,rank:h,order:this.#E.get(R.ownerId).order}));if(E.length===0)return;let T=Math.min(...E.map((R)=>R.rank)),x=E.filter((R)=>R.rank===T),Y=x.filter((R)=>R.order>this.#N).sort((R,h)=>R.order-h.order)[0]??x.sort((R,h)=>R.order-h.order)[0];this.#c(Y.pending,Y.order)}}#Z(f,_){let E=f.requestClass==="foreground"?0:f.requestClass==="background"?1:2,T=Math.floor(Math.max(0,_-f.enqueuedAt)/this.#f.agingMs);return Math.max(0,E-T)}#c(f,_){if(!this.#G(f,!1))return;f.settled=!0,f.admitted=!0,this.#N=_;let E=this.#j(f.domainKey,f.ownerId,f.requestClass);f.permit=E,f.resolve(E)}#Q(f){let _=this.#T.get(f.domainKey),E=this.#E.get(f.ownerId),T=_&&E?this.#V(_,E,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#x,limit:this.#f.globalMaxInFlight};this.#k(f,new i("wait_timeout",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}#$(f,_){this.#k(f,_)}#k(f,_){if(!this.#G(f))return;f.settled=!0,f.reject(_),this.#J()}#G(f,_=!0){if(f.settled||f.admitted)return!1;let E=this.#_.indexOf(f);if(E<0)return!1;this.#_.splice(E,1);let T=this.#T.get(f.domainKey),x=this.#E.get(f.ownerId);if(T&&x)this.#K(T,x,f);if(this.#I(f),_)this.#L(f.domainKey,f.ownerId);return!0}#K(f,_,E){if(f.queued=Math.max(0,f.queued-1),_.queued=Math.max(0,_.queued-1),this.#u=Math.max(0,this.#u-E.pendingBytes),f.pendingBytes=Math.max(0,f.pendingBytes-E.pendingBytes),_.pendingBytes=Math.max(0,_.pendingBytes-E.pendingBytes),E.requestClass!=="foreground")this.#U=Math.max(0,this.#U-1),f.nonForegroundQueued=Math.max(0,f.nonForegroundQueued-1),_.nonForegroundQueued=Math.max(0,_.nonForegroundQueued-1),this.#Y=Math.max(0,this.#Y-E.pendingBytes),f.nonForegroundPendingBytes=Math.max(0,f.nonForegroundPendingBytes-E.pendingBytes),_.nonForegroundPendingBytes=Math.max(0,_.nonForegroundPendingBytes-E.pendingBytes);if(E.requestClass==="internal")this.#S=Math.max(0,this.#S-1),f.internalQueued=Math.max(0,f.internalQueued-1),_.internalQueued=Math.max(0,_.internalQueued-1),this.#D=Math.max(0,this.#D-E.pendingBytes),f.internalPendingBytes=Math.max(0,f.internalPendingBytes-E.pendingBytes),_.internalPendingBytes=Math.max(0,_.internalPendingBytes-E.pendingBytes)}#I(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}#L(f,_){let E=this.#T.get(f);if(E&&E.inFlight===0&&E.queued===0)this.#T.delete(f);let T=this.#E.get(_);if(T&&T.inFlight===0&&T.queued===0)this.#E.delete(_)}#F(f){let _=Math.max(0,Math.floor(this.#R()-f.enqueuedAt));if(f.admitted)return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:this.#x,limit:this.#f.globalMaxInFlight,waitMs:_,maxWaitMs:f.maxWaitMs};let E=this.#T.get(f.domainKey),T=this.#E.get(f.ownerId),x=E&&T?this.#V(E,T,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#x,limit:this.#f.globalMaxInFlight};return{state:"queued",requestClass:f.requestClass,resource:x.resource,scope:x.scope,reason:"capacity",queuePosition:this.#t(f,x.scope),queueDepth:this.#_.length,inFlight:x.inFlight,limit:x.limit,waitMs:_,maxWaitMs:f.maxWaitMs}}#v(f,_){return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:this.#x,limit:this.#f.globalMaxInFlight,waitMs:_,maxWaitMs:f.maxWaitMs}}#t(f,_){let E=this.#_.filter((T)=>{switch(_){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,E.indexOf(f)+1)}#H(f,_,E,T){return new i(f,E.scope,_.requestClass,E.resource,E.inFlight,E.limit,T,_.maxWaitMs)}}var H_;function L_(){return H_??=new G_,H_}function Z_(f,_={}){let E=_.maxBytes??134217728,T=_.maxNodes??1e5;if(!Number.isSafeInteger(E)||E<=0||E>=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 x=new WeakSet,A=0,Y=0,R=!1,h=(M)=>{if(R||M<=0)return;if(!Number.isSafeInteger(M)||M>E-A){A=E+1,R=!0;return}A+=M},U=(M)=>{if(R)return;if(Y+=1,Y>T){h(E+1);return}if(M===null){h(4);return}switch(typeof M){case"string":h(Buffer.byteLength(M,"utf8"));return;case"number":case"bigint":h(8);return;case"boolean":h(4);return;case"undefined":case"function":case"symbol":return;case"object":break}if(x.has(M))return;if(x.add(M),ArrayBuffer.isView(M)){h(32+M.byteLength);return}if(M instanceof ArrayBuffer){h(32+M.byteLength);return}if(M instanceof Date){h(40);return}if(M instanceof RegExp){h(32+Buffer.byteLength(M.source,"utf8"));return}if(M instanceof Map){h(32);for(let[P,u]of M)if(U(P),U(u),R)return;return}if(M instanceof Set){h(32);for(let P of M)if(U(P),R)return;return}if(M instanceof WeakMap||M instanceof WeakSet){h(32);return}if(Array.isArray(M)){h(16);for(let P of M)if(U(P),R)return;return}h(32);for(let P of Reflect.ownKeys(M)){if(typeof P!=="string")continue;let u=Object.getOwnPropertyDescriptor(M,P);if(!u?.enumerable||!("value"in u))continue;if(h(8+Buffer.byteLength(P,"utf8")),U(u.value),R)return}};return U(f),A}function c_(f){return Z_([f.messages,f.context,f.tools,f.requestOptions],{maxBytes:I})}var Q_=new WeakSet;class s extends Error{budgetMs;elapsedMs;code="PROVIDER_RECOVERY_BUDGET_EXCEEDED";constructor(f,_){super(`Provider recovery budget exhausted after ${f}ms`);this.budgetMs=f;this.elapsedMs=_;this.name="ProviderRecoveryBudgetExceededError"}}var kE=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],HE=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],$E=["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 K_(f){return(f instanceof Error?f.message:String(f)).toLowerCase()}function GE(f){let _=K_(f);return HE.some((E)=>_.includes(E))}function Lf(f){if(f!==null&&typeof f==="object")Q_.add(f)}function KT(f){return f!==null&&typeof f==="object"&&Q_.has(f)}function LE(f){return f!==null&&typeof f==="object"&&"code"in f?f.code:void 0}function ZE(f){if(f===null||typeof f!=="object")return;let _=f;for(let E of["status","statusCode"]){let T=_[E];if(typeof T==="number"&&Number.isInteger(T))return T}return}function cE(f){let _=f.match(/^(?:error:\s*)?(\d{3})\b/),E=f.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),T=Number(_?.[1]??E?.[1]);return Number.isInteger(T)?T:void 0}function l(f,_){let E=K_(f),T=LE(f);if(T==="STREAM_IDLE_TIMEOUT"||T==="PROVIDER_RECOVERY_BUDGET_EXCEEDED"||f instanceof Error&&f.name==="AbortError"||E.includes("request aborted")||E==="aborted")return{retryable:!1};if(kE.some((A)=>E.includes(A))||GE(f))return{retryable:!1};if(_?.shouldRetry==="false")return{retryable:!1,statusCode:_.statusCode};let x=_?.statusCode??ZE(f)??cE(E);if(_?.shouldRetry==="true")return{retryable:!0,reason:x===429?"rate_limit":x===408||x===409?"timeout":"server_error",statusCode:x};if(x===429)return{retryable:!0,reason:"rate_limit",statusCode:x};if(x===408||x===409)return{retryable:!0,reason:"timeout",statusCode:x};if(x!==void 0&&x>=500&&x<=599)return{retryable:!0,reason:"server_error",statusCode:x};if(T==="PROVIDER_STREAM_CLOSED"||E.includes("stream closed before completion")||E.includes("ended without")||E.includes("stream ended before"))return{retryable:!0,reason:"stream_closed",statusCode:x};if($E.some((A)=>E.includes(A)))return{retryable:!0,reason:"transport",statusCode:x};if(E.includes("timeout")||E.includes("timed out")||E.includes("temporarily unavailable")||E.includes("upstream_error")||E.includes("overloaded")||E.includes("rate limit")||E.includes("too many requests")||E.includes("service unavailable")||E.includes("server error")||E.includes("internal error")||E.includes("please retry")||E.includes("try your request again"))return{retryable:!0,reason:E.includes("rate")||E.includes("too many")?"rate_limit":E.includes("timeout")||E.includes("timed out")?"timeout":"server_error",statusCode:x};return{retryable:!1,statusCode:x}}function Zf(f,_){if(!f)return;if(f.retryAfterMs!==void 0){let x=Number.parseFloat(f.retryAfterMs);if(Number.isFinite(x))return Math.max(0,x)}if(f.retryAfter===void 0)return;let E=Number.parseFloat(f.retryAfter);if(Number.isFinite(E))return Math.max(0,E*1000);let T=Date.parse(f.retryAfter);return Number.isFinite(T)?Math.max(0,T-_):void 0}function I_(f,_,E={}){let T=E.now??Date.now(),x=E.maxDelayMs??60000,A=Zf(_,T);if(A!==void 0)return Math.min(Math.ceil(A),x);let Y=Math.max(0,f-1),R=E.maxExponentialDelayMs??8000,h=Math.min(500*2**Y,R),U=Math.max(0,Math.min(1,E.random??Math.random())),M=h*(0.75+U*0.25);return Math.min(Math.round(M),x)}function t_(f,_){let E=f.onPayload;f.onPayload=async(T,x)=>{let A=E?await E(T,x):T;return _(A===void 0?T:A,x)}}function QE(f){if(!f.reasoningEnabled)return;return f.reasoningEffort??f.reasoningLevel??"high"}function KE(f){switch(f){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function IE(f,_,E,T){let x=T?void 0:QE(E);if(!x){if(_.api==="anthropic-messages")f.thinkingEnabled=!1;if(_.api==="google-generative-ai"||_.api==="google-vertex")f.thinking={enabled:!1};return}switch(_.api){case"anthropic-messages":f.thinkingEnabled=!0,f.effort=x;break;case"google-generative-ai":case"google-vertex":f.thinking={enabled:!0,level:KE(x)};break;case"mistral-conversations":f.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":f.reasoning=x;break;default:f.reasoningEffort=x}}function FE(f,_,E){if(!E)return;switch(_){case"anthropic-messages":case"bedrock-converse-stream":f.toolChoice={type:"tool",name:E};break;case"openai-completions":case"mistral-conversations":case"pi-messages":f.toolChoice={type:"function",function:{name:E}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":f.toolChoice={type:"function",name:E};break;case"google-generative-ai":case"google-vertex":f.toolChoice="any";break}}function vE(f,_,E){let T=E.serviceTier;if(!T)return;if(_.api==="openai-responses"||_.api==="openai-codex-responses"||_.api==="azure-openai-responses"){f.serviceTier=T;return}if(_.api!=="openai-completions"&&!(_.api==="anthropic-messages"&&T==="fast"))return;t_(f,(x)=>{if(!x||typeof x!=="object"||Array.isArray(x))return x;return _.api==="anthropic-messages"?{...x,speed:"fast"}:{...x,service_tier:T}})}function tE(f,_,E){let T=E.responseVerbosity;if(!T)return;if(v_(_,T),_.api==="openai-codex-responses"){f.textVerbosity=T;return}t_(f,(x)=>{if(!x||typeof x!=="object"||Array.isArray(x))return x;if(_.api==="openai-completions")return{...x,verbosity:T};let A="text"in x&&x.text&&typeof x.text==="object"&&!Array.isArray(x.text)?x.text:{};return{...x,text:{...A,verbosity:T}}})}function w_(f,_,E,T,x=!1){let A={apiKey:f.apiKey,headers:f.customHeaders,signal:E,temperature:T?.temperature??f.temperature??0,maxTokens:T?.maxOutputTokens??f.maxOutputTokens,timeoutMs:f.timeout,maxRetries:0,cacheRetention:f.enablePromptCaching?"short":"none"};if(IE(A,_,f,x),FE(A,_.api,T?.toolChoice?.toolName),vE(A,_,f),tE(A,_,f),_.api==="azure-openai-responses")A.azureBaseUrl=f.baseUrl,A.azureApiVersion=f.apiVersion,A.azureDeploymentName=_.id;return A}function F_(f,_){let E=_.get("x-should-retry");return{statusCode:f,..._.get("retry-after")!==null?{retryAfter:_.get("retry-after")??void 0}:{},..._.get("retry-after-ms")!==null?{retryAfterMs:_.get("retry-after-ms")??void 0}:{},...E==="true"||E==="false"?{shouldRetry:E}:{}}}var wE=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function p_(f,_,E){let T=f.onResponse;if(f.onResponse=async(A,Y)=>{let R=new Headers(A.headers);E(F_(A.status,R)),await T?.(A,Y)},!wE.has(_.api)||typeof globalThis.fetch!=="function")return;let x=typeof f.fetch==="function"?f.fetch:globalThis.fetch.bind(globalThis);f.fetch=async(A,Y)=>{let R=await x(A,Y);return E(F_(R.status,R.headers)),R}}function q_(f){return{promptTokens:f.input+f.cacheRead+f.cacheWrite,completionTokens:f.output,totalTokens:f.totalTokens,costUsd:f.cost.total,...f.reasoning!==void 0?{reasoningTokens:f.reasoning}:{},...f.cacheWrite>0?{cacheCreationInputTokens:f.cacheWrite}:{},...f.cacheRead>0?{cacheReadInputTokens:f.cacheRead}:{}}}var Yf=300000,pE=30000;class m_ 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 s_ extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function cf(f){return f.reason instanceof Error?f.reason:new DOMException("Aborted","AbortError")}function qE(f){return f.idleTimeoutMs&&f.idleTimeoutMs>0?f.idleTimeoutMs:Yf}function mE(f,_){if(_===0)return;let E=_!==void 0&&_>0?_:pE;return Math.max(1,Math.min(E,Math.floor(f/2)))}function sE(f,_,E){if(E?.aborted)return Promise.reject(cf(E));return new Promise((T,x)=>{let A=!1,Y=()=>{clearTimeout(M),E?.removeEventListener("abort",U)},R=(P)=>{if(A)return;A=!0,Y(),T(P)},h=(P)=>{if(A)return;A=!0,Y(),x(P instanceof Error?P:Error(String(P)))},U=()=>{if(E)h(cf(E))},M=setTimeout(()=>R({kind:"timer"}),Math.max(0,_));if(E?.addEventListener("abort",U,{once:!0}),E?.aborted){U();return}f.then((P)=>R({kind:"next",result:P}),h)})}async function*lE(f,_,E){let T=qE(_),x=mE(T,_.stallWarningMs);if(_.signal?.aborted)throw cf(_.signal);let A=Date.now(),Y=Promise.resolve().then(()=>f.next()),R;for(;;){let U=await sE(Y,(R?T:x??T)-(Date.now()-A),_.signal);if(U.kind==="next"){if(R)yield{...R,phase:"recovered",durationMs:Math.max(R.durationMs,Date.now()-A)};return U.result}if(!R&&x!==void 0){E.stallCount++,R={phase:"detected",stallCount:E.stallCount,durationMs:x,warningAfterMs:x,timeoutMs:T,outputStarted:E.outputStarted},yield R;continue}let M=new m_(T);throw _.abort?.(M),M}}async function*l_(f,_,E,T,x={}){let Y=f.stream(_,E,T)[Symbol.asyncIterator](),R=0,h=!1,U={stallCount:0,outputStarted:!1};try{while(!0){let M=lE(Y,x,U),P=await M.next();while(!P.done)yield{providerStall:P.value},P=await M.next();let u=P.value;if(u.done)throw new s_;let D=u.value;switch(D.type){case"text_delta":U.outputStarted=!0,yield{content:D.delta};break;case"thinking_delta":U.outputStarted=!0,yield{reasoningContent:D.delta};break;case"toolcall_end":U.outputStarted=!0,yield{toolCalls:[{index:R++,id:D.toolCall.id,type:"function",function:{name:D.toolCall.name,arguments:JSON.stringify(D.toolCall.arguments)}}]};break;case"done":h=!0,yield{finishReason:D.reason,usage:q_(D.message.usage)};return;case"error":throw Error(D.error.errorMessage??`Request ${D.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!h)Promise.resolve(Y.return?.()).catch(()=>{return})}}var a_=q("Chat"),aE=1;function yE(f){return Boolean(f&&f.role==="user"&&Array.isArray(f.content)&&f.content.some((_)=>_.type==="image_url"))}function gE(f,_){let E=l(f,_);if(!E.retryable||!E.reason)return;let T=E.statusCode;switch(E.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 x=Zf(_,Date.now());return{reason:E.reason,...T!==void 0?{statusCode:T}:{},...x!==void 0?{retryAfterMs:x}:{}}}function oE(f){return f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT"}class If{config;models;model;admissionFallbackOwnerId=`pi-service-${process.pid}-${aE++}`;constructor(f){let _=jf(f);this.config={...f,maxContextTokens:_.model.contextWindow,maxOutputTokens:f.maxOutputTokens??_.model.maxTokens},this.models=_.models,this.model=_.model,a_.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(f,_,E,T){let x="",A="",Y=[],R,h;for await(let U of this.streamChat(f,_,E,T)){x+=U.content??"",A+=U.reasoningContent??"";for(let M of U.toolCalls??[])if(M.id&&M.type==="function"&&M.function?.name)Y.push(M);R=U.usage??R,h=U.finishReason??h}return{content:x,...A?{reasoningContent:A}:{},...Y.length>0?{toolCalls:Y}:{},usage:R,finishReason:h}}async*streamChat(f,_,E,T){let x=T?.toolChoice?.toolName;if(x&&!_?.some((S)=>S.name===x))throw Error(`Required tool is unavailable: ${x}`);let A=df(f);if(A.some((S)=>yE(S))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let Y=Boolean(x)||rf(A),R=await of(A,this.model,_,E,x),h=c_({messages:A,context:R,tools:_,requestOptions:T}),U=T?.providerRecovery;if(U&&!g_(U.budgetMs))throw Error("Invalid bounded foreground Provider recovery budget");let M=U?.mode==="bounded_foreground"&&U.budgetMs>0?{budgetMs:U.budgetMs,startedAt:void 0}:void 0,P=M?"bounded_foreground":"standard",u=this.config.maxRetries??2,D=this.config.maxRetries??(M?y_:2),G=M!==void 0&&this.config.maxRetries===void 0,L=0,Q,Pf=this.config.providerCircuitRegistry??h_(),ff=this.config.providerCircuitBreakerOpenMs??zf,Uf=Math.max(Af,Math.min(this.config.streamIdleTimeout??Yf,Xf)),o_=this.config.providerRequestAdmissionScheduler??L_(),d_=this.config.providerRequestConcurrency??Hf,Ff=this.config.providerRequestAdmissionMs??$f,r_=this.config.providerRequestPendingBytes??Gf,uf=T?.providerAdmission??{sessionId:this.admissionFallbackOwnerId,ownerId:this.admissionFallbackOwnerId,requestClass:"internal"},e_=(S)=>Pf.get({provider:S.provider,api:S.api,baseUrl:S.baseUrl??this.config.baseUrl??"",model:S.id,serviceTier:this.config.serviceTier,apiVersion:this.config.apiVersion,apiKey:this.config.apiKey,customHeaders:this.config.customHeaders,openDurationMs:ff,probeLeaseMs:Uf}),i_=(S)=>({provider:S.provider,api:S.api,baseUrl:S.baseUrl??this.config.baseUrl??"",model:S.id,serviceTier:this.config.serviceTier,apiVersion:this.config.apiVersion,apiKey:this.config.apiKey,customHeaders:this.config.customHeaders,maxConcurrent:d_,maxPendingBytes:r_}),C=(S=Date.now())=>{if(!M)return;let O=M.startedAt===void 0?0:Math.min(M.budgetMs,Math.max(0,S-M.startedAt));return{recoveryBudgetMs:M.budgetMs,recoveryElapsedMs:O,recoveryRemainingMs:Math.max(0,M.budgetMs-O)}},F=()=>({mode:P,...C()??{}}),vf=()=>{if(M&&M.startedAt===void 0)M.startedAt=Date.now()},v=()=>{let S=C();return new s(M?.budgetMs??0,S?.recoveryElapsedMs??0)},a=()=>!G||L<D+1,Df=(S,O)=>{let{state:W,...V}=O;return{phase:S,...V,...C()?{recoveryRemainingMs:C()?.recoveryRemainingMs}:{}}},tf=(S)=>({phase:"rejected",requestClass:S.requestClass,resource:S.resource,scope:S.scope,reason:S.reason,queuePosition:0,queueDepth:Math.max(0,S.queued),inFlight:Math.max(0,S.inFlight),limit:Math.max(0,S.limit),waitMs:S.reason==="wait_timeout"?S.maxWaitMs:0,maxWaitMs:S.maxWaitMs,...C()?{recoveryRemainingMs:C()?.recoveryRemainingMs}:{}}),n_=async function*(S){let O=C()?.recoveryRemainingMs,W=O!==void 0&&M?.startedAt!==void 0?Math.min(Ff,O):Ff,V;try{V=o_.admit({scope:i_(S),sessionId:uf.sessionId,ownerId:uf.ownerId,requestClass:uf.requestClass,maxWaitMs:W,pendingBytes:h,signal:E})}catch(N){if(n(N)){if(N.reason==="wait_timeout"&&M?.startedAt!==void 0&&(C()?.recoveryRemainingMs??0)<=0)throw v();yield{providerAdmission:tf(N)}}throw N}let c=V.getSnapshot();if(c.state==="admitted")return await V.ready;yield{providerAdmission:Df("queued",c)};let K=V.ready.then((N)=>({kind:"ready",permit:N}),(N)=>({kind:"error",error:N}));while(!0){let N=V.getSnapshot(),J=Math.max(1,Math.min($_,Math.max(1,W-N.waitMs))),k,X=new Promise((t)=>{k=setTimeout(()=>t({kind:"heartbeat"}),J),k.unref?.()}),H=await Promise.race([K,X]);if(k)clearTimeout(k);if(H.kind==="heartbeat"){yield{providerAdmission:Df("queued",V.getSnapshot())};continue}if(H.kind==="error"){if(n(H.error)){if(H.error.reason==="wait_timeout"&&M?.startedAt!==void 0&&(C()?.recoveryRemainingMs??0)<=0)throw v();yield{providerAdmission:tf(H.error)}}throw H.error}return yield{providerAdmission:Df("admitted",V.getSnapshot())},H.permit}},fE=(S)=>{if(!a())throw v();if(G)L++;Q=void 0;let O=new AbortController,W=E?yf(E,O.signal):O.signal,V;if(M?.startedAt!==void 0){let N=C()?.recoveryRemainingMs??0;if(N<=0)throw v();let J=new s(M.budgetMs,M.budgetMs);V=setTimeout(()=>O.abort(J),N),V.unref?.()}let c=w_(this.config,S,W,T,Y);p_(c,S,(N)=>{Q=N});let K=l_(this.models,S,R,c,{idleTimeoutMs:this.config.streamIdleTimeout??Yf,signal:W,abort:(N)=>O.abort(N)});return async function*(){try{yield*K}finally{if(V)clearTimeout(V)}}()},wf=this,p=(S)=>({phase:S.phase,reason:S.reason,...S.statusCode!==void 0?{statusCode:S.statusCode}:{},...S.retryAfterMs!==void 0?{retryAfterMs:S.retryAfterMs}:{},...S.nextProbeAt!==void 0?{nextProbeAt:S.nextProbeAt}:{},openDurationMs:S.openDurationMs,sampleCount:S.sampleCount,failureCount:S.failureCount,...C()?{recoveryRemainingMs:C()?.recoveryRemainingMs}:{}}),pf=(S,O)=>({phase:S,reason:O.reason,...O.statusCode!==void 0?{statusCode:O.statusCode}:{},retryAfterMs:O.retryAfterMs,...O.nextProbeAt!==void 0?{nextProbeAt:O.nextProbeAt}:{},openDurationMs:O.openDurationMs,sampleCount:O.sampleCount,failureCount:O.failureCount,...C()?{recoveryRemainingMs:C()?.recoveryRemainingMs}:{}}),_E=(S)=>({phase:"probe",reason:S.reason??"server_error",...S.statusCode!==void 0?{statusCode:S.statusCode}:{},openDurationMs:S.openDurationMs??ff,...S.sampleCount!==void 0?{sampleCount:S.sampleCount}:{},...S.failureCount!==void 0?{failureCount:S.failureCount}:{},...C()?{recoveryRemainingMs:C()?.recoveryRemainingMs}:{}}),Of=(S,O,W)=>({providerRetry:{phase:"exhausted",attempt:S,maxRetries:D,reason:O,...W!==void 0?{statusCode:W}:{},...F(),exhaustedBy:"recovery_budget"}}),qf=async function*(S,O,W,V){let c,K=!1,N,J,k=e_(S);for(let X=0;X<=W;X++){if(!a())break;let H,t;while(!H){let B=k.preflight();while(!B.eligible){if(N=B.reason,J=B.statusCode,!M||!V){let Z=pf("rejected",B);throw yield{providerCircuit:Z},new e(Z)}vf();let b=C()?.recoveryRemainingMs??0;if(b<=0){let Z=v();throw yield Of(G?Math.max(0,L-1):X,B.reason,B.statusCode),Z}yield{providerCircuit:pf("waiting",B)};let w=Math.min(Math.max(1,B.retryAfterMs),Qf,b);if(await d(w,E,{throwOnAbort:!0}),(C()?.recoveryRemainingMs??0)<=0){let Z=v();throw yield Of(G?Math.max(0,L-1):X,B.reason,B.statusCode),Z}B=k.preflight()}try{t=yield*n_(S)}catch($){if($ instanceof s)yield Of(G?Math.max(0,L-1):X,N??"timeout",J);throw $}let z=k.check();if(z.allowed)H=z;else t.release(),t=void 0}let y=H.token;if(H.probe)yield{providerCircuit:_E(H)};try{let B=!1,z=!1;for await(let $ of fE(S)){if($.providerStall){yield $;continue}let b=G?L-1:X;if(b>0&&N&&!B)B=!0,yield{providerRetry:{phase:"recovered",attempt:b,maxRetries:D,reason:N,...J!==void 0?{statusCode:J}:{},...F()}};if(!z){z=!0;let w=k.recordSuccess(y);if(w)yield{providerCircuit:p(w)}}K=!0,O(),yield $}if(!z){let $=k.recordSuccess(y);if($)yield{providerCircuit:p($)}}return}catch(B){if(t?.release(),c=B,wf.logIdleTimeout(B,K,S),await wf.handleAbort(E),B instanceof s){if(K)throw Lf(B),B;throw yield{providerRetry:{phase:"exhausted",attempt:G?Math.max(0,L-1):X,maxRetries:D,reason:N??"timeout",...J!==void 0?{statusCode:J}:{},...F(),exhaustedBy:"recovery_budget"}},B}let z=l(B,Q);if(K)throw Lf(B),B;let $=gE(B,Q),b=$?k.recordFailure(y,$):Q&&!oE(B)?k.recordNeutral(y):void 0;if(b)yield{providerCircuit:p(b)};if(!z.retryable||!z.reason){if(X>0&&N)yield{providerRetry:{phase:"exhausted",attempt:G?Math.max(0,L-1):X,maxRetries:D,reason:N,...J!==void 0?{statusCode:J}:{},...F()}};throw B}N=z.reason,J=z.statusCode;let w=X<W&&a();if(b&&b.phase!=="closed"&&w&&(!M||!V)){let Z={...p(b),phase:"rejected"};throw yield{providerCircuit:Z},new e(Z)}if(w){vf();let Z=G?L:X+1,TE=I_(Z,Q,M?{maxDelayMs:Kf,maxExponentialDelayMs:Kf}:void 0),sf=b&&b.phase!=="closed"?b.retryAfterMs??0:0;if(M&&sf>0&&b)yield{providerCircuit:{...p(b),phase:"waiting"}};let xE=C(),Bf=Math.max(TE,sf),g=M?Math.min(Bf,xE?.recoveryRemainingMs??Bf):Bf,Ef={attempt:Z,maxRetries:D,reason:z.reason,...z.statusCode!==void 0?{statusCode:z.statusCode}:{}};if(yield{providerRetry:{phase:"scheduled",...Ef,delayMs:g,nextRetryAt:Date.now()+g,...F()}},M){let o=g;while(o>0){let lf=Math.min(o,Qf);if(await d(lf,E,{throwOnAbort:!0}),o-=lf,(C()?.recoveryRemainingMs??0)<=0){let Tf=v();throw yield{providerRetry:{phase:"exhausted",...Ef,...F(),exhaustedBy:"recovery_budget"}},Tf}if(o>0){if(b&&b.phase!=="closed"&&b.nextProbeAt!==void 0){let Tf=Math.max(0,b.nextProbeAt-Date.now());if(Tf>0)yield{providerCircuit:{...p(b),phase:"waiting",retryAfterMs:Tf}}}yield{providerRetry:{phase:"waiting",...Ef,delayMs:g,nextRetryAt:Date.now()+o,...F()}}}}}else await d(g,E,{throwOnAbort:!0});yield{providerRetry:{phase:"attempt",...Ef,...F()}}}else yield{providerRetry:{phase:"exhausted",attempt:G?Math.max(0,L-1):X,maxRetries:D,reason:z.reason,...z.statusCode!==void 0?{statusCode:z.statusCode}:{},...F(),...M&&(V||!a())?{exhaustedBy:"attempt_limit"}:{}}}}finally{k.abandon(y),t?.release()}}throw c},Nf,mf=!1,_f=this.config.fallbackModels??[],EE=M&&_f.length>0?Math.min(u,D):D;try{for await(let S of qf(this.model,()=>{mf=!0},EE,_f.length===0))yield S;return}catch(S){if(Nf=S,mf||!n(S)&&!Jf(S)&&!l(S,Q).retryable)throw S}for(let[S,O]of _f.entries()){if(!a())break;yield{modelFallback:!0};let W=!1;try{let V=f_(this.config,O),c=S===_f.length-1,K=M&&!c?Math.min(u,D):D;for await(let N of qf(V,()=>{W=!0},K,c))yield N;return}catch(V){if(Nf=V,W||!n(V)&&!Jf(V)&&!l(V,Q).retryable)throw V}}throw Nf}async handleAbort(f){if(f?.aborted)await d(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;a_.warn("[PiAIChatService] Provider stream idle timeout",{provider:E.provider,model:E.id,timeoutMs:f.timeoutMs,replayBoundaryCrossed:_})}getConfig(){return{...this.config}}updateConfig(f){let _={...this.config,...f},E=jf(_);this.config={..._,maxContextTokens:E.model.contextWindow,maxOutputTokens:_.maxOutputTokens??E.model.maxTokens},this.models=E.models,this.model=E.model}}var dE=q("Service");async function Tx(f){let _=f;if(_.provider){let E=af(_.provider);if(Object.keys(E).length>0)_={..._,customHeaders:{...E,..._.customHeaders}},dE.debug(`Injected ${_.provider} specific headers:`,Object.keys(E))}return rE(_)}function rE(f){return new If(f)}
|
|
5
|
-
export{nE as Kd,ET as Ld,yf as Md,n as Nd,Z_ as Od,GE as Pd,KT as Qd,If as Rd,Tx as Sd};
|
package/dist/chunk-fer18bbe.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Td as a,Ud as b,Vd as c}from"./chunk-7fqsgdee.js";import"./chunk-qp2z1r7y.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
|
package/dist/chunk-fz91aw1w.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import{f as T,g as W,h as X,i as Y}from"./chunk-6h28xs47.js";import"./chunk-8vtyatd6.js";import"./chunk-f4sp074f.js";import"./chunk-8y3skwtt.js";import"./chunk-4dthhzfe.js";import"./chunk-5vbrcvxg.js";import"./chunk-vhamhbej.js";import"./chunk-ssymrsyx.js";import"./chunk-y6tkxqjx.js";import"./chunk-1atpfmpe.js";import"./chunk-mrsc4a55.js";import"./chunk-t4y3h47y.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import{cd as R}from"./chunk-szdcprq7.js";import"./chunk-fk4wbmv6.js";import{yd as Q}from"./chunk-ecf8dh3c.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-egczvfsv.js";import"./chunk-7fqsgdee.js";import"./chunk-qp2z1r7y.js";import"./chunk-j66r48pz.js";import"./chunk-sjtbp01y.js";import"./chunk-tpa75y39.js";import"./chunk-2yvte5a7.js";import"./chunk-sqd5ge5s.js";import"./chunk-yvyqhw5q.js";import"./chunk-cxzx7j0p.js";import"./chunk-cyw6cpac.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import{Sg as M}from"./chunk-807x1cw8.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";import m from"chalk";import K from"open";var A=`
|
|
2
|
-
____ _ _
|
|
3
|
-
| __ )| | __ _ __| | ___
|
|
4
|
-
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
5
|
-
| |_) | | (_| | (_| | __/
|
|
6
|
-
|____/|_|\\__,_|\\__,_|\\___|
|
|
7
|
-
`,C={command:"web",describe:"Start Blade server and open web interface",builder:T,handler:async(Z)=>{let H=W(Z);if(await Q(),!process.env.BLADE_SERVER_PASSWORD)console.log(m.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(m.gray(` Set this environment variable to enable Basic Auth.
|
|
8
|
-
`));let F=await Y.listenAsync(H);if(console.log(m.cyan(A)),console.log(m.gray(` v${M()}
|
|
9
|
-
`)),H.hostname==="0.0.0.0"){let q=`http://localhost:${F.port}`;console.log(m.blue.bold(" Local access: "),m.white(q));let x=X();for(let z of x)console.log(m.blue.bold(" Network access: "),m.white(`http://${z}:${F.port}`));K(q).catch(()=>{})}else{let q=F.url.toString();console.log(m.blue.bold(" Web interface: "),m.white(q)),K(q).catch(()=>{})}console.log(""),console.log(m.gray(` Press Ctrl+C to stop the server.
|
|
10
|
-
`));let J,$=new Promise((q)=>{J=q}),b=R(async()=>{await F.stop(),J()});try{await $}finally{b(),await F.stop()}}};export{C as webCommand};
|
package/dist/chunk-j7edwwg1.js
DELETED
package/dist/chunk-mqmf40p2.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Ab as p,Bb as q,Cb as r,cb as a,db as b,fb as c,jb as d,kb as e,lb as f,mb as g,nb as h,ob as i,pb as j,qb as k,vb as l,wb as m,xb as n,yb as o}from"./chunk-1atpfmpe.js";import"./chunk-mrsc4a55.js";import"./chunk-t4y3h47y.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import"./chunk-wwvb6znp.js";import"./chunk-egczvfsv.js";import"./chunk-qp2z1r7y.js";import"./chunk-tpa75y39.js";import"./chunk-2yvte5a7.js";import"./chunk-yvyqhw5q.js";import"./chunk-cxzx7j0p.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-807x1cw8.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.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};
|