switchboard-router 0.9.6 → 0.9.8
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/app/{.next-cli-build/static/chunks/1321-d31d839184ff87c5.js → .next/static/chunks/1321-0003ef56aef2b3ab.js} +1 -1
- package/app/.next-cli-build/BUILD_ID +1 -1
- package/app/.next-cli-build/app-path-routes-manifest.json +10 -10
- package/app/.next-cli-build/build-manifest.json +2 -2
- package/app/.next-cli-build/prerender-manifest.json +3 -3
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/agent-library/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/basic-chat/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/cli-tools/[toolId]/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/cli-tools/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/combos/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/combos/routing/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/console-log/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/endpoint/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/media-providers/[kind]/[id]/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/media-providers/[kind]/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/media-providers/combo/[id]/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/media-providers/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/media-providers/web/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/mitm/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/profile/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/providers/[id]/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/providers/new/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/providers/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/pxpipe/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/quota/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/skills/[id]/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/skills/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/token-saver/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/translator/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/(dashboard)/dashboard/usage/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/_global-error.html +1 -1
- package/app/.next-cli-build/server/app/_global-error.rsc +1 -1
- package/app/.next-cli-build/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/app/.next-cli-build/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/app/.next-cli-build/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/app/.next-cli-build/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/_not-found.html +1 -1
- package/app/.next-cli-build/server/app/_not-found.rsc +3 -3
- package/app/.next-cli-build/server/app/_not-found.segments/_full.segment.rsc +3 -3
- package/app/.next-cli-build/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +3 -3
- package/app/.next-cli-build/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/app/.next-cli-build/server/app/api/cli-tools/aider-settings/route.js +2 -2
- package/app/.next-cli-build/server/app/api/cli-tools/all-statuses/route.js +5 -5
- package/app/.next-cli-build/server/app/api/cli-tools/antigravity-mitm/alias/route.js +2 -2
- package/app/.next-cli-build/server/app/api/cli-tools/cline-settings/route.js +2 -2
- package/app/.next-cli-build/server/app/api/cli-tools/codex-settings/route.js +1 -1
- package/app/.next-cli-build/server/app/api/cli-tools/cowork-mcp-registry/route.js +2 -2
- package/app/.next-cli-build/server/app/api/cli-tools/cowork-mcp-tools/route.js +2 -2
- package/app/.next-cli-build/server/app/api/cli-tools/cowork-settings/route.js +2 -2
- package/app/.next-cli-build/server/app/api/cli-tools/deepseek-tui-settings/route.js +2 -2
- package/app/.next-cli-build/server/app/api/cli-tools/droid-settings/route.js +2 -2
- package/app/.next-cli-build/server/app/api/cli-tools/gemini-cli-settings/route.js +2 -2
- package/app/.next-cli-build/server/app/api/cli-tools/grok-settings/route.js +2 -2
- package/app/.next-cli-build/server/app/api/cli-tools/hermes-settings/route.js +3 -3
- package/app/.next-cli-build/server/app/api/cli-tools/jcode-settings/route.js +2 -2
- package/app/.next-cli-build/server/app/api/cli-tools/kilo-settings/route.js +2 -2
- package/app/.next-cli-build/server/app/api/cli-tools/openclaw-settings/route.js +2 -2
- package/app/.next-cli-build/server/app/api/cli-tools/opencode-settings/route.js +1 -1
- package/app/.next-cli-build/server/app/api/cli-tools/pi-settings/route.js +1 -1
- package/app/.next-cli-build/server/app/api/version/route.js +1 -1
- package/app/.next-cli-build/server/app/callback/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/callback.html +1 -1
- package/app/.next-cli-build/server/app/callback.rsc +3 -3
- package/app/.next-cli-build/server/app/callback.segments/_full.segment.rsc +3 -3
- package/app/.next-cli-build/server/app/callback.segments/_tree.segment.rsc +1 -1
- package/app/.next-cli-build/server/app/callback.segments/callback/__PAGE__.segment.rsc +3 -3
- package/app/.next-cli-build/server/app/dashboard/settings/pricing/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/dashboard/settings/pricing.html +1 -1
- package/app/.next-cli-build/server/app/dashboard/settings/pricing.rsc +3 -3
- package/app/.next-cli-build/server/app/dashboard/settings/pricing.segments/_full.segment.rsc +3 -3
- package/app/.next-cli-build/server/app/dashboard/settings/pricing.segments/_tree.segment.rsc +1 -1
- package/app/.next-cli-build/server/app/dashboard/settings/pricing.segments/dashboard/settings/pricing/__PAGE__.segment.rsc +3 -3
- package/app/.next-cli-build/server/app/index.html +1 -1
- package/app/.next-cli-build/server/app/index.rsc +3 -3
- package/app/.next-cli-build/server/app/index.segments/__PAGE__.segment.rsc +3 -3
- package/app/.next-cli-build/server/app/index.segments/_full.segment.rsc +3 -3
- package/app/.next-cli-build/server/app/index.segments/_tree.segment.rsc +1 -1
- package/app/.next-cli-build/server/app/landing/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/landing.html +1 -1
- package/app/.next-cli-build/server/app/landing.rsc +3 -3
- package/app/.next-cli-build/server/app/landing.segments/_full.segment.rsc +3 -3
- package/app/.next-cli-build/server/app/landing.segments/_tree.segment.rsc +1 -1
- package/app/.next-cli-build/server/app/landing.segments/landing/__PAGE__.segment.rsc +3 -3
- package/app/.next-cli-build/server/app/login/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app/login.html +1 -1
- package/app/.next-cli-build/server/app/login.rsc +3 -3
- package/app/.next-cli-build/server/app/login.segments/_full.segment.rsc +3 -3
- package/app/.next-cli-build/server/app/login.segments/_tree.segment.rsc +1 -1
- package/app/.next-cli-build/server/app/login.segments/login/__PAGE__.segment.rsc +3 -3
- package/app/.next-cli-build/server/app/page_client-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/app-paths-manifest.json +10 -10
- package/app/.next-cli-build/server/chunks/1350.js +1 -1
- package/app/.next-cli-build/server/chunks/194.js +1 -1
- package/app/.next-cli-build/server/chunks/369.js +2 -4
- package/app/.next-cli-build/server/chunks/7454.js +1 -1
- package/app/.next-cli-build/server/chunks/8400.js +29 -24
- package/app/.next-cli-build/server/chunks/869.js +1 -1
- package/app/.next-cli-build/server/chunks/8998.js +9 -6
- package/app/.next-cli-build/server/middleware-build-manifest.js +1 -1
- package/app/.next-cli-build/server/pages/404.html +1 -1
- package/app/.next-cli-build/server/pages/500.html +1 -1
- package/app/.next-cli-build/server/server-reference-manifest.js +1 -1
- package/app/.next-cli-build/server/server-reference-manifest.json +1 -1
- package/app/{.next/static/chunks/1321-d31d839184ff87c5.js → .next-cli-build/static/chunks/1321-0003ef56aef2b3ab.js} +1 -1
- package/app/open-sse/identity/tls/bin/darwin/arm64/switchboard-claude-tls +0 -0
- package/app/open-sse/identity/tls/bin/darwin/x64/switchboard-claude-tls +0 -0
- package/app/open-sse/identity/tls/bin/linux/arm64/switchboard-claude-tls +0 -0
- package/app/open-sse/identity/tls/bin/linux/x64/switchboard-claude-tls +0 -0
- package/app/open-sse/identity/tls/bin/win32/arm64/switchboard-claude-tls.exe +0 -0
- package/app/open-sse/identity/tls/bin/win32/x64/switchboard-claude-tls.exe +0 -0
- package/app/package.json +1 -1
- package/package.json +1 -1
- /package/app/.next/static/{Dj3B1SY51GKVJr4nnDlac → Kxe3gixpS84MCzX8yohZb}/_buildManifest.js +0 -0
- /package/app/.next/static/{Dj3B1SY51GKVJr4nnDlac → Kxe3gixpS84MCzX8yohZb}/_ssgManifest.js +0 -0
- /package/app/.next-cli-build/static/{Dj3B1SY51GKVJr4nnDlac → Kxe3gixpS84MCzX8yohZb}/_buildManifest.js +0 -0
- /package/app/.next-cli-build/static/{Dj3B1SY51GKVJr4nnDlac → Kxe3gixpS84MCzX8yohZb}/_ssgManifest.js +0 -0
|
@@ -182,7 +182,9 @@ ${e(h)}\r
|
|
|
182
182
|
`);f.push(a),j+=a.byteLength}else{let a=v.encode(`${c}; name="${d(e(b))}"`+(h.name?`; filename="${d(h.name)}"`:"")+"\r\n"+`Content-Type: ${h.type||"application/octet-stream"}\r
|
|
183
183
|
\r
|
|
184
184
|
`);f.push(a,h,g),"number"==typeof h.size?j+=a.byteLength+h.size+g.byteLength:l=!0}let m=v.encode(`--${b}--\r
|
|
185
|
-
`);f.push(m),j+=m.byteLength,l&&(j=null),i=a,h=async function*(){for(let a of f)a.stream?yield*a.stream():yield a},o=`multipart/form-data; boundary=${b}`}else if(l.is.Blob(a))i=a,j=a.size,a.type&&(o=a.type);else if("function"==typeof a[Symbol.asyncIterator]){if(b)throw TypeError("keepalive");if(d.isDisturbed(a)||a.locked)throw TypeError("Response body object should not be disturbed or locked");c=l.is.ReadableStream(a)?a:e(a)}return("string"==typeof i||p(i))&&(h=()=>(j="string"==typeof i?Buffer.byteLength(i):i.length,i)),null!=h&&(async()=>{let a=h(),b=a?.[Symbol.asyncIterator]?.();if(b)for await(let a of b){if(n(c))break;a.length&&g.enqueue(new Uint8Array(a))}else a?.length&&!n(c)&&g.enqueue("string"==typeof a?v.encode(a):new Uint8Array(a));queueMicrotask(()=>f(g))})(),[{stream:c,source:i,length:j},o]}function y(a,b,c,d){try{l.brandCheck(a,c)}catch(a){return Promise.reject(a)}if(z(a=d(a)))return Promise.reject(TypeError("Body is unusable: Body has already been read"));let e=Promise.withResolvers(),f=e.reject,h=a=>{try{e.resolve(b(a))}catch(a){f(a)}};return null==a.body?h(Buffer.allocUnsafe(0)):g(a.body,h,f),e.promise}function z(a){let b=a.body;return null!=b&&(b.stream.locked||d.isDisturbed(b.stream))}function A(a){let b=h(a.headersList);return"failure"===b?null:b}a.exports={extractBody:x,safelyExtractBody:function(a,b=!1){return l.is.ReadableStream(a)&&(m(!d.isDisturbed(a),"The body has already been consumed."),m(!a.locked,"The stream is locked.")),x(a,b)},cloneBody:function(a){let{0:b,1:c}=u?.(a.stream,!0)??a.stream.tee();return a.stream=b,{stream:c,length:a.length,source:a.source}},mixinBody:function(a,b){Object.assign(a.prototype,{blob(){return y(this,a=>{let c=A(b(this));return null===c?c="":c&&(c=q(c)),new Blob([a],{type:c})},a,b)},arrayBuffer(){return y(this,a=>new Uint8Array(a).buffer,a,b)},text(){return y(this,t,a,b)},json(){return y(this,s,a,b)},formData(){return y(this,a=>{let c=A(b(this));if(null!==c)switch(c.essence){case"multipart/form-data":{let b=r(a,c),d=new i;return j(d,b),d}case"application/x-www-form-urlencoded":{let b=new URLSearchParams(a.toString()),c=new i;for(let[a,d]of b)c.append(a,d);return c}}throw TypeError('Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".')},a,b)},bytes(){return y(this,a=>new Uint8Array(a),a,b)},textStream(){let a=b(this);if(z(a))throw TypeError("Body is unusable: Body has already been read");if(null==a.body){let a,b=new ReadableStream({start:b=>{a=b},pull:()=>Promise.resolve(),cancel:()=>Promise.resolve()},{size:()=>1});return a.close(),b}let c=a.body.stream,d=new TextDecoderStream("UTF-8");return c.pipeThrough(d)}})},streamRegistry:new FinalizationRegistry(a=>{let b=a.deref();!b||b.locked||o(b)||n(b)||b.cancel("Response object has been garbage collected").catch(w)}),bodyUnusable:z}},35689:(a,b,c)=>{"use strict";let{PoolBase:d,kClients:e,kNeedDrain:f,kAddClient:g,kGetDispatcher:h,kHasDispatcher:i,kRemoveClient:j}=c(39065),k=c(40106),{InvalidArgumentError:l}=c(61448),m=c(84285),{kUrl:n}=c(49176),o=c(55285),p=Symbol("options"),q=Symbol("connections"),r=Symbol("factory");function s(a,b){return new k(a,b)}class t extends d{constructor(a,{connections:b,factory:c=s,connect:d,connectTimeout:f,tls:g,maxCachedSessions:h,socketPath:i,autoSelectFamily:j,autoSelectFamilyAttemptTimeout:k,allowH2:t,useH2c:u,clientTtl:v,...w}={}){if(null!=b&&(!Number.isFinite(b)||b<0))throw new l("invalid connections");if("function"!=typeof c)throw new l("factory must be a function.");if(null!=d&&"function"!=typeof d&&"object"!=typeof d)throw new l("connect must be a function or an object");"function"!=typeof d&&(d=o({...g,maxCachedSessions:h,allowH2:t,useH2c:u,socketPath:i,timeout:f,..."boolean"==typeof j?{autoSelectFamily:j,autoSelectFamilyAttemptTimeout:k}:void 0,...d})),super(w),this[q]=b||null,this[n]=m.parseOrigin(a),this[p]={...m.deepClone(w),connect:d,allowH2:t,useH2c:u,clientTtl:v,socketPath:i},this[r]=c,this.on("connect",(a,b)=>{if(null!=v&&v>0)for(let a of b)Object.assign(a,{ttl:Date.now()})}),this.on("connectionError",(a,b,c)=>{for(let a of b){let b=this[e].indexOf(a);-1!==b&&this[e].splice(b,1)}})}[h](){let a=this[p].clientTtl;for(let b=0;b<this[e].length;b++){let c=this[e][b];if(null!=a&&a>0&&c.ttl&&Date.now()-c.ttl>a)this[j](c),b--;else if(!c[f])return c}if(!this[q]||this[e].length<this[q]){let a=this[r](this[n],this[p]);return this[g](a),a}}[i](){let a=this[p].clientTtl;for(let b=0;b<this[e].length;b++){let c=this[e][b];if(null!=a&&a>0&&c.ttl&&Date.now()-c.ttl>a)this[j](c),b--;else if(!c[f])return!0}if(!this[q]||this[e].length<this[q]){let a=this[r](this[n],this[p]);return this[g](a),!0}return!1}}a.exports=t},36105:(a,b,c)=>{var d=c(45654);d.pki=d.pki||{};var e=a.exports=d.pki.oids=d.oids=d.oids||{};function f(a,b){e[a]=b,e[b]=a}f("1.2.840.113549.1.1.1","rsaEncryption"),f("1.2.840.113549.1.1.4","md5WithRSAEncryption"),f("1.2.840.113549.1.1.5","sha1WithRSAEncryption"),f("1.2.840.113549.1.1.7","RSAES-OAEP"),f("1.2.840.113549.1.1.8","mgf1"),f("1.2.840.113549.1.1.9","pSpecified"),f("1.2.840.113549.1.1.10","RSASSA-PSS"),f("1.2.840.113549.1.1.11","sha256WithRSAEncryption"),f("1.2.840.113549.1.1.12","sha384WithRSAEncryption"),f("1.2.840.113549.1.1.13","sha512WithRSAEncryption"),f("1.3.101.112","EdDSA25519"),f("1.2.840.10040.4.3","dsa-with-sha1"),f("1.3.14.3.2.7","desCBC"),f("1.3.14.3.2.26","sha1"),f("1.3.14.3.2.29","sha1WithRSASignature"),f("2.16.840.1.101.3.4.2.1","sha256"),f("2.16.840.1.101.3.4.2.2","sha384"),f("2.16.840.1.101.3.4.2.3","sha512"),f("2.16.840.1.101.3.4.2.4","sha224"),f("2.16.840.1.101.3.4.2.5","sha512-224"),f("2.16.840.1.101.3.4.2.6","sha512-256"),f("1.2.840.113549.2.2","md2"),f("1.2.840.113549.2.5","md5"),f("1.2.840.113549.1.7.1","data"),f("1.2.840.113549.1.7.2","signedData"),f("1.2.840.113549.1.7.3","envelopedData"),f("1.2.840.113549.1.7.4","signedAndEnvelopedData"),f("1.2.840.113549.1.7.5","digestedData"),f("1.2.840.113549.1.7.6","encryptedData"),f("1.2.840.113549.1.9.1","emailAddress"),f("1.2.840.113549.1.9.2","unstructuredName"),f("1.2.840.113549.1.9.3","contentType"),f("1.2.840.113549.1.9.4","messageDigest"),f("1.2.840.113549.1.9.5","signingTime"),f("1.2.840.113549.1.9.6","counterSignature"),f("1.2.840.113549.1.9.7","challengePassword"),f("1.2.840.113549.1.9.8","unstructuredAddress"),f("1.2.840.113549.1.9.14","extensionRequest"),f("1.2.840.113549.1.9.20","friendlyName"),f("1.2.840.113549.1.9.21","localKeyId"),f("1.2.840.113549.1.9.22.1","x509Certificate"),f("1.2.840.113549.1.12.10.1.1","keyBag"),f("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag"),f("1.2.840.113549.1.12.10.1.3","certBag"),f("1.2.840.113549.1.12.10.1.4","crlBag"),f("1.2.840.113549.1.12.10.1.5","secretBag"),f("1.2.840.113549.1.12.10.1.6","safeContentsBag"),f("1.2.840.113549.1.5.13","pkcs5PBES2"),f("1.2.840.113549.1.5.12","pkcs5PBKDF2"),f("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4"),f("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4"),f("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC"),f("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC"),f("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC"),f("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC"),f("1.2.840.113549.2.7","hmacWithSHA1"),f("1.2.840.113549.2.8","hmacWithSHA224"),f("1.2.840.113549.2.9","hmacWithSHA256"),f("1.2.840.113549.2.10","hmacWithSHA384"),f("1.2.840.113549.2.11","hmacWithSHA512"),f("1.2.840.113549.3.7","des-EDE3-CBC"),f("2.16.840.1.101.3.4.1.2","aes128-CBC"),f("2.16.840.1.101.3.4.1.22","aes192-CBC"),f("2.16.840.1.101.3.4.1.42","aes256-CBC"),f("2.5.4.3","commonName"),f("2.5.4.4","surname"),f("2.5.4.5","serialNumber"),f("2.5.4.6","countryName"),f("2.5.4.7","localityName"),f("2.5.4.8","stateOrProvinceName"),f("2.5.4.9","streetAddress"),f("2.5.4.10","organizationName"),f("2.5.4.11","organizationalUnitName"),f("2.5.4.12","title"),f("2.5.4.13","description"),f("2.5.4.15","businessCategory"),f("2.5.4.17","postalCode"),f("2.5.4.42","givenName"),f("2.5.4.65","pseudonym"),f("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName"),f("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName"),f("2.16.840.1.113730.1.1","nsCertType"),f("2.16.840.1.113730.1.13","nsComment"),e["2.5.29.1"]="authorityKeyIdentifier",e["2.5.29.2"]="keyAttributes",e["2.5.29.3"]="certificatePolicies",e["2.5.29.4"]="keyUsageRestriction",e["2.5.29.5"]="policyMapping",e["2.5.29.6"]="subtreesConstraint",e["2.5.29.7"]="subjectAltName",e["2.5.29.8"]="issuerAltName",e["2.5.29.9"]="subjectDirectoryAttributes",e["2.5.29.10"]="basicConstraints",e["2.5.29.11"]="nameConstraints",e["2.5.29.12"]="policyConstraints",e["2.5.29.13"]="basicConstraints",f("2.5.29.14","subjectKeyIdentifier"),f("2.5.29.15","keyUsage"),e["2.5.29.16"]="privateKeyUsagePeriod",f("2.5.29.17","subjectAltName"),f("2.5.29.18","issuerAltName"),f("2.5.29.19","basicConstraints"),e["2.5.29.20"]="cRLNumber",e["2.5.29.21"]="cRLReason",e["2.5.29.22"]="expirationDate",e["2.5.29.23"]="instructionCode",e["2.5.29.24"]="invalidityDate",e["2.5.29.25"]="cRLDistributionPoints",e["2.5.29.26"]="issuingDistributionPoint",e["2.5.29.27"]="deltaCRLIndicator",e["2.5.29.28"]="issuingDistributionPoint",e["2.5.29.29"]="certificateIssuer",e["2.5.29.30"]="nameConstraints",f("2.5.29.31","cRLDistributionPoints"),f("2.5.29.32","certificatePolicies"),e["2.5.29.33"]="policyMappings",e["2.5.29.34"]="policyConstraints",f("2.5.29.35","authorityKeyIdentifier"),e["2.5.29.36"]="policyConstraints",f("2.5.29.37","extKeyUsage"),e["2.5.29.46"]="freshestCRL",e["2.5.29.54"]="inhibitAnyPolicy",f("1.3.6.1.4.1.11129.2.4.2","timestampList"),f("1.3.6.1.5.5.7.1.1","authorityInfoAccess"),f("1.3.6.1.5.5.7.3.1","serverAuth"),f("1.3.6.1.5.5.7.3.2","clientAuth"),f("1.3.6.1.5.5.7.3.3","codeSigning"),f("1.3.6.1.5.5.7.3.4","emailProtection"),f("1.3.6.1.5.5.7.3.8","timeStamping")},36649:(a,b,c)=>{"use strict";let{wellknownHeaderNames:d,headerNameLowerCasedRecord:e}=c(28820);class f{value=null;left=null;middle=null;right=null;code;constructor(a,b,c){if(void 0===c||c>=a.length)throw TypeError("Unreachable");if((this.code=a.charCodeAt(c))>127)throw TypeError("key must be ascii string");a.length!==++c?this.middle=new f(a,b,c):this.value=b}add(a,b){let c=a.length;if(0===c)throw TypeError("Unreachable");let d=0,e=this;for(;;){let g=a.charCodeAt(d);if(g>127)throw TypeError("key must be ascii string");if(e.code===g)if(c===++d){e.value=b;break}else if(null!==e.middle)e=e.middle;else{e.middle=new f(a,b,d);break}else if(e.code<g)if(null!==e.left)e=e.left;else{e.left=new f(a,b,d);break}else if(null!==e.right)e=e.right;else{e.right=new f(a,b,d);break}}}search(a){let b=a.length,c=0,d=this;for(;null!==d&&c<b;){let e=a[c];for(e<=90&&e>=65&&(e|=32);null!==d;){if(e===d.code){if(b===++c)return d;d=d.middle;break}d=d.code<e?d.left:d.right}}return null}}class g{node=null;insert(a,b){null===this.node?this.node=new f(a,b,0):this.node.add(a,b)}lookup(a){return this.node?.search(a)?.value??null}}let h=new g;for(let a=0;a<d.length;++a){let b=e[d[a]];h.insert(b,b)}a.exports={TernarySearchTree:g,tree:h}},36902:(a,b,c)=>{var d=c(45654);c(33889),c(32e3),c(29984),function(){if(d.prime){a.exports=d.prime;return}var b=a.exports=d.prime=d.prime||{},c=d.jsbn.BigInteger,e=[6,4,2,4,2,4,6,2],f=new c(null);f.fromInt(30);var g=function(a,b){return a|b};function h(a,b,c,f){var g,h=i(a,b),j=(g=h.bitLength())<=100?27:g<=150?18:g<=200?15:g<=250?12:g<=300?9:g<=350?8:g<=400?7:g<=500?6:g<=600?5:g<=800?4:g<=1250?3:2;"millerRabinTests"in c&&(j=c.millerRabinTests);var k=10;"maxBlockTime"in c&&(k=c.maxBlockTime),function a(b,c,f,g,h,j,k){var l=+new Date;do{if(b.bitLength()>c&&(b=i(c,f)),b.isProbablePrime(h))return k(null,b);b.dAddOffset(e[g++%8],0)}while(j<0||new Date-l<j);d.util.setImmediate(function(){a(b,c,f,g,h,j,k)})}(h,a,b,0,j,k,f)}function i(a,b){var d=new c(a,b),e=a-1;return d.testBit(e)||d.bitwiseTo(c.ONE.shiftLeft(e),g,d),d.dAddOffset(31-d.mod(f).byteValue(),0),d}b.generateProbablePrime=function(a,b,e){"function"==typeof b&&(e=b,b={});var f,g,j,k,l=(b=b||{}).algorithm||"PRIMEINC";"string"==typeof l&&(l={name:l}),l.options=l.options||{};var m=b.prng||d.random;if("PRIMEINC"===l.name){return f=a,g={nextBytes:function(a){for(var b=m.getBytesSync(a.length),c=0;c<a.length;++c)a[c]=b.charCodeAt(c)}},j=l.options,k=e,"workers"in j?function(a,b,e,f){if("u"<typeof Worker)return h(a,b,e,f);var g=i(a,b),j=e.workers,k=e.workLoad||100,l=30*k/8,m=e.workerScript||"forge/prime.worker.js";if(-1===j)return d.util.estimateCores(function(a,b){a&&(b=2),j=b-1,n()});function n(){j=Math.max(1,j);for(var d=[],e=0;e<j;++e)d[e]=new Worker(m);for(var h=j,e=0;e<j;++e)d[e].addEventListener("message",o);var n=!1;function o(e){if(!n){--h;var j=e.data;if(j.found){for(var m=0;m<d.length;++m)d[m].terminate();return n=!0,f(null,new c(j.prime,16))}g.bitLength()>a&&(g=i(a,b));var o=g.toString(16);e.target.postMessage({hex:o,workLoad:k}),g.dAddOffset(l,0)}}}n()}(f,g,j,k):h(f,g,j,k)}throw Error("Invalid prime generation algorithm: "+l.name)}}()},37071:(a,b,c)=>{"use strict";c.d(b,{T:()=>r});var d=c(67671);let e=`You are Codex, based on GPT-5. You are running as a coding agent in the Codex CLI on a user's computer.
|
|
185
|
+
`);f.push(m),j+=m.byteLength,l&&(j=null),i=a,h=async function*(){for(let a of f)a.stream?yield*a.stream():yield a},o=`multipart/form-data; boundary=${b}`}else if(l.is.Blob(a))i=a,j=a.size,a.type&&(o=a.type);else if("function"==typeof a[Symbol.asyncIterator]){if(b)throw TypeError("keepalive");if(d.isDisturbed(a)||a.locked)throw TypeError("Response body object should not be disturbed or locked");c=l.is.ReadableStream(a)?a:e(a)}return("string"==typeof i||p(i))&&(h=()=>(j="string"==typeof i?Buffer.byteLength(i):i.length,i)),null!=h&&(async()=>{let a=h(),b=a?.[Symbol.asyncIterator]?.();if(b)for await(let a of b){if(n(c))break;a.length&&g.enqueue(new Uint8Array(a))}else a?.length&&!n(c)&&g.enqueue("string"==typeof a?v.encode(a):new Uint8Array(a));queueMicrotask(()=>f(g))})(),[{stream:c,source:i,length:j},o]}function y(a,b,c,d){try{l.brandCheck(a,c)}catch(a){return Promise.reject(a)}if(z(a=d(a)))return Promise.reject(TypeError("Body is unusable: Body has already been read"));let e=Promise.withResolvers(),f=e.reject,h=a=>{try{e.resolve(b(a))}catch(a){f(a)}};return null==a.body?h(Buffer.allocUnsafe(0)):g(a.body,h,f),e.promise}function z(a){let b=a.body;return null!=b&&(b.stream.locked||d.isDisturbed(b.stream))}function A(a){let b=h(a.headersList);return"failure"===b?null:b}a.exports={extractBody:x,safelyExtractBody:function(a,b=!1){return l.is.ReadableStream(a)&&(m(!d.isDisturbed(a),"The body has already been consumed."),m(!a.locked,"The stream is locked.")),x(a,b)},cloneBody:function(a){let{0:b,1:c}=u?.(a.stream,!0)??a.stream.tee();return a.stream=b,{stream:c,length:a.length,source:a.source}},mixinBody:function(a,b){Object.assign(a.prototype,{blob(){return y(this,a=>{let c=A(b(this));return null===c?c="":c&&(c=q(c)),new Blob([a],{type:c})},a,b)},arrayBuffer(){return y(this,a=>new Uint8Array(a).buffer,a,b)},text(){return y(this,t,a,b)},json(){return y(this,s,a,b)},formData(){return y(this,a=>{let c=A(b(this));if(null!==c)switch(c.essence){case"multipart/form-data":{let b=r(a,c),d=new i;return j(d,b),d}case"application/x-www-form-urlencoded":{let b=new URLSearchParams(a.toString()),c=new i;for(let[a,d]of b)c.append(a,d);return c}}throw TypeError('Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".')},a,b)},bytes(){return y(this,a=>new Uint8Array(a),a,b)},textStream(){let a=b(this);if(z(a))throw TypeError("Body is unusable: Body has already been read");if(null==a.body){let a,b=new ReadableStream({start:b=>{a=b},pull:()=>Promise.resolve(),cancel:()=>Promise.resolve()},{size:()=>1});return a.close(),b}let c=a.body.stream,d=new TextDecoderStream("UTF-8");return c.pipeThrough(d)}})},streamRegistry:new FinalizationRegistry(a=>{let b=a.deref();!b||b.locked||o(b)||n(b)||b.cancel("Response object has been garbage collected").catch(w)}),bodyUnusable:z}},35689:(a,b,c)=>{"use strict";let{PoolBase:d,kClients:e,kNeedDrain:f,kAddClient:g,kGetDispatcher:h,kHasDispatcher:i,kRemoveClient:j}=c(39065),k=c(40106),{InvalidArgumentError:l}=c(61448),m=c(84285),{kUrl:n}=c(49176),o=c(55285),p=Symbol("options"),q=Symbol("connections"),r=Symbol("factory");function s(a,b){return new k(a,b)}class t extends d{constructor(a,{connections:b,factory:c=s,connect:d,connectTimeout:f,tls:g,maxCachedSessions:h,socketPath:i,autoSelectFamily:j,autoSelectFamilyAttemptTimeout:k,allowH2:t,useH2c:u,clientTtl:v,...w}={}){if(null!=b&&(!Number.isFinite(b)||b<0))throw new l("invalid connections");if("function"!=typeof c)throw new l("factory must be a function.");if(null!=d&&"function"!=typeof d&&"object"!=typeof d)throw new l("connect must be a function or an object");"function"!=typeof d&&(d=o({...g,maxCachedSessions:h,allowH2:t,useH2c:u,socketPath:i,timeout:f,..."boolean"==typeof j?{autoSelectFamily:j,autoSelectFamilyAttemptTimeout:k}:void 0,...d})),super(w),this[q]=b||null,this[n]=m.parseOrigin(a),this[p]={...m.deepClone(w),connect:d,allowH2:t,useH2c:u,clientTtl:v,socketPath:i},this[r]=c,this.on("connect",(a,b)=>{if(null!=v&&v>0)for(let a of b)Object.assign(a,{ttl:Date.now()})}),this.on("connectionError",(a,b,c)=>{for(let a of b){let b=this[e].indexOf(a);-1!==b&&this[e].splice(b,1)}})}[h](){let a=this[p].clientTtl;for(let b=0;b<this[e].length;b++){let c=this[e][b];if(null!=a&&a>0&&c.ttl&&Date.now()-c.ttl>a)this[j](c),b--;else if(!c[f])return c}if(!this[q]||this[e].length<this[q]){let a=this[r](this[n],this[p]);return this[g](a),a}}[i](){let a=this[p].clientTtl;for(let b=0;b<this[e].length;b++){let c=this[e][b];if(null!=a&&a>0&&c.ttl&&Date.now()-c.ttl>a)this[j](c),b--;else if(!c[f])return!0}if(!this[q]||this[e].length<this[q]){let a=this[r](this[n],this[p]);return this[g](a),!0}return!1}}a.exports=t},36105:(a,b,c)=>{var d=c(45654);d.pki=d.pki||{};var e=a.exports=d.pki.oids=d.oids=d.oids||{};function f(a,b){e[a]=b,e[b]=a}f("1.2.840.113549.1.1.1","rsaEncryption"),f("1.2.840.113549.1.1.4","md5WithRSAEncryption"),f("1.2.840.113549.1.1.5","sha1WithRSAEncryption"),f("1.2.840.113549.1.1.7","RSAES-OAEP"),f("1.2.840.113549.1.1.8","mgf1"),f("1.2.840.113549.1.1.9","pSpecified"),f("1.2.840.113549.1.1.10","RSASSA-PSS"),f("1.2.840.113549.1.1.11","sha256WithRSAEncryption"),f("1.2.840.113549.1.1.12","sha384WithRSAEncryption"),f("1.2.840.113549.1.1.13","sha512WithRSAEncryption"),f("1.3.101.112","EdDSA25519"),f("1.2.840.10040.4.3","dsa-with-sha1"),f("1.3.14.3.2.7","desCBC"),f("1.3.14.3.2.26","sha1"),f("1.3.14.3.2.29","sha1WithRSASignature"),f("2.16.840.1.101.3.4.2.1","sha256"),f("2.16.840.1.101.3.4.2.2","sha384"),f("2.16.840.1.101.3.4.2.3","sha512"),f("2.16.840.1.101.3.4.2.4","sha224"),f("2.16.840.1.101.3.4.2.5","sha512-224"),f("2.16.840.1.101.3.4.2.6","sha512-256"),f("1.2.840.113549.2.2","md2"),f("1.2.840.113549.2.5","md5"),f("1.2.840.113549.1.7.1","data"),f("1.2.840.113549.1.7.2","signedData"),f("1.2.840.113549.1.7.3","envelopedData"),f("1.2.840.113549.1.7.4","signedAndEnvelopedData"),f("1.2.840.113549.1.7.5","digestedData"),f("1.2.840.113549.1.7.6","encryptedData"),f("1.2.840.113549.1.9.1","emailAddress"),f("1.2.840.113549.1.9.2","unstructuredName"),f("1.2.840.113549.1.9.3","contentType"),f("1.2.840.113549.1.9.4","messageDigest"),f("1.2.840.113549.1.9.5","signingTime"),f("1.2.840.113549.1.9.6","counterSignature"),f("1.2.840.113549.1.9.7","challengePassword"),f("1.2.840.113549.1.9.8","unstructuredAddress"),f("1.2.840.113549.1.9.14","extensionRequest"),f("1.2.840.113549.1.9.20","friendlyName"),f("1.2.840.113549.1.9.21","localKeyId"),f("1.2.840.113549.1.9.22.1","x509Certificate"),f("1.2.840.113549.1.12.10.1.1","keyBag"),f("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag"),f("1.2.840.113549.1.12.10.1.3","certBag"),f("1.2.840.113549.1.12.10.1.4","crlBag"),f("1.2.840.113549.1.12.10.1.5","secretBag"),f("1.2.840.113549.1.12.10.1.6","safeContentsBag"),f("1.2.840.113549.1.5.13","pkcs5PBES2"),f("1.2.840.113549.1.5.12","pkcs5PBKDF2"),f("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4"),f("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4"),f("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC"),f("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC"),f("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC"),f("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC"),f("1.2.840.113549.2.7","hmacWithSHA1"),f("1.2.840.113549.2.8","hmacWithSHA224"),f("1.2.840.113549.2.9","hmacWithSHA256"),f("1.2.840.113549.2.10","hmacWithSHA384"),f("1.2.840.113549.2.11","hmacWithSHA512"),f("1.2.840.113549.3.7","des-EDE3-CBC"),f("2.16.840.1.101.3.4.1.2","aes128-CBC"),f("2.16.840.1.101.3.4.1.22","aes192-CBC"),f("2.16.840.1.101.3.4.1.42","aes256-CBC"),f("2.5.4.3","commonName"),f("2.5.4.4","surname"),f("2.5.4.5","serialNumber"),f("2.5.4.6","countryName"),f("2.5.4.7","localityName"),f("2.5.4.8","stateOrProvinceName"),f("2.5.4.9","streetAddress"),f("2.5.4.10","organizationName"),f("2.5.4.11","organizationalUnitName"),f("2.5.4.12","title"),f("2.5.4.13","description"),f("2.5.4.15","businessCategory"),f("2.5.4.17","postalCode"),f("2.5.4.42","givenName"),f("2.5.4.65","pseudonym"),f("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName"),f("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName"),f("2.16.840.1.113730.1.1","nsCertType"),f("2.16.840.1.113730.1.13","nsComment"),e["2.5.29.1"]="authorityKeyIdentifier",e["2.5.29.2"]="keyAttributes",e["2.5.29.3"]="certificatePolicies",e["2.5.29.4"]="keyUsageRestriction",e["2.5.29.5"]="policyMapping",e["2.5.29.6"]="subtreesConstraint",e["2.5.29.7"]="subjectAltName",e["2.5.29.8"]="issuerAltName",e["2.5.29.9"]="subjectDirectoryAttributes",e["2.5.29.10"]="basicConstraints",e["2.5.29.11"]="nameConstraints",e["2.5.29.12"]="policyConstraints",e["2.5.29.13"]="basicConstraints",f("2.5.29.14","subjectKeyIdentifier"),f("2.5.29.15","keyUsage"),e["2.5.29.16"]="privateKeyUsagePeriod",f("2.5.29.17","subjectAltName"),f("2.5.29.18","issuerAltName"),f("2.5.29.19","basicConstraints"),e["2.5.29.20"]="cRLNumber",e["2.5.29.21"]="cRLReason",e["2.5.29.22"]="expirationDate",e["2.5.29.23"]="instructionCode",e["2.5.29.24"]="invalidityDate",e["2.5.29.25"]="cRLDistributionPoints",e["2.5.29.26"]="issuingDistributionPoint",e["2.5.29.27"]="deltaCRLIndicator",e["2.5.29.28"]="issuingDistributionPoint",e["2.5.29.29"]="certificateIssuer",e["2.5.29.30"]="nameConstraints",f("2.5.29.31","cRLDistributionPoints"),f("2.5.29.32","certificatePolicies"),e["2.5.29.33"]="policyMappings",e["2.5.29.34"]="policyConstraints",f("2.5.29.35","authorityKeyIdentifier"),e["2.5.29.36"]="policyConstraints",f("2.5.29.37","extKeyUsage"),e["2.5.29.46"]="freshestCRL",e["2.5.29.54"]="inhibitAnyPolicy",f("1.3.6.1.4.1.11129.2.4.2","timestampList"),f("1.3.6.1.5.5.7.1.1","authorityInfoAccess"),f("1.3.6.1.5.5.7.3.1","serverAuth"),f("1.3.6.1.5.5.7.3.2","clientAuth"),f("1.3.6.1.5.5.7.3.3","codeSigning"),f("1.3.6.1.5.5.7.3.4","emailProtection"),f("1.3.6.1.5.5.7.3.8","timeStamping")},36649:(a,b,c)=>{"use strict";let{wellknownHeaderNames:d,headerNameLowerCasedRecord:e}=c(28820);class f{value=null;left=null;middle=null;right=null;code;constructor(a,b,c){if(void 0===c||c>=a.length)throw TypeError("Unreachable");if((this.code=a.charCodeAt(c))>127)throw TypeError("key must be ascii string");a.length!==++c?this.middle=new f(a,b,c):this.value=b}add(a,b){let c=a.length;if(0===c)throw TypeError("Unreachable");let d=0,e=this;for(;;){let g=a.charCodeAt(d);if(g>127)throw TypeError("key must be ascii string");if(e.code===g)if(c===++d){e.value=b;break}else if(null!==e.middle)e=e.middle;else{e.middle=new f(a,b,d);break}else if(e.code<g)if(null!==e.left)e=e.left;else{e.left=new f(a,b,d);break}else if(null!==e.right)e=e.right;else{e.right=new f(a,b,d);break}}}search(a){let b=a.length,c=0,d=this;for(;null!==d&&c<b;){let e=a[c];for(e<=90&&e>=65&&(e|=32);null!==d;){if(e===d.code){if(b===++c)return d;d=d.middle;break}d=d.code<e?d.left:d.right}}return null}}class g{node=null;insert(a,b){null===this.node?this.node=new f(a,b,0):this.node.add(a,b)}lookup(a){return this.node?.search(a)?.value??null}}let h=new g;for(let a=0;a<d.length;++a){let b=e[d[a]];h.insert(b,b)}a.exports={TernarySearchTree:g,tree:h}},36902:(a,b,c)=>{var d=c(45654);c(33889),c(32e3),c(29984),function(){if(d.prime){a.exports=d.prime;return}var b=a.exports=d.prime=d.prime||{},c=d.jsbn.BigInteger,e=[6,4,2,4,2,4,6,2],f=new c(null);f.fromInt(30);var g=function(a,b){return a|b};function h(a,b,c,f){var g,h=i(a,b),j=(g=h.bitLength())<=100?27:g<=150?18:g<=200?15:g<=250?12:g<=300?9:g<=350?8:g<=400?7:g<=500?6:g<=600?5:g<=800?4:g<=1250?3:2;"millerRabinTests"in c&&(j=c.millerRabinTests);var k=10;"maxBlockTime"in c&&(k=c.maxBlockTime),function a(b,c,f,g,h,j,k){var l=+new Date;do{if(b.bitLength()>c&&(b=i(c,f)),b.isProbablePrime(h))return k(null,b);b.dAddOffset(e[g++%8],0)}while(j<0||new Date-l<j);d.util.setImmediate(function(){a(b,c,f,g,h,j,k)})}(h,a,b,0,j,k,f)}function i(a,b){var d=new c(a,b),e=a-1;return d.testBit(e)||d.bitwiseTo(c.ONE.shiftLeft(e),g,d),d.dAddOffset(31-d.mod(f).byteValue(),0),d}b.generateProbablePrime=function(a,b,e){"function"==typeof b&&(e=b,b={});var f,g,j,k,l=(b=b||{}).algorithm||"PRIMEINC";"string"==typeof l&&(l={name:l}),l.options=l.options||{};var m=b.prng||d.random;if("PRIMEINC"===l.name){return f=a,g={nextBytes:function(a){for(var b=m.getBytesSync(a.length),c=0;c<a.length;++c)a[c]=b.charCodeAt(c)}},j=l.options,k=e,"workers"in j?function(a,b,e,f){if("u"<typeof Worker)return h(a,b,e,f);var g=i(a,b),j=e.workers,k=e.workLoad||100,l=30*k/8,m=e.workerScript||"forge/prime.worker.js";if(-1===j)return d.util.estimateCores(function(a,b){a&&(b=2),j=b-1,n()});function n(){j=Math.max(1,j);for(var d=[],e=0;e<j;++e)d[e]=new Worker(m);for(var h=j,e=0;e<j;++e)d[e].addEventListener("message",o);var n=!1;function o(e){if(!n){--h;var j=e.data;if(j.found){for(var m=0;m<d.length;++m)d[m].terminate();return n=!0,f(null,new c(j.prime,16))}g.bitLength()>a&&(g=i(a,b));var o=g.toString(16);e.target.postMessage({hex:o,workLoad:k}),g.dAddOffset(l,0)}}}n()}(f,g,j,k):h(f,g,j,k)}throw Error("Invalid prime generation algorithm: "+l.name)}}()},37417:(a,b,c)=>{"use strict";let{InvalidArgumentError:d,MaxOriginsReachedError:e}=c(61448),{kBusy:f,kClients:g,kConnected:h,kRunning:i,kClose:j,kDestroy:k,kDispatch:l,kUrl:m}=c(49176),n=c(5318),o=c(35689),p=c(40106),q=c(84285),r=Symbol("onConnect"),s=Symbol("onDisconnect"),t=Symbol("onConnectionError"),u=Symbol("onDrain"),v=Symbol("factory"),w=Symbol("options"),x=Symbol("origins");function y(a,b){return b&&1===b.connections?new p(a,b):new o(a,b)}class z extends n{constructor({factory:a=y,maxOrigins:b=1/0,connect:c,...e}={}){if("function"!=typeof a)throw new d("factory must be a function.");if(null!=c&&"function"!=typeof c&&"object"!=typeof c)throw new d("connect must be a function or an object");if("number"!=typeof b||Number.isNaN(b)||b<=0)throw new d("maxOrigins must be a number greater than 0");super(e),c&&"function"!=typeof c&&(c={...c}),this[w]={...q.deepClone(e),maxOrigins:b,connect:c},this[v]=a,this[g]=new Map,this[x]=new Set,this[u]=(a,b)=>{this.emit("drain",a,[this,...b])},this[r]=(a,b)=>{this.emit("connect",a,[this,...b])},this[s]=(a,b,c)=>{this.emit("disconnect",a,[this,...b],c)},this[t]=(a,b,c)=>{this.emit("connectionError",a,[this,...b],c)}}get[i](){let a=0;for(let b of this[g].values())a+=b[i];return a}[l](a,b){let c;if(a.origin&&("string"==typeof a.origin||a.origin instanceof URL))c=String(a.origin);else throw new d("opts.origin must be a non-empty string or URL.");let i=a.allowH2??this[w].allowH2,j=!1===i?`${c}#http1-only`:c;if(this[x].size>=this[w].maxOrigins&&!this[x].has(c))throw new e;let k=this[g].get(j);if(!k){k=this[v](a.origin,!1===i?{...this[w],allowH2:!1}:this[w]);let b=()=>{if(this[g].get(j)!==k||k[h]>0||k[f])return;this[g].delete(j),k.destroyed||k.close();let a=!1;for(let b of this[g].keys())if(b===c||b===`${c}#http1-only`){a=!0;break}a||this[x].delete(c)};k.on("drain",this[u]).on("connect",this[r]).on("disconnect",(a,c,d)=>{b(),this[s](a,c,d)}).on("connectionError",(a,c,d)=>{b(),this[t](a,c,d)}),this[g].set(j,k),this[x].add(c)}return k.dispatch(a,b)}[j](){let a=[];for(let b of this[g].values())a.push(b.close());return this[g].clear(),Promise.all(a)}[k](a){let b=[];for(let c of this[g].values())b.push(c.destroy(a));return this[g].clear(),Promise.all(b)}get stats(){let a={};for(let b of this[g].values())b.stats&&(a[b[m].origin]=b.stats);return a}}a.exports=z},37436:(a,b,c)=>{"use strict";let d=c(29021),e=c(33873),f=c(21820),g="switchboard";function h(){return"win32"===process.platform?e.join(process.env.APPDATA||e.join(f.homedir(),"AppData","Roaming"),g):e.join(f.homedir(),`.${g}`)}let i=function(){let a=process.env.DATA_DIR;if(!a)return h();try{return d.mkdirSync(a,{recursive:!0}),a}catch(b){if(b?.code==="EACCES"||b?.code==="EPERM")return console.warn(`[DATA_DIR] '${a}' not writable → fallback ~/.${g}`),h();throw b}}(),j=e.join(i,"mitm");a.exports={DATA_DIR:i,MITM_DIR:j}},37606:(a,b,c)=>{"use strict";c.d(b,{Ay:()=>A});var d=c(67671),e=c(38421),f=c(19016),g=c(24725),h=c(50969);let i=e.xq["perplexity-web"].baseUrl,j="2.18",k={"pplx-auto":["concise","pplx_pro"],"pplx-sonar":["copilot","experimental"],"pplx-gpt":["copilot","gpt54"],"pplx-gemini":["copilot","gemini31pro_high"],"pplx-sonnet":["copilot","claude46sonnet"],"pplx-opus":["copilot","claude46opus"],"pplx-nemotron":["copilot","nv_nemotron_3_super"]},l={"pplx-gpt":"gpt54_thinking","pplx-sonnet":"claude46sonnetthinking","pplx-opus":"claude46opusthinking"},m=/\[\d+\]/g,n=/<grok:[^>]*>.*?<\/grok:[^>]*>/gs,o=/<grok:[^>]*\/>/g,p=/<[?]xml[^?]*[?]>/g,q=/<\/?response\b[^>]*>/gi,r=/ {2,}/g,s=/\n{3,}/g,t=new Map;function u(a){let b=a.map(a=>`${a.role}:${a.content}`).join("\n"),c=0x811c9dc5;for(let a=0;a<b.length;a++)c^=b.charCodeAt(a),c=0x1000193*c>>>0;return c.toString(16).padStart(8,"0")}function v(a,b,c,d){if(!d)return;let e=u([...a,{role:"user",content:b},{role:"assistant",content:c}]);if(t.set(e,{backendUuid:d,ts:Date.now()}),t.size>200){let a=null,b=1/0;for(let[c,d]of t)d.ts<b&&(b=d.ts,a=c);a&&t.delete(a)}}function w(a,b=!0){let c=a;return c=(c=(c=(c=(c=c.replace(p,"")).replace(m,"")).replace(n,"")).replace(o,"")).replace(q,""),b&&(c=(c=(c=c.replace(r," ")).replace(s,"\n\n")).trim()),c}async function*x(a,b){let c=a.getReader(),d=new TextDecoder,e="",f=[];function g(){if(0===f.length)return null;let a=f.join("\n");f=[];let b=a.trim();if(!b||"[DONE]"===b)return"done";try{return JSON.parse(b)}catch{return null}}try{for(;;){if(b?.aborted)return;let{value:a,done:h}=await c.read();if(h)break;for(e+=d.decode(a,{stream:!0});;){let a=e.indexOf("\n");if(a<0)break;let b=e.slice(0,a);e=e.slice(a+1);let c=b.endsWith("\r")?b.slice(0,-1):b;if(""===c){let a=g();if("done"===a)return;a&&(yield a);continue}if(c.startsWith("data:")&&f.push(c.slice(5).trimStart()),"event: end_of_stream"===c)return}}(e+=d.decode()).trim().startsWith("data:")&&f.push(e.trim().slice(5).trimStart());let a=g();a&&"done"!==a&&(yield a)}finally{c.releaseLock()}}async function*y(a,b){let c="",d=null,e=0,f=new Set;for await(let g of x(a,b)){if(g.error_code||g.error_message)return void(yield{error:g.error_message||`Perplexity error: ${g.error_code}`,done:!0});g.backend_uuid&&(d=g.backend_uuid);let a=g.blocks??[];for(let b of a){let a=b.intended_usage??"";if("pro_search_steps"===a&&b.plan_block?.steps){for(let a of b.plan_block.steps)if("SEARCH_WEB"===a.step_type)for(let b of a.search_web_content?.queries??[]){let a=b.query??"";a&&!f.has(a)&&(f.add(a),yield{thinking:`Searching: ${a}`,backendUuid:d??void 0})}else if("READ_RESULTS"===a.step_type)for(let b of(a.read_results_content?.urls??[]).slice(0,3))b&&!f.has(b)&&(f.add(b),yield{thinking:`Reading: ${b}`,backendUuid:d??void 0})}if("plan"===a&&b.plan_block?.goals)for(let a of b.plan_block.goals){let b=a.description??"";b&&!f.has(b)&&(f.add(b),yield{thinking:b,backendUuid:d??void 0})}if(!a.includes("markdown"))continue;let g=b.markdown_block;if(!g)continue;let h=g.chunks??[];if(0!==h.length)if("DONE"===g.progress)c=h.join("");else{let a=c+h.join("");if(a.length>e){let b=a.slice(e);c=a,e=a.length,yield{delta:b,answer:c,backendUuid:d??void 0}}}}if(0===a.length&&g.text){let a=g.text.trim();if(a.length>e){let b=a.slice(e);c=a,e=a.length,yield{delta:b,answer:c,backendUuid:d??void 0}}}if(g.final||"COMPLETED"===g.status)break}yield{delta:"",answer:c,backendUuid:d??void 0,done:!0}}async function z(a,b,c,d,e,f,g){let h="",i=null,j=[];for await(let b of y(a,g)){if(b.backendUuid&&(i=b.backendUuid),b.error)return new Response(JSON.stringify({error:{message:b.error,type:"upstream_error",code:"PPLX_ERROR"}}),{status:502,headers:{"Content-Type":"application/json"}});if(b.thinking){j.push(b.thinking);continue}if(b.done){h=b.answer||h;break}b.answer&&(h=b.answer)}v(e,f,h=w(h),i);let k=j.length>0?j.join("\n"):void 0,l={role:"assistant",content:h};k&&(l.reasoning_content=k);let m=Math.ceil(f.length/4),n=Math.ceil(h.length/4);return new Response(JSON.stringify({id:c,object:"chat.completion",created:d,model:b,system_fingerprint:null,choices:[{index:0,message:l,finish_reason:"stop",logprobs:null}],usage:{prompt_tokens:m,completion_tokens:n,total_tokens:m+n}}),{status:200,headers:{"Content-Type":"application/json"}})}class A extends d.Hv{constructor(){super("perplexity-web",e.xq["perplexity-web"])}async execute({model:a,body:b,stream:c,credentials:d,signal:e,log:m,proxyOptions:n=null}){var o,p,q,r,s;let x,A,B,C,D,E=b?.messages;if(!E||!Array.isArray(E)||0===E.length)return{response:new Response(JSON.stringify({error:{message:"Missing or empty messages array",type:"invalid_request"}}),{status:400,headers:{"Content-Type":"application/json"}}),url:i,headers:{},transformedBody:b};(b?.thinking===!0||b?.reasoning_effort!=null&&"none"!==b.reasoning_effort)&&l[a]?(x="copilot",A=l[a],m?.info?.("PPLX-WEB",`Thinking mode → ${a} using ${A}`)):k[a]?[x,A]=k[a]:(x="copilot",A=a,m?.info?.("PPLX-WEB",`Unmapped model ${a}, using as raw preference`));let F=function(a){let b="",c=[];for(let d of a){let a=String(d.role||"user");"developer"===a&&(a="system");let e="";"string"==typeof d.content?e=d.content:Array.isArray(d.content)&&(e=d.content.filter(a=>"text"===a.type).map(a=>String(a.text||"")).join(" ")),e.trim()&&("system"===a?b+=e+"\n":("user"===a||"assistant"===a)&&c.push({role:a,content:e}))}let d="";return c.length>0&&"user"===c[c.length-1].role&&(d=c.pop().content),{systemMsg:b,history:c,currentMsg:d}}(E),G=function(a){if(0===a.length)return null;let b=u(a),c=t.get(b);return c?Date.now()-c.ts>36e5?(t.delete(b),null):c.backendUuid:null}(F.history);G&&m?.info?.("PPLX-WEB",`Session continue: ${G.slice(0,12)}...`);let H=function(a,b,c){if(b)return a.currentMsg;let d={},e=[];a.systemMsg.trim()&&e.push(a.systemMsg.trim());let f=function(a){if(!Array.isArray(a)||0===a.length)return"";let b=a.map(a=>{let b=a?.function||a||{},c=b.name||"unnamed",d=(b.description||"").split("\n")[0].slice(0,200);return`- ${c}: ${d}`});return`Available tools (reference only, cannot invoke):
|
|
186
|
+
${b.join("\n")}`}(c);f&&e.push(f),e.push("You have built-in web search. Answer questions directly using search results."),d.instructions=e,a.history.length>0&&(d.history=a.history),a.currentMsg?d.query=a.currentMsg:0===a.history.length&&(d.query="");let g=JSON.stringify(d);return g.length>96e3?g.slice(-96e3):g}(F,G,b?.tools);if(!H.trim())return{response:new Response(JSON.stringify({error:{message:"Empty query after processing",type:"invalid_request"}}),{status:400,headers:{"Content-Type":"application/json"}}),url:i,headers:{},transformedBody:b};let I=(o=x,p=A,D="u">typeof Intl?Intl.DateTimeFormat().resolvedOptions().timeZone:"UTC",{query_str:H,params:{query_str:H,search_focus:"internet",mode:o,model_preference:p,sources:["web"],attachments:[],frontend_uuid:crypto.randomUUID(),frontend_context_uuid:crypto.randomUUID(),version:j,language:"en-US",timezone:D,search_recency_filter:null,is_incognito:!0,use_schematized_api:!0,last_backend_uuid:G}}),J={"Content-Type":"application/json",Accept:"text/event-stream",Origin:"https://www.perplexity.ai",Referer:"https://www.perplexity.ai/","User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36","X-App-ApiClient":"default","X-App-ApiVersion":j};d.accessToken?J.Authorization=`Bearer ${d.accessToken}`:d.apiKey&&(J.Cookie=`__Secure-next-auth.session-token=${d.apiKey}`),m?.info?.("PPLX-WEB",`Query to ${a} (pref=${A}, mode=${x}), len=${H.length}`);let K={method:"POST",headers:J,body:JSON.stringify(I),identity:this.config.identity,provider:this.provider,format:this.config.format};e&&(K.signal=e);try{B=await (0,h.Fm)(i,K,n)}catch(a){return m?.error?.("PPLX-WEB",`Fetch failed: ${a.message||String(a)}`),{response:new Response(JSON.stringify({error:{message:`Perplexity connection failed: ${a.message||String(a)}`,type:"upstream_error"}}),{status:502,headers:{"Content-Type":"application/json"}}),url:i,headers:J,transformedBody:I}}if(!B.ok){let a=B.status,b=`Perplexity returned HTTP ${a}`;return 401===a||403===a?b="Perplexity auth failed — session cookie may be expired. Re-paste your __Secure-next-auth.session-token.":429===a&&(b="Perplexity rate limited. Wait a moment and retry."),m?.warn?.("PPLX-WEB",b),{response:new Response(JSON.stringify({error:{message:b,type:"upstream_error",code:`HTTP_${a}`}}),{status:a,headers:{"Content-Type":"application/json"}}),url:i,headers:J,transformedBody:I}}if(!B.body)return{response:new Response(JSON.stringify({error:{message:"Perplexity returned empty response body",type:"upstream_error"}}),{status:502,headers:{"Content-Type":"application/json"}}),url:i,headers:J,transformedBody:I};let L=`chatcmpl-pplx-${crypto.randomUUID().slice(0,12)}`,M=Math.floor(Date.now()/1e3);if(c){let b;C=new Response((q=B.body,r=F.history,s=F.currentMsg,b=new TextEncoder,new ReadableStream({async start(c){try{c.enqueue(b.encode((0,g.N)({id:L,object:"chat.completion.chunk",created:M,model:a,system_fingerprint:null,choices:[{index:0,delta:{role:"assistant"},finish_reason:null,logprobs:null}]})));let d="",h=null;for await(let f of y(q,e)){if(f.backendUuid&&(h=f.backendUuid),f.error){c.enqueue(b.encode((0,g.N)({id:L,object:"chat.completion.chunk",created:M,model:a,system_fingerprint:null,choices:[{index:0,delta:{content:`[Error: ${f.error}]`},finish_reason:null,logprobs:null}]})));break}if(f.thinking){c.enqueue(b.encode((0,g.N)({id:L,object:"chat.completion.chunk",created:M,model:a,system_fingerprint:null,choices:[{index:0,delta:{reasoning_content:f.thinking+"\n"},finish_reason:null,logprobs:null}]})));continue}if(f.done){d=f.answer||d;break}let e=f.delta||"";e&&(e=w(e,!1))&&c.enqueue(b.encode((0,g.N)({id:L,object:"chat.completion.chunk",created:M,model:a,system_fingerprint:null,choices:[{index:0,delta:{content:e},finish_reason:null,logprobs:null}]}))),f.answer&&(d=f.answer)}c.enqueue(b.encode((0,g.N)({id:L,object:"chat.completion.chunk",created:M,model:a,system_fingerprint:null,choices:[{index:0,delta:{},finish_reason:"stop",logprobs:null}]}))),c.enqueue(b.encode(f.$U)),v(r,s,w(d),h)}catch(d){c.enqueue(b.encode((0,g.N)({id:L,object:"chat.completion.chunk",created:M,model:a,system_fingerprint:null,choices:[{index:0,delta:{content:`[Stream error: ${d.message||String(d)}]`},finish_reason:"stop",logprobs:null}]}))),c.enqueue(b.encode(f.$U))}finally{c.close()}}})),{status:200,headers:{...f.uB}})}else C=await z(B.body,a,L,M,F.history,F.currentMsg,e);return{response:C,url:i,headers:J,transformedBody:I}}}},37691:(a,b,c)=>{var d=c(45654);c(1277),c(33889);var e=a.exports=d.sha512=d.sha512||{};d.md.sha512=d.md.algorithms.sha512=e;var f=d.sha384=d.sha512.sha384=d.sha512.sha384||{};f.create=function(){return e.create("SHA-384")},d.md.sha384=d.md.algorithms.sha384=f,d.sha512.sha256=d.sha512.sha256||{create:function(){return e.create("SHA-512/256")}},d.md["sha512/256"]=d.md.algorithms["sha512/256"]=d.sha512.sha256,d.sha512.sha224=d.sha512.sha224||{create:function(){return e.create("SHA-512/224")}},d.md["sha512/224"]=d.md.algorithms["sha512/224"]=d.sha512.sha224,e.create=function(a){if(h||(g=String.fromCharCode(128)+d.util.fillString("\0",128),i=[[0x428a2f98,0xd728ae22],[0x71374491,0x23ef65cd],[0xb5c0fbcf,0xec4d3b2f],[0xe9b5dba5,0x8189dbbc],[0x3956c25b,0xf348b538],[0x59f111f1,0xb605d019],[0x923f82a4,0xaf194f9b],[0xab1c5ed5,0xda6d8118],[0xd807aa98,0xa3030242],[0x12835b01,0x45706fbe],[0x243185be,0x4ee4b28c],[0x550c7dc3,0xd5ffb4e2],[0x72be5d74,0xf27b896f],[0x80deb1fe,0x3b1696b1],[0x9bdc06a7,0x25c71235],[0xc19bf174,0xcf692694],[0xe49b69c1,0x9ef14ad2],[0xefbe4786,0x384f25e3],[0xfc19dc6,0x8b8cd5b5],[0x240ca1cc,0x77ac9c65],[0x2de92c6f,0x592b0275],[0x4a7484aa,0x6ea6e483],[0x5cb0a9dc,0xbd41fbd4],[0x76f988da,0x831153b5],[0x983e5152,0xee66dfab],[0xa831c66d,0x2db43210],[0xb00327c8,0x98fb213f],[0xbf597fc7,0xbeef0ee4],[0xc6e00bf3,0x3da88fc2],[0xd5a79147,0x930aa725],[0x6ca6351,0xe003826f],[0x14292967,0xa0e6e70],[0x27b70a85,0x46d22ffc],[0x2e1b2138,0x5c26c926],[0x4d2c6dfc,0x5ac42aed],[0x53380d13,0x9d95b3df],[0x650a7354,0x8baf63de],[0x766a0abb,0x3c77b2a8],[0x81c2c92e,0x47edaee6],[0x92722c85,0x1482353b],[0xa2bfe8a1,0x4cf10364],[0xa81a664b,0xbc423001],[0xc24b8b70,0xd0f89791],[0xc76c51a3,0x654be30],[0xd192e819,0xd6ef5218],[0xd6990624,0x5565a910],[0xf40e3585,0x5771202a],[0x106aa070,0x32bbd1b8],[0x19a4c116,0xb8d2d0c8],[0x1e376c08,0x5141ab53],[0x2748774c,0xdf8eeb99],[0x34b0bcb5,0xe19b48a8],[0x391c0cb3,0xc5c95a63],[0x4ed8aa4a,0xe3418acb],[0x5b9cca4f,0x7763e373],[0x682e6ff3,0xd6b2b8a3],[0x748f82ee,0x5defb2fc],[0x78a5636f,0x43172f60],[0x84c87814,0xa1f0ab72],[0x8cc70208,0x1a6439ec],[0x90befffa,0x23631e28],[0xa4506ceb,0xde82bde9],[0xbef9a3f7,0xb2c67915],[0xc67178f2,0xe372532b],[0xca273ece,0xea26619c],[0xd186b8c7,0x21c0c207],[0xeada7dd6,0xcde0eb1e],[0xf57d4f7f,0xee6ed178],[0x6f067aa,0x72176fba],[0xa637dc5,0xa2c898a6],[0x113f9804,0xbef90dae],[0x1b710b35,0x131c471b],[0x28db77f5,0x23047d84],[0x32caab7b,0x40c72493],[0x3c9ebe0a,0x15c9bebc],[0x431d67c4,0x9c100d4c],[0x4cc5d4be,0xcb3e42b6],[0x597f299c,0xfc657e2a],[0x5fcb6fab,0x3ad6faec],[0x6c44198c,0x4a475817]],(j={})["SHA-512"]=[[0x6a09e667,0xf3bcc908],[0xbb67ae85,0x84caa73b],[0x3c6ef372,0xfe94f82b],[0xa54ff53a,0x5f1d36f1],[0x510e527f,0xade682d1],[0x9b05688c,0x2b3e6c1f],[0x1f83d9ab,0xfb41bd6b],[0x5be0cd19,0x137e2179]],j["SHA-384"]=[[0xcbbb9d5d,0xc1059ed8],[0x629a292a,0x367cd507],[0x9159015a,0x3070dd17],[0x152fecd8,0xf70e5939],[0x67332667,0xffc00b31],[0x8eb44a87,0x68581511],[0xdb0c2e0d,0x64f98fa7],[0x47b5481d,0xbefa4fa4]],j["SHA-512/256"]=[[0x22312194,0xfc2bf72c],[0x9f555fa3,0xc84c64c2],[0x2393b86b,0x6f53b151],[0x96387719,0x5940eabd],[0x96283ee2,0xa88effe3],[0xbe5e1e25,0x53863992],[0x2b0199fc,0x2c85b8aa],[0xeb72ddc,0x81c52ca2]],j["SHA-512/224"]=[[0x8c3d37c8,0x19544da2],[0x73e19966,0x89dcd4d6],[0x1dfab7ae,0x32ff9c82],[0x679dd514,0x582f9fcf],[0xf6d2b69,0x7bd44da8],[0x77e36f73,0x4c48942],[0x3f9d85a8,0x6a1d36c8],[0x1112e6ad,0x91d692a1]],h=!0),void 0===a&&(a="SHA-512"),!(a in j))throw Error("Invalid SHA-512 algorithm: "+a);for(var b=j[a],c=null,e=d.util.createBuffer(),f=Array(80),l=0;l<80;++l)f[l]=[,,];var m=64;switch(a){case"SHA-384":m=48;break;case"SHA-512/256":m=32;break;case"SHA-512/224":m=28}var n={algorithm:a.replace("-","").toLowerCase(),blockLength:128,digestLength:m,messageLength:0,fullMessageLength:null,messageLengthSize:16};return n.start=function(){n.messageLength=0,n.fullMessageLength=n.messageLength128=[];for(var a=n.messageLengthSize/4,f=0;f<a;++f)n.fullMessageLength.push(0);e=d.util.createBuffer(),c=Array(b.length);for(var f=0;f<b.length;++f)c[f]=b[f].slice(0);return n},n.start(),n.update=function(a,b){"utf8"===b&&(a=d.util.encodeUtf8(a));var g=a.length;n.messageLength+=g,g=[g/0x100000000>>>0,g>>>0];for(var h=n.fullMessageLength.length-1;h>=0;--h)n.fullMessageLength[h]+=g[1],g[1]=g[0]+(n.fullMessageLength[h]/0x100000000>>>0),n.fullMessageLength[h]=n.fullMessageLength[h]>>>0,g[0]=g[1]/0x100000000>>>0;return e.putBytes(a),k(c,f,e),(e.read>2048||0===e.length())&&e.compact(),n},n.digest=function(){var b,h,i=d.util.createBuffer();i.putBytes(e.bytes());var j=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize&n.blockLength-1;i.putBytes(g.substr(0,n.blockLength-j));for(var l=8*n.fullMessageLength[0],m=0;m<n.fullMessageLength.length-1;++m)l+=(b=8*n.fullMessageLength[m+1])/0x100000000>>>0,i.putInt32(l>>>0),l=b>>>0;i.putInt32(l);for(var o=Array(c.length),m=0;m<c.length;++m)o[m]=c[m].slice(0);k(o,f,i);var p=d.util.createBuffer();h="SHA-512"===a?o.length:"SHA-384"===a?o.length-2:o.length-4;for(var m=0;m<h;++m)p.putInt32(o[m][0]),(m!==h-1||"SHA-512/224"!==a)&&p.putInt32(o[m][1]);return p},n};var g=null,h=!1,i=null,j=null;function k(a,b,c){for(var d,e,f,g,h,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N=c.length();N>=128;){for(G=0;G<16;++G)b[G][0]=c.getInt32()>>>0,b[G][1]=c.getInt32()>>>0;for(;G<80;++G)d=(((H=(J=b[G-2])[0])>>>19|(I=J[1])<<13)^(I>>>29|H<<3)^H>>>6)>>>0,e=((H<<13|I>>>19)^(I<<3|H>>>29)^(H<<26|I>>>6))>>>0,f=(((H=(L=b[G-15])[0])>>>1|(I=L[1])<<31)^(H>>>8|I<<24)^H>>>7)>>>0,g=((H<<31|I>>>1)^(H<<24|I>>>8)^(H<<25|I>>>7))>>>0,K=b[G-7],M=b[G-16],I=e+K[1]+g+M[1],b[G][0]=d+K[0]+f+M[0]+(I/0x100000000>>>0)>>>0,b[G][1]=I>>>0;for(q=a[0][0],r=a[0][1],s=a[1][0],t=a[1][1],u=a[2][0],v=a[2][1],w=a[3][0],x=a[3][1],y=a[4][0],z=a[4][1],A=a[5][0],B=a[5][1],C=a[6][0],D=a[6][1],E=a[7][0],F=a[7][1],G=0;G<80;++G)k=((y>>>14|z<<18)^(y>>>18|z<<14)^(z>>>9|y<<23))>>>0,l=((y<<18|z>>>14)^(y<<14|z>>>18)^(z<<23|y>>>9))>>>0,m=(C^y&(A^C))>>>0,n=(D^z&(B^D))>>>0,h=((q>>>28|r<<4)^(r>>>2|q<<30)^(r>>>7|q<<25))>>>0,j=((q<<4|r>>>28)^(r<<30|q>>>2)^(r<<25|q>>>7))>>>0,o=(q&s|u&(q^s))>>>0,p=(r&t|v&(r^t))>>>0,I=F+l+n+i[G][1]+b[G][1],d=E+k+m+i[G][0]+b[G][0]+(I/0x100000000>>>0)>>>0,e=I>>>0,f=h+o+((I=j+p)/0x100000000>>>0)>>>0,g=I>>>0,E=C,F=D,C=A,D=B,A=y,B=z,y=w+d+((I=x+e)/0x100000000>>>0)>>>0,z=I>>>0,w=u,x=v,u=s,v=t,s=q,t=r,q=d+f+((I=e+g)/0x100000000>>>0)>>>0,r=I>>>0;I=a[0][1]+r,a[0][0]=a[0][0]+q+(I/0x100000000>>>0)>>>0,a[0][1]=I>>>0,I=a[1][1]+t,a[1][0]=a[1][0]+s+(I/0x100000000>>>0)>>>0,a[1][1]=I>>>0,I=a[2][1]+v,a[2][0]=a[2][0]+u+(I/0x100000000>>>0)>>>0,a[2][1]=I>>>0,I=a[3][1]+x,a[3][0]=a[3][0]+w+(I/0x100000000>>>0)>>>0,a[3][1]=I>>>0,I=a[4][1]+z,a[4][0]=a[4][0]+y+(I/0x100000000>>>0)>>>0,a[4][1]=I>>>0,I=a[5][1]+B,a[5][0]=a[5][0]+A+(I/0x100000000>>>0)>>>0,a[5][1]=I>>>0,I=a[6][1]+D,a[6][0]=a[6][0]+C+(I/0x100000000>>>0)>>>0,a[6][1]=I>>>0,I=a[7][1]+F,a[7][0]=a[7][0]+E+(I/0x100000000>>>0)>>>0,a[7][1]=I>>>0,N-=128}}},37703:(a,b,c)=>{"use strict";c.d(b,{getMitmAlias:()=>h,o5:()=>g}),c(24081);var d=c(58609);let e=(0,d.U)("modelAliases");(0,d.U)("customModels");let f=(0,d.U)("mitmAlias");async function g(a,b){await e.set(a,b)}async function h(a){return a?await f.get(a)||{}:await f.getAll()}},37858:(a,b,c)=>{"use strict";let{createInflate:d,createGunzip:e,createBrotliDecompress:f,createZstdDecompress:g}=c(38522),{pipeline:h}=c(57075),i=c(60823),j={gzip:e,"x-gzip":e,br:f,deflate:d,compress:d,"x-compress":d,zstd:g},k=[204,304],l=!1;class m extends i{#V=[];#W;#X;#Y;constructor(a,{skipStatusCodes:b=k,skipErrorResponses:c=!0}={}){super(a),this.#X=b,this.#Y=c}#Z(a,b){return!!(!a||b<200||this.#X.includes(b))||!!this.#Y&&!!(b>=400)}#$(a){let b=a.split(",");if(b.length>5)throw Error(`too many content-encodings in response: ${b.length}, maximum allowed is 5`);let c=[];for(let a=b.length-1;a>=0;a--){let d=b[a].trim();if(d){if(!j[d])return c.length=0,c;c.push(j[d]())}}return c}#_(a,b){a.on("readable",()=>{let c;for(;null!==(c=a.read())&&!1!==super.onResponseData(b,c););}),a.on("error",a=>{super.onResponseError(b,a)})}#aa(a){let b=this.#V[0];this.#_(b,a),b.on("end",()=>{super.onResponseEnd(a,this.#W)})}#ab(a){let b=this.#V[this.#V.length-1];this.#_(b,a),h(this.#V,b=>{b?super.onResponseError(a,b):super.onResponseEnd(a,this.#W)})}#ac(){this.#V.length=0}onResponseStart(a,b,c,d){let e=c["content-encoding"];if(this.#Z(e,b))return super.onResponseStart(a,b,c,d);let f=this.#$(e.toLowerCase());if(0===f.length)return this.#ac(),super.onResponseStart(a,b,c,d);this.#V=f;let{"content-encoding":g,"content-length":h,...i}=c;if(a?.rawHeaders){let b=a.rawHeaders;if(Array.isArray(b)){let c=[];for(let a=0;a<b.length;a+=2){let d=b[a],e=(Buffer.isBuffer(d)?d.toString("latin1"):`${d}`).toLowerCase();"content-encoding"!==e&&"content-length"!==e&&c.push(b[a],b[a+1])}a.rawHeaders=c}else if("object"==typeof b)for(let a of Object.keys(b)){let c=a.toLowerCase();("content-encoding"===c||"content-length"===c)&&delete b[a]}}return 1===this.#V.length?this.#aa(a):this.#ab(a),super.onResponseStart(a,b,i,d)}onResponseData(a,b){this.#V.length>0?this.#V[0].write(b):super.onResponseData(a,b)}onResponseEnd(a,b){if(this.#V.length>0){this.#W=b,this.#V[0].end(),this.#ac();return}super.onResponseEnd(a,b)}onResponseError(a,b){if(this.#V.length>0){for(let a of this.#V)a.destroy(b);this.#ac()}super.onResponseError(a,b)}}a.exports=function(a={}){return l||(process.emitWarning("DecompressInterceptor is experimental and subject to change","ExperimentalWarning"),l=!0),b=>(c,d)=>"HEAD"===c.method?b(c,d):b(c,new m(d,a))}},38421:(a,b,c)=>{"use strict";c.d(b,{Ak:()=>e,Yg:()=>h,sr:()=>d.sr,xq:()=>d.xq});var d=c(15251);function e(a){return(a?.providerSpecificData?.baseUrl?.trim()||"http://localhost:11434").replace(/\/$/,"")}let f=d.xq["xiaomi-tokenplan"]?.regions||{},g=d.xq["xiaomi-tokenplan"]?.defaultRegion;function h(a){return f[a?.providerSpecificData?.region]||f[g]}},38528:(a,b,c)=>{"use strict";c.d(b,{IQ:()=>h,U:()=>f,eZ:()=>g,gD:()=>i,u9:()=>j});var d=c(15251),e=c(50969);let f=a=>d.xq[a]?.usage||{};function g(a){if(!a)return null;try{if(a instanceof Date)return a.toISOString();if("number"==typeof a)return new Date(a<1e12?1e3*a:a).toISOString();if("string"==typeof a){if(/^\d+$/.test(a)){let b=Number(a);return new Date(b<1e12?1e3*b:b).toISOString()}return new Date(a).toISOString()}return null}catch(b){return console.warn(`Failed to parse reset time: ${a}`,b),null}}function h(a,b=0){if("number"==typeof a&&Number.isFinite(a))return a;if("string"==typeof a&&a.trim()){let b=Number(a);if(Number.isFinite(b))return b}return b}function i(a){return"string"==typeof a?a.trim()||null:a&&"object"==typeof a&&"string"==typeof a.id&&a.id.trim()||null}async function j(a,b,c=1e4,d=null){let f=new AbortController,g=setTimeout(()=>f.abort(),c);try{return await (0,e.Fm)(a,{...b,signal:f.signal},d)}finally{clearTimeout(g)}}},38627:(a,b,c)=>{var d=c(45654);c(1277),c(33889);var e=a.exports=d.md5=d.md5||{};d.md.md5=d.md.algorithms.md5=e,e.create=function(){j||function(){f=String.fromCharCode(128)+d.util.fillString("\0",64),g=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1,6,11,0,5,10,15,4,9,14,3,8,13,2,7,12,5,8,11,14,1,4,7,10,13,0,3,6,9,12,15,2,0,7,14,5,12,3,10,1,8,15,6,13,4,11,2,9],h=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],i=Array(64);for(var a=0;a<64;++a)i[a]=Math.floor(0x100000000*Math.abs(Math.sin(a+1)));j=!0}();var a=null,b=d.util.createBuffer(),c=Array(16),e={algorithm:"md5",blockLength:64,digestLength:16,messageLength:0,fullMessageLength:null,messageLengthSize:8};return e.start=function(){e.messageLength=0,e.fullMessageLength=e.messageLength64=[];for(var c=e.messageLengthSize/4,f=0;f<c;++f)e.fullMessageLength.push(0);return b=d.util.createBuffer(),a={h0:0x67452301,h1:0xefcdab89,h2:0x98badcfe,h3:0x10325476},e},e.start(),e.update=function(f,g){"utf8"===g&&(f=d.util.encodeUtf8(f));var h=f.length;e.messageLength+=h,h=[h/0x100000000>>>0,h>>>0];for(var i=e.fullMessageLength.length-1;i>=0;--i)e.fullMessageLength[i]+=h[1],h[1]=h[0]+(e.fullMessageLength[i]/0x100000000>>>0),e.fullMessageLength[i]=e.fullMessageLength[i]>>>0,h[0]=h[1]/0x100000000>>>0;return b.putBytes(f),k(a,c,b),(b.read>2048||0===b.length())&&b.compact(),e},e.digest=function(){var g=d.util.createBuffer();g.putBytes(b.bytes());var h=e.fullMessageLength[e.fullMessageLength.length-1]+e.messageLengthSize&e.blockLength-1;g.putBytes(f.substr(0,e.blockLength-h));for(var i,j=0,l=e.fullMessageLength.length-1;l>=0;--l)j=(i=8*e.fullMessageLength[l]+j)/0x100000000>>>0,g.putInt32Le(i>>>0);var m={h0:a.h0,h1:a.h1,h2:a.h2,h3:a.h3};k(m,c,g);var n=d.util.createBuffer();return n.putInt32Le(m.h0),n.putInt32Le(m.h1),n.putInt32Le(m.h2),n.putInt32Le(m.h3),n},e};var f=null,g=null,h=null,i=null,j=!1;function k(a,b,c){for(var d,e,f,j,k,l,m,n,o=c.length();o>=64;){for(e=a.h0,f=a.h1,j=a.h2,k=a.h3,n=0;n<16;++n)b[n]=c.getInt32Le(),d=e+(k^f&(j^k))+i[n]+b[n],m=h[n],e=k,k=j,j=f,f+=d<<m|d>>>32-m;for(;n<32;++n)d=e+(j^k&(f^j))+i[n]+b[g[n]],m=h[n],e=k,k=j,j=f,f+=d<<m|d>>>32-m;for(;n<48;++n)d=e+(f^j^k)+i[n]+b[g[n]],m=h[n],e=k,k=j,j=f,f+=d<<m|d>>>32-m;for(;n<64;++n)d=e+(j^(f|~k))+i[n]+b[g[n]],m=h[n],e=k,k=j,j=f,f+=d<<m|d>>>32-m;a.h0=a.h0+e|0,a.h1=a.h1+f|0,a.h2=a.h2+j|0,a.h3=a.h3+k|0,o-=64}}},38650:(a,b,c)=>{"use strict";let{Writable:d}=c(57075),{EventEmitter:e}=c(78474),{assertCacheKey:f,assertCacheValue:g}=c(79468);class h extends e{#h=1024;#ad=0x6400000;#g=5242880;#ae=0;#af=0;#ag=new Map;#ah=!1;constructor(a){if(super(),a){if("object"!=typeof a)throw TypeError("MemoryCacheStore options must be an object");if(void 0!==a.maxCount){if("number"!=typeof a.maxCount||!Number.isInteger(a.maxCount)||a.maxCount<0)throw TypeError("MemoryCacheStore options.maxCount must be a non-negative integer");this.#h=a.maxCount}if(void 0!==a.maxSize){if("number"!=typeof a.maxSize||!Number.isInteger(a.maxSize)||a.maxSize<0)throw TypeError("MemoryCacheStore options.maxSize must be a non-negative integer");this.#ad=a.maxSize}if(void 0!==a.maxEntrySize){if("number"!=typeof a.maxEntrySize||!Number.isInteger(a.maxEntrySize)||a.maxEntrySize<0)throw TypeError("MemoryCacheStore options.maxEntrySize must be a non-negative integer");this.#g=a.maxEntrySize}}}get size(){return this.#ae}isFull(){return this.#ae>=this.#ad||this.#af>=this.#h}get(a){f(a);let b=`${a.origin}:${a.path}`,c=Date.now(),d=this.#ag.get(b),e=d?i(a,d,c):null;return null==e?void 0:{statusMessage:e.statusMessage,statusCode:e.statusCode,headers:e.headers,body:e.body,vary:e.vary?e.vary:void 0,etag:e.etag,cacheControlDirectives:e.cacheControlDirectives,cachedAt:e.cachedAt,staleAt:e.staleAt,deleteAt:e.deleteAt}}createWriteStream(a,b){f(a),g(b);let c=`${a.origin}:${a.path}`,e=this,h={...a,...b,body:[],size:0};return new d({write(a,b,c){"string"==typeof a&&(a=Buffer.from(a,b)),h.size+=a.byteLength,h.size>e.#g?this.destroy():h.body.push(a),c(null)},final(b){let d=e.#ag.get(c);d||(d=[],e.#ag.set(c,d));let f=i(a,d,Date.now());if(f){let a=d.indexOf(f);d.splice(a,1,h),e.#ae-=f.size}else d.push(h),e.#af+=1;if(e.#ae+=h.size,e.#ae>e.#ad||e.#af>e.#h){for(let[a,b]of(e.#ah||(e.emit("maxSizeExceeded",{size:e.#ae,maxSize:e.#ad,count:e.#af,maxCount:e.#h}),e.#ah=!0),e.#ag)){for(let a of b.splice(0,b.length/2))e.#ae-=a.size,e.#af-=1;0===b.length&&e.#ag.delete(a)}e.#ae<e.#ad&&e.#af<e.#h&&(e.#ah=!1)}b(null)}})}delete(a){if("object"!=typeof a)throw TypeError(`expected key to be object, got ${typeof a}`);let b=`${a.origin}:${a.path}`;for(let a of this.#ag.get(b)??[])this.#ae-=a.size,this.#af-=1;this.#ag.delete(b)}}function i(a,b,c){for(let d=0;d<b.length;d++){let e=b[d];if(e.deleteAt>c&&e.method===a.method&&function(a,b){if(null==b.vary)return!0;for(let c in b.vary)if(Object.hasOwn(b.vary,c)&&!function(a,b){if(null==a&&null==b)return!0;if(null==a&&null!=b||null!=a&&null==b)return!1;if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)return!1;for(let c=0;c<a.length;c++)if(a[c]!==b[c])return!1;return!0}return a===b}(a.headers?.[c],b.vary[c]))return!1;return!0}(a,e))return e}}a.exports=h},39065:(a,b,c)=>{"use strict";let{PoolStats:d}=c(19071),e=c(5318),f=c(50329),{kConnected:g,kSize:h,kRunning:i,kPending:j,kQueued:k,kBusy:l,kFree:m,kUrl:n,kClose:o,kDestroy:p,kDispatch:q}=c(49176),r=Symbol("clients"),s=Symbol("needDrain"),t=Symbol("queue"),u=Symbol("closed resolve"),v=Symbol("onDrain"),w=Symbol("onConnect"),x=Symbol("onDisconnect"),y=Symbol("onConnectionError"),z=Symbol("get dispatcher"),A=Symbol("has dispatcher"),B=Symbol("add client"),C=Symbol("remove client");class D extends e{[t]=new f;[k]=0;[r]=[];[s]=!1;[v](a,b,c){let d=this[t],e=!1;for(;!e;){let b=d.shift();if(!b)break;this[k]--,e=!a.dispatch(b.opts,b.handler)}if(a[s]=e,!e&&this[s]&&(this[s]=!1,this.emit("drain",b,[this,...c])),this[u]&&d.isEmpty()){let a=[];for(let b=0;b<this[r].length;b++){let c=this[r][b];c.destroyed||a.push(c.close())}return Promise.all(a).then(this[u])}}[w]=(a,b)=>{this.emit("connect",a,[this,...b])};[x]=(a,b,c)=>{this.emit("disconnect",a,[this,...b],c)};[y]=(a,b,c)=>{this.emit("connectionError",a,[this,...b],c)};get[l](){return this[s]}get[g](){let a=0;for(let{[g]:b}of this[r])a+=b;return a}get[m](){let a=0;for(let{[g]:b,[s]:c}of this[r])a+=b&&!c;return a}get[j](){let a=this[k];for(let{[j]:b}of this[r])a+=b;return a}get[i](){let a=0;for(let{[i]:b}of this[r])a+=b;return a}get[h](){let a=this[k];for(let{[h]:b}of this[r])a+=b;return a}get stats(){return new d(this)}[o](){if(!this[t].isEmpty())return new Promise(a=>{this[u]=a});{let a=[];for(let b=0;b<this[r].length;b++){let c=this[r][b];c.destroyed||a.push(c.close())}return Promise.all(a)}}[p](a){for(;;){let b=this[t].shift();if(!b)break;b.handler.onResponseError(null,a)}let b=Array(this[r].length);for(let c=0;c<this[r].length;c++)b[c]=this[r][c].destroy(a);return Promise.all(b)}[q](a,b){let c=this[z]();return c?c.dispatch(a,b)||(c[s]=!0,this[s]=!this[A]()):(this[s]=!0,this[t].push({opts:a,handler:b}),this[k]++),!this[s]}[A](){for(let a=0;a<this[r].length;a++){let b=this[r][a];if(!b[s]&&!0!==b.closed&&!0!==b.destroyed)return!0}return!1}[B](a){return a.on("drain",this[v].bind(this,a)).on("connect",this[w]).on("disconnect",this[x]).on("connectionError",this[y]),this[r].push(a),this[s]&&queueMicrotask(()=>{this[s]&&this[v](a,a[n],[a,this])}),this}[C](a){let b=this[r].indexOf(a);-1!==b&&this[r].splice(b,1),a.close(()=>{}),this[s]=!this[r].some(a=>!a[s]&&!0!==a.closed&&!0!==a.destroyed)}}a.exports={PoolBase:D,kClients:r,kNeedDrain:s,kAddClient:B,kRemoveClient:C,kGetDispatcher:z,kHasDispatcher:A}},39490:(a,b,c)=>{"use strict";RegExp("<think>([\\s\\S]*?)</think>\\s*")},39541:(a,b,c)=>{"use strict";function d(a){if(!a||"object"!=typeof a)return null;let b=a.output_config?.effort;if("string"==typeof b&&b){let a=b.toLowerCase();return"none"===a||"off"===a?{mode:"none"}:"auto"===a?{mode:"auto"}:{mode:"level",level:a}}let c=a.thinking;if(c&&"object"==typeof c){if("disabled"===c.type)return{mode:"none"};if("adaptive"===c.type||"enabled"===c.type){let a=Number(c.budget_tokens);return Number.isFinite(a)&&a>0?{mode:"budget",budget:a}:{mode:"auto"}}}let d=a.reasoning_effort??("object"==typeof a.reasoning?a.reasoning?.effort:null);if("string"==typeof d&&d){let a=d.toLowerCase();return"none"===a||"off"===a?{mode:"none"}:"auto"===a?{mode:"auto"}:{mode:"level",level:a}}let e=a.thinkingConfig||a.generationConfig?.thinkingConfig||a.request?.generationConfig?.thinkingConfig;if(e&&"object"==typeof e){if("string"==typeof e.thinkingLevel)return{mode:"level",level:e.thinkingLevel.toLowerCase()};let a=Number(e.thinkingBudget);if(Number.isFinite(a))return 0===a?{mode:"none"}:a<0?{mode:"auto"}:{mode:"budget",budget:a}}if(!1===a.enable_thinking)return{mode:"none"};if(!0===a.enable_thinking){let b=Number(a.thinking_budget);return Number.isFinite(b)&&b>0?{mode:"budget",budget:b}:{mode:"auto"}}return null}c.d(b,{sS:()=>d}),c(49471),c(15251),c(26317)},39804:(a,b,c)=>{var d=c(45654);c(45518),c(27080);var e=a.exports=d.tls;function f(a,b,c){var f=b.entity===d.tls.ConnectionEnd.client;a.read.cipherState={init:!1,cipher:d.cipher.createDecipher("AES-CBC",f?c.keys.server_write_key:c.keys.client_write_key),iv:f?c.keys.server_write_IV:c.keys.client_write_IV},a.write.cipherState={init:!1,cipher:d.cipher.createCipher("AES-CBC",f?c.keys.client_write_key:c.keys.server_write_key),iv:f?c.keys.client_write_IV:c.keys.server_write_IV},a.read.cipherFunction=j,a.write.cipherFunction=g,a.read.macLength=a.write.macLength=c.mac_length,a.read.macFunction=a.write.macFunction=e.hmac_sha1}function g(a,b){var c,f=!1,g=b.macFunction(b.macKey,b.sequenceNumber,a);a.fragment.putBytes(g),b.updateSequenceNumber(),c=a.version.minor===e.Versions.TLS_1_0.minor?b.cipherState.init?null:b.cipherState.iv:d.random.getBytesSync(16),b.cipherState.init=!0;var i=b.cipherState.cipher;return i.start({iv:c}),a.version.minor>=e.Versions.TLS_1_1.minor&&i.output.putBytes(c),i.update(a.fragment),i.finish(h)&&(a.fragment=i.output,a.length=a.fragment.length(),f=!0),f}function h(a,b,c){if(!c){var d=a-b.length()%a;b.fillWithByte(d-1,d)}return!0}function i(a,b,c){var d=!0;if(c){for(var e=b.length(),f=b.last(),g=e-1-f;g<e-1;++g)d=d&&b.at(g)==f;d&&b.truncate(f+1)}return d}function j(a,b){var c,f,g,h,j,k=!1;j=a.version.minor===e.Versions.TLS_1_0.minor?b.cipherState.init?null:b.cipherState.iv:a.fragment.getBytes(16),b.cipherState.init=!0;var l=b.cipherState.cipher;l.start({iv:j}),l.update(a.fragment),k=l.finish(i);var m=b.macLength,n=d.random.getBytesSync(m),o=l.output.length();o>=m?(a.fragment=l.output.getBytes(o-m),n=l.output.getBytes(m)):a.fragment=l.output.getBytes(),a.fragment=d.util.createBuffer(a.fragment),a.length=a.fragment.length();var p=b.macFunction(b.macKey,b.sequenceNumber,a);return b.updateSequenceNumber(),k=(c=b.macKey,f=n,g=p,(h=d.hmac.create()).start("SHA1",c),h.update(f),f=h.digest().getBytes(),h.start(null,null),h.update(g),f===(g=h.digest().getBytes())&&k)}e.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA={id:[0,47],name:"TLS_RSA_WITH_AES_128_CBC_SHA",initSecurityParameters:function(a){a.bulk_cipher_algorithm=e.BulkCipherAlgorithm.aes,a.cipher_type=e.CipherType.block,a.enc_key_length=16,a.block_length=16,a.fixed_iv_length=16,a.record_iv_length=16,a.mac_algorithm=e.MACAlgorithm.hmac_sha1,a.mac_length=20,a.mac_key_length=20},initConnectionState:f},e.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA={id:[0,53],name:"TLS_RSA_WITH_AES_256_CBC_SHA",initSecurityParameters:function(a){a.bulk_cipher_algorithm=e.BulkCipherAlgorithm.aes,a.cipher_type=e.CipherType.block,a.enc_key_length=32,a.block_length=16,a.fixed_iv_length=16,a.record_iv_length=16,a.mac_algorithm=e.MACAlgorithm.hmac_sha1,a.mac_length=20,a.mac_key_length=20},initConnectionState:f}},40106:(a,b,c)=>{"use strict";let d=c(34589),e=c(77030),f=c(37067),g=c(84285),{ClientStats:h}=c(19071),{channels:i}=c(62571),j=c(76316),k=c(5318),{InvalidArgumentError:l,InformationalError:m,ClientDestroyedError:n}=c(61448),o=c(55285),{kUrl:p,kServerName:q,kClient:r,kBusy:s,kConnect:t,kResuming:u,kRunning:v,kPending:w,kSize:x,kQueue:y,kConnected:z,kConnecting:A,kNeedDrain:B,kKeepAliveDefaultTimeout:C,kHostHeader:D,kPendingIdx:E,kRunningIdx:F,kError:G,kPipelining:H,kKeepAliveTimeoutValue:I,kMaxHeadersSize:J,kKeepAliveMaxTimeout:K,kKeepAliveTimeoutThreshold:L,kHeadersTimeout:M,kBodyTimeout:N,kStrictContentLength:O,kConnector:P,kMaxRequests:Q,kCounter:R,kClose:S,kDestroy:T,kDispatch:U,kLocalAddress:V,kMaxResponseSize:W,kOnError:X,kHTTPContext:Y,kMaxConcurrentStreams:Z,kHostAuthority:$,kResume:_,kHTTP2Options:aa}=c(49176),ab=c(97678),ac=c(80985),ad=Symbol("kClosedResolve"),ae=f&&f.maxHeaderSize&&Number.isInteger(f.maxHeaderSize)&&f.maxHeaderSize>0?()=>f.maxHeaderSize:()=>{throw new l("http module not available or http.maxHeaderSize invalid")},af=()=>{},ag=!1;function ah(a){!0!==ag&&(process.emitWarning(`Use h2Options.${a} instead. ${a} for H2 will be deprecated in future major.`,{code:"UNDICI-H2-OPTIONS"}),ag=!0)}function ai(a){return a[Y]?.version==="h2"?a[Z]:a[H]??a[Y]?.defaultPipelining??1}class aj extends k{constructor(a,{maxHeaderSize:b,headersTimeout:c,socketTimeout:d,requestTimeout:f,connectTimeout:h,bodyTimeout:i,idleTimeout:j,keepAlive:k,keepAliveTimeout:m,maxKeepAliveTimeout:n,keepAliveMaxTimeout:r,keepAliveTimeoutThreshold:s,socketPath:t,pipelining:v,tls:w,strictContentLength:x,maxCachedSessions:z,connect:A,maxRequestsPerClient:G,localAddress:R,maxResponseSize:S,autoSelectFamily:T,autoSelectFamilyAttemptTimeout:U,maxConcurrentStreams:Z,allowH2:ab,useH2c:ac,initialWindowSize:af,connectionWindowSize:ag,pingInterval:ai,webSocket:aj,h2Options:al}={}){if(void 0!==k)throw new l("unsupported keepAlive, use pipelining=0 instead");if(void 0!==d)throw new l("unsupported socketTimeout, use headersTimeout & bodyTimeout instead");if(void 0!==f)throw new l("unsupported requestTimeout, use headersTimeout & bodyTimeout instead");if(void 0!==j)throw new l("unsupported idleTimeout, use keepAliveTimeout instead");if(void 0!==n)throw new l("unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead");if(null!=b){if(!Number.isInteger(b)||b<1)throw new l("invalid maxHeaderSize")}else b=ae();if(null!=t&&"string"!=typeof t)throw new l("invalid socketPath");if(null!=h&&(!Number.isFinite(h)||h<0))throw new l("invalid connectTimeout");if(null!=m&&(!Number.isFinite(m)||m<=0))throw new l("invalid keepAliveTimeout");if(null!=r&&(!Number.isFinite(r)||r<=0))throw new l("invalid keepAliveMaxTimeout");if(null!=s&&!Number.isFinite(s))throw new l("invalid keepAliveTimeoutThreshold");if(null!=c&&(!Number.isInteger(c)||c<0))throw new l("headersTimeout must be a positive integer or zero");if(null!=i&&(!Number.isInteger(i)||i<0))throw new l("bodyTimeout must be a positive integer or zero");if(null!=A&&"function"!=typeof A&&"object"!=typeof A)throw new l("connect must be a function or an object");if(null!=G&&(!Number.isInteger(G)||G<0))throw new l("maxRequestsPerClient must be a positive number");if(null!=R&&("string"!=typeof R||0===e.isIP(R)))throw new l("localAddress must be valid string IP address");if(null!=S&&(!Number.isInteger(S)||S<-1))throw new l("maxResponseSize must be a positive number");if(null!=U&&(!Number.isInteger(U)||U<-1))throw new l("autoSelectFamilyAttemptTimeout must be a positive number");if(null!=ab&&"boolean"!=typeof ab)throw new l("allowH2 must be a valid boolean value");if(!1!==ab)if(null!=al){if(null!=al.useH2c&&"boolean"!=typeof al.useH2c)throw new l("h2Options.useH2c must be a valid boolean value");if(al.settings?.initialWindowSize!=null&&(!Number.isInteger(al.settings.initialWindowSize)||al.settings.initialWindowSize<1))throw new l("h2Options.settings.initialWindowSize must be a positive integer, greater than 0");if(null!=al.maxConcurrentStreams&&(!Number.isInteger(al.connectionWindowSize)||al.maxConcurrentStreams<1))throw new l("h2Options.maxConcurrentStreams must be a positive integer, greater than 0");if(null!=al.connectionWindowSize&&(!Number.isInteger(al.connectionWindowSize)||al.connectionWindowSize<1))throw new l("h2Options.connectionWindowSize must be a positive integer, greater than 0");if(null!=al.pingInterval&&("number"!=typeof al.pingInterval||!Number.isInteger(al.pingInterval)||al.pingInterval<0))throw new l("h2Options.pingInterval must be a positive integer, greater or equal to 0")}else{if(null!=ac&&"boolean"!=typeof ac)throw ah("useH2c"),new l("useH2c must be a valid boolean value");if(null!=Z&&("number"!=typeof Z||Z<1))throw ah("maxConcurrentStreams"),new l("maxConcurrentStreams must be a positive integer, greater than 0");if(null!=af&&(!Number.isInteger(af)||af<1))throw ah("initialWindowSize"),new l("initialWindowSize must be a positive integer, greater than 0");if(null!=ag&&(!Number.isInteger(ag)||ag<1))throw ah("connectionWindowSize"),new l("connectionWindowSize must be a positive integer, greater than 0");if(null!=ai&&("number"!=typeof ai||!Number.isInteger(ai)||ai<0))throw ah("pingInterval"),new l("pingInterval must be a positive integer, greater or equal to 0")}if(super({webSocket:aj}),"function"!=typeof A)A=o({...w,maxCachedSessions:z,allowH2:ab,socketPath:t,useH2c:al?.useH2c??ac,timeout:h,..."boolean"==typeof T?{autoSelectFamily:T,autoSelectFamilyAttemptTimeout:U}:void 0,...A});else{const a=A;A=(b,c)=>a({...b,...null!=t?{socketPath:t}:null,...null!=ab?{allowH2:ab}:null},c)}this[p]=g.parseOrigin(a),this[$]=`${this[p].hostname}${this[p].port?`:${this[p].port}`:""}`,this[P]=A,this[H]=null!=v?v:1,this[J]=b,this[C]=null==m?4e3:m,this[K]=null==r?6e5:r,this[L]=null==s?2e3:s,this[I]=this[C],this[q]=null,this[V]=null!=R?R:null,this[u]=0,this[B]=0,this[D]=`host: ${this[$]}\r
|
|
187
|
+
`,this[N]=null!=i?i:3e5,this[M]=null!=c?c:3e5,this[O]=null==x||x,this[Q]=G,this[ad]=null,this[W]=S>-1?S:-1,this[Y]=null,this[aa]={pingInterval:al?.pingInterval??ai??6e4,connectionWindowSize:al?.connectionWindowSize??ag??524288,maxConcurrentStreams:al?.maxConcurrentStreams??Z??100,sessionOptions:{initialWindowSize:al?.initialWindowSize??af??262144}},this[y]=[],this[F]=0,this[E]=0,this[_]=a=>ao(this,a),this[X]=a=>ak(this,a)}get pipelining(){return this[H]}set pipelining(a){this[H]=a,this[_](!0)}get stats(){return new h(this)}get[w](){return this[y].length-this[E]}get[v](){return this[E]-this[F]}get[x](){return this[y].length-this[F]}get[z](){return!!this[Y]&&!this[A]&&!this[Y].destroyed}get[s](){let a=this[Y]?.version==="h2";return!!(this[Y]?.busy(null)||this[x]>=(ai(this)||1)||this[w]>0&&!a)}[t](a){al(this),this.once("connect",a)}[U](a,b){let c=new j(this[p].origin,a,b);return this[y].push(c),this[u]||(null==g.bodyLength(c.body)&&g.isIterable(c.body)?(this[u]=1,queueMicrotask(()=>ao(this))):this[_](!0)),this[u]&&2!==this[B]&&this[s]&&(this[B]=2),this[B]<2}[S](){return new Promise(a=>{this[x]?this[ad]=a:a(null)})}[T](a){return new Promise(b=>{let c=this[y].splice(this[E]);for(let b=0;b<c.length;b++){let d=c[b];null!=d&&g.errorRequest(this,d,a)}let d=()=>{this[ad]&&(this[ad](),this[ad]=null),b(null)};this[Y]?(this[Y].destroy(a,d),this[Y]=null):queueMicrotask(d),this[_]()})}}function ak(a,b){if(0===a[v]&&"UND_ERR_INFO"!==b.code&&"UND_ERR_SOCKET"!==b.code){d(a[E]===a[F]);let c=a[y].splice(a[F]);for(let d=0;d<c.length;d++){let e=c[d];null!=e&&g.errorRequest(a,e,b)}d(0===a[x])}}function al(a){d(!a[A]),d(!a[Y]);let{host:b,hostname:c,protocol:f,port:h}=a[p];if("["===c[0]){let a=c.indexOf("]");d(-1!==a);let b=c.substring(1,a);d(e.isIPv6(b)),c=b}a[A]=!0,i.beforeConnect.hasSubscribers&&i.beforeConnect.publish({connectParams:{host:b,hostname:c,protocol:f,port:h,version:a[Y]?.version,servername:a[q],localAddress:a[V]},connector:a[P]});try{a[P]({host:b,hostname:c,protocol:f,port:h,servername:a[q],localAddress:a[V]},(e,j)=>{if(e){am(a,e,{host:b,hostname:c,protocol:f,port:h}),a[_]();return}if(a.destroyed){g.destroy(j.on("error",af),new n),a[_]();return}d(j);try{a[Y]="h2"===j.alpnProtocol?ac(a,j):ab(a,j)}catch(d){j.destroy().on("error",af),am(a,d,{host:b,hostname:c,protocol:f,port:h}),a[_]();return}a[A]=!1,j[R]=0,j[Q]=a[Q],j[r]=a,j[G]=null,i.connected.hasSubscribers&&i.connected.publish({connectParams:{host:b,hostname:c,protocol:f,port:h,version:a[Y]?.version,servername:a[q],localAddress:a[V]},connector:a[P],socket:j}),a.emit("connect",a[p],[a]),a[_]()})}catch(d){am(a,d,{host:b,hostname:c,protocol:f,port:h}),a[_]()}}function am(a,b,{host:c,hostname:d,protocol:e,port:f}){if(!a.destroyed){if(a[A]=!1,i.connectError.hasSubscribers&&i.connectError.publish({connectParams:{host:c,hostname:d,protocol:e,port:f,version:a[Y]?.version,servername:a[q],localAddress:a[V]},connector:a[P],error:b}),"ERR_TLS_CERT_ALTNAME_INVALID"===b.code){let c=a[y].splice(a[F],a[v]);a[E]=a[F];for(let d=0;d<c.length;d++)g.errorRequest(a,c[d],b);for(;a[w]>0&&a[y][a[E]].servername===a[q];){let c=a[y].splice(a[E],1)[0];g.errorRequest(a,c,b)}}else ak(a,b);a.emit("connectionError",a[p],[a],b)}}function an(a){a[B]=0,a.emit("drain",a[p],[a])}function ao(a,b){2!==a[u]&&(a[u]=2,function(a,b){for(;;){if(a.destroyed)return void d(0===a[w]);if(a[ad]&&!a[x]){a[ad](),a[ad]=null;return}if(a[Y]&&a[Y].resume(),a[s])a[B]=2;else if(2===a[B]){b?(a[B]=1,queueMicrotask(()=>an(a))):an(a);continue}if(0===a[w]||a[v]>=(ai(a)||1))return;let c=a[y][a[E]];if(null===c)return;if("https:"===a[p].protocol&&a[q]!==c.servername){if(a[v]>0)return;a[q]=c.servername,a[Y]?.destroy(new m("servername changed"),()=>{a[Y]=null,ao(a)})}if(a[A])return;if(!a[Y]){a[q]=c.servername,al(a);return}if(a[Y].destroyed||a[Y].busy(c))return;!c.aborted&&a[Y].write(c)?a[E]++:a[y].splice(a[E],1)}}(a,b),a[u]=0,a[F]>256&&(a[y].splice(0,a[F]),a[E]-=a[F],a[F]=0))}a.exports=aj},40404:(a,b,c)=>{"use strict";c.d(b,{T:()=>u});var d=c(67671);let e=`You are Codex, based on GPT-5. You are running as a coding agent in the Codex CLI on a user's computer.
|
|
186
188
|
|
|
187
189
|
## General
|
|
188
190
|
|
|
@@ -298,9 +300,10 @@ You are producing plain text that will later be styled by the CLI. Follow these
|
|
|
298
300
|
* Optionally include line/column (1‑based): :line[:column] or #Lline[Ccolumn] (column defaults to 1).
|
|
299
301
|
* Do not use URIs like file://, vscode://, or https://.
|
|
300
302
|
* Do not provide range of lines
|
|
301
|
-
* Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\\repo\\project\\main.rs:12:5`;var f=c(38421),g=c(98976),h=c(10342),i=c(26408),j=c(13161),k=c(86363),l=c(49623),m=c(97137);let n=/^(rs|fc|resp|msg)_/,o=new Set(["image_generation","web_search","web_search_preview","file_search","computer","computer_use_preview","code_interpreter","mcp","local_shell","tool_search"]),p=new Set(["custom"]),q=new Set(["model","input","instructions","tools","tool_choice","stream","store","reasoning","service_tier","include","prompt_cache_key","client_metadata","text"]);class r extends d.Hv{constructor(){super("codex",f.xq.codex),this._currentSessionId=null}buildHeaders(a,b=!0){let c=super.buildHeaders(a,b);c.session_id=this._currentSessionId||a?.connectionId||"default",c.originator||(c.originator="codex_cli_rs");let d=a?.providerSpecificData?.workspaceId;return"string"==typeof d&&d&&!c["chatgpt-account-id"]&&(c["chatgpt-account-id"]=d),c}buildUrl(a,b,c=0,d=null){let e=super.buildUrl(a,b,c,d);return this._isCompact?`${e}/compact`:e}async refreshCredentials(a,b){return a?.refreshToken?(0,g.Vq)("codex",a,b):null}needsRefresh(a){return(0,g.fp)("codex",a)}async prefetchImages(a){if(Array.isArray(a?.input))for(let b of a.input){if(!Array.isArray(b.content))continue;let a=b.content.map(async a=>{if("image_url"!==a.type)return a;let b="string"==typeof a.image_url?a.image_url:a.image_url?.url,c=a.image_url?.detail||"auto";if(!b)return a;if(b.startsWith("data:"))return{type:"input_image",image_url:b,detail:c};let d=await (0,i.ni)(b,{timeoutMs:15e3});return{type:"input_image",image_url:d?.url||b,detail:c}});b.content=await Promise.all(a)}}async execute(a){let b=Array.isArray(a.body?.input)?a.body.input.reduce((a,b)=>a+(Array.isArray(b.content)?b.content.filter(a=>"image_url"===a.type).length:0),0):0,c=Array.isArray(a.body?.input)?a.body.input.length:0;if((0,k.s)("CODEX",`execute start | inputItems=${c} | images=${b} | session=${this._currentSessionId?"resolved":"pending"}`),b>0){let b=Date.now();await this.prefetchImages(a.body),(0,k.s)("CODEX",`prefetchImages done | ${Date.now()-b}ms`)}else await this.prefetchImages(a.body);return(0,m.v)({execute:()=>super.execute(a),retryConfig:this.config.retry,signal:a.signal,log:a.log,provider:"codex"})}parseError(a,b){if(429===a.status&&b)try{let a=JSON.parse(b),c=a?.error;if(c?.type==="usage_limit_reached"){let a=Date.now(),d=null;if("number"==typeof c.resets_at&&c.resets_at>0){let b=1e3*c.resets_at;b>a&&(d=b)}if(!d&&"number"==typeof c.resets_in_seconds&&c.resets_in_seconds>0&&(d=a+1e3*c.resets_in_seconds),d)return{status:429,message:c.message||b,resetsAtMs:d}}}catch{}return super.parseError(a,b)}transformRequest(a,b,c,d){this._isCompact=!!b._compact,delete b._compact,this._currentSessionId=(0,l.oV)({headers:d?.rawHeaders,body:b,connectionId:d?.connectionId,workspaceId:d?.providerSpecificData?.workspaceId,scope:"codex"});let f=(0,h.m)(b.input);if(f&&(b.input=f),(!b.input||Array.isArray(b.input)&&0===b.input.length)&&(b.input=[{type:"message",role:"user",content:[{type:"input_text",text:"..."}]}]),Array.isArray(b.input))for(let a of b.input)!(!a||"object"!=typeof a||Array.isArray(a))&&("system"!==a.role||a.type&&"message"!==a.type||(a.role="developer"));Array.isArray(b.input)&&(b.input=b.input.filter(a=>{if("string"==typeof a&&n.test(a))return!1;if(a&&"object"==typeof a&&!Array.isArray(a)){if("item_reference"===a.type)return!1;"string"==typeof a.id&&n.test(a.id)&&delete a.id}return!0})),function(a){if(!Array.isArray(a.tools))return;let b=new Set;if(a.tools=a.tools.filter(a=>{if(!a||"object"!=typeof a||Array.isArray(a))return!1;let c="string"==typeof a.type?a.type:"";if("namespace"===c){if(Array.isArray(a.tools))for(let c of a.tools){let a="string"==typeof c?.name?c.name.trim().slice(0,128):"";a&&b.add(a)}return!0}if("function"!==c)return!!p.has(c)||!!c&&!a.function&&"string"!=typeof a.name&&o.has(c);let d=a.function&&"object"==typeof a.function&&!Array.isArray(a.function)?a.function:null,e=("string"==typeof a.name?a.name:"string"==typeof d?.name?d.name:"").trim();if(!e)return!1;let f="string"==typeof a.description?a.description:"string"==typeof d?.description?d.description:"",g=a.parameters&&"object"==typeof a.parameters&&!Array.isArray(a.parameters)?a.parameters:d?.parameters&&"object"==typeof d.parameters&&!Array.isArray(d.parameters)?d.parameters:{type:"object",properties:{}};for(let b of Object.keys(a))delete a[b];return a.type="function",a.name=e.slice(0,128),f&&(a.description=f),a.parameters=g,b.add(e),!0}),a.tool_choice&&"object"==typeof a.tool_choice&&!Array.isArray(a.tool_choice)&&"function"===a.tool_choice.type){let c="string"==typeof a.tool_choice.name?a.tool_choice.name.trim():"";c&&b.has(c)||delete a.tool_choice}}(b),b.stream=!0,b.instructions&&""!==b.instructions.trim()||(b.instructions=e),b.store=!1,!b.prompt_cache_key&&this._currentSessionId&&(b.prompt_cache_key=this._currentSessionId),b.model=(0,j.kt)("cx",b.model||a);let g=null;for(let a of["none","low","medium","high","xhigh"])if(b.model.endsWith(`-${a}`)){g=a,b.model=b.model.replace(`-${a}`,"");break}if(b.reasoning)b.reasoning.summary||(b.reasoning.summary="auto");else{let a=b.reasoning_effort||g||"low";b.reasoning={effort:a,summary:"auto"}}for(let a of(delete b.reasoning_effort,b.reasoning&&b.reasoning.effort&&"none"!==b.reasoning.effort&&(b.include=["reasoning.encrypted_content"]),delete b.temperature,delete b.top_p,delete b.frequency_penalty,delete b.presence_penalty,delete b.logprobs,delete b.top_logprobs,delete b.n,delete b.seed,delete b.max_tokens,delete b.max_completion_tokens,delete b.max_output_tokens,delete b.user,delete b.prompt_cache_retention,delete b.metadata,delete b.stream_options,delete b.safety_identifier,delete b.previous_response_id,Object.keys(b)))q.has(a)||delete b[a];return b}}},37417:(a,b,c)=>{"use strict";let{InvalidArgumentError:d,MaxOriginsReachedError:e}=c(61448),{kBusy:f,kClients:g,kConnected:h,kRunning:i,kClose:j,kDestroy:k,kDispatch:l,kUrl:m}=c(49176),n=c(5318),o=c(35689),p=c(40106),q=c(84285),r=Symbol("onConnect"),s=Symbol("onDisconnect"),t=Symbol("onConnectionError"),u=Symbol("onDrain"),v=Symbol("factory"),w=Symbol("options"),x=Symbol("origins");function y(a,b){return b&&1===b.connections?new p(a,b):new o(a,b)}class z extends n{constructor({factory:a=y,maxOrigins:b=1/0,connect:c,...e}={}){if("function"!=typeof a)throw new d("factory must be a function.");if(null!=c&&"function"!=typeof c&&"object"!=typeof c)throw new d("connect must be a function or an object");if("number"!=typeof b||Number.isNaN(b)||b<=0)throw new d("maxOrigins must be a number greater than 0");super(e),c&&"function"!=typeof c&&(c={...c}),this[w]={...q.deepClone(e),maxOrigins:b,connect:c},this[v]=a,this[g]=new Map,this[x]=new Set,this[u]=(a,b)=>{this.emit("drain",a,[this,...b])},this[r]=(a,b)=>{this.emit("connect",a,[this,...b])},this[s]=(a,b,c)=>{this.emit("disconnect",a,[this,...b],c)},this[t]=(a,b,c)=>{this.emit("connectionError",a,[this,...b],c)}}get[i](){let a=0;for(let b of this[g].values())a+=b[i];return a}[l](a,b){let c;if(a.origin&&("string"==typeof a.origin||a.origin instanceof URL))c=String(a.origin);else throw new d("opts.origin must be a non-empty string or URL.");let i=a.allowH2??this[w].allowH2,j=!1===i?`${c}#http1-only`:c;if(this[x].size>=this[w].maxOrigins&&!this[x].has(c))throw new e;let k=this[g].get(j);if(!k){k=this[v](a.origin,!1===i?{...this[w],allowH2:!1}:this[w]);let b=()=>{if(this[g].get(j)!==k||k[h]>0||k[f])return;this[g].delete(j),k.destroyed||k.close();let a=!1;for(let b of this[g].keys())if(b===c||b===`${c}#http1-only`){a=!0;break}a||this[x].delete(c)};k.on("drain",this[u]).on("connect",this[r]).on("disconnect",(a,c,d)=>{b(),this[s](a,c,d)}).on("connectionError",(a,c,d)=>{b(),this[t](a,c,d)}),this[g].set(j,k),this[x].add(c)}return k.dispatch(a,b)}[j](){let a=[];for(let b of this[g].values())a.push(b.close());return this[g].clear(),Promise.all(a)}[k](a){let b=[];for(let c of this[g].values())b.push(c.destroy(a));return this[g].clear(),Promise.all(b)}get stats(){let a={};for(let b of this[g].values())b.stats&&(a[b[m].origin]=b.stats);return a}}a.exports=z},37436:(a,b,c)=>{"use strict";let d=c(29021),e=c(33873),f=c(21820),g="switchboard";function h(){return"win32"===process.platform?e.join(process.env.APPDATA||e.join(f.homedir(),"AppData","Roaming"),g):e.join(f.homedir(),`.${g}`)}let i=function(){let a=process.env.DATA_DIR;if(!a)return h();try{return d.mkdirSync(a,{recursive:!0}),a}catch(b){if(b?.code==="EACCES"||b?.code==="EPERM")return console.warn(`[DATA_DIR] '${a}' not writable → fallback ~/.${g}`),h();throw b}}(),j=e.join(i,"mitm");a.exports={DATA_DIR:i,MITM_DIR:j}},37606:(a,b,c)=>{"use strict";c.d(b,{Ay:()=>A});var d=c(67671),e=c(38421),f=c(19016),g=c(24725),h=c(50969);let i=e.xq["perplexity-web"].baseUrl,j="2.18",k={"pplx-auto":["concise","pplx_pro"],"pplx-sonar":["copilot","experimental"],"pplx-gpt":["copilot","gpt54"],"pplx-gemini":["copilot","gemini31pro_high"],"pplx-sonnet":["copilot","claude46sonnet"],"pplx-opus":["copilot","claude46opus"],"pplx-nemotron":["copilot","nv_nemotron_3_super"]},l={"pplx-gpt":"gpt54_thinking","pplx-sonnet":"claude46sonnetthinking","pplx-opus":"claude46opusthinking"},m=/\[\d+\]/g,n=/<grok:[^>]*>.*?<\/grok:[^>]*>/gs,o=/<grok:[^>]*\/>/g,p=/<[?]xml[^?]*[?]>/g,q=/<\/?response\b[^>]*>/gi,r=/ {2,}/g,s=/\n{3,}/g,t=new Map;function u(a){let b=a.map(a=>`${a.role}:${a.content}`).join("\n"),c=0x811c9dc5;for(let a=0;a<b.length;a++)c^=b.charCodeAt(a),c=0x1000193*c>>>0;return c.toString(16).padStart(8,"0")}function v(a,b,c,d){if(!d)return;let e=u([...a,{role:"user",content:b},{role:"assistant",content:c}]);if(t.set(e,{backendUuid:d,ts:Date.now()}),t.size>200){let a=null,b=1/0;for(let[c,d]of t)d.ts<b&&(b=d.ts,a=c);a&&t.delete(a)}}function w(a,b=!0){let c=a;return c=(c=(c=(c=(c=c.replace(p,"")).replace(m,"")).replace(n,"")).replace(o,"")).replace(q,""),b&&(c=(c=(c=c.replace(r," ")).replace(s,"\n\n")).trim()),c}async function*x(a,b){let c=a.getReader(),d=new TextDecoder,e="",f=[];function g(){if(0===f.length)return null;let a=f.join("\n");f=[];let b=a.trim();if(!b||"[DONE]"===b)return"done";try{return JSON.parse(b)}catch{return null}}try{for(;;){if(b?.aborted)return;let{value:a,done:h}=await c.read();if(h)break;for(e+=d.decode(a,{stream:!0});;){let a=e.indexOf("\n");if(a<0)break;let b=e.slice(0,a);e=e.slice(a+1);let c=b.endsWith("\r")?b.slice(0,-1):b;if(""===c){let a=g();if("done"===a)return;a&&(yield a);continue}if(c.startsWith("data:")&&f.push(c.slice(5).trimStart()),"event: end_of_stream"===c)return}}(e+=d.decode()).trim().startsWith("data:")&&f.push(e.trim().slice(5).trimStart());let a=g();a&&"done"!==a&&(yield a)}finally{c.releaseLock()}}async function*y(a,b){let c="",d=null,e=0,f=new Set;for await(let g of x(a,b)){if(g.error_code||g.error_message)return void(yield{error:g.error_message||`Perplexity error: ${g.error_code}`,done:!0});g.backend_uuid&&(d=g.backend_uuid);let a=g.blocks??[];for(let b of a){let a=b.intended_usage??"";if("pro_search_steps"===a&&b.plan_block?.steps){for(let a of b.plan_block.steps)if("SEARCH_WEB"===a.step_type)for(let b of a.search_web_content?.queries??[]){let a=b.query??"";a&&!f.has(a)&&(f.add(a),yield{thinking:`Searching: ${a}`,backendUuid:d??void 0})}else if("READ_RESULTS"===a.step_type)for(let b of(a.read_results_content?.urls??[]).slice(0,3))b&&!f.has(b)&&(f.add(b),yield{thinking:`Reading: ${b}`,backendUuid:d??void 0})}if("plan"===a&&b.plan_block?.goals)for(let a of b.plan_block.goals){let b=a.description??"";b&&!f.has(b)&&(f.add(b),yield{thinking:b,backendUuid:d??void 0})}if(!a.includes("markdown"))continue;let g=b.markdown_block;if(!g)continue;let h=g.chunks??[];if(0!==h.length)if("DONE"===g.progress)c=h.join("");else{let a=c+h.join("");if(a.length>e){let b=a.slice(e);c=a,e=a.length,yield{delta:b,answer:c,backendUuid:d??void 0}}}}if(0===a.length&&g.text){let a=g.text.trim();if(a.length>e){let b=a.slice(e);c=a,e=a.length,yield{delta:b,answer:c,backendUuid:d??void 0}}}if(g.final||"COMPLETED"===g.status)break}yield{delta:"",answer:c,backendUuid:d??void 0,done:!0}}async function z(a,b,c,d,e,f,g){let h="",i=null,j=[];for await(let b of y(a,g)){if(b.backendUuid&&(i=b.backendUuid),b.error)return new Response(JSON.stringify({error:{message:b.error,type:"upstream_error",code:"PPLX_ERROR"}}),{status:502,headers:{"Content-Type":"application/json"}});if(b.thinking){j.push(b.thinking);continue}if(b.done){h=b.answer||h;break}b.answer&&(h=b.answer)}v(e,f,h=w(h),i);let k=j.length>0?j.join("\n"):void 0,l={role:"assistant",content:h};k&&(l.reasoning_content=k);let m=Math.ceil(f.length/4),n=Math.ceil(h.length/4);return new Response(JSON.stringify({id:c,object:"chat.completion",created:d,model:b,system_fingerprint:null,choices:[{index:0,message:l,finish_reason:"stop",logprobs:null}],usage:{prompt_tokens:m,completion_tokens:n,total_tokens:m+n}}),{status:200,headers:{"Content-Type":"application/json"}})}class A extends d.Hv{constructor(){super("perplexity-web",e.xq["perplexity-web"])}async execute({model:a,body:b,stream:c,credentials:d,signal:e,log:m,proxyOptions:n=null}){var o,p,q,r,s;let x,A,B,C,D,E=b?.messages;if(!E||!Array.isArray(E)||0===E.length)return{response:new Response(JSON.stringify({error:{message:"Missing or empty messages array",type:"invalid_request"}}),{status:400,headers:{"Content-Type":"application/json"}}),url:i,headers:{},transformedBody:b};(b?.thinking===!0||b?.reasoning_effort!=null&&"none"!==b.reasoning_effort)&&l[a]?(x="copilot",A=l[a],m?.info?.("PPLX-WEB",`Thinking mode → ${a} using ${A}`)):k[a]?[x,A]=k[a]:(x="copilot",A=a,m?.info?.("PPLX-WEB",`Unmapped model ${a}, using as raw preference`));let F=function(a){let b="",c=[];for(let d of a){let a=String(d.role||"user");"developer"===a&&(a="system");let e="";"string"==typeof d.content?e=d.content:Array.isArray(d.content)&&(e=d.content.filter(a=>"text"===a.type).map(a=>String(a.text||"")).join(" ")),e.trim()&&("system"===a?b+=e+"\n":("user"===a||"assistant"===a)&&c.push({role:a,content:e}))}let d="";return c.length>0&&"user"===c[c.length-1].role&&(d=c.pop().content),{systemMsg:b,history:c,currentMsg:d}}(E),G=function(a){if(0===a.length)return null;let b=u(a),c=t.get(b);return c?Date.now()-c.ts>36e5?(t.delete(b),null):c.backendUuid:null}(F.history);G&&m?.info?.("PPLX-WEB",`Session continue: ${G.slice(0,12)}...`);let H=function(a,b,c){if(b)return a.currentMsg;let d={},e=[];a.systemMsg.trim()&&e.push(a.systemMsg.trim());let f=function(a){if(!Array.isArray(a)||0===a.length)return"";let b=a.map(a=>{let b=a?.function||a||{},c=b.name||"unnamed",d=(b.description||"").split("\n")[0].slice(0,200);return`- ${c}: ${d}`});return`Available tools (reference only, cannot invoke):
|
|
302
|
-
${b.join("\n")}`}(c);f&&e.push(f),e.push("You have built-in web search. Answer questions directly using search results."),d.instructions=e,a.history.length>0&&(d.history=a.history),a.currentMsg?d.query=a.currentMsg:0===a.history.length&&(d.query="");let g=JSON.stringify(d);return g.length>96e3?g.slice(-96e3):g}(F,G,b?.tools);if(!H.trim())return{response:new Response(JSON.stringify({error:{message:"Empty query after processing",type:"invalid_request"}}),{status:400,headers:{"Content-Type":"application/json"}}),url:i,headers:{},transformedBody:b};let I=(o=x,p=A,D="u">typeof Intl?Intl.DateTimeFormat().resolvedOptions().timeZone:"UTC",{query_str:H,params:{query_str:H,search_focus:"internet",mode:o,model_preference:p,sources:["web"],attachments:[],frontend_uuid:crypto.randomUUID(),frontend_context_uuid:crypto.randomUUID(),version:j,language:"en-US",timezone:D,search_recency_filter:null,is_incognito:!0,use_schematized_api:!0,last_backend_uuid:G}}),J={"Content-Type":"application/json",Accept:"text/event-stream",Origin:"https://www.perplexity.ai",Referer:"https://www.perplexity.ai/","User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36","X-App-ApiClient":"default","X-App-ApiVersion":j};d.accessToken?J.Authorization=`Bearer ${d.accessToken}`:d.apiKey&&(J.Cookie=`__Secure-next-auth.session-token=${d.apiKey}`),m?.info?.("PPLX-WEB",`Query to ${a} (pref=${A}, mode=${x}), len=${H.length}`);let K={method:"POST",headers:J,body:JSON.stringify(I),identity:this.config.identity,provider:this.provider,format:this.config.format};e&&(K.signal=e);try{B=await (0,h.Fm)(i,K,n)}catch(a){return m?.error?.("PPLX-WEB",`Fetch failed: ${a.message||String(a)}`),{response:new Response(JSON.stringify({error:{message:`Perplexity connection failed: ${a.message||String(a)}`,type:"upstream_error"}}),{status:502,headers:{"Content-Type":"application/json"}}),url:i,headers:J,transformedBody:I}}if(!B.ok){let a=B.status,b=`Perplexity returned HTTP ${a}`;return 401===a||403===a?b="Perplexity auth failed — session cookie may be expired. Re-paste your __Secure-next-auth.session-token.":429===a&&(b="Perplexity rate limited. Wait a moment and retry."),m?.warn?.("PPLX-WEB",b),{response:new Response(JSON.stringify({error:{message:b,type:"upstream_error",code:`HTTP_${a}`}}),{status:a,headers:{"Content-Type":"application/json"}}),url:i,headers:J,transformedBody:I}}if(!B.body)return{response:new Response(JSON.stringify({error:{message:"Perplexity returned empty response body",type:"upstream_error"}}),{status:502,headers:{"Content-Type":"application/json"}}),url:i,headers:J,transformedBody:I};let L=`chatcmpl-pplx-${crypto.randomUUID().slice(0,12)}`,M=Math.floor(Date.now()/1e3);if(c){let b;C=new Response((q=B.body,r=F.history,s=F.currentMsg,b=new TextEncoder,new ReadableStream({async start(c){try{c.enqueue(b.encode((0,g.N)({id:L,object:"chat.completion.chunk",created:M,model:a,system_fingerprint:null,choices:[{index:0,delta:{role:"assistant"},finish_reason:null,logprobs:null}]})));let d="",h=null;for await(let f of y(q,e)){if(f.backendUuid&&(h=f.backendUuid),f.error){c.enqueue(b.encode((0,g.N)({id:L,object:"chat.completion.chunk",created:M,model:a,system_fingerprint:null,choices:[{index:0,delta:{content:`[Error: ${f.error}]`},finish_reason:null,logprobs:null}]})));break}if(f.thinking){c.enqueue(b.encode((0,g.N)({id:L,object:"chat.completion.chunk",created:M,model:a,system_fingerprint:null,choices:[{index:0,delta:{reasoning_content:f.thinking+"\n"},finish_reason:null,logprobs:null}]})));continue}if(f.done){d=f.answer||d;break}let e=f.delta||"";e&&(e=w(e,!1))&&c.enqueue(b.encode((0,g.N)({id:L,object:"chat.completion.chunk",created:M,model:a,system_fingerprint:null,choices:[{index:0,delta:{content:e},finish_reason:null,logprobs:null}]}))),f.answer&&(d=f.answer)}c.enqueue(b.encode((0,g.N)({id:L,object:"chat.completion.chunk",created:M,model:a,system_fingerprint:null,choices:[{index:0,delta:{},finish_reason:"stop",logprobs:null}]}))),c.enqueue(b.encode(f.$U)),v(r,s,w(d),h)}catch(d){c.enqueue(b.encode((0,g.N)({id:L,object:"chat.completion.chunk",created:M,model:a,system_fingerprint:null,choices:[{index:0,delta:{content:`[Stream error: ${d.message||String(d)}]`},finish_reason:"stop",logprobs:null}]}))),c.enqueue(b.encode(f.$U))}finally{c.close()}}})),{status:200,headers:{...f.uB}})}else C=await z(B.body,a,L,M,F.history,F.currentMsg,e);return{response:C,url:i,headers:J,transformedBody:I}}}},37691:(a,b,c)=>{var d=c(45654);c(1277),c(33889);var e=a.exports=d.sha512=d.sha512||{};d.md.sha512=d.md.algorithms.sha512=e;var f=d.sha384=d.sha512.sha384=d.sha512.sha384||{};f.create=function(){return e.create("SHA-384")},d.md.sha384=d.md.algorithms.sha384=f,d.sha512.sha256=d.sha512.sha256||{create:function(){return e.create("SHA-512/256")}},d.md["sha512/256"]=d.md.algorithms["sha512/256"]=d.sha512.sha256,d.sha512.sha224=d.sha512.sha224||{create:function(){return e.create("SHA-512/224")}},d.md["sha512/224"]=d.md.algorithms["sha512/224"]=d.sha512.sha224,e.create=function(a){if(h||(g=String.fromCharCode(128)+d.util.fillString("\0",128),i=[[0x428a2f98,0xd728ae22],[0x71374491,0x23ef65cd],[0xb5c0fbcf,0xec4d3b2f],[0xe9b5dba5,0x8189dbbc],[0x3956c25b,0xf348b538],[0x59f111f1,0xb605d019],[0x923f82a4,0xaf194f9b],[0xab1c5ed5,0xda6d8118],[0xd807aa98,0xa3030242],[0x12835b01,0x45706fbe],[0x243185be,0x4ee4b28c],[0x550c7dc3,0xd5ffb4e2],[0x72be5d74,0xf27b896f],[0x80deb1fe,0x3b1696b1],[0x9bdc06a7,0x25c71235],[0xc19bf174,0xcf692694],[0xe49b69c1,0x9ef14ad2],[0xefbe4786,0x384f25e3],[0xfc19dc6,0x8b8cd5b5],[0x240ca1cc,0x77ac9c65],[0x2de92c6f,0x592b0275],[0x4a7484aa,0x6ea6e483],[0x5cb0a9dc,0xbd41fbd4],[0x76f988da,0x831153b5],[0x983e5152,0xee66dfab],[0xa831c66d,0x2db43210],[0xb00327c8,0x98fb213f],[0xbf597fc7,0xbeef0ee4],[0xc6e00bf3,0x3da88fc2],[0xd5a79147,0x930aa725],[0x6ca6351,0xe003826f],[0x14292967,0xa0e6e70],[0x27b70a85,0x46d22ffc],[0x2e1b2138,0x5c26c926],[0x4d2c6dfc,0x5ac42aed],[0x53380d13,0x9d95b3df],[0x650a7354,0x8baf63de],[0x766a0abb,0x3c77b2a8],[0x81c2c92e,0x47edaee6],[0x92722c85,0x1482353b],[0xa2bfe8a1,0x4cf10364],[0xa81a664b,0xbc423001],[0xc24b8b70,0xd0f89791],[0xc76c51a3,0x654be30],[0xd192e819,0xd6ef5218],[0xd6990624,0x5565a910],[0xf40e3585,0x5771202a],[0x106aa070,0x32bbd1b8],[0x19a4c116,0xb8d2d0c8],[0x1e376c08,0x5141ab53],[0x2748774c,0xdf8eeb99],[0x34b0bcb5,0xe19b48a8],[0x391c0cb3,0xc5c95a63],[0x4ed8aa4a,0xe3418acb],[0x5b9cca4f,0x7763e373],[0x682e6ff3,0xd6b2b8a3],[0x748f82ee,0x5defb2fc],[0x78a5636f,0x43172f60],[0x84c87814,0xa1f0ab72],[0x8cc70208,0x1a6439ec],[0x90befffa,0x23631e28],[0xa4506ceb,0xde82bde9],[0xbef9a3f7,0xb2c67915],[0xc67178f2,0xe372532b],[0xca273ece,0xea26619c],[0xd186b8c7,0x21c0c207],[0xeada7dd6,0xcde0eb1e],[0xf57d4f7f,0xee6ed178],[0x6f067aa,0x72176fba],[0xa637dc5,0xa2c898a6],[0x113f9804,0xbef90dae],[0x1b710b35,0x131c471b],[0x28db77f5,0x23047d84],[0x32caab7b,0x40c72493],[0x3c9ebe0a,0x15c9bebc],[0x431d67c4,0x9c100d4c],[0x4cc5d4be,0xcb3e42b6],[0x597f299c,0xfc657e2a],[0x5fcb6fab,0x3ad6faec],[0x6c44198c,0x4a475817]],(j={})["SHA-512"]=[[0x6a09e667,0xf3bcc908],[0xbb67ae85,0x84caa73b],[0x3c6ef372,0xfe94f82b],[0xa54ff53a,0x5f1d36f1],[0x510e527f,0xade682d1],[0x9b05688c,0x2b3e6c1f],[0x1f83d9ab,0xfb41bd6b],[0x5be0cd19,0x137e2179]],j["SHA-384"]=[[0xcbbb9d5d,0xc1059ed8],[0x629a292a,0x367cd507],[0x9159015a,0x3070dd17],[0x152fecd8,0xf70e5939],[0x67332667,0xffc00b31],[0x8eb44a87,0x68581511],[0xdb0c2e0d,0x64f98fa7],[0x47b5481d,0xbefa4fa4]],j["SHA-512/256"]=[[0x22312194,0xfc2bf72c],[0x9f555fa3,0xc84c64c2],[0x2393b86b,0x6f53b151],[0x96387719,0x5940eabd],[0x96283ee2,0xa88effe3],[0xbe5e1e25,0x53863992],[0x2b0199fc,0x2c85b8aa],[0xeb72ddc,0x81c52ca2]],j["SHA-512/224"]=[[0x8c3d37c8,0x19544da2],[0x73e19966,0x89dcd4d6],[0x1dfab7ae,0x32ff9c82],[0x679dd514,0x582f9fcf],[0xf6d2b69,0x7bd44da8],[0x77e36f73,0x4c48942],[0x3f9d85a8,0x6a1d36c8],[0x1112e6ad,0x91d692a1]],h=!0),void 0===a&&(a="SHA-512"),!(a in j))throw Error("Invalid SHA-512 algorithm: "+a);for(var b=j[a],c=null,e=d.util.createBuffer(),f=Array(80),l=0;l<80;++l)f[l]=[,,];var m=64;switch(a){case"SHA-384":m=48;break;case"SHA-512/256":m=32;break;case"SHA-512/224":m=28}var n={algorithm:a.replace("-","").toLowerCase(),blockLength:128,digestLength:m,messageLength:0,fullMessageLength:null,messageLengthSize:16};return n.start=function(){n.messageLength=0,n.fullMessageLength=n.messageLength128=[];for(var a=n.messageLengthSize/4,f=0;f<a;++f)n.fullMessageLength.push(0);e=d.util.createBuffer(),c=Array(b.length);for(var f=0;f<b.length;++f)c[f]=b[f].slice(0);return n},n.start(),n.update=function(a,b){"utf8"===b&&(a=d.util.encodeUtf8(a));var g=a.length;n.messageLength+=g,g=[g/0x100000000>>>0,g>>>0];for(var h=n.fullMessageLength.length-1;h>=0;--h)n.fullMessageLength[h]+=g[1],g[1]=g[0]+(n.fullMessageLength[h]/0x100000000>>>0),n.fullMessageLength[h]=n.fullMessageLength[h]>>>0,g[0]=g[1]/0x100000000>>>0;return e.putBytes(a),k(c,f,e),(e.read>2048||0===e.length())&&e.compact(),n},n.digest=function(){var b,h,i=d.util.createBuffer();i.putBytes(e.bytes());var j=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize&n.blockLength-1;i.putBytes(g.substr(0,n.blockLength-j));for(var l=8*n.fullMessageLength[0],m=0;m<n.fullMessageLength.length-1;++m)l+=(b=8*n.fullMessageLength[m+1])/0x100000000>>>0,i.putInt32(l>>>0),l=b>>>0;i.putInt32(l);for(var o=Array(c.length),m=0;m<c.length;++m)o[m]=c[m].slice(0);k(o,f,i);var p=d.util.createBuffer();h="SHA-512"===a?o.length:"SHA-384"===a?o.length-2:o.length-4;for(var m=0;m<h;++m)p.putInt32(o[m][0]),(m!==h-1||"SHA-512/224"!==a)&&p.putInt32(o[m][1]);return p},n};var g=null,h=!1,i=null,j=null;function k(a,b,c){for(var d,e,f,g,h,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N=c.length();N>=128;){for(G=0;G<16;++G)b[G][0]=c.getInt32()>>>0,b[G][1]=c.getInt32()>>>0;for(;G<80;++G)d=(((H=(J=b[G-2])[0])>>>19|(I=J[1])<<13)^(I>>>29|H<<3)^H>>>6)>>>0,e=((H<<13|I>>>19)^(I<<3|H>>>29)^(H<<26|I>>>6))>>>0,f=(((H=(L=b[G-15])[0])>>>1|(I=L[1])<<31)^(H>>>8|I<<24)^H>>>7)>>>0,g=((H<<31|I>>>1)^(H<<24|I>>>8)^(H<<25|I>>>7))>>>0,K=b[G-7],M=b[G-16],I=e+K[1]+g+M[1],b[G][0]=d+K[0]+f+M[0]+(I/0x100000000>>>0)>>>0,b[G][1]=I>>>0;for(q=a[0][0],r=a[0][1],s=a[1][0],t=a[1][1],u=a[2][0],v=a[2][1],w=a[3][0],x=a[3][1],y=a[4][0],z=a[4][1],A=a[5][0],B=a[5][1],C=a[6][0],D=a[6][1],E=a[7][0],F=a[7][1],G=0;G<80;++G)k=((y>>>14|z<<18)^(y>>>18|z<<14)^(z>>>9|y<<23))>>>0,l=((y<<18|z>>>14)^(y<<14|z>>>18)^(z<<23|y>>>9))>>>0,m=(C^y&(A^C))>>>0,n=(D^z&(B^D))>>>0,h=((q>>>28|r<<4)^(r>>>2|q<<30)^(r>>>7|q<<25))>>>0,j=((q<<4|r>>>28)^(r<<30|q>>>2)^(r<<25|q>>>7))>>>0,o=(q&s|u&(q^s))>>>0,p=(r&t|v&(r^t))>>>0,I=F+l+n+i[G][1]+b[G][1],d=E+k+m+i[G][0]+b[G][0]+(I/0x100000000>>>0)>>>0,e=I>>>0,f=h+o+((I=j+p)/0x100000000>>>0)>>>0,g=I>>>0,E=C,F=D,C=A,D=B,A=y,B=z,y=w+d+((I=x+e)/0x100000000>>>0)>>>0,z=I>>>0,w=u,x=v,u=s,v=t,s=q,t=r,q=d+f+((I=e+g)/0x100000000>>>0)>>>0,r=I>>>0;I=a[0][1]+r,a[0][0]=a[0][0]+q+(I/0x100000000>>>0)>>>0,a[0][1]=I>>>0,I=a[1][1]+t,a[1][0]=a[1][0]+s+(I/0x100000000>>>0)>>>0,a[1][1]=I>>>0,I=a[2][1]+v,a[2][0]=a[2][0]+u+(I/0x100000000>>>0)>>>0,a[2][1]=I>>>0,I=a[3][1]+x,a[3][0]=a[3][0]+w+(I/0x100000000>>>0)>>>0,a[3][1]=I>>>0,I=a[4][1]+z,a[4][0]=a[4][0]+y+(I/0x100000000>>>0)>>>0,a[4][1]=I>>>0,I=a[5][1]+B,a[5][0]=a[5][0]+A+(I/0x100000000>>>0)>>>0,a[5][1]=I>>>0,I=a[6][1]+D,a[6][0]=a[6][0]+C+(I/0x100000000>>>0)>>>0,a[6][1]=I>>>0,I=a[7][1]+F,a[7][0]=a[7][0]+E+(I/0x100000000>>>0)>>>0,a[7][1]=I>>>0,N-=128}}},37703:(a,b,c)=>{"use strict";c.d(b,{getMitmAlias:()=>h,o5:()=>g}),c(24081);var d=c(58609);let e=(0,d.U)("modelAliases");(0,d.U)("customModels");let f=(0,d.U)("mitmAlias");async function g(a,b){await e.set(a,b)}async function h(a){return a?await f.get(a)||{}:await f.getAll()}},37858:(a,b,c)=>{"use strict";let{createInflate:d,createGunzip:e,createBrotliDecompress:f,createZstdDecompress:g}=c(38522),{pipeline:h}=c(57075),i=c(60823),j={gzip:e,"x-gzip":e,br:f,deflate:d,compress:d,"x-compress":d,zstd:g},k=[204,304],l=!1;class m extends i{#V=[];#W;#X;#Y;constructor(a,{skipStatusCodes:b=k,skipErrorResponses:c=!0}={}){super(a),this.#X=b,this.#Y=c}#Z(a,b){return!!(!a||b<200||this.#X.includes(b))||!!this.#Y&&!!(b>=400)}#$(a){let b=a.split(",");if(b.length>5)throw Error(`too many content-encodings in response: ${b.length}, maximum allowed is 5`);let c=[];for(let a=b.length-1;a>=0;a--){let d=b[a].trim();if(d){if(!j[d])return c.length=0,c;c.push(j[d]())}}return c}#_(a,b){a.on("readable",()=>{let c;for(;null!==(c=a.read())&&!1!==super.onResponseData(b,c););}),a.on("error",a=>{super.onResponseError(b,a)})}#aa(a){let b=this.#V[0];this.#_(b,a),b.on("end",()=>{super.onResponseEnd(a,this.#W)})}#ab(a){let b=this.#V[this.#V.length-1];this.#_(b,a),h(this.#V,b=>{b?super.onResponseError(a,b):super.onResponseEnd(a,this.#W)})}#ac(){this.#V.length=0}onResponseStart(a,b,c,d){let e=c["content-encoding"];if(this.#Z(e,b))return super.onResponseStart(a,b,c,d);let f=this.#$(e.toLowerCase());if(0===f.length)return this.#ac(),super.onResponseStart(a,b,c,d);this.#V=f;let{"content-encoding":g,"content-length":h,...i}=c;if(a?.rawHeaders){let b=a.rawHeaders;if(Array.isArray(b)){let c=[];for(let a=0;a<b.length;a+=2){let d=b[a],e=(Buffer.isBuffer(d)?d.toString("latin1"):`${d}`).toLowerCase();"content-encoding"!==e&&"content-length"!==e&&c.push(b[a],b[a+1])}a.rawHeaders=c}else if("object"==typeof b)for(let a of Object.keys(b)){let c=a.toLowerCase();("content-encoding"===c||"content-length"===c)&&delete b[a]}}return 1===this.#V.length?this.#aa(a):this.#ab(a),super.onResponseStart(a,b,i,d)}onResponseData(a,b){this.#V.length>0?this.#V[0].write(b):super.onResponseData(a,b)}onResponseEnd(a,b){if(this.#V.length>0){this.#W=b,this.#V[0].end(),this.#ac();return}super.onResponseEnd(a,b)}onResponseError(a,b){if(this.#V.length>0){for(let a of this.#V)a.destroy(b);this.#ac()}super.onResponseError(a,b)}}a.exports=function(a={}){return l||(process.emitWarning("DecompressInterceptor is experimental and subject to change","ExperimentalWarning"),l=!0),b=>(c,d)=>"HEAD"===c.method?b(c,d):b(c,new m(d,a))}},38421:(a,b,c)=>{"use strict";c.d(b,{Ak:()=>e,Yg:()=>h,sr:()=>d.sr,xq:()=>d.xq});var d=c(15251);function e(a){return(a?.providerSpecificData?.baseUrl?.trim()||"http://localhost:11434").replace(/\/$/,"")}let f=d.xq["xiaomi-tokenplan"]?.regions||{},g=d.xq["xiaomi-tokenplan"]?.defaultRegion;function h(a){return f[a?.providerSpecificData?.region]||f[g]}},38528:(a,b,c)=>{"use strict";c.d(b,{IQ:()=>h,U:()=>f,eZ:()=>g,gD:()=>i,u9:()=>j});var d=c(15251),e=c(50969);let f=a=>d.xq[a]?.usage||{};function g(a){if(!a)return null;try{if(a instanceof Date)return a.toISOString();if("number"==typeof a)return new Date(a<1e12?1e3*a:a).toISOString();if("string"==typeof a){if(/^\d+$/.test(a)){let b=Number(a);return new Date(b<1e12?1e3*b:b).toISOString()}return new Date(a).toISOString()}return null}catch(b){return console.warn(`Failed to parse reset time: ${a}`,b),null}}function h(a,b=0){if("number"==typeof a&&Number.isFinite(a))return a;if("string"==typeof a&&a.trim()){let b=Number(a);if(Number.isFinite(b))return b}return b}function i(a){return"string"==typeof a?a.trim()||null:a&&"object"==typeof a&&"string"==typeof a.id&&a.id.trim()||null}async function j(a,b,c=1e4,d=null){let f=new AbortController,g=setTimeout(()=>f.abort(),c);try{return await (0,e.Fm)(a,{...b,signal:f.signal},d)}finally{clearTimeout(g)}}},38627:(a,b,c)=>{var d=c(45654);c(1277),c(33889);var e=a.exports=d.md5=d.md5||{};d.md.md5=d.md.algorithms.md5=e,e.create=function(){j||function(){f=String.fromCharCode(128)+d.util.fillString("\0",64),g=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1,6,11,0,5,10,15,4,9,14,3,8,13,2,7,12,5,8,11,14,1,4,7,10,13,0,3,6,9,12,15,2,0,7,14,5,12,3,10,1,8,15,6,13,4,11,2,9],h=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],i=Array(64);for(var a=0;a<64;++a)i[a]=Math.floor(0x100000000*Math.abs(Math.sin(a+1)));j=!0}();var a=null,b=d.util.createBuffer(),c=Array(16),e={algorithm:"md5",blockLength:64,digestLength:16,messageLength:0,fullMessageLength:null,messageLengthSize:8};return e.start=function(){e.messageLength=0,e.fullMessageLength=e.messageLength64=[];for(var c=e.messageLengthSize/4,f=0;f<c;++f)e.fullMessageLength.push(0);return b=d.util.createBuffer(),a={h0:0x67452301,h1:0xefcdab89,h2:0x98badcfe,h3:0x10325476},e},e.start(),e.update=function(f,g){"utf8"===g&&(f=d.util.encodeUtf8(f));var h=f.length;e.messageLength+=h,h=[h/0x100000000>>>0,h>>>0];for(var i=e.fullMessageLength.length-1;i>=0;--i)e.fullMessageLength[i]+=h[1],h[1]=h[0]+(e.fullMessageLength[i]/0x100000000>>>0),e.fullMessageLength[i]=e.fullMessageLength[i]>>>0,h[0]=h[1]/0x100000000>>>0;return b.putBytes(f),k(a,c,b),(b.read>2048||0===b.length())&&b.compact(),e},e.digest=function(){var g=d.util.createBuffer();g.putBytes(b.bytes());var h=e.fullMessageLength[e.fullMessageLength.length-1]+e.messageLengthSize&e.blockLength-1;g.putBytes(f.substr(0,e.blockLength-h));for(var i,j=0,l=e.fullMessageLength.length-1;l>=0;--l)j=(i=8*e.fullMessageLength[l]+j)/0x100000000>>>0,g.putInt32Le(i>>>0);var m={h0:a.h0,h1:a.h1,h2:a.h2,h3:a.h3};k(m,c,g);var n=d.util.createBuffer();return n.putInt32Le(m.h0),n.putInt32Le(m.h1),n.putInt32Le(m.h2),n.putInt32Le(m.h3),n},e};var f=null,g=null,h=null,i=null,j=!1;function k(a,b,c){for(var d,e,f,j,k,l,m,n,o=c.length();o>=64;){for(e=a.h0,f=a.h1,j=a.h2,k=a.h3,n=0;n<16;++n)b[n]=c.getInt32Le(),d=e+(k^f&(j^k))+i[n]+b[n],m=h[n],e=k,k=j,j=f,f+=d<<m|d>>>32-m;for(;n<32;++n)d=e+(j^k&(f^j))+i[n]+b[g[n]],m=h[n],e=k,k=j,j=f,f+=d<<m|d>>>32-m;for(;n<48;++n)d=e+(f^j^k)+i[n]+b[g[n]],m=h[n],e=k,k=j,j=f,f+=d<<m|d>>>32-m;for(;n<64;++n)d=e+(j^(f|~k))+i[n]+b[g[n]],m=h[n],e=k,k=j,j=f,f+=d<<m|d>>>32-m;a.h0=a.h0+e|0,a.h1=a.h1+f|0,a.h2=a.h2+j|0,a.h3=a.h3+k|0,o-=64}}},38650:(a,b,c)=>{"use strict";let{Writable:d}=c(57075),{EventEmitter:e}=c(78474),{assertCacheKey:f,assertCacheValue:g}=c(79468);class h extends e{#h=1024;#ad=0x6400000;#g=5242880;#ae=0;#af=0;#ag=new Map;#ah=!1;constructor(a){if(super(),a){if("object"!=typeof a)throw TypeError("MemoryCacheStore options must be an object");if(void 0!==a.maxCount){if("number"!=typeof a.maxCount||!Number.isInteger(a.maxCount)||a.maxCount<0)throw TypeError("MemoryCacheStore options.maxCount must be a non-negative integer");this.#h=a.maxCount}if(void 0!==a.maxSize){if("number"!=typeof a.maxSize||!Number.isInteger(a.maxSize)||a.maxSize<0)throw TypeError("MemoryCacheStore options.maxSize must be a non-negative integer");this.#ad=a.maxSize}if(void 0!==a.maxEntrySize){if("number"!=typeof a.maxEntrySize||!Number.isInteger(a.maxEntrySize)||a.maxEntrySize<0)throw TypeError("MemoryCacheStore options.maxEntrySize must be a non-negative integer");this.#g=a.maxEntrySize}}}get size(){return this.#ae}isFull(){return this.#ae>=this.#ad||this.#af>=this.#h}get(a){f(a);let b=`${a.origin}:${a.path}`,c=Date.now(),d=this.#ag.get(b),e=d?i(a,d,c):null;return null==e?void 0:{statusMessage:e.statusMessage,statusCode:e.statusCode,headers:e.headers,body:e.body,vary:e.vary?e.vary:void 0,etag:e.etag,cacheControlDirectives:e.cacheControlDirectives,cachedAt:e.cachedAt,staleAt:e.staleAt,deleteAt:e.deleteAt}}createWriteStream(a,b){f(a),g(b);let c=`${a.origin}:${a.path}`,e=this,h={...a,...b,body:[],size:0};return new d({write(a,b,c){"string"==typeof a&&(a=Buffer.from(a,b)),h.size+=a.byteLength,h.size>e.#g?this.destroy():h.body.push(a),c(null)},final(b){let d=e.#ag.get(c);d||(d=[],e.#ag.set(c,d));let f=i(a,d,Date.now());if(f){let a=d.indexOf(f);d.splice(a,1,h),e.#ae-=f.size}else d.push(h),e.#af+=1;if(e.#ae+=h.size,e.#ae>e.#ad||e.#af>e.#h){for(let[a,b]of(e.#ah||(e.emit("maxSizeExceeded",{size:e.#ae,maxSize:e.#ad,count:e.#af,maxCount:e.#h}),e.#ah=!0),e.#ag)){for(let a of b.splice(0,b.length/2))e.#ae-=a.size,e.#af-=1;0===b.length&&e.#ag.delete(a)}e.#ae<e.#ad&&e.#af<e.#h&&(e.#ah=!1)}b(null)}})}delete(a){if("object"!=typeof a)throw TypeError(`expected key to be object, got ${typeof a}`);let b=`${a.origin}:${a.path}`;for(let a of this.#ag.get(b)??[])this.#ae-=a.size,this.#af-=1;this.#ag.delete(b)}}function i(a,b,c){for(let d=0;d<b.length;d++){let e=b[d];if(e.deleteAt>c&&e.method===a.method&&function(a,b){if(null==b.vary)return!0;for(let c in b.vary)if(Object.hasOwn(b.vary,c)&&!function(a,b){if(null==a&&null==b)return!0;if(null==a&&null!=b||null!=a&&null==b)return!1;if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)return!1;for(let c=0;c<a.length;c++)if(a[c]!==b[c])return!1;return!0}return a===b}(a.headers?.[c],b.vary[c]))return!1;return!0}(a,e))return e}}a.exports=h},39065:(a,b,c)=>{"use strict";let{PoolStats:d}=c(19071),e=c(5318),f=c(50329),{kConnected:g,kSize:h,kRunning:i,kPending:j,kQueued:k,kBusy:l,kFree:m,kUrl:n,kClose:o,kDestroy:p,kDispatch:q}=c(49176),r=Symbol("clients"),s=Symbol("needDrain"),t=Symbol("queue"),u=Symbol("closed resolve"),v=Symbol("onDrain"),w=Symbol("onConnect"),x=Symbol("onDisconnect"),y=Symbol("onConnectionError"),z=Symbol("get dispatcher"),A=Symbol("has dispatcher"),B=Symbol("add client"),C=Symbol("remove client");class D extends e{[t]=new f;[k]=0;[r]=[];[s]=!1;[v](a,b,c){let d=this[t],e=!1;for(;!e;){let b=d.shift();if(!b)break;this[k]--,e=!a.dispatch(b.opts,b.handler)}if(a[s]=e,!e&&this[s]&&(this[s]=!1,this.emit("drain",b,[this,...c])),this[u]&&d.isEmpty()){let a=[];for(let b=0;b<this[r].length;b++){let c=this[r][b];c.destroyed||a.push(c.close())}return Promise.all(a).then(this[u])}}[w]=(a,b)=>{this.emit("connect",a,[this,...b])};[x]=(a,b,c)=>{this.emit("disconnect",a,[this,...b],c)};[y]=(a,b,c)=>{this.emit("connectionError",a,[this,...b],c)};get[l](){return this[s]}get[g](){let a=0;for(let{[g]:b}of this[r])a+=b;return a}get[m](){let a=0;for(let{[g]:b,[s]:c}of this[r])a+=b&&!c;return a}get[j](){let a=this[k];for(let{[j]:b}of this[r])a+=b;return a}get[i](){let a=0;for(let{[i]:b}of this[r])a+=b;return a}get[h](){let a=this[k];for(let{[h]:b}of this[r])a+=b;return a}get stats(){return new d(this)}[o](){if(!this[t].isEmpty())return new Promise(a=>{this[u]=a});{let a=[];for(let b=0;b<this[r].length;b++){let c=this[r][b];c.destroyed||a.push(c.close())}return Promise.all(a)}}[p](a){for(;;){let b=this[t].shift();if(!b)break;b.handler.onResponseError(null,a)}let b=Array(this[r].length);for(let c=0;c<this[r].length;c++)b[c]=this[r][c].destroy(a);return Promise.all(b)}[q](a,b){let c=this[z]();return c?c.dispatch(a,b)||(c[s]=!0,this[s]=!this[A]()):(this[s]=!0,this[t].push({opts:a,handler:b}),this[k]++),!this[s]}[A](){for(let a=0;a<this[r].length;a++){let b=this[r][a];if(!b[s]&&!0!==b.closed&&!0!==b.destroyed)return!0}return!1}[B](a){return a.on("drain",this[v].bind(this,a)).on("connect",this[w]).on("disconnect",this[x]).on("connectionError",this[y]),this[r].push(a),this[s]&&queueMicrotask(()=>{this[s]&&this[v](a,a[n],[a,this])}),this}[C](a){let b=this[r].indexOf(a);-1!==b&&this[r].splice(b,1),a.close(()=>{}),this[s]=!this[r].some(a=>!a[s]&&!0!==a.closed&&!0!==a.destroyed)}}a.exports={PoolBase:D,kClients:r,kNeedDrain:s,kAddClient:B,kRemoveClient:C,kGetDispatcher:z,kHasDispatcher:A}},39490:(a,b,c)=>{"use strict";RegExp("<think>([\\s\\S]*?)</think>\\s*")},39541:(a,b,c)=>{"use strict";function d(a){if(!a||"object"!=typeof a)return null;let b=a.output_config?.effort;if("string"==typeof b&&b){let a=b.toLowerCase();return"none"===a||"off"===a?{mode:"none"}:"auto"===a?{mode:"auto"}:{mode:"level",level:a}}let c=a.thinking;if(c&&"object"==typeof c){if("disabled"===c.type)return{mode:"none"};if("adaptive"===c.type||"enabled"===c.type){let a=Number(c.budget_tokens);return Number.isFinite(a)&&a>0?{mode:"budget",budget:a}:{mode:"auto"}}}let d=a.reasoning_effort??("object"==typeof a.reasoning?a.reasoning?.effort:null);if("string"==typeof d&&d){let a=d.toLowerCase();return"none"===a||"off"===a?{mode:"none"}:"auto"===a?{mode:"auto"}:{mode:"level",level:a}}let e=a.thinkingConfig||a.generationConfig?.thinkingConfig||a.request?.generationConfig?.thinkingConfig;if(e&&"object"==typeof e){if("string"==typeof e.thinkingLevel)return{mode:"level",level:e.thinkingLevel.toLowerCase()};let a=Number(e.thinkingBudget);if(Number.isFinite(a))return 0===a?{mode:"none"}:a<0?{mode:"auto"}:{mode:"budget",budget:a}}if(!1===a.enable_thinking)return{mode:"none"};if(!0===a.enable_thinking){let b=Number(a.thinking_budget);return Number.isFinite(b)&&b>0?{mode:"budget",budget:b}:{mode:"auto"}}return null}c.d(b,{sS:()=>d}),c(49471),c(15251),c(26317)},39804:(a,b,c)=>{var d=c(45654);c(45518),c(27080);var e=a.exports=d.tls;function f(a,b,c){var f=b.entity===d.tls.ConnectionEnd.client;a.read.cipherState={init:!1,cipher:d.cipher.createDecipher("AES-CBC",f?c.keys.server_write_key:c.keys.client_write_key),iv:f?c.keys.server_write_IV:c.keys.client_write_IV},a.write.cipherState={init:!1,cipher:d.cipher.createCipher("AES-CBC",f?c.keys.client_write_key:c.keys.server_write_key),iv:f?c.keys.client_write_IV:c.keys.server_write_IV},a.read.cipherFunction=j,a.write.cipherFunction=g,a.read.macLength=a.write.macLength=c.mac_length,a.read.macFunction=a.write.macFunction=e.hmac_sha1}function g(a,b){var c,f=!1,g=b.macFunction(b.macKey,b.sequenceNumber,a);a.fragment.putBytes(g),b.updateSequenceNumber(),c=a.version.minor===e.Versions.TLS_1_0.minor?b.cipherState.init?null:b.cipherState.iv:d.random.getBytesSync(16),b.cipherState.init=!0;var i=b.cipherState.cipher;return i.start({iv:c}),a.version.minor>=e.Versions.TLS_1_1.minor&&i.output.putBytes(c),i.update(a.fragment),i.finish(h)&&(a.fragment=i.output,a.length=a.fragment.length(),f=!0),f}function h(a,b,c){if(!c){var d=a-b.length()%a;b.fillWithByte(d-1,d)}return!0}function i(a,b,c){var d=!0;if(c){for(var e=b.length(),f=b.last(),g=e-1-f;g<e-1;++g)d=d&&b.at(g)==f;d&&b.truncate(f+1)}return d}function j(a,b){var c,f,g,h,j,k=!1;j=a.version.minor===e.Versions.TLS_1_0.minor?b.cipherState.init?null:b.cipherState.iv:a.fragment.getBytes(16),b.cipherState.init=!0;var l=b.cipherState.cipher;l.start({iv:j}),l.update(a.fragment),k=l.finish(i);var m=b.macLength,n=d.random.getBytesSync(m),o=l.output.length();o>=m?(a.fragment=l.output.getBytes(o-m),n=l.output.getBytes(m)):a.fragment=l.output.getBytes(),a.fragment=d.util.createBuffer(a.fragment),a.length=a.fragment.length();var p=b.macFunction(b.macKey,b.sequenceNumber,a);return b.updateSequenceNumber(),k=(c=b.macKey,f=n,g=p,(h=d.hmac.create()).start("SHA1",c),h.update(f),f=h.digest().getBytes(),h.start(null,null),h.update(g),f===(g=h.digest().getBytes())&&k)}e.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA={id:[0,47],name:"TLS_RSA_WITH_AES_128_CBC_SHA",initSecurityParameters:function(a){a.bulk_cipher_algorithm=e.BulkCipherAlgorithm.aes,a.cipher_type=e.CipherType.block,a.enc_key_length=16,a.block_length=16,a.fixed_iv_length=16,a.record_iv_length=16,a.mac_algorithm=e.MACAlgorithm.hmac_sha1,a.mac_length=20,a.mac_key_length=20},initConnectionState:f},e.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA={id:[0,53],name:"TLS_RSA_WITH_AES_256_CBC_SHA",initSecurityParameters:function(a){a.bulk_cipher_algorithm=e.BulkCipherAlgorithm.aes,a.cipher_type=e.CipherType.block,a.enc_key_length=32,a.block_length=16,a.fixed_iv_length=16,a.record_iv_length=16,a.mac_algorithm=e.MACAlgorithm.hmac_sha1,a.mac_length=20,a.mac_key_length=20},initConnectionState:f}},40106:(a,b,c)=>{"use strict";let d=c(34589),e=c(77030),f=c(37067),g=c(84285),{ClientStats:h}=c(19071),{channels:i}=c(62571),j=c(76316),k=c(5318),{InvalidArgumentError:l,InformationalError:m,ClientDestroyedError:n}=c(61448),o=c(55285),{kUrl:p,kServerName:q,kClient:r,kBusy:s,kConnect:t,kResuming:u,kRunning:v,kPending:w,kSize:x,kQueue:y,kConnected:z,kConnecting:A,kNeedDrain:B,kKeepAliveDefaultTimeout:C,kHostHeader:D,kPendingIdx:E,kRunningIdx:F,kError:G,kPipelining:H,kKeepAliveTimeoutValue:I,kMaxHeadersSize:J,kKeepAliveMaxTimeout:K,kKeepAliveTimeoutThreshold:L,kHeadersTimeout:M,kBodyTimeout:N,kStrictContentLength:O,kConnector:P,kMaxRequests:Q,kCounter:R,kClose:S,kDestroy:T,kDispatch:U,kLocalAddress:V,kMaxResponseSize:W,kOnError:X,kHTTPContext:Y,kMaxConcurrentStreams:Z,kHostAuthority:$,kResume:_,kHTTP2Options:aa}=c(49176),ab=c(97678),ac=c(80985),ad=Symbol("kClosedResolve"),ae=f&&f.maxHeaderSize&&Number.isInteger(f.maxHeaderSize)&&f.maxHeaderSize>0?()=>f.maxHeaderSize:()=>{throw new l("http module not available or http.maxHeaderSize invalid")},af=()=>{},ag=!1;function ah(a){!0!==ag&&(process.emitWarning(`Use h2Options.${a} instead. ${a} for H2 will be deprecated in future major.`,{code:"UNDICI-H2-OPTIONS"}),ag=!0)}function ai(a){return a[Y]?.version==="h2"?a[Z]:a[H]??a[Y]?.defaultPipelining??1}class aj extends k{constructor(a,{maxHeaderSize:b,headersTimeout:c,socketTimeout:d,requestTimeout:f,connectTimeout:h,bodyTimeout:i,idleTimeout:j,keepAlive:k,keepAliveTimeout:m,maxKeepAliveTimeout:n,keepAliveMaxTimeout:r,keepAliveTimeoutThreshold:s,socketPath:t,pipelining:v,tls:w,strictContentLength:x,maxCachedSessions:z,connect:A,maxRequestsPerClient:G,localAddress:R,maxResponseSize:S,autoSelectFamily:T,autoSelectFamilyAttemptTimeout:U,maxConcurrentStreams:Z,allowH2:ab,useH2c:ac,initialWindowSize:af,connectionWindowSize:ag,pingInterval:ai,webSocket:aj,h2Options:al}={}){if(void 0!==k)throw new l("unsupported keepAlive, use pipelining=0 instead");if(void 0!==d)throw new l("unsupported socketTimeout, use headersTimeout & bodyTimeout instead");if(void 0!==f)throw new l("unsupported requestTimeout, use headersTimeout & bodyTimeout instead");if(void 0!==j)throw new l("unsupported idleTimeout, use keepAliveTimeout instead");if(void 0!==n)throw new l("unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead");if(null!=b){if(!Number.isInteger(b)||b<1)throw new l("invalid maxHeaderSize")}else b=ae();if(null!=t&&"string"!=typeof t)throw new l("invalid socketPath");if(null!=h&&(!Number.isFinite(h)||h<0))throw new l("invalid connectTimeout");if(null!=m&&(!Number.isFinite(m)||m<=0))throw new l("invalid keepAliveTimeout");if(null!=r&&(!Number.isFinite(r)||r<=0))throw new l("invalid keepAliveMaxTimeout");if(null!=s&&!Number.isFinite(s))throw new l("invalid keepAliveTimeoutThreshold");if(null!=c&&(!Number.isInteger(c)||c<0))throw new l("headersTimeout must be a positive integer or zero");if(null!=i&&(!Number.isInteger(i)||i<0))throw new l("bodyTimeout must be a positive integer or zero");if(null!=A&&"function"!=typeof A&&"object"!=typeof A)throw new l("connect must be a function or an object");if(null!=G&&(!Number.isInteger(G)||G<0))throw new l("maxRequestsPerClient must be a positive number");if(null!=R&&("string"!=typeof R||0===e.isIP(R)))throw new l("localAddress must be valid string IP address");if(null!=S&&(!Number.isInteger(S)||S<-1))throw new l("maxResponseSize must be a positive number");if(null!=U&&(!Number.isInteger(U)||U<-1))throw new l("autoSelectFamilyAttemptTimeout must be a positive number");if(null!=ab&&"boolean"!=typeof ab)throw new l("allowH2 must be a valid boolean value");if(!1!==ab)if(null!=al){if(null!=al.useH2c&&"boolean"!=typeof al.useH2c)throw new l("h2Options.useH2c must be a valid boolean value");if(al.settings?.initialWindowSize!=null&&(!Number.isInteger(al.settings.initialWindowSize)||al.settings.initialWindowSize<1))throw new l("h2Options.settings.initialWindowSize must be a positive integer, greater than 0");if(null!=al.maxConcurrentStreams&&(!Number.isInteger(al.connectionWindowSize)||al.maxConcurrentStreams<1))throw new l("h2Options.maxConcurrentStreams must be a positive integer, greater than 0");if(null!=al.connectionWindowSize&&(!Number.isInteger(al.connectionWindowSize)||al.connectionWindowSize<1))throw new l("h2Options.connectionWindowSize must be a positive integer, greater than 0");if(null!=al.pingInterval&&("number"!=typeof al.pingInterval||!Number.isInteger(al.pingInterval)||al.pingInterval<0))throw new l("h2Options.pingInterval must be a positive integer, greater or equal to 0")}else{if(null!=ac&&"boolean"!=typeof ac)throw ah("useH2c"),new l("useH2c must be a valid boolean value");if(null!=Z&&("number"!=typeof Z||Z<1))throw ah("maxConcurrentStreams"),new l("maxConcurrentStreams must be a positive integer, greater than 0");if(null!=af&&(!Number.isInteger(af)||af<1))throw ah("initialWindowSize"),new l("initialWindowSize must be a positive integer, greater than 0");if(null!=ag&&(!Number.isInteger(ag)||ag<1))throw ah("connectionWindowSize"),new l("connectionWindowSize must be a positive integer, greater than 0");if(null!=ai&&("number"!=typeof ai||!Number.isInteger(ai)||ai<0))throw ah("pingInterval"),new l("pingInterval must be a positive integer, greater or equal to 0")}if(super({webSocket:aj}),"function"!=typeof A)A=o({...w,maxCachedSessions:z,allowH2:ab,socketPath:t,useH2c:al?.useH2c??ac,timeout:h,..."boolean"==typeof T?{autoSelectFamily:T,autoSelectFamilyAttemptTimeout:U}:void 0,...A});else{const a=A;A=(b,c)=>a({...b,...null!=t?{socketPath:t}:null,...null!=ab?{allowH2:ab}:null},c)}this[p]=g.parseOrigin(a),this[$]=`${this[p].hostname}${this[p].port?`:${this[p].port}`:""}`,this[P]=A,this[H]=null!=v?v:1,this[J]=b,this[C]=null==m?4e3:m,this[K]=null==r?6e5:r,this[L]=null==s?2e3:s,this[I]=this[C],this[q]=null,this[V]=null!=R?R:null,this[u]=0,this[B]=0,this[D]=`host: ${this[$]}\r
|
|
303
|
-
`,this[N]=null!=i?i:3e5,this[M]=null!=c?c:3e5,this[O]=null==x||x,this[Q]=G,this[ad]=null,this[W]=S>-1?S:-1,this[Y]=null,this[aa]={pingInterval:al?.pingInterval??ai??6e4,connectionWindowSize:al?.connectionWindowSize??ag??524288,maxConcurrentStreams:al?.maxConcurrentStreams??Z??100,sessionOptions:{initialWindowSize:al?.initialWindowSize??af??262144}},this[y]=[],this[F]=0,this[E]=0,this[_]=a=>ao(this,a),this[X]=a=>ak(this,a)}get pipelining(){return this[H]}set pipelining(a){this[H]=a,this[_](!0)}get stats(){return new h(this)}get[w](){return this[y].length-this[E]}get[v](){return this[E]-this[F]}get[x](){return this[y].length-this[F]}get[z](){return!!this[Y]&&!this[A]&&!this[Y].destroyed}get[s](){let a=this[Y]?.version==="h2";return!!(this[Y]?.busy(null)||this[x]>=(ai(this)||1)||this[w]>0&&!a)}[t](a){al(this),this.once("connect",a)}[U](a,b){let c=new j(this[p].origin,a,b);return this[y].push(c),this[u]||(null==g.bodyLength(c.body)&&g.isIterable(c.body)?(this[u]=1,queueMicrotask(()=>ao(this))):this[_](!0)),this[u]&&2!==this[B]&&this[s]&&(this[B]=2),this[B]<2}[S](){return new Promise(a=>{this[x]?this[ad]=a:a(null)})}[T](a){return new Promise(b=>{let c=this[y].splice(this[E]);for(let b=0;b<c.length;b++){let d=c[b];null!=d&&g.errorRequest(this,d,a)}let d=()=>{this[ad]&&(this[ad](),this[ad]=null),b(null)};this[Y]?(this[Y].destroy(a,d),this[Y]=null):queueMicrotask(d),this[_]()})}}function ak(a,b){if(0===a[v]&&"UND_ERR_INFO"!==b.code&&"UND_ERR_SOCKET"!==b.code){d(a[E]===a[F]);let c=a[y].splice(a[F]);for(let d=0;d<c.length;d++){let e=c[d];null!=e&&g.errorRequest(a,e,b)}d(0===a[x])}}function al(a){d(!a[A]),d(!a[Y]);let{host:b,hostname:c,protocol:f,port:h}=a[p];if("["===c[0]){let a=c.indexOf("]");d(-1!==a);let b=c.substring(1,a);d(e.isIPv6(b)),c=b}a[A]=!0,i.beforeConnect.hasSubscribers&&i.beforeConnect.publish({connectParams:{host:b,hostname:c,protocol:f,port:h,version:a[Y]?.version,servername:a[q],localAddress:a[V]},connector:a[P]});try{a[P]({host:b,hostname:c,protocol:f,port:h,servername:a[q],localAddress:a[V]},(e,j)=>{if(e){am(a,e,{host:b,hostname:c,protocol:f,port:h}),a[_]();return}if(a.destroyed){g.destroy(j.on("error",af),new n),a[_]();return}d(j);try{a[Y]="h2"===j.alpnProtocol?ac(a,j):ab(a,j)}catch(d){j.destroy().on("error",af),am(a,d,{host:b,hostname:c,protocol:f,port:h}),a[_]();return}a[A]=!1,j[R]=0,j[Q]=a[Q],j[r]=a,j[G]=null,i.connected.hasSubscribers&&i.connected.publish({connectParams:{host:b,hostname:c,protocol:f,port:h,version:a[Y]?.version,servername:a[q],localAddress:a[V]},connector:a[P],socket:j}),a.emit("connect",a[p],[a]),a[_]()})}catch(d){am(a,d,{host:b,hostname:c,protocol:f,port:h}),a[_]()}}function am(a,b,{host:c,hostname:d,protocol:e,port:f}){if(!a.destroyed){if(a[A]=!1,i.connectError.hasSubscribers&&i.connectError.publish({connectParams:{host:c,hostname:d,protocol:e,port:f,version:a[Y]?.version,servername:a[q],localAddress:a[V]},connector:a[P],error:b}),"ERR_TLS_CERT_ALTNAME_INVALID"===b.code){let c=a[y].splice(a[F],a[v]);a[E]=a[F];for(let d=0;d<c.length;d++)g.errorRequest(a,c[d],b);for(;a[w]>0&&a[y][a[E]].servername===a[q];){let c=a[y].splice(a[E],1)[0];g.errorRequest(a,c,b)}}else ak(a,b);a.emit("connectionError",a[p],[a],b)}}function an(a){a[B]=0,a.emit("drain",a[p],[a])}function ao(a,b){2!==a[u]&&(a[u]=2,function(a,b){for(;;){if(a.destroyed)return void d(0===a[w]);if(a[ad]&&!a[x]){a[ad](),a[ad]=null;return}if(a[Y]&&a[Y].resume(),a[s])a[B]=2;else if(2===a[B]){b?(a[B]=1,queueMicrotask(()=>an(a))):an(a);continue}if(0===a[w]||a[v]>=(ai(a)||1))return;let c=a[y][a[E]];if(null===c)return;if("https:"===a[p].protocol&&a[q]!==c.servername){if(a[v]>0)return;a[q]=c.servername,a[Y]?.destroy(new m("servername changed"),()=>{a[Y]=null,ao(a)})}if(a[A])return;if(!a[Y]){a[q]=c.servername,al(a);return}if(a[Y].destroyed||a[Y].busy(c))return;!c.aborted&&a[Y].write(c)?a[E]++:a[y].splice(a[E],1)}}(a,b),a[u]=0,a[F]>256&&(a[y].splice(0,a[F]),a[E]-=a[F],a[F]=0))}a.exports=aj},40603:(a,b,c)=>{"use strict";let{EventEmitter:d}=c(78474),{Buffer:e}=c(4573),{InvalidArgumentError:f,Socks5ProxyError:g}=c(61448),{debuglog:h}=c(57975),{parseAddress:i}=c(33297),j=h("undici:socks5"),k=e.alloc(0),l={NO_AUTH:0,GSSAPI:1,USERNAME_PASSWORD:2,NO_ACCEPTABLE:255},m={CONNECT:1,BIND:2,UDP_ASSOCIATE:3},n={IPV4:1,DOMAIN:3,IPV6:4},o={SUCCEEDED:0,GENERAL_FAILURE:1,CONNECTION_NOT_ALLOWED:2,NETWORK_UNREACHABLE:3,HOST_UNREACHABLE:4,CONNECTION_REFUSED:5,TTL_EXPIRED:6,COMMAND_NOT_SUPPORTED:7,ADDRESS_TYPE_NOT_SUPPORTED:8},p={INITIAL:"initial",HANDSHAKING:"handshaking",AUTHENTICATING:"authenticating",AUTHENTICATED:"authenticated",CONNECTING:"connecting",CONNECTED:"connected",ERROR:"error",CLOSED:"closed"};class q extends d{constructor(a,b={}){if(super(),!a)throw new f("socket is required");this.socket=a,this.options=b,this.state=p.INITIAL,this.buffer=k,this.onSocketData=this.onData.bind(this),this.onSocketError=this.onError.bind(this),this.onSocketClose=this.onClose.bind(this),this.authMethods=[],b.username&&b.password&&this.authMethods.push(l.USERNAME_PASSWORD),this.authMethods.push(l.NO_AUTH),this.socket.on("data",this.onSocketData),this.socket.on("error",this.onSocketError),this.socket.on("close",this.onSocketClose)}onData(a){j("received data",a.length,"bytes in state",this.state),this.buffer=e.concat([this.buffer,a]);try{switch(this.state){case p.HANDSHAKING:this.handleHandshakeResponse();break;case p.AUTHENTICATING:this.handleAuthResponse();break;case p.CONNECTING:this.handleConnectResponse()}}catch(a){this.onError(a)}}onError(a){j("socket error",a),this.state=p.ERROR,this.emit("error",a),this.destroy()}onClose(){j("socket closed"),this.state=p.CLOSED,this.emit("close")}destroy(){this.socket&&!this.socket.destroyed&&this.socket.destroy()}markAuthenticated(){this.state=p.AUTHENTICATED,this.emit("authenticated")}handshake(){if(this.state!==p.INITIAL)throw new f("Handshake already started");j("starting handshake with",this.authMethods.length,"auth methods"),this.state=p.HANDSHAKING;let a=e.alloc(2+this.authMethods.length);a[0]=5,a[1]=this.authMethods.length,this.authMethods.forEach((b,c)=>{a[2+c]=b}),this.socket.write(a)}handleHandshakeResponse(){if(this.buffer.length<2)return;let a=this.buffer[0],b=this.buffer[1];if(5!==a)throw new g(`Invalid SOCKS version: ${a}`,"UND_ERR_SOCKS5_VERSION");if(b===l.NO_ACCEPTABLE)throw new g("No acceptable authentication method","UND_ERR_SOCKS5_AUTH_REJECTED");if(this.buffer=this.buffer.subarray(2),j("server selected auth method",b),b===l.NO_AUTH)this.markAuthenticated();else if(b===l.USERNAME_PASSWORD)this.state=p.AUTHENTICATING,this.sendAuthRequest();else throw new g(`Unsupported authentication method: ${b}`,"UND_ERR_SOCKS5_AUTH_METHOD")}sendAuthRequest(){let{username:a,password:b}=this.options;if(!a||!b)throw new f("Username and password required for authentication");j("sending username/password auth");let c=e.from(a),d=e.from(b);if(c.length>255||d.length>255)throw new f("Username or password too long");let g=e.alloc(3+c.length+d.length);g[0]=1,g[1]=c.length,c.copy(g,2),g[2+c.length]=d.length,d.copy(g,3+c.length),this.socket.write(g)}handleAuthResponse(){if(this.buffer.length<2)return;let a=this.buffer[0],b=this.buffer[1];if(1!==a)throw new g(`Invalid auth sub-negotiation version: ${a}`,"UND_ERR_SOCKS5_AUTH_VERSION");if(0!==b)throw new g("Authentication failed","UND_ERR_SOCKS5_AUTH_FAILED");this.buffer=this.buffer.subarray(2),j("authentication successful"),this.markAuthenticated()}connect(a,b){if(this.state===p.CONNECTING||this.state===p.CONNECTED)throw new f("Connection already in progress");if(this.state!==p.AUTHENTICATED)throw new f("Client must be authenticated before CONNECT");j("connecting to",a,b),this.state=p.CONNECTING;let c=this.buildConnectRequest(m.CONNECT,a,b);this.socket.write(c)}buildConnectRequest(a,b,c){let{type:d,buffer:f}=i(b),g=e.alloc(4+f.length+2);return g[0]=5,g[1]=a,g[2]=0,g[3]=d,f.copy(g,4),g.writeUInt16BE(c,4+f.length),g}handleConnectResponse(){let a;if(this.buffer.length<4)return;let b=this.buffer[0],c=this.buffer[1],d=this.buffer[3];if(5!==b)throw new g(`Invalid SOCKS version in reply: ${b}`,"UND_ERR_SOCKS5_REPLY_VERSION");let e=4;if(d===n.IPV4)e+=6;else if(d===n.DOMAIN){if(this.buffer.length<5)return;e+=1+this.buffer[4]+2}else if(d===n.IPV6)e+=18;else throw new g(`Invalid address type in reply: ${d}`,"UND_ERR_SOCKS5_ADDR_TYPE");if(this.buffer.length<e)return;if(c!==o.SUCCEEDED){let a=this.getReplyErrorMessage(c);throw new g(`SOCKS5 connection failed: ${a}`,`UND_ERR_SOCKS5_REPLY_${c}`)}let f=4;if(d===n.IPV4)a=Array.from(this.buffer.subarray(f,f+4)).join("."),f+=4;else if(d===n.DOMAIN){let b=this.buffer[f];f+=1,a=this.buffer.subarray(f,f+b).toString(),f+=b}else if(d===n.IPV6){let b=[];for(let a=0;a<8;a++){let c=this.buffer.readUInt16BE(f+2*a);b.push(c.toString(16))}a=b.join(":"),f+=16}let h=this.buffer.readUInt16BE(f);this.buffer=k,this.state=p.CONNECTED,this.socket.removeListener("data",this.onSocketData),j("connected, bound address:",a,"port:",h),this.emit("connected",{address:a,port:h})}getReplyErrorMessage(a){switch(a){case o.GENERAL_FAILURE:return"General SOCKS server failure";case o.CONNECTION_NOT_ALLOWED:return"Connection not allowed by ruleset";case o.NETWORK_UNREACHABLE:return"Network unreachable";case o.HOST_UNREACHABLE:return"Host unreachable";case o.CONNECTION_REFUSED:return"Connection refused";case o.TTL_EXPIRED:return"TTL expired";case o.COMMAND_NOT_SUPPORTED:return"Command not supported";case o.ADDRESS_TYPE_NOT_SUPPORTED:return"Address type not supported";default:return`Unknown error code: ${a}`}}}a.exports={Socks5Client:q,AUTH_METHODS:l,COMMANDS:m,ADDRESS_TYPES:n,REPLY_CODES:o,STATES:p}},41702:(a,b,c)=>{var d=c(45654);c(33889),d.mgf=d.mgf||{},(a.exports=d.mgf.mgf1=d.mgf1=d.mgf1||{}).create=function(a){return{generate:function(b,c){for(var e=new d.util.ByteBuffer,f=Math.ceil(c/a.digestLength),g=0;g<f;g++){var h=new d.util.ByteBuffer;h.putInt32(g),a.start(),a.update(b+h.getBytes()),e.putBuffer(a.digest())}return e.truncate(e.length()-c),e.getBytes()}}}},41883:(a,b,c)=>{"use strict";c.d(b,{w:()=>k});var d=c(67671),e=c(38421),f=c(96997),g=c(50969);let h=new Map;function i(a){if("string"!=typeof a)return null;try{let b=JSON.parse(a);if("authorized_user"===b.type&&b.client_id&&b.client_secret&&b.refresh_token)return b;return null}catch{return null}}async function j(a,b,c,d){if(h.has(a))return h.get(a);let e=await (0,g.Fm)(`https://aiplatform.googleapis.com/v1/publishers/google/models/__probe__:generateContent?key=${a}`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",identity:c.identity,provider:b,format:c.format},d),f=await e.json().catch(()=>null),i=(f?.[0]?.error?.message||f?.error?.message||"").match(/projects\/([^/]+)\//),j=i?.[1]||null;return j&&h.set(a,j),j}class k extends d.Hv{constructor(a="vertex"){super(a,e.xq[a]||{})}buildUrl(a,b,c=0,d=null){let e=(0,f.Sc)(d?.apiKey),g=i(d?.apiKey),h=!!e||!!g||!!d?.accessToken,j=h?null:d?.apiKey,k=e?.project_id||g?.quota_project_id||d?.providerSpecificData?.projectId;if("vertex-partner"===this.provider){if(!k)throw Error("Vertex partner models require a project_id. Add it in providerSpecificData or use Service Account JSON.");let a=`https://aiplatform.googleapis.com/v1/projects/${k}/locations/global/endpoints/openapi/chat/completions`;return j?`${a}?key=${j}`:a}let l=b?"streamGenerateContent":"generateContent";if(h){if(!k)throw Error("Vertex OAuth/ADC requires a project_id. Add quota_project_id to your ADC JSON or set providerSpecificData.projectId.");let c=d?.providerSpecificData?.location||"us-central1",e=`https://aiplatform.googleapis.com/v1/projects/${k}/locations/${c}/publishers/google/models/${a}:${l}`;return b&&(e+="?alt=sse"),e}let m=`https://aiplatform.googleapis.com/v1/publishers/google/models/${a}:${l}`;return b&&(m+="?alt=sse"),j&&(m+=b?`&key=${j}`:`?key=${j}`),m}buildHeaders(a,b=!0){let c={"Content-Type":"application/json"};return a.accessToken&&(c.Authorization=`Bearer ${a.accessToken}`),b&&(c.Accept="text/event-stream"),c}async refreshCredentials(a,b,c=null){let d=(0,f.Sc)(a?.apiKey);if(d){let a=await (0,f.pb)(d,b);return a?{accessToken:a.accessToken,expiresAt:a.expiresAt}:null}let e=i(a?.apiKey);if(e){let a=await (0,f.I9)(e.refresh_token,e.client_id,e.client_secret,b,this.provider,c);return a?.accessToken?{accessToken:a.accessToken,expiresAt:a.expiresAt}:null}return null}async execute({model:a,body:b,stream:c,credentials:d,signal:e,log:h,proxyOptions:k=null}){let l=(0,f.Sc)(d?.apiKey),m=i(d?.apiKey);if(l){let a=await (0,f.pb)(l,h);if(!a?.accessToken)throw Error("Vertex: failed to mint access token from Service Account JSON");d.accessToken=a.accessToken}if(m){let a=await (0,f.I9)(m.refresh_token,m.client_id,m.client_secret,h,this.provider,k);if(!a?.accessToken)throw Error("Vertex: failed to refresh access token from ADC JSON (authorized_user)");d.accessToken=a.accessToken}if("vertex-partner"===this.provider&&!l&&!m&&!d?.providerSpecificData?.projectId){let a=await j(d.apiKey,this.provider,this.config,k);if(!a)throw Error("Vertex: could not resolve project_id from API key. Please add it manually in provider settings.");h?.debug?.("VERTEX",`Resolved project_id: ${a}`),d.providerSpecificData={...d.providerSpecificData,projectId:a}}let n=this.buildUrl(a,c,0,d),o=this.buildHeaders(d,c),p=this.transformRequest(a,b,c,d);return{response:await (0,g.Fm)(n,{method:"POST",headers:o,body:JSON.stringify(p),signal:e},k),url:n,headers:o,transformedBody:p}}}},42425:(a,b,c)=>{"use strict";let{Transform:d}=c(57075),e=c(38522),{redirectStatusSet:f,referrerPolicyTokens:g,badPortsSet:h}=c(19608),{getGlobalOrigin:i}=c(79412),{collectAnHTTPQuotedString:j,parseMIMEType:k}=c(16537),{performance:l}=c(643),{ReadableStreamFrom:m,isValidHTTPToken:n,normalizedMethodRecordsBase:o}=c(84285),p=c(34589),{isUint8Array:q}=c(73429),{webidl:r}=c(32984),{isomorphicEncode:s,collectASequenceOfCodePoints:t,removeChars:u}=c(70745);function v(a){let b=a.urlList,c=b.length;return 0===c?null:b[c-1].toString()}function w(a){for(let b=0;b<a.length;++b){let c=a.charCodeAt(b);if(c>126||c<32)return!1}return!0}function x(a){return a.urlList[a.urlList.length-1]}function y(a){return!1===(" "===a[0]||" "===a[0]||" "===a[a.length-1]||" "===a[a.length-1]||a.includes("\n")||a.includes("\r")||a.includes("\0"))}function z(){return{referrerPolicy:"strict-origin-when-cross-origin"}}function A(a,b=!1){return(p(r.is.URL(a)),J(a=new URL(a)))?"no-referrer":(a.username="",a.password="",a.hash="",!0===b&&(a.pathname="",a.search=""),a)}let B=RegExp.prototype.test.bind(/^127\.(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){2}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$/),C=RegExp.prototype.test.bind(/^(?:(?:0{1,4}:){7}|(?:0{1,4}:){1,6}:|::)0{0,3}1$/);function D(a){return a.includes(":")?("["===a[0]&&"]"===a[a.length-1]&&(a=a.slice(1,-1)),C(a)):B(a)}function E(a){var b;return!!r.is.URL(a)&&("about:blank"===a.href||"about:srcdoc"===a.href||"data:"===a.protocol||"blob:"===a.protocol||null!=(b=a.origin)&&"null"!==b&&(!!("https:"===(b=new URL(b)).protocol||"wss:"===b.protocol||D(b.hostname)||"localhost"===b.hostname||"localhost."===b.hostname||b.hostname.endsWith(".localhost")||b.hostname.endsWith(".localhost."))||"file:"===b.protocol))}function F(a,b){return a.origin===b.origin&&"null"===a.origin||a.protocol===b.protocol&&a.hostname===b.hostname&&a.port===b.port}let G=Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()));function H(a,b,c=0,d=1){class e{#ai;#aj;#ak;constructor(a,b){this.#ai=a,this.#aj=b,this.#ak=0}next(){let e;if("object"!=typeof this||this===null||!(#ai in this))throw TypeError(`'next' called on an object that does not implement interface ${a} Iterator.`);let f=this.#ak,g=b(this.#ai);if(f>=g.length)return{value:void 0,done:!0};let{[c]:h,[d]:i}=g[f];switch(this.#ak=f+1,this.#aj){case"key":e=h;break;case"value":e=i;break;case"key+value":e=[h,i]}return{value:e,done:!1}}}return delete e.prototype.constructor,Object.setPrototypeOf(e.prototype,G),Object.defineProperties(e.prototype,{[Symbol.toStringTag]:{writable:!1,enumerable:!1,configurable:!0,value:`${a} Iterator`},next:{writable:!0,enumerable:!0,configurable:!0}}),function(a,b){return new e(a,b)}}async function I(a,b,c){try{let d=[],e=0;for(;;){let{done:f,value:g}=await a.read();if(f)return void b(Buffer.concat(d,e));if(!q(g))return void c(TypeError("Received non-Uint8Array chunk"));d.push(g),e+=g.length}}catch(a){c(a)}}function J(a){p("protocol"in a);let b=a.protocol;return"about:"===b||"blob:"===b||"data:"===b}function K(a){return"string"==typeof a&&":"===a[5]&&"h"===a[0]&&"t"===a[1]&&"t"===a[2]&&"p"===a[3]&&"s"===a[4]||"https:"===a.protocol}function L(a){p("protocol"in a);let b=a.protocol;return"http:"===b||"https:"===b}class M extends d{#al;constructor(a){super(),this.#al=a}_transform(a,b,c){if(!this._inflateStream){if(0===a.length)return void c();this._inflateStream=(15&a[0])==8?e.createInflate(this.#al):e.createInflateRaw(this.#al),this._inflateStream.on("data",this.push.bind(this)),this._inflateStream.on("end",()=>this.push(null)),this._inflateStream.on("error",a=>this.destroy(a))}this._inflateStream.write(a,b,c)}_final(a){this._inflateStream&&(this._inflateStream.end(),this._inflateStream=null),a()}}function N(a,b){let c=b.get(a,!0);if(null===c)return null;let d={position:0},e=[],f="";for(;d.position<c.length;){if(f+=t(a=>'"'!==a&&","!==a,c,d),d.position<c.length)if(34===c.charCodeAt(d.position)){if(f+=j(c,d),d.position<c.length)continue}else p(44===c.charCodeAt(d.position)),d.position++;f=u(f,!0,!0,a=>9===a||32===a),e.push(f),f=""}return e}class O{get baseUrl(){return i()}get origin(){return this.baseUrl?.origin}policyContainer=z()}class P{settingsObject=new O}a.exports={isAborted:function(a){return"aborted"===a.controller.state},isCancelled:function(a){return"aborted"===a.controller.state||"terminated"===a.controller.state},isValidEncodedURL:w,ReadableStreamFrom:m,tryUpgradeRequestToAPotentiallyTrustworthyURL:function(a){},clampAndCoarsenConnectionTimingInfo:function(a,b,c){return!a?.startTime||a.startTime<b?{domainLookupStartTime:b,domainLookupEndTime:b,connectionStartTime:b,connectionEndTime:b,secureConnectionStartTime:b,ALPNNegotiatedProtocol:a?.ALPNNegotiatedProtocol}:{domainLookupStartTime:a.domainLookupStartTime,domainLookupEndTime:a.domainLookupEndTime,connectionStartTime:a.connectionStartTime,connectionEndTime:a.connectionEndTime,secureConnectionStartTime:a.secureConnectionStartTime,ALPNNegotiatedProtocol:a.ALPNNegotiatedProtocol}},coarsenedSharedCurrentTime:function(a){return l.now()},determineRequestsReferrer:function(a){let b=a.referrerPolicy;p(b);let c=null;if("client"===a.referrer){let a=i();if(!a||"null"===a.origin)return"no-referrer";c=new URL(a)}else r.is.URL(a.referrer)&&(c=a.referrer);let d=A(c),e=A(c,!0);switch(d.toString().length>4096&&(d=e),b){case"no-referrer":return"no-referrer";case"origin":if(null!=e)return e;return A(c,!0);case"unsafe-url":return d;case"strict-origin":{let b=x(a);if(E(d)&&!E(b))return"no-referrer";return e}case"strict-origin-when-cross-origin":{let b=x(a);if(F(d,b))return d;if(E(d)&&!E(b))return"no-referrer";return e}case"same-origin":if(F(a,d))return d;return"no-referrer";case"origin-when-cross-origin":if(F(a,d))return d;return e;case"no-referrer-when-downgrade":{let b=x(a);if(E(d)&&!E(b))return"no-referrer";return d}}},makePolicyContainer:z,clonePolicyContainer:function(a){return{referrerPolicy:a.referrerPolicy}},appendFetchMetadata:function(a){let b=null;b=a.mode,a.headersList.set("sec-fetch-mode",b,!0)},appendRequestOriginHeader:function(a){let b=a.origin;if("client"!==b&&void 0!==b){if("cors"===a.responseTainting||"websocket"===a.mode)a.headersList.append("origin",b,!0);else if("GET"!==a.method&&"HEAD"!==a.method){switch(a.referrerPolicy){case"no-referrer":b=null;break;case"no-referrer-when-downgrade":case"strict-origin":case"strict-origin-when-cross-origin":a.origin&&K(a.origin)&&!K(x(a))&&(b=null);break;case"same-origin":F(a,x(a))||(b=null)}a.headersList.append("origin",b,!0)}}},TAOCheck:function(){return"success"},corsCheck:function(){return"success"},crossOriginResourcePolicyCheck:function(){return"allowed"},createOpaqueTimingInfo:function(a){return{startTime:a.startTime??0,redirectStartTime:0,redirectEndTime:0,postRedirectStartTime:a.startTime??0,finalServiceWorkerStartTime:0,finalNetworkResponseStartTime:0,finalNetworkRequestStartTime:0,endTime:0,encodedBodySize:0,decodedBodySize:0,finalConnectionTimingInfo:null}},setRequestReferrerPolicyOnRedirect:function(a,b){let c=function(a){let b=(a.headersList.get("referrer-policy",!0)??"").split(","),c="";if(b.length)for(let a=b.length;0!==a;a--){let d=b[a-1].trim();if(g.has(d)){c=d;break}}return c}(b);""!==c&&(a.referrerPolicy=c)},isValidHTTPToken:n,requestBadPort:function(a){let b=x(a);return L(b)&&h.has(b.port)?"blocked":"allowed"},requestCurrentURL:x,responseURL:v,responseLocationURL:function(a,b){var c;if(!f.has(a.status))return null;let d=a.headersList.get("location",!0);return null!==d&&y(d)&&(w(d)||(c=d,d=Buffer.from(c,"binary").toString("utf8")),d=new URL(d,v(a))),d&&!d.hash&&(d.hash=b),d},isURLPotentiallyTrustworthy:E,isValidReasonPhrase:function(a){for(let b=0;b<a.length;++b){let c=a.charCodeAt(b);if(!(9===c||c>=32&&c<=126||c>=128&&c<=255))return!1}return!0},sameOrigin:F,normalizeMethod:function(a){return o[a.toLowerCase()]??a},iteratorMixin:function(a,b,c,d=0,e=1){let f=H(a,c,d,e),g={keys:{writable:!0,enumerable:!0,configurable:!0,value:function(){return r.brandCheck(this,b),f(this,"key")}},values:{writable:!0,enumerable:!0,configurable:!0,value:function(){return r.brandCheck(this,b),f(this,"value")}},entries:{writable:!0,enumerable:!0,configurable:!0,value:function(){return r.brandCheck(this,b),f(this,"key+value")}},forEach:{writable:!0,enumerable:!0,configurable:!0,value:function(c,d=globalThis){if(r.brandCheck(this,b),r.argumentLengthCheck(arguments,1,`${a}.forEach`),"function"!=typeof c)throw TypeError(`Failed to execute 'forEach' on '${a}': parameter 1 is not of type 'Function'.`);for(let{0:a,1:b}of f(this,"key+value"))c.call(d,b,a,this)}}};return Object.defineProperties(b.prototype,{...g,[Symbol.iterator]:{writable:!0,enumerable:!1,configurable:!0,value:g.entries.value}})},createIterator:H,isValidHeaderName:n,isValidHeaderValue:y,isErrorLike:function(a){return a instanceof Error||a?.constructor?.name==="Error"||a?.constructor?.name==="DOMException"},fullyReadBody:function(a,b,c){try{let d=a.stream.getReader();I(d,b,c)}catch(a){c(a)}},readableStreamClose:function(a){try{a.close(),a.byobRequest?.respond(0)}catch(a){if(!a.message.includes("Controller is already closed")&&!a.message.includes("ReadableStream is already closed"))throw a}},urlIsLocal:J,urlHasHttpsScheme:K,urlIsHttpHttpsScheme:L,readAllBytes:I,simpleRangeHeaderValue:function(a,b){if(!a.startsWith("bytes"))return"failure";let c={position:5};if(b&&t(a=>" "===a||" "===a,a,c),61!==a.charCodeAt(c.position))return"failure";c.position++,b&&t(a=>" "===a||" "===a,a,c);let d=t(a=>{let b=a.charCodeAt(0);return b>=48&&b<=57},a,c),e=d.length?Number(d):null;if(b&&t(a=>" "===a||" "===a,a,c),45!==a.charCodeAt(c.position))return"failure";c.position++,b&&t(a=>" "===a||" "===a,a,c);let f=t(a=>{let b=a.charCodeAt(0);return b>=48&&b<=57},a,c),g=f.length?Number(f):null;return c.position<a.length||null===g&&null===e||null!==e&&null!==g&&e>g?"failure":{rangeStartValue:e,rangeEndValue:g}},buildContentRange:function(a,b,c){let d="bytes ";return d+=s(`${a}`),d+="-",d+=s(`${b}`),d+="/",d+=s(`${c}`)},createInflate:function(a){return new M(a)},extractMimeType:function(a){let b=null,c=null,d=null,e=N("content-type",a);if(null===e)return"failure";for(let a of e){let e=k(a);"failure"!==e&&"*/*"!==e.essence&&((d=e).essence!==c?(b=null,d.parameters.has("charset")&&(b=d.parameters.get("charset")),c=d.essence):d.parameters.has("charset")||null===b||d.parameters.set("charset",b))}return null==d?"failure":d},getDecodeSplit:N,environmentSettingsObject:new P,isOriginIPPotentiallyTrustworthy:D,hasAuthenticationEntry:function(a){return!1},includesCredentials:function(a){return!!(a.username||a.password)},isTraversableNavigable:function(a){return null!=a&&"client"!==a&&"no-traversable"!==a}}},42430:(a,b,c)=>{"use strict";let{addAbortListener:d}=c(78474),{environmentSettingsObject:e,readableStreamClose:f}=c(42425),{states:g,opcodes:h,sentCloseFrameState:i}=c(62026),{webidl:j}=c(32984),{getURLRecord:k,isValidSubprotocol:l,isEstablished:m,utf8Decode:n}=c(94050),{establishWebSocketConnection:o,failWebsocketConnection:p,closeWebSocketConnection:q}=c(4654),{channels:r}=c(62571),{WebsocketFrameSend:s}=c(45221),{ByteParser:t}=c(64821),{WebSocketError:u,createUnvalidatedWebSocketError:v}=c(87404),{kEnumerableProperty:w}=c(84285),{utf8DecodeBytes:x}=c(67449),y=!1;class z{#am;#an;#ao;#ap;#aq;#ar;#as=!1;#at={onConnectionEstablished:(a,b)=>this.#au(a,b),onMessage:(a,b)=>this.#av(a,b),onParserError:a=>p(this.#at,null,a.message),onParserDrain:()=>this.#at.socket.resume(),onSocketData:a=>{this.#aw.write(a)||this.#at.socket.pause()},onSocketError:a=>{this.#at.readyState=g.CLOSING,r.socketError.hasSubscribers&&r.socketError.publish(a),this.#at.socket.destroy()},onSocketClose:()=>this.#ax(),onPing:()=>{},onPong:()=>{},readyState:g.CONNECTING,socket:null,closeState:new Set,controller:null,wasEverConnected:!1};#aw;constructor(a,b){y||(process.emitWarning("WebSocketStream is experimental! Expect it to change at any time.",{code:"UNDICI-WSS"}),y=!0),j.argumentLengthCheck(arguments,1,"WebSocket"),a=j.converters.USVString(a),null!==b&&(b=j.converters.WebSocketStreamOptions(b));const c=k(a,e.settingsObject.baseUrl),f=b.protocols;if(f.length!==new Set(f.map(a=>a.toLowerCase())).size||f.length>0&&!f.every(a=>l(a)))throw new DOMException("Invalid Sec-WebSocket-Protocol value","SyntaxError");if(this.#am=c.toString(),this.#an=Promise.withResolvers(),this.#ao=Promise.withResolvers(),null!=b.signal){const a=b.signal;if(a.aborted){this.#an.reject(a.reason),this.#ao.reject(a.reason);return}d(a,()=>{m(this.#at.readyState)||(p(this.#at),this.#at.readyState=g.CLOSING,this.#an.reject(a.reason),this.#ao.reject(a.reason),this.#as=!0)})}const h=e.settingsObject;this.#at.controller=o(c,f,h,this.#at,b)}get url(){return this.#am.toString()}get opened(){return this.#an.promise}get closed(){return this.#ao.promise}close(a){null!==a&&(a=j.converters.WebSocketCloseInfo(a));let b=a.closeCode??null,c=a.reason;q(this.#at,b,c,!0)}#ay(a){a=j.converters.WebSocketStreamWrite(a);let b=Promise.withResolvers(),c=null,d=null;if(j.is.BufferSource(a))c=new Uint8Array(ArrayBuffer.isView(a)?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):a.slice()),d=h.BINARY;else{let e;try{e=j.converters.DOMString(a)}catch(a){return b.reject(a),b.promise}c=new TextEncoder().encode(e),d=h.TEXT}if(!this.#at.closeState.has(i.SENT)&&!this.#at.closeState.has(i.RECEIVED)){let a=new s(c);this.#at.socket.write(a.createFrame(d),()=>{b.resolve(void 0)})}return b.promise}#au(a,b){this.#at.socket=a.socket;let c=this.#at.controller.dispatcher?.webSocketOptions?.maxFragments,d=this.#at.controller.dispatcher?.webSocketOptions?.maxPayloadSize,e=new t(this.#at,b,{maxFragments:c,maxPayloadSize:d});e.on("drain",()=>this.#at.onParserDrain()),e.on("error",a=>this.#at.onParserError(a)),this.#aw=e,this.#at.readyState=g.OPEN;let f=b??"",h=a.headersList.get("sec-websocket-protocol")??"",i=new ReadableStream({start:a=>{this.#aq=a},cancel:a=>this.#az(a)}),j=new WritableStream({write:a=>this.#ay(a),close:()=>q(this.#at,null,null),abort:a=>this.#aA(a)});this.#ap=i,this.#ar=j,this.#an.resolve({extensions:f,protocol:h,readable:i,writable:j})}#av(a,b){let c;if(this.#at.readyState===g.OPEN){if(a===h.TEXT)try{c=n(b)}catch{p(this.#at,1007,"Received invalid UTF-8 in text frame.");return}else a===h.BINARY&&(c=new Uint8Array(b.buffer,b.byteOffset,b.byteLength));this.#aq.enqueue(c)}}#ax(){let a=this.#at.closeState.has(i.SENT)&&this.#at.closeState.has(i.RECEIVED);if(this.#at.readyState=g.CLOSED,this.#as)return;this.#at.wasEverConnected||this.#an.reject(new u("Socket never opened"));let b=this.#aw?.closingInfo,c=b?.code??1005;this.#at.closeState.has(i.SENT)||this.#at.closeState.has(i.RECEIVED)||(c=1006);let d=b?.reason==null?"":x(Buffer.from(b.reason));if(a)f(this.#aq),this.#ar.locked||this.#ar.abort(new DOMException("A closed WebSocketStream cannot be written to","InvalidStateError")),this.#ao.resolve({closeCode:c,reason:d});else{let a=v("unclean close",c,d);this.#aq?.error(a),this.#ar?.abort(a),this.#ao.reject(a)}}#aA(a){let b=null,c="";j.is.WebSocketError(a)&&(b=a.closeCode,c=a.reason),q(this.#at,b,c)}#az(a){this.#aA(a)}}Object.defineProperties(z.prototype,{url:w,opened:w,closed:w,close:w,[Symbol.toStringTag]:{value:"WebSocketStream",writable:!1,enumerable:!1,configurable:!0}}),j.converters.WebSocketStreamOptions=j.dictionaryConverter([{key:"protocols",converter:j.sequenceConverter(j.converters.USVString),defaultValue:()=>[]},{key:"signal",converter:j.nullableConverter(j.converters.AbortSignal),defaultValue:()=>null}]),j.converters.WebSocketCloseInfo=j.dictionaryConverter([{key:"closeCode",converter:a=>j.converters["unsigned short"](a,j.attributes.EnforceRange)},{key:"reason",converter:j.converters.USVString,defaultValue:()=>""}]),j.converters.WebSocketStreamWrite=function(a){return"string"==typeof a?j.converters.USVString(a):j.converters.BufferSource(a)},a.exports={WebSocketStream:z}},43086:(a,b,c)=>{"use strict";let d=c(5318),{kClose:e,kDestroy:f,kClosed:g,kDestroyed:h,kDispatch:i,kNoProxyAgent:j,kHttpProxyAgent:k,kHttpsProxyAgent:l}=c(49176),m=c(48841),n=c(37417),o={"http:":80,"https:":443};class p extends d{#aB=null;#aC=null;#y=null;constructor(a={}){super(),this.#y=a;const{httpProxy:b,httpsProxy:c,noProxy:d,...e}=a;this[j]=new n(e);const f=b??process.env.http_proxy??process.env.HTTP_PROXY;f?this[k]=new m({...e,uri:f}):this[k]=this[j];const g=c??process.env.https_proxy??process.env.HTTPS_PROXY;g?this[l]=new m({...e,uri:g}):this[l]=this[k],this.#aD()}[i](a,b){let c=new URL(a.origin);return this.#aE(c).dispatch(a,b)}[e](){return Promise.all([this[j].close(),!this[k][g]&&this[k].close(),!this[l][g]&&this[l].close()])}[f](a){return Promise.all([this[j].destroy(a),!this[k][h]&&this[k].destroy(a),!this[l][h]&&this[l].destroy(a)])}#aE(a){let{protocol:b,host:c,port:d}=a;return(c=c.replace(/:\d*$/,"").replace(/^\[(.+)\]$/,"$1").toLowerCase(),d=Number.parseInt(d,10)||o[b]||0,this.#aF(c,d))?"https:"===b?this[l]:this[k]:this[j]}#aF(a,b){if(this.#aG&&this.#aD(),0===this.#aC.length)return!0;if("*"===this.#aB)return!1;for(let c=0;c<this.#aC.length;c++){let d=this.#aC[c];if((!d.port||d.port===b)&&(a===d.hostname||a.slice(-(d.hostname.length+1))===`.${d.hostname}`))return!1}return!0}#aD(){let a=this.#y.noProxy??this.#aH,b=a.split(/[,\s]/),c=[];for(let a=0;a<b.length;a++){let d,e,f=b[a];if(!f)continue;let g=f.match(/^\[(.+)\]:(\d+)$/);if(g)d=g[1],e=Number.parseInt(g[2],10);else{let a=f.replace(/^\[(.+)\]$/,"$1"),b=1===(a.match(/:/g)||[]).length&&a.match(/^(.+):(\d+)$/);d=b?b[1]:a,e=b?Number.parseInt(b[2],10):0}c.push({hostname:d.replace(/^\*?\./,"").toLowerCase(),port:e})}this.#aB=a,this.#aC=c}get #aG(){return void 0===this.#y.noProxy&&this.#aB!==this.#aH}get #aH(){return process.env.no_proxy??process.env.NO_PROXY??""}}a.exports=p},43835:(a,b,c)=>{"use strict";c.d(b,{$D:()=>m,P9:()=>j,We:()=>h,aZ:()=>n,rG:()=>i});var d=c(39541),e=c(26317);let f="-agentic",g="-thinking";function h(a){return"google"===a||"github"===a?"arn:aws:codewhisperer:us-east-1:699475941385:profile/EHGA3GRVQMUK":"arn:aws:codewhisperer:us-east-1:638616132270:profile/AAAACCCCXXXX"}let i=`
|
|
303
|
+
* Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\\repo\\project\\main.rs:12:5`;var f=c(38421),g=c(98976),h=c(10342),i=c(26408),j=c(13161),k=c(86363),l=c(49623),m=c(97137),n=c(68531),o=c(73081);let p=new TextEncoder,q=/^(rs|fc|resp|msg)_/,r=new Set(["image_generation","web_search","web_search_preview","file_search","computer","computer_use_preview","code_interpreter","mcp","local_shell","tool_search"]),s=new Set(["custom"]),t=new Set(["model","input","instructions","tools","tool_choice","stream","store","reasoning","service_tier","include","prompt_cache_key","client_metadata","text"]);class u extends d.Hv{constructor(){super("codex",f.xq.codex),this._currentSessionId=null}buildHeaders(a,b=!0){let c=super.buildHeaders(a,b);c.session_id=this._currentSessionId||a?.connectionId||"default",c.originator||(c.originator="codex_cli_rs");let d=a?.providerSpecificData?.workspaceId;return"string"==typeof d&&d&&!c["chatgpt-account-id"]&&(c["chatgpt-account-id"]=d),c}buildUrl(a,b,c=0,d=null){let e=super.buildUrl(a,b,c,d);return this._isCompact?`${e}/compact`:e}async refreshCredentials(a,b){return a?.refreshToken?(0,g.Vq)("codex",a,b):null}needsRefresh(a){return(0,g.fp)("codex",a)}async prefetchImages(a){if(Array.isArray(a?.input))for(let b of a.input){if(!Array.isArray(b.content))continue;let a=b.content.map(async a=>{if("image_url"!==a.type)return a;let b="string"==typeof a.image_url?a.image_url:a.image_url?.url,c=a.image_url?.detail||"auto";if(!b)return a;if(b.startsWith("data:"))return{type:"input_image",image_url:b,detail:c};let d=await (0,i.ni)(b,{timeoutMs:15e3});return{type:"input_image",image_url:d?.url||b,detail:c}});b.content=await Promise.all(a)}}async execute(a){let b=Array.isArray(a.body?.input)?a.body.input.reduce((a,b)=>a+(Array.isArray(b.content)?b.content.filter(a=>"image_url"===a.type).length:0),0):0,c=Array.isArray(a.body?.input)?a.body.input.length:0;if((0,k.s)("CODEX",`execute start | inputItems=${c} | images=${b} | session=${this._currentSessionId?"resolved":"pending"}`),b>0){let b=Date.now();await this.prefetchImages(a.body),(0,k.s)("CODEX",`prefetchImages done | ${Date.now()-b}ms`)}else await this.prefetchImages(a.body);let d=await this._executeOverWebSocket(a);return d||(0,m.v)({execute:()=>super.execute(a),retryConfig:this.config.retry,signal:a.signal,log:a.log,provider:"codex"})}async _executeOverWebSocket(a){if("off"===process.env.CODEX_WS_TRANSPORT||process.env.VITEST||this._isCompact||!1===a.stream)return null;try{let b=this.transformRequest(a.model,a.body,a.stream,a.credentials),c=this.buildUrl(a.model,a.stream,0,a.credentials),d={...this.buildHeaders(a.credentials,a.stream,c,a.model)};delete d["Content-Type"],delete d.Accept;let e=function({wsUrl:a,headers:b,request:c,WebSocket:d=globalThis.WebSocket,signal:e}={}){let f;if("function"!=typeof d)throw Error("no WebSocket implementation available");try{f=new d(a,{headers:b})}catch(a){throw Error(`codex ws connect failed: ${a.message}`)}let g=!1,h=()=>{try{f.close()}catch{}};e?.addEventListener?.("abort",h,{once:!0});let i=new Promise((b,d)=>{f.onopen=()=>{try{f.send(JSON.stringify({type:"response.create",...c})),(0,k.s)("CODEX-WS",`opened ${a} | request sent`),b()}catch(a){d(Error(`codex ws send failed: ${a.message}`))}},f.onerror=()=>d(Error("codex ws handshake failed"))});return{response:new Response(new ReadableStream({start(a){let b=b=>{if(!g){g=!0,e?.removeEventListener?.("abort",h);try{f.close()}catch{}try{b?a.error(b):a.close()}catch{}}};f.onmessage=c=>{let d="string"==typeof c.data?c.data:"",e=null;try{e=JSON.parse(d)?.type||null}catch{}e&&(a.enqueue(p.encode(`event: ${e}
|
|
304
|
+
data: ${d}
|
|
305
|
+
|
|
306
|
+
`)),(0,o.nu)(e,{response:{}})&&((0,k.s)("CODEX-WS",`terminal ${e} | closing`),b()))},f.onclose=()=>b(g?null:Error("codex ws closed before terminal event"))},cancel(){g=!0,e?.removeEventListener?.("abort",h);try{f.close()}catch{}}}),{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Switchboard-Transport":"responses-websocket"}}),url:a,headers:b,ready:i,format:n.h.OPENAI_RESPONSES}}({wsUrl:String(c).replace(/^http:\/\//i,"ws://").replace(/^https:\/\//i,"wss://"),headers:d,request:b,signal:a.signal});return await e.ready,(0,k.s)("CODEX-WS",`transport=responses_websocket | ${c}`),{response:e.response,url:c,headers:d,transformedBody:b}}catch(b){return a.log?.warn?.("CODEX-WS",`websocket transport failed, falling back to HTTP: ${b.message}`),(0,k.s)("CODEX-WS",`handshake failed: ${b.message}`),null}}parseError(a,b){if(429===a.status&&b)try{let a=JSON.parse(b),c=a?.error;if(c?.type==="usage_limit_reached"){let a=Date.now(),d=null;if("number"==typeof c.resets_at&&c.resets_at>0){let b=1e3*c.resets_at;b>a&&(d=b)}if(!d&&"number"==typeof c.resets_in_seconds&&c.resets_in_seconds>0&&(d=a+1e3*c.resets_in_seconds),d)return{status:429,message:c.message||b,resetsAtMs:d}}}catch{}return super.parseError(a,b)}transformRequest(a,b,c,d){this._isCompact=!!b._compact,delete b._compact,this._currentSessionId=(0,l.oV)({headers:d?.rawHeaders,body:b,connectionId:d?.connectionId,workspaceId:d?.providerSpecificData?.workspaceId,scope:"codex"});let f=(0,h.m)(b.input);if(f&&(b.input=f),(!b.input||Array.isArray(b.input)&&0===b.input.length)&&(b.input=[{type:"message",role:"user",content:[{type:"input_text",text:"..."}]}]),Array.isArray(b.input))for(let a of b.input)!(!a||"object"!=typeof a||Array.isArray(a))&&("system"!==a.role||a.type&&"message"!==a.type||(a.role="developer"));Array.isArray(b.input)&&(b.input=b.input.filter(a=>{if("string"==typeof a&&q.test(a))return!1;if(a&&"object"==typeof a&&!Array.isArray(a)){if("item_reference"===a.type)return!1;"string"==typeof a.id&&q.test(a.id)&&delete a.id}return!0})),function(a){if(!Array.isArray(a.tools))return;let b=new Set;if(a.tools=a.tools.filter(a=>{if(!a||"object"!=typeof a||Array.isArray(a))return!1;let c="string"==typeof a.type?a.type:"";if("namespace"===c){if(Array.isArray(a.tools))for(let c of a.tools){let a="string"==typeof c?.name?c.name.trim().slice(0,128):"";a&&b.add(a)}return!0}if("function"!==c)return!!s.has(c)||!!c&&!a.function&&"string"!=typeof a.name&&r.has(c);let d=a.function&&"object"==typeof a.function&&!Array.isArray(a.function)?a.function:null,e=("string"==typeof a.name?a.name:"string"==typeof d?.name?d.name:"").trim();if(!e)return!1;let f="string"==typeof a.description?a.description:"string"==typeof d?.description?d.description:"",g=a.parameters&&"object"==typeof a.parameters&&!Array.isArray(a.parameters)?a.parameters:d?.parameters&&"object"==typeof d.parameters&&!Array.isArray(d.parameters)?d.parameters:{type:"object",properties:{}};for(let b of Object.keys(a))delete a[b];return a.type="function",a.name=e.slice(0,128),f&&(a.description=f),a.parameters=g,b.add(e),!0}),a.tool_choice&&"object"==typeof a.tool_choice&&!Array.isArray(a.tool_choice)&&"function"===a.tool_choice.type){let c="string"==typeof a.tool_choice.name?a.tool_choice.name.trim():"";c&&b.has(c)||delete a.tool_choice}}(b),b.stream=!0,b.instructions&&""!==b.instructions.trim()||(b.instructions=e),b.store=!1,!b.prompt_cache_key&&this._currentSessionId&&(b.prompt_cache_key=this._currentSessionId),b.model=(0,j.kt)("cx",b.model||a);let g=null;for(let a of["none","low","medium","high","xhigh"])if(b.model.endsWith(`-${a}`)){g=a,b.model=b.model.replace(`-${a}`,"");break}if(b.reasoning)b.reasoning.summary||(b.reasoning.summary="auto");else{let a=b.reasoning_effort||g||"low";b.reasoning={effort:a,summary:"auto"}}for(let a of(delete b.reasoning_effort,b.reasoning&&b.reasoning.effort&&"none"!==b.reasoning.effort&&(b.include=["reasoning.encrypted_content"]),delete b.temperature,delete b.top_p,delete b.frequency_penalty,delete b.presence_penalty,delete b.logprobs,delete b.top_logprobs,delete b.n,delete b.seed,delete b.max_tokens,delete b.max_completion_tokens,delete b.max_output_tokens,delete b.user,delete b.prompt_cache_retention,delete b.metadata,delete b.stream_options,delete b.safety_identifier,delete b.previous_response_id,Object.keys(b)))t.has(a)||delete b[a];return b}}},40603:(a,b,c)=>{"use strict";let{EventEmitter:d}=c(78474),{Buffer:e}=c(4573),{InvalidArgumentError:f,Socks5ProxyError:g}=c(61448),{debuglog:h}=c(57975),{parseAddress:i}=c(33297),j=h("undici:socks5"),k=e.alloc(0),l={NO_AUTH:0,GSSAPI:1,USERNAME_PASSWORD:2,NO_ACCEPTABLE:255},m={CONNECT:1,BIND:2,UDP_ASSOCIATE:3},n={IPV4:1,DOMAIN:3,IPV6:4},o={SUCCEEDED:0,GENERAL_FAILURE:1,CONNECTION_NOT_ALLOWED:2,NETWORK_UNREACHABLE:3,HOST_UNREACHABLE:4,CONNECTION_REFUSED:5,TTL_EXPIRED:6,COMMAND_NOT_SUPPORTED:7,ADDRESS_TYPE_NOT_SUPPORTED:8},p={INITIAL:"initial",HANDSHAKING:"handshaking",AUTHENTICATING:"authenticating",AUTHENTICATED:"authenticated",CONNECTING:"connecting",CONNECTED:"connected",ERROR:"error",CLOSED:"closed"};class q extends d{constructor(a,b={}){if(super(),!a)throw new f("socket is required");this.socket=a,this.options=b,this.state=p.INITIAL,this.buffer=k,this.onSocketData=this.onData.bind(this),this.onSocketError=this.onError.bind(this),this.onSocketClose=this.onClose.bind(this),this.authMethods=[],b.username&&b.password&&this.authMethods.push(l.USERNAME_PASSWORD),this.authMethods.push(l.NO_AUTH),this.socket.on("data",this.onSocketData),this.socket.on("error",this.onSocketError),this.socket.on("close",this.onSocketClose)}onData(a){j("received data",a.length,"bytes in state",this.state),this.buffer=e.concat([this.buffer,a]);try{switch(this.state){case p.HANDSHAKING:this.handleHandshakeResponse();break;case p.AUTHENTICATING:this.handleAuthResponse();break;case p.CONNECTING:this.handleConnectResponse()}}catch(a){this.onError(a)}}onError(a){j("socket error",a),this.state=p.ERROR,this.emit("error",a),this.destroy()}onClose(){j("socket closed"),this.state=p.CLOSED,this.emit("close")}destroy(){this.socket&&!this.socket.destroyed&&this.socket.destroy()}markAuthenticated(){this.state=p.AUTHENTICATED,this.emit("authenticated")}handshake(){if(this.state!==p.INITIAL)throw new f("Handshake already started");j("starting handshake with",this.authMethods.length,"auth methods"),this.state=p.HANDSHAKING;let a=e.alloc(2+this.authMethods.length);a[0]=5,a[1]=this.authMethods.length,this.authMethods.forEach((b,c)=>{a[2+c]=b}),this.socket.write(a)}handleHandshakeResponse(){if(this.buffer.length<2)return;let a=this.buffer[0],b=this.buffer[1];if(5!==a)throw new g(`Invalid SOCKS version: ${a}`,"UND_ERR_SOCKS5_VERSION");if(b===l.NO_ACCEPTABLE)throw new g("No acceptable authentication method","UND_ERR_SOCKS5_AUTH_REJECTED");if(this.buffer=this.buffer.subarray(2),j("server selected auth method",b),b===l.NO_AUTH)this.markAuthenticated();else if(b===l.USERNAME_PASSWORD)this.state=p.AUTHENTICATING,this.sendAuthRequest();else throw new g(`Unsupported authentication method: ${b}`,"UND_ERR_SOCKS5_AUTH_METHOD")}sendAuthRequest(){let{username:a,password:b}=this.options;if(!a||!b)throw new f("Username and password required for authentication");j("sending username/password auth");let c=e.from(a),d=e.from(b);if(c.length>255||d.length>255)throw new f("Username or password too long");let g=e.alloc(3+c.length+d.length);g[0]=1,g[1]=c.length,c.copy(g,2),g[2+c.length]=d.length,d.copy(g,3+c.length),this.socket.write(g)}handleAuthResponse(){if(this.buffer.length<2)return;let a=this.buffer[0],b=this.buffer[1];if(1!==a)throw new g(`Invalid auth sub-negotiation version: ${a}`,"UND_ERR_SOCKS5_AUTH_VERSION");if(0!==b)throw new g("Authentication failed","UND_ERR_SOCKS5_AUTH_FAILED");this.buffer=this.buffer.subarray(2),j("authentication successful"),this.markAuthenticated()}connect(a,b){if(this.state===p.CONNECTING||this.state===p.CONNECTED)throw new f("Connection already in progress");if(this.state!==p.AUTHENTICATED)throw new f("Client must be authenticated before CONNECT");j("connecting to",a,b),this.state=p.CONNECTING;let c=this.buildConnectRequest(m.CONNECT,a,b);this.socket.write(c)}buildConnectRequest(a,b,c){let{type:d,buffer:f}=i(b),g=e.alloc(4+f.length+2);return g[0]=5,g[1]=a,g[2]=0,g[3]=d,f.copy(g,4),g.writeUInt16BE(c,4+f.length),g}handleConnectResponse(){let a;if(this.buffer.length<4)return;let b=this.buffer[0],c=this.buffer[1],d=this.buffer[3];if(5!==b)throw new g(`Invalid SOCKS version in reply: ${b}`,"UND_ERR_SOCKS5_REPLY_VERSION");let e=4;if(d===n.IPV4)e+=6;else if(d===n.DOMAIN){if(this.buffer.length<5)return;e+=1+this.buffer[4]+2}else if(d===n.IPV6)e+=18;else throw new g(`Invalid address type in reply: ${d}`,"UND_ERR_SOCKS5_ADDR_TYPE");if(this.buffer.length<e)return;if(c!==o.SUCCEEDED){let a=this.getReplyErrorMessage(c);throw new g(`SOCKS5 connection failed: ${a}`,`UND_ERR_SOCKS5_REPLY_${c}`)}let f=4;if(d===n.IPV4)a=Array.from(this.buffer.subarray(f,f+4)).join("."),f+=4;else if(d===n.DOMAIN){let b=this.buffer[f];f+=1,a=this.buffer.subarray(f,f+b).toString(),f+=b}else if(d===n.IPV6){let b=[];for(let a=0;a<8;a++){let c=this.buffer.readUInt16BE(f+2*a);b.push(c.toString(16))}a=b.join(":"),f+=16}let h=this.buffer.readUInt16BE(f);this.buffer=k,this.state=p.CONNECTED,this.socket.removeListener("data",this.onSocketData),j("connected, bound address:",a,"port:",h),this.emit("connected",{address:a,port:h})}getReplyErrorMessage(a){switch(a){case o.GENERAL_FAILURE:return"General SOCKS server failure";case o.CONNECTION_NOT_ALLOWED:return"Connection not allowed by ruleset";case o.NETWORK_UNREACHABLE:return"Network unreachable";case o.HOST_UNREACHABLE:return"Host unreachable";case o.CONNECTION_REFUSED:return"Connection refused";case o.TTL_EXPIRED:return"TTL expired";case o.COMMAND_NOT_SUPPORTED:return"Command not supported";case o.ADDRESS_TYPE_NOT_SUPPORTED:return"Address type not supported";default:return`Unknown error code: ${a}`}}}a.exports={Socks5Client:q,AUTH_METHODS:l,COMMANDS:m,ADDRESS_TYPES:n,REPLY_CODES:o,STATES:p}},41702:(a,b,c)=>{var d=c(45654);c(33889),d.mgf=d.mgf||{},(a.exports=d.mgf.mgf1=d.mgf1=d.mgf1||{}).create=function(a){return{generate:function(b,c){for(var e=new d.util.ByteBuffer,f=Math.ceil(c/a.digestLength),g=0;g<f;g++){var h=new d.util.ByteBuffer;h.putInt32(g),a.start(),a.update(b+h.getBytes()),e.putBuffer(a.digest())}return e.truncate(e.length()-c),e.getBytes()}}}},41883:(a,b,c)=>{"use strict";c.d(b,{w:()=>k});var d=c(67671),e=c(38421),f=c(96997),g=c(50969);let h=new Map;function i(a){if("string"!=typeof a)return null;try{let b=JSON.parse(a);if("authorized_user"===b.type&&b.client_id&&b.client_secret&&b.refresh_token)return b;return null}catch{return null}}async function j(a,b,c,d){if(h.has(a))return h.get(a);let e=await (0,g.Fm)(`https://aiplatform.googleapis.com/v1/publishers/google/models/__probe__:generateContent?key=${a}`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",identity:c.identity,provider:b,format:c.format},d),f=await e.json().catch(()=>null),i=(f?.[0]?.error?.message||f?.error?.message||"").match(/projects\/([^/]+)\//),j=i?.[1]||null;return j&&h.set(a,j),j}class k extends d.Hv{constructor(a="vertex"){super(a,e.xq[a]||{})}buildUrl(a,b,c=0,d=null){let e=(0,f.Sc)(d?.apiKey),g=i(d?.apiKey),h=!!e||!!g||!!d?.accessToken,j=h?null:d?.apiKey,k=e?.project_id||g?.quota_project_id||d?.providerSpecificData?.projectId;if("vertex-partner"===this.provider){if(!k)throw Error("Vertex partner models require a project_id. Add it in providerSpecificData or use Service Account JSON.");let a=`https://aiplatform.googleapis.com/v1/projects/${k}/locations/global/endpoints/openapi/chat/completions`;return j?`${a}?key=${j}`:a}let l=b?"streamGenerateContent":"generateContent";if(h){if(!k)throw Error("Vertex OAuth/ADC requires a project_id. Add quota_project_id to your ADC JSON or set providerSpecificData.projectId.");let c=d?.providerSpecificData?.location||"us-central1",e=`https://aiplatform.googleapis.com/v1/projects/${k}/locations/${c}/publishers/google/models/${a}:${l}`;return b&&(e+="?alt=sse"),e}let m=`https://aiplatform.googleapis.com/v1/publishers/google/models/${a}:${l}`;return b&&(m+="?alt=sse"),j&&(m+=b?`&key=${j}`:`?key=${j}`),m}buildHeaders(a,b=!0){let c={"Content-Type":"application/json"};return a.accessToken&&(c.Authorization=`Bearer ${a.accessToken}`),b&&(c.Accept="text/event-stream"),c}async refreshCredentials(a,b,c=null){let d=(0,f.Sc)(a?.apiKey);if(d){let a=await (0,f.pb)(d,b);return a?{accessToken:a.accessToken,expiresAt:a.expiresAt}:null}let e=i(a?.apiKey);if(e){let a=await (0,f.I9)(e.refresh_token,e.client_id,e.client_secret,b,this.provider,c);return a?.accessToken?{accessToken:a.accessToken,expiresAt:a.expiresAt}:null}return null}async execute({model:a,body:b,stream:c,credentials:d,signal:e,log:h,proxyOptions:k=null}){let l=(0,f.Sc)(d?.apiKey),m=i(d?.apiKey);if(l){let a=await (0,f.pb)(l,h);if(!a?.accessToken)throw Error("Vertex: failed to mint access token from Service Account JSON");d.accessToken=a.accessToken}if(m){let a=await (0,f.I9)(m.refresh_token,m.client_id,m.client_secret,h,this.provider,k);if(!a?.accessToken)throw Error("Vertex: failed to refresh access token from ADC JSON (authorized_user)");d.accessToken=a.accessToken}if("vertex-partner"===this.provider&&!l&&!m&&!d?.providerSpecificData?.projectId){let a=await j(d.apiKey,this.provider,this.config,k);if(!a)throw Error("Vertex: could not resolve project_id from API key. Please add it manually in provider settings.");h?.debug?.("VERTEX",`Resolved project_id: ${a}`),d.providerSpecificData={...d.providerSpecificData,projectId:a}}let n=this.buildUrl(a,c,0,d),o=this.buildHeaders(d,c),p=this.transformRequest(a,b,c,d);return{response:await (0,g.Fm)(n,{method:"POST",headers:o,body:JSON.stringify(p),signal:e},k),url:n,headers:o,transformedBody:p}}}},42425:(a,b,c)=>{"use strict";let{Transform:d}=c(57075),e=c(38522),{redirectStatusSet:f,referrerPolicyTokens:g,badPortsSet:h}=c(19608),{getGlobalOrigin:i}=c(79412),{collectAnHTTPQuotedString:j,parseMIMEType:k}=c(16537),{performance:l}=c(643),{ReadableStreamFrom:m,isValidHTTPToken:n,normalizedMethodRecordsBase:o}=c(84285),p=c(34589),{isUint8Array:q}=c(73429),{webidl:r}=c(32984),{isomorphicEncode:s,collectASequenceOfCodePoints:t,removeChars:u}=c(70745);function v(a){let b=a.urlList,c=b.length;return 0===c?null:b[c-1].toString()}function w(a){for(let b=0;b<a.length;++b){let c=a.charCodeAt(b);if(c>126||c<32)return!1}return!0}function x(a){return a.urlList[a.urlList.length-1]}function y(a){return!1===(" "===a[0]||" "===a[0]||" "===a[a.length-1]||" "===a[a.length-1]||a.includes("\n")||a.includes("\r")||a.includes("\0"))}function z(){return{referrerPolicy:"strict-origin-when-cross-origin"}}function A(a,b=!1){return(p(r.is.URL(a)),J(a=new URL(a)))?"no-referrer":(a.username="",a.password="",a.hash="",!0===b&&(a.pathname="",a.search=""),a)}let B=RegExp.prototype.test.bind(/^127\.(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){2}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$/),C=RegExp.prototype.test.bind(/^(?:(?:0{1,4}:){7}|(?:0{1,4}:){1,6}:|::)0{0,3}1$/);function D(a){return a.includes(":")?("["===a[0]&&"]"===a[a.length-1]&&(a=a.slice(1,-1)),C(a)):B(a)}function E(a){var b;return!!r.is.URL(a)&&("about:blank"===a.href||"about:srcdoc"===a.href||"data:"===a.protocol||"blob:"===a.protocol||null!=(b=a.origin)&&"null"!==b&&(!!("https:"===(b=new URL(b)).protocol||"wss:"===b.protocol||D(b.hostname)||"localhost"===b.hostname||"localhost."===b.hostname||b.hostname.endsWith(".localhost")||b.hostname.endsWith(".localhost."))||"file:"===b.protocol))}function F(a,b){return a.origin===b.origin&&"null"===a.origin||a.protocol===b.protocol&&a.hostname===b.hostname&&a.port===b.port}let G=Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()));function H(a,b,c=0,d=1){class e{#ai;#aj;#ak;constructor(a,b){this.#ai=a,this.#aj=b,this.#ak=0}next(){let e;if("object"!=typeof this||this===null||!(#ai in this))throw TypeError(`'next' called on an object that does not implement interface ${a} Iterator.`);let f=this.#ak,g=b(this.#ai);if(f>=g.length)return{value:void 0,done:!0};let{[c]:h,[d]:i}=g[f];switch(this.#ak=f+1,this.#aj){case"key":e=h;break;case"value":e=i;break;case"key+value":e=[h,i]}return{value:e,done:!1}}}return delete e.prototype.constructor,Object.setPrototypeOf(e.prototype,G),Object.defineProperties(e.prototype,{[Symbol.toStringTag]:{writable:!1,enumerable:!1,configurable:!0,value:`${a} Iterator`},next:{writable:!0,enumerable:!0,configurable:!0}}),function(a,b){return new e(a,b)}}async function I(a,b,c){try{let d=[],e=0;for(;;){let{done:f,value:g}=await a.read();if(f)return void b(Buffer.concat(d,e));if(!q(g))return void c(TypeError("Received non-Uint8Array chunk"));d.push(g),e+=g.length}}catch(a){c(a)}}function J(a){p("protocol"in a);let b=a.protocol;return"about:"===b||"blob:"===b||"data:"===b}function K(a){return"string"==typeof a&&":"===a[5]&&"h"===a[0]&&"t"===a[1]&&"t"===a[2]&&"p"===a[3]&&"s"===a[4]||"https:"===a.protocol}function L(a){p("protocol"in a);let b=a.protocol;return"http:"===b||"https:"===b}class M extends d{#al;constructor(a){super(),this.#al=a}_transform(a,b,c){if(!this._inflateStream){if(0===a.length)return void c();this._inflateStream=(15&a[0])==8?e.createInflate(this.#al):e.createInflateRaw(this.#al),this._inflateStream.on("data",this.push.bind(this)),this._inflateStream.on("end",()=>this.push(null)),this._inflateStream.on("error",a=>this.destroy(a))}this._inflateStream.write(a,b,c)}_final(a){this._inflateStream&&(this._inflateStream.end(),this._inflateStream=null),a()}}function N(a,b){let c=b.get(a,!0);if(null===c)return null;let d={position:0},e=[],f="";for(;d.position<c.length;){if(f+=t(a=>'"'!==a&&","!==a,c,d),d.position<c.length)if(34===c.charCodeAt(d.position)){if(f+=j(c,d),d.position<c.length)continue}else p(44===c.charCodeAt(d.position)),d.position++;f=u(f,!0,!0,a=>9===a||32===a),e.push(f),f=""}return e}class O{get baseUrl(){return i()}get origin(){return this.baseUrl?.origin}policyContainer=z()}class P{settingsObject=new O}a.exports={isAborted:function(a){return"aborted"===a.controller.state},isCancelled:function(a){return"aborted"===a.controller.state||"terminated"===a.controller.state},isValidEncodedURL:w,ReadableStreamFrom:m,tryUpgradeRequestToAPotentiallyTrustworthyURL:function(a){},clampAndCoarsenConnectionTimingInfo:function(a,b,c){return!a?.startTime||a.startTime<b?{domainLookupStartTime:b,domainLookupEndTime:b,connectionStartTime:b,connectionEndTime:b,secureConnectionStartTime:b,ALPNNegotiatedProtocol:a?.ALPNNegotiatedProtocol}:{domainLookupStartTime:a.domainLookupStartTime,domainLookupEndTime:a.domainLookupEndTime,connectionStartTime:a.connectionStartTime,connectionEndTime:a.connectionEndTime,secureConnectionStartTime:a.secureConnectionStartTime,ALPNNegotiatedProtocol:a.ALPNNegotiatedProtocol}},coarsenedSharedCurrentTime:function(a){return l.now()},determineRequestsReferrer:function(a){let b=a.referrerPolicy;p(b);let c=null;if("client"===a.referrer){let a=i();if(!a||"null"===a.origin)return"no-referrer";c=new URL(a)}else r.is.URL(a.referrer)&&(c=a.referrer);let d=A(c),e=A(c,!0);switch(d.toString().length>4096&&(d=e),b){case"no-referrer":return"no-referrer";case"origin":if(null!=e)return e;return A(c,!0);case"unsafe-url":return d;case"strict-origin":{let b=x(a);if(E(d)&&!E(b))return"no-referrer";return e}case"strict-origin-when-cross-origin":{let b=x(a);if(F(d,b))return d;if(E(d)&&!E(b))return"no-referrer";return e}case"same-origin":if(F(a,d))return d;return"no-referrer";case"origin-when-cross-origin":if(F(a,d))return d;return e;case"no-referrer-when-downgrade":{let b=x(a);if(E(d)&&!E(b))return"no-referrer";return d}}},makePolicyContainer:z,clonePolicyContainer:function(a){return{referrerPolicy:a.referrerPolicy}},appendFetchMetadata:function(a){let b=null;b=a.mode,a.headersList.set("sec-fetch-mode",b,!0)},appendRequestOriginHeader:function(a){let b=a.origin;if("client"!==b&&void 0!==b){if("cors"===a.responseTainting||"websocket"===a.mode)a.headersList.append("origin",b,!0);else if("GET"!==a.method&&"HEAD"!==a.method){switch(a.referrerPolicy){case"no-referrer":b=null;break;case"no-referrer-when-downgrade":case"strict-origin":case"strict-origin-when-cross-origin":a.origin&&K(a.origin)&&!K(x(a))&&(b=null);break;case"same-origin":F(a,x(a))||(b=null)}a.headersList.append("origin",b,!0)}}},TAOCheck:function(){return"success"},corsCheck:function(){return"success"},crossOriginResourcePolicyCheck:function(){return"allowed"},createOpaqueTimingInfo:function(a){return{startTime:a.startTime??0,redirectStartTime:0,redirectEndTime:0,postRedirectStartTime:a.startTime??0,finalServiceWorkerStartTime:0,finalNetworkResponseStartTime:0,finalNetworkRequestStartTime:0,endTime:0,encodedBodySize:0,decodedBodySize:0,finalConnectionTimingInfo:null}},setRequestReferrerPolicyOnRedirect:function(a,b){let c=function(a){let b=(a.headersList.get("referrer-policy",!0)??"").split(","),c="";if(b.length)for(let a=b.length;0!==a;a--){let d=b[a-1].trim();if(g.has(d)){c=d;break}}return c}(b);""!==c&&(a.referrerPolicy=c)},isValidHTTPToken:n,requestBadPort:function(a){let b=x(a);return L(b)&&h.has(b.port)?"blocked":"allowed"},requestCurrentURL:x,responseURL:v,responseLocationURL:function(a,b){var c;if(!f.has(a.status))return null;let d=a.headersList.get("location",!0);return null!==d&&y(d)&&(w(d)||(c=d,d=Buffer.from(c,"binary").toString("utf8")),d=new URL(d,v(a))),d&&!d.hash&&(d.hash=b),d},isURLPotentiallyTrustworthy:E,isValidReasonPhrase:function(a){for(let b=0;b<a.length;++b){let c=a.charCodeAt(b);if(!(9===c||c>=32&&c<=126||c>=128&&c<=255))return!1}return!0},sameOrigin:F,normalizeMethod:function(a){return o[a.toLowerCase()]??a},iteratorMixin:function(a,b,c,d=0,e=1){let f=H(a,c,d,e),g={keys:{writable:!0,enumerable:!0,configurable:!0,value:function(){return r.brandCheck(this,b),f(this,"key")}},values:{writable:!0,enumerable:!0,configurable:!0,value:function(){return r.brandCheck(this,b),f(this,"value")}},entries:{writable:!0,enumerable:!0,configurable:!0,value:function(){return r.brandCheck(this,b),f(this,"key+value")}},forEach:{writable:!0,enumerable:!0,configurable:!0,value:function(c,d=globalThis){if(r.brandCheck(this,b),r.argumentLengthCheck(arguments,1,`${a}.forEach`),"function"!=typeof c)throw TypeError(`Failed to execute 'forEach' on '${a}': parameter 1 is not of type 'Function'.`);for(let{0:a,1:b}of f(this,"key+value"))c.call(d,b,a,this)}}};return Object.defineProperties(b.prototype,{...g,[Symbol.iterator]:{writable:!0,enumerable:!1,configurable:!0,value:g.entries.value}})},createIterator:H,isValidHeaderName:n,isValidHeaderValue:y,isErrorLike:function(a){return a instanceof Error||a?.constructor?.name==="Error"||a?.constructor?.name==="DOMException"},fullyReadBody:function(a,b,c){try{let d=a.stream.getReader();I(d,b,c)}catch(a){c(a)}},readableStreamClose:function(a){try{a.close(),a.byobRequest?.respond(0)}catch(a){if(!a.message.includes("Controller is already closed")&&!a.message.includes("ReadableStream is already closed"))throw a}},urlIsLocal:J,urlHasHttpsScheme:K,urlIsHttpHttpsScheme:L,readAllBytes:I,simpleRangeHeaderValue:function(a,b){if(!a.startsWith("bytes"))return"failure";let c={position:5};if(b&&t(a=>" "===a||" "===a,a,c),61!==a.charCodeAt(c.position))return"failure";c.position++,b&&t(a=>" "===a||" "===a,a,c);let d=t(a=>{let b=a.charCodeAt(0);return b>=48&&b<=57},a,c),e=d.length?Number(d):null;if(b&&t(a=>" "===a||" "===a,a,c),45!==a.charCodeAt(c.position))return"failure";c.position++,b&&t(a=>" "===a||" "===a,a,c);let f=t(a=>{let b=a.charCodeAt(0);return b>=48&&b<=57},a,c),g=f.length?Number(f):null;return c.position<a.length||null===g&&null===e||null!==e&&null!==g&&e>g?"failure":{rangeStartValue:e,rangeEndValue:g}},buildContentRange:function(a,b,c){let d="bytes ";return d+=s(`${a}`),d+="-",d+=s(`${b}`),d+="/",d+=s(`${c}`)},createInflate:function(a){return new M(a)},extractMimeType:function(a){let b=null,c=null,d=null,e=N("content-type",a);if(null===e)return"failure";for(let a of e){let e=k(a);"failure"!==e&&"*/*"!==e.essence&&((d=e).essence!==c?(b=null,d.parameters.has("charset")&&(b=d.parameters.get("charset")),c=d.essence):d.parameters.has("charset")||null===b||d.parameters.set("charset",b))}return null==d?"failure":d},getDecodeSplit:N,environmentSettingsObject:new P,isOriginIPPotentiallyTrustworthy:D,hasAuthenticationEntry:function(a){return!1},includesCredentials:function(a){return!!(a.username||a.password)},isTraversableNavigable:function(a){return null!=a&&"client"!==a&&"no-traversable"!==a}}},42430:(a,b,c)=>{"use strict";let{addAbortListener:d}=c(78474),{environmentSettingsObject:e,readableStreamClose:f}=c(42425),{states:g,opcodes:h,sentCloseFrameState:i}=c(62026),{webidl:j}=c(32984),{getURLRecord:k,isValidSubprotocol:l,isEstablished:m,utf8Decode:n}=c(94050),{establishWebSocketConnection:o,failWebsocketConnection:p,closeWebSocketConnection:q}=c(4654),{channels:r}=c(62571),{WebsocketFrameSend:s}=c(45221),{ByteParser:t}=c(64821),{WebSocketError:u,createUnvalidatedWebSocketError:v}=c(87404),{kEnumerableProperty:w}=c(84285),{utf8DecodeBytes:x}=c(67449),y=!1;class z{#am;#an;#ao;#ap;#aq;#ar;#as=!1;#at={onConnectionEstablished:(a,b)=>this.#au(a,b),onMessage:(a,b)=>this.#av(a,b),onParserError:a=>p(this.#at,null,a.message),onParserDrain:()=>this.#at.socket.resume(),onSocketData:a=>{this.#aw.write(a)||this.#at.socket.pause()},onSocketError:a=>{this.#at.readyState=g.CLOSING,r.socketError.hasSubscribers&&r.socketError.publish(a),this.#at.socket.destroy()},onSocketClose:()=>this.#ax(),onPing:()=>{},onPong:()=>{},readyState:g.CONNECTING,socket:null,closeState:new Set,controller:null,wasEverConnected:!1};#aw;constructor(a,b){y||(process.emitWarning("WebSocketStream is experimental! Expect it to change at any time.",{code:"UNDICI-WSS"}),y=!0),j.argumentLengthCheck(arguments,1,"WebSocket"),a=j.converters.USVString(a),null!==b&&(b=j.converters.WebSocketStreamOptions(b));const c=k(a,e.settingsObject.baseUrl),f=b.protocols;if(f.length!==new Set(f.map(a=>a.toLowerCase())).size||f.length>0&&!f.every(a=>l(a)))throw new DOMException("Invalid Sec-WebSocket-Protocol value","SyntaxError");if(this.#am=c.toString(),this.#an=Promise.withResolvers(),this.#ao=Promise.withResolvers(),null!=b.signal){const a=b.signal;if(a.aborted){this.#an.reject(a.reason),this.#ao.reject(a.reason);return}d(a,()=>{m(this.#at.readyState)||(p(this.#at),this.#at.readyState=g.CLOSING,this.#an.reject(a.reason),this.#ao.reject(a.reason),this.#as=!0)})}const h=e.settingsObject;this.#at.controller=o(c,f,h,this.#at,b)}get url(){return this.#am.toString()}get opened(){return this.#an.promise}get closed(){return this.#ao.promise}close(a){null!==a&&(a=j.converters.WebSocketCloseInfo(a));let b=a.closeCode??null,c=a.reason;q(this.#at,b,c,!0)}#ay(a){a=j.converters.WebSocketStreamWrite(a);let b=Promise.withResolvers(),c=null,d=null;if(j.is.BufferSource(a))c=new Uint8Array(ArrayBuffer.isView(a)?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):a.slice()),d=h.BINARY;else{let e;try{e=j.converters.DOMString(a)}catch(a){return b.reject(a),b.promise}c=new TextEncoder().encode(e),d=h.TEXT}if(!this.#at.closeState.has(i.SENT)&&!this.#at.closeState.has(i.RECEIVED)){let a=new s(c);this.#at.socket.write(a.createFrame(d),()=>{b.resolve(void 0)})}return b.promise}#au(a,b){this.#at.socket=a.socket;let c=this.#at.controller.dispatcher?.webSocketOptions?.maxFragments,d=this.#at.controller.dispatcher?.webSocketOptions?.maxPayloadSize,e=new t(this.#at,b,{maxFragments:c,maxPayloadSize:d});e.on("drain",()=>this.#at.onParserDrain()),e.on("error",a=>this.#at.onParserError(a)),this.#aw=e,this.#at.readyState=g.OPEN;let f=b??"",h=a.headersList.get("sec-websocket-protocol")??"",i=new ReadableStream({start:a=>{this.#aq=a},cancel:a=>this.#az(a)}),j=new WritableStream({write:a=>this.#ay(a),close:()=>q(this.#at,null,null),abort:a=>this.#aA(a)});this.#ap=i,this.#ar=j,this.#an.resolve({extensions:f,protocol:h,readable:i,writable:j})}#av(a,b){let c;if(this.#at.readyState===g.OPEN){if(a===h.TEXT)try{c=n(b)}catch{p(this.#at,1007,"Received invalid UTF-8 in text frame.");return}else a===h.BINARY&&(c=new Uint8Array(b.buffer,b.byteOffset,b.byteLength));this.#aq.enqueue(c)}}#ax(){let a=this.#at.closeState.has(i.SENT)&&this.#at.closeState.has(i.RECEIVED);if(this.#at.readyState=g.CLOSED,this.#as)return;this.#at.wasEverConnected||this.#an.reject(new u("Socket never opened"));let b=this.#aw?.closingInfo,c=b?.code??1005;this.#at.closeState.has(i.SENT)||this.#at.closeState.has(i.RECEIVED)||(c=1006);let d=b?.reason==null?"":x(Buffer.from(b.reason));if(a)f(this.#aq),this.#ar.locked||this.#ar.abort(new DOMException("A closed WebSocketStream cannot be written to","InvalidStateError")),this.#ao.resolve({closeCode:c,reason:d});else{let a=v("unclean close",c,d);this.#aq?.error(a),this.#ar?.abort(a),this.#ao.reject(a)}}#aA(a){let b=null,c="";j.is.WebSocketError(a)&&(b=a.closeCode,c=a.reason),q(this.#at,b,c)}#az(a){this.#aA(a)}}Object.defineProperties(z.prototype,{url:w,opened:w,closed:w,close:w,[Symbol.toStringTag]:{value:"WebSocketStream",writable:!1,enumerable:!1,configurable:!0}}),j.converters.WebSocketStreamOptions=j.dictionaryConverter([{key:"protocols",converter:j.sequenceConverter(j.converters.USVString),defaultValue:()=>[]},{key:"signal",converter:j.nullableConverter(j.converters.AbortSignal),defaultValue:()=>null}]),j.converters.WebSocketCloseInfo=j.dictionaryConverter([{key:"closeCode",converter:a=>j.converters["unsigned short"](a,j.attributes.EnforceRange)},{key:"reason",converter:j.converters.USVString,defaultValue:()=>""}]),j.converters.WebSocketStreamWrite=function(a){return"string"==typeof a?j.converters.USVString(a):j.converters.BufferSource(a)},a.exports={WebSocketStream:z}},43086:(a,b,c)=>{"use strict";let d=c(5318),{kClose:e,kDestroy:f,kClosed:g,kDestroyed:h,kDispatch:i,kNoProxyAgent:j,kHttpProxyAgent:k,kHttpsProxyAgent:l}=c(49176),m=c(48841),n=c(37417),o={"http:":80,"https:":443};class p extends d{#aB=null;#aC=null;#y=null;constructor(a={}){super(),this.#y=a;const{httpProxy:b,httpsProxy:c,noProxy:d,...e}=a;this[j]=new n(e);const f=b??process.env.http_proxy??process.env.HTTP_PROXY;f?this[k]=new m({...e,uri:f}):this[k]=this[j];const g=c??process.env.https_proxy??process.env.HTTPS_PROXY;g?this[l]=new m({...e,uri:g}):this[l]=this[k],this.#aD()}[i](a,b){let c=new URL(a.origin);return this.#aE(c).dispatch(a,b)}[e](){return Promise.all([this[j].close(),!this[k][g]&&this[k].close(),!this[l][g]&&this[l].close()])}[f](a){return Promise.all([this[j].destroy(a),!this[k][h]&&this[k].destroy(a),!this[l][h]&&this[l].destroy(a)])}#aE(a){let{protocol:b,host:c,port:d}=a;return(c=c.replace(/:\d*$/,"").replace(/^\[(.+)\]$/,"$1").toLowerCase(),d=Number.parseInt(d,10)||o[b]||0,this.#aF(c,d))?"https:"===b?this[l]:this[k]:this[j]}#aF(a,b){if(this.#aG&&this.#aD(),0===this.#aC.length)return!0;if("*"===this.#aB)return!1;for(let c=0;c<this.#aC.length;c++){let d=this.#aC[c];if((!d.port||d.port===b)&&(a===d.hostname||a.slice(-(d.hostname.length+1))===`.${d.hostname}`))return!1}return!0}#aD(){let a=this.#y.noProxy??this.#aH,b=a.split(/[,\s]/),c=[];for(let a=0;a<b.length;a++){let d,e,f=b[a];if(!f)continue;let g=f.match(/^\[(.+)\]:(\d+)$/);if(g)d=g[1],e=Number.parseInt(g[2],10);else{let a=f.replace(/^\[(.+)\]$/,"$1"),b=1===(a.match(/:/g)||[]).length&&a.match(/^(.+):(\d+)$/);d=b?b[1]:a,e=b?Number.parseInt(b[2],10):0}c.push({hostname:d.replace(/^\*?\./,"").toLowerCase(),port:e})}this.#aB=a,this.#aC=c}get #aG(){return void 0===this.#y.noProxy&&this.#aB!==this.#aH}get #aH(){return process.env.no_proxy??process.env.NO_PROXY??""}}a.exports=p},43835:(a,b,c)=>{"use strict";c.d(b,{$D:()=>m,P9:()=>j,We:()=>h,aZ:()=>n,rG:()=>i});var d=c(39541),e=c(26317);let f="-agentic",g="-thinking";function h(a){return"google"===a||"github"===a?"arn:aws:codewhisperer:us-east-1:699475941385:profile/EHGA3GRVQMUK":"arn:aws:codewhisperer:us-east-1:638616132270:profile/AAAACCCCXXXX"}let i=`
|
|
304
307
|
# CRITICAL: CHUNKED WRITE PROTOCOL (MANDATORY)
|
|
305
308
|
|
|
306
309
|
You MUST follow these rules for ALL file operations. Violation causes server timeouts and task failure.
|
|
@@ -391,7 +394,7 @@ ${a.format(b)}`.trim())}}a.exports=G},65737:(a,b,c)=>{var d=c(45654);c(45518),c(
|
|
|
391
394
|
FROM ${e} JOIN vault_entries ON vault_entries.id = ${e}.entryId
|
|
392
395
|
WHERE ${e} MATCH ? AND ${e}.conversationId = ? AND vault_entries.expiresAt > ?${d} ORDER BY rank LIMIT ?`,f)}catch{o=[]}if(0===o.length&&l.length>0){var h;let b=l.map(()=>"lower(vault_chunks.text) LIKE ?").join(" OR "),d=c?[a,n,c,...l.map(a=>`%${a}%`),4*i]:[a,n,...l.map(a=>`%${a}%`),4*i];h=m.all(`SELECT vault_chunks.entryId AS entryId, vault_chunks.chunkIndex AS chunkIndex, vault_chunks.text AS text
|
|
393
396
|
FROM vault_chunks JOIN vault_entries ON vault_entries.id = vault_chunks.entryId
|
|
394
|
-
WHERE vault_chunks.conversationId = ? AND vault_entries.expiresAt > ?${c?" AND vault_chunks.entryId = ?":""} AND (${b}) LIMIT ?`,d),o=Array.isArray(h)&&Array.isArray(l)?h.map(a=>({...a,score:l.reduce((b,c)=>b+Number(String(a?.text||"").toLowerCase().includes(c)),0)})).sort((a,b)=>b.score-a.score).slice(0,i):[]}let p=function(a,b){if(!Array.isArray(b))return[];let c=new Map;for(let d of b.slice(0,20)){let b=d?.entryId;if(!(!b||c.has(b)))try{c.set(b,a.get("SELECT toolName FROM vault_entries WHERE id = ?",[b])?.toolName??null)}catch{c.set(b,null)}}return b.map(a=>({entryId:a.entryId,chunkIndex:a.chunkIndex,text:a.text,toolName:c.get(a.entryId)??null}))}(m,o.slice(0,i));var j=[...new Set(p.map(a=>a.entryId))],k=new Date().toISOString();if(Array.isArray(j)&&k)for(let a of j.slice(0,20))try{m.run("UPDATE vault_entries SET lastAccessedAt = ? WHERE id = ?",[k,a])}catch{}return p}catch{return[]}}async function j(a){try{if("string"!=typeof a||!a)return null;let b=await (0,d.c)(),c=b.get("SELECT id, conversationId, toolName, content, expiresAt FROM vault_entries WHERE id = ?",[a]);if(!c)return null;let f=new Date().toISOString();if(c.expiresAt<f){try{b.run("DELETE FROM vault_chunks WHERE entryId = ?",[a]),g(b)&&b.run(`DELETE FROM ${e} WHERE entryId = ?`,[a]),b.run("DELETE FROM vault_entries WHERE id = ?",[a])}catch{}return null}try{b.run("UPDATE vault_entries SET lastAccessedAt = ? WHERE id = ?",[f,a])}catch{}return{id:c.id,conversationId:c.conversationId,toolName:c.toolName,content:c.content}}catch{return null}}async function k(){try{var a=await (0,d.c)(),b=new Date().toISOString();if("string"!=typeof b||!b)return 0;let c="SELECT id FROM vault_entries WHERE expiresAt < ?";if(a.run(`DELETE FROM vault_chunks WHERE entryId IN (${c})`,[b]),g(a))try{a.run(`DELETE FROM ${e} WHERE entryId IN (${c})`,[b])}catch{}return a.run("DELETE FROM vault_entries WHERE expiresAt < ?",[b])?.changes??0}catch{return 0}}},70906:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{q:()=>i});var e=c(77168),f=c(77326);c(72345);var g=c(95695);c(63995);var h=a([e,g]);async function i(a,b=!1,c=null){let d=(0,g.SB)(a.provider),e={accessToken:a.accessToken,refreshToken:a.refreshToken,idToken:a.idToken,expiresAt:a.expiresAt||a.tokenExpiresAt,lastRefreshAt:a.lastRefreshAt,connectionId:a.id,providerSpecificData:a.providerSpecificData,copilotToken:a.providerSpecificData?.copilotToken,copilotTokenExpiresAt:a.providerSpecificData?.copilotTokenExpiresAt};if(!(b||d.needsRefresh(e)))return{connection:a,refreshed:!1};let h=await d.refreshCredentials(e,console,c);if(!h){if(a.accessToken)return{connection:a,refreshed:!1};throw Error("Failed to refresh credentials. Please re-authorize the connection.")}let j={updatedAt:new Date().toISOString()};h.accessToken&&(j.accessToken=h.accessToken),h.refreshToken&&(j.refreshToken=h.refreshToken),h.idToken&&(j.idToken=h.idToken),h.lastRefreshAt&&(j.lastRefreshAt=h.lastRefreshAt),h.expiresIn?(j.expiresAt=new Date(Date.now()+1e3*h.expiresIn).toISOString(),j.expiresIn=h.expiresIn):h.expiresAt&&(j.expiresAt=h.expiresAt);let k={...h.providerSpecificData||{},...h.copilotToken?{copilotToken:h.copilotToken}:{},...h.copilotTokenExpiresAt?{copilotTokenExpiresAt:h.copilotTokenExpiresAt}:{}};return Object.keys(k).length>0&&(j.providerSpecificData={...a.providerSpecificData||{},...k}),await (0,f.updateProviderConnection)(a.id,j),{connection:{...a,...j,providerSpecificData:j.providerSpecificData||a.providerSpecificData},refreshed:!0}}[e,g]=h.then?(await h)():h,d()}catch(a){d(a)}})},71137:(a,b,c)=>{"use strict";c.d(b,{CP:()=>p,yI:()=>m});var d=c(27137),e=c(74075);let f="1"===process.env.CURSOR_PROTOBUF_DEBUG,g=(a,...b)=>f&&console.log(`[PROTOBUF:${a}]`,...b);new TextDecoder;let h="1.1.3",i=new Set([1,2,3,9,10,11,27,1,25]);function j(a){let b=[];for(;a>=128;)b.push(127&a|128),a>>>=7;return b.push(127&a),new Uint8Array(b)}function k(a,b,c){let d=j(a<<3|b);if(0===b)return l(d,j(c));if(2===b){let a="string"==typeof c?new TextEncoder().encode(c):c instanceof Uint8Array?c:Buffer.isBuffer(c)?new Uint8Array(c):new Uint8Array(0);return l(d,j(a.length),a)}return new Uint8Array(0)}function l(...a){let b=new Uint8Array(a.reduce((a,b)=>a+b.length,0)),c=0;for(let d of a)b.set(d,c),c+=d.length;return b}function m(a,b,c=[],f=null,h=!1){g("BODY",`Generating: ${a.length} msgs, model=${b}, tools=${c.length}, reasoning=${f||"none"}, forceAgentMode=${h}`);let i=function(a,b,c=[],e=null,f=!1){return k(1,2,function(a,b,c=[],e=null,f=!1){let h,i=c?.length>0,m=i||f,n=[],o=[],p=[];for(let b=0;b<a.length;b++){let c=a[b],d=Array.isArray(c?.tool_calls)&&c.tool_calls.length>0,e=Array.isArray(c?.tool_results)&&c.tool_results.length>0;if(c?.role==="assistant"&&d&&e){g("ENCODE",`normalizing mixed assistant tool payload at msg[${b}] (calls=${c.tool_calls.length}, results=${c.tool_results.length})`),p.push({...c,tool_results:[]});let d=a[b+1],e=d?.role==="assistant"&&Array.isArray(d?.tool_results)&&d.tool_results.length>0,f=new Set(c.tool_results.map(a=>a?.tool_call_id).filter(a=>"string"==typeof a)),h=new Set((d?.tool_results||[]).map(a=>a?.tool_call_id).filter(a=>"string"==typeof a)),i=f.size>0&&f.size===h.size;if(i){for(let a of f)if(!h.has(a)){i=!1;break}}e&&i||p.push({role:"assistant",content:"",tool_results:c.tool_results});continue}p.push(c)}for(let a=0;a<p.length;a++){let b=p[a],c="user"===b.role?1:2,e=(0,d.A)(),f=a===p.length-1;n.push({content:b.content,role:c,messageId:e,isLast:f,hasTools:i,toolResults:b.tool_results||[]}),o.push({messageId:e,role:c})}let q=0;return"medium"===e?q=1:"high"===e&&(q=2),l(...n.map(a=>k(1,2,function(a,b,c,d=!1,e=!1,f=[],g=null){let h=f.length>0;return l(k(1,2,a),k(2,0,b),k(13,2,c),...g?[k(32,2,g)]:[],...h?f.map(a=>k(18,2,function(a){var b;let c,d,e=function(a){let b="string"==typeof a&&a.length>0?a:"tool";if(b.startsWith("mcp__")){let a=b.slice(5),c=a.indexOf("__");if(c>=0){let b=a.slice(0,c)||"custom",d=a.slice(c+2)||"tool";return`mcp_${b}_${d}`}return`mcp_custom_${a||"tool"}`}return b.startsWith("mcp_")?b:`mcp_custom_${b}`}(a.tool_name||a.name||""),f=a.raw_args||"{}",g=a.result_content||a.result||"",{toolCallId:h,modelCallId:i}=(b=a.tool_call_id||"",c="\nmc_",(d=b.indexOf(c))>=0?{toolCallId:b.slice(0,d),modelCallId:b.slice(d+c.length)}:{toolCallId:b,modelCallId:null}),j=a.tool_index||a.index||1,{serverName:m,selectedTool:n}=function(a){if("string"!=typeof a||!a.startsWith("mcp_"))return{serverName:"custom",selectedTool:a||"tool"};let b=a.slice(4),c=b.indexOf("_");return c<0?{serverName:"custom",selectedTool:b||"tool"}:{serverName:b.slice(0,c)||"custom",selectedTool:b.slice(c+1)||"tool"}}(e);return l(k(1,2,h),k(2,2,e),k(3,0,j>0?j:1),...i?[k(12,2,i)]:[],k(5,2,f),k(8,2,function(a,b,c,d,e=1){return l(k(1,0,19),k(28,2,l(k(1,2,c),k(2,2,d))),k(35,2,a),...b?[k(48,2,b)]:[],k(49,0,e>0?e:1))}(h,i,n,g,j)),k(11,2,function(a,b,c,d,e,f,g=1){let h;return l(k(1,0,19),k(27,2,(h=l(k(1,2,c),k(3,2,e),k(4,2,d)),k(1,2,h))),k(3,2,a),k(9,2,b),k(10,2,e),k(48,0,g>0?g:1),...f?[k(49,2,f)]:[])}(h,e,n,m,f,i,j)))}(a))):[],k(29,0,+!!e),k(47,0,e?2:1),...d&&e?[k(51,2,j(1))]:[])}(a.content,a.role,a.messageId,a.isLast,a.hasTools,a.toolResults))),k(2,0,1),k(3,2,new Uint8Array(0)),k(4,0,1),k(5,2,l(k(1,2,b),k(4,2,new Uint8Array(0)))),k(8,2,""),k(13,0,1),k(15,2,(h=l(k(1,2,new Uint8Array(0)),k(2,2,new Uint8Array(0))),l(k(1,2,"cursor\\aisettings"),k(3,2,new Uint8Array(0)),k(6,2,h),k(8,0,1),k(9,0,1)))),k(19,0,1),k(23,2,(0,d.A)()),k(26,2,l(k(1,2,process.platform||"linux"),k(2,2,process.arch||"x64"),k(3,2,process.version||"v20.0.0"),k(4,2,process.cwd?.()||"/"),k(5,2,new Date().toISOString()))),k(27,0,+!!m),...m?[k(29,2,j(1))]:[],...o.map(a=>k(30,2,function(a,b,c=null){return l(k(1,2,a),...c?[k(2,2,c)]:[],k(3,0,b))}(a.messageId,a.role))),...c?.length>0?c.map(a=>{let b,c,d;return k(34,2,(b=a.function?.name||a.name||"",c=a.function?.description||a.description||"",d=a.function?.parameters||a.input_schema||{},l(...b?[k(1,2,b)]:[],...c?[k(2,2,c)]:[],...Object.keys(d).length>0?[k(3,2,JSON.stringify(d))]:[],k(4,2,"custom"))))}):[],k(35,0,0),k(38,0,0),k(46,0,m?2:1),k(47,2,""),k(48,0,+!m),k(49,0,q),k(51,0,0),k(53,0,1),k(54,2,m?"Agent":"Ask"))}(a,b,c,e,f))}(a,b,c,f,h),n=function(a,b=!1){let c=a,d=0;b&&(c=new Uint8Array(e.gzipSync(Buffer.from(a))),d=1);let f=new Uint8Array(5+c.length);return f[0]=d,f[1]=c.length>>24&255,f[2]=c.length>>16&255,f[3]=c.length>>8&255,f[4]=255&c.length,f.set(c,5),f}(i,!1);return g("BODY",`Protobuf=${i.length}B, Framed=${n.length}B`),n}function n(a,b){let c=0,d=0,e=b;for(;e<a.length;){let b=a[e];if(c|=(127&b)<<d,e++,!(128&b))break;d+=7}return[c,e]}function o(a){let b=new Map,c=0;for(;c<a.length;){let[d,e,f,g]=function(a,b){let c;if(b>=a.length)return[null,null,null,b];let[d,e]=n(a,b),f=7&d,g=e;if(0===f)[c,g]=n(a,g);else if(2===f){let[b,d]=n(a,g);c=a.slice(d,d+b),g=d+b}else 1===f?(c=a.slice(g,g+8),g+=8):5===f?(c=a.slice(g,g+4),g+=4):c=null;return[d>>3,f,c,g]}(a,c);if(null===d)break;b.has(d)||b.set(d,[]),b.get(d).push({wireType:e,value:f}),c=g}return b}function p(a){try{let b=o(a);for(let a of b.keys())i.has(a)||g("SCHEMA",`Unknown response field #${a} detected. Schema v${h} may be outdated.`);if(b.has(1)){let a=function(a){let b=o(a),c="",d="",e="",f=!1;if(b.has(3)&&(c=new TextDecoder().decode(b.get(3)[0].value).split("\n")[0]),b.has(9)&&(d=new TextDecoder().decode(b.get(9)[0].value)),b.has(11)&&(f=0!==b.get(11)[0].value),b.has(27))try{let a=o(b.get(27)[0].value);if(a.has(1)){let b=o(a.get(1)[0].value);b.has(1)&&(d=new TextDecoder().decode(b.get(1)[0].value)),b.has(3)&&(e=new TextDecoder().decode(b.get(3)[0].value))}}catch(a){g("EXTRACT",`MCP parse error: ${a.message}`)}return(!e&&b.has(10)&&(e=new TextDecoder().decode(b.get(10)[0].value)),c&&d)?{id:c,type:"function",function:{name:d,arguments:e||"{}"},isLast:f}:null}(b.get(1)[0].value);if(a)return g("EXTRACT",`Tool call: ${a.function.name}`),{text:null,error:null,toolCall:a,thinking:null}}if(b.has(2)){let{text:a,thinking:c}=function(a){let b=o(a),c=null,d=null;if(b.has(1)&&(c=new TextDecoder().decode(b.get(1)[0].value)),b.has(25))try{let a=o(b.get(25)[0].value);a.has(1)&&(d=new TextDecoder().decode(a.get(1)[0].value))}catch(a){g("EXTRACT",`Thinking parse error: ${a.message}`)}return{text:c,thinking:d}}(b.get(2)[0].value);if(a||c)return{text:a,error:null,toolCall:null,thinking:c}}return{text:null,error:null,toolCall:null,thinking:null}}catch(b){return g("EXTRACT",`Decode failed (schema v${h}): ${b.message}`),{text:null,error:null,toolCall:null,thinking:null,raw:Buffer.from(a).toString("base64"),decodeError:b.message}}}},71253:(a,b,c)=>{"use strict";c.d(b,{PROVIDER_PRICING:()=>f,calculateCostFromTokens:()=>j,gH:()=>h,getPricingForModel:()=>i});var d=c(57690);let e={"claude-opus-4-6":{input:5,output:25,cached:.5,reasoning:25,cache_creation:6.25},"claude-opus-4-5-20251101":{input:5,output:25,cached:.5,reasoning:25,cache_creation:6.25},"claude-sonnet-4-6":{input:3,output:15,cached:.3,reasoning:15,cache_creation:3.75},"claude-sonnet-4-5-20250929":{input:3,output:15,cached:.3,reasoning:15,cache_creation:3.75},"claude-haiku-4-5-20251001":{input:1,output:5,cached:.1,reasoning:5,cache_creation:1.25},"claude-sonnet-4-20250514":{input:3,output:15,cached:1.5,reasoning:15,cache_creation:3},"claude-opus-4-20250514":{input:15,output:25,cached:7.5,reasoning:112.5,cache_creation:15},"claude-3-5-sonnet-20241022":{input:3,output:15,cached:1.5,reasoning:15,cache_creation:3},"claude-haiku-4.5":{input:.5,output:2.5,cached:.05,reasoning:3.75,cache_creation:.5},"claude-opus-4.1":{input:5,output:25,cached:.5,reasoning:37.5,cache_creation:5},"claude-opus-4.5":{input:5,output:25,cached:.5,reasoning:37.5,cache_creation:5},"claude-opus-4.6":{input:5,output:25,cached:.5,reasoning:37.5,cache_creation:5},"claude-sonnet-4":{input:3,output:15,cached:.3,reasoning:22.5,cache_creation:3},"claude-sonnet-4.5":{input:3,output:15,cached:.3,reasoning:22.5,cache_creation:3},"claude-sonnet-4.6":{input:3,output:15,cached:.3,reasoning:22.5,cache_creation:3},"claude-opus-4-5-thinking":{input:5,output:25,cached:.5,reasoning:37.5,cache_creation:5},"claude-opus-4-6-thinking":{input:5,output:25,cached:.5,reasoning:37.5,cache_creation:5},"gpt-3.5-turbo":{input:.5,output:1.5,cached:.25,reasoning:2.25,cache_creation:.5},"gpt-4":{input:2.5,output:10,cached:1.25,reasoning:15,cache_creation:2.5},"gpt-4-turbo":{input:10,output:30,cached:5,reasoning:45,cache_creation:10},"gpt-4o":{input:2.5,output:10,cached:1.25,reasoning:15,cache_creation:2.5},"gpt-4o-mini":{input:.15,output:.6,cached:.075,reasoning:.9,cache_creation:.15},"gpt-4.1":{input:2.5,output:10,cached:1.25,reasoning:15,cache_creation:2.5},"gpt-5":{input:3,output:12,cached:1.5,reasoning:18,cache_creation:3},"gpt-5-mini":{input:.75,output:3,cached:.375,reasoning:4.5,cache_creation:.75},"gpt-5-codex":{input:3,output:12,cached:1.5,reasoning:18,cache_creation:3},"gpt-5.1":{input:4,output:16,cached:2,reasoning:24,cache_creation:4},"gpt-5.1-codex":{input:4,output:16,cached:2,reasoning:24,cache_creation:4},"gpt-5.1-codex-mini":{input:1.5,output:6,cached:.75,reasoning:9,cache_creation:1.5},"gpt-5.1-codex-mini-high":{input:2,output:8,cached:1,reasoning:12,cache_creation:2},"gpt-5.1-codex-max":{input:8,output:32,cached:4,reasoning:48,cache_creation:8},"gpt-5.2":{input:5,output:20,cached:2.5,reasoning:30,cache_creation:5},"gpt-5.2-codex":{input:5,output:20,cached:2.5,reasoning:30,cache_creation:5},"gpt-5.3-codex":{input:6,output:24,cached:3,reasoning:36,cache_creation:6},"gpt-5.3-codex-spark":{input:3,output:12,cached:.3,reasoning:12,cache_creation:3},o1:{input:15,output:60,cached:7.5,reasoning:90,cache_creation:15},"o1-mini":{input:3,output:12,cached:1.5,reasoning:18,cache_creation:3},"gemini-3-flash-preview":{input:.5,output:3,cached:.03,reasoning:4.5,cache_creation:.5},"gemini-3-pro-preview":{input:2,output:12,cached:.25,reasoning:18,cache_creation:2},"gemini-3.1-pro-low":{input:2,output:12,cached:.25,reasoning:18,cache_creation:2},"gemini-3.1-pro-high":{input:4,output:18,cached:.5,reasoning:27,cache_creation:4},"gemini-pro-agent":{input:4,output:18,cached:.5,reasoning:27,cache_creation:4},"gemini-3-flash-agent":{input:.5,output:3,cached:.03,reasoning:4.5,cache_creation:.5},"gemini-3.5-flash-low":{input:.5,output:3,cached:.03,reasoning:4.5,cache_creation:.5},"gemini-3.5-flash-extra-low":{input:.5,output:3,cached:.03,reasoning:4.5,cache_creation:.5},"gemini-3-flash":{input:.5,output:3,cached:.03,reasoning:4.5,cache_creation:.5},"gemini-2.5-pro":{input:2,output:12,cached:.25,reasoning:18,cache_creation:2},"gemini-2.5-flash":{input:.3,output:2.5,cached:.03,reasoning:3.75,cache_creation:.3},"gemini-2.5-flash-lite":{input:.15,output:1.25,cached:.015,reasoning:1.875,cache_creation:.15},"qwen3-coder-plus":{input:1,output:4,cached:.5,reasoning:6,cache_creation:1},"qwen3-coder-flash":{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5},"kimi-k2":{input:1,output:4,cached:.5,reasoning:6,cache_creation:1},"kimi-k2-thinking":{input:1.5,output:6,cached:.75,reasoning:9,cache_creation:1.5},"kimi-k2.5":{input:1.2,output:4.8,cached:.6,reasoning:7.2,cache_creation:1.2},"kimi-k2.5-thinking":{input:1.8,output:7.2,cached:.9,reasoning:10.8,cache_creation:1.8},"kimi-latest":{input:1,output:4,cached:.5,reasoning:6,cache_creation:1},"deepseek-chat":{input:.14,output:.28,cached:.0028,reasoning:.28,cache_creation:.14},"deepseek-reasoner":{input:.14,output:.28,cached:.0028,reasoning:.28,cache_creation:.14},"deepseek-r1":{input:.14,output:.28,cached:.0028,reasoning:.28,cache_creation:.14},"deepseek-v3.2-chat":{input:.14,output:.28,cached:.0028,reasoning:.28,cache_creation:.14},"deepseek-v3.2-reasoner":{input:.14,output:.28,cached:.0028,reasoning:.28,cache_creation:.14},"deepseek-v4-flash":{input:.14,output:.28,cached:.0028,reasoning:.28,cache_creation:.14},"deepseek-v4-pro":{input:.435,output:.87,cached:.003625,reasoning:.87,cache_creation:.435},"glm-4.6":{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5},"glm-4.6v":{input:.75,output:3,cached:.375,reasoning:4.5,cache_creation:.75},"glm-4.7":{input:.75,output:3,cached:.375,reasoning:4.5,cache_creation:.75},"glm-5":{input:1,output:4,cached:.5,reasoning:6,cache_creation:1},"MiniMax-M3":{input:.3,output:1.2,cached:.06,reasoning:1.8,cache_creation:.3},"MiniMax-M2.1":{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5},"MiniMax-M2.5":{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5},"MiniMax-M2.7":{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5},"minimax-m2.1":{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5},"minimax-m2.5":{input:.6,output:2.4,cached:.3,reasoning:3.6,cache_creation:.6},"grok-code-fast-1":{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5},auto:{input:2,output:8,cached:1,reasoning:12,cache_creation:2},"oswe-vscode-prime":{input:1,output:4,cached:.5,reasoning:6,cache_creation:1},"gpt-oss-120b-medium":{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5},"vision-model":{input:1.5,output:6,cached:.75,reasoning:9,cache_creation:1.5},"coder-model":{input:1.5,output:6,cached:.75,reasoning:9,cache_creation:1.5}},f={gh:{"gpt-5.3-codex":{input:1.75,output:14,cached:.175,reasoning:14,cache_creation:1.75}}},g=[{pattern:"*-codex-xhigh",pricing:{input:10,output:40,cached:5,reasoning:60,cache_creation:10}},{pattern:"*-codex-high",pricing:{input:8,output:32,cached:4,reasoning:48,cache_creation:8}},{pattern:"*-codex-max",pricing:{input:8,output:32,cached:4,reasoning:48,cache_creation:8}},{pattern:"*-codex-mini-*",pricing:{input:1.5,output:6,cached:.75,reasoning:9,cache_creation:1.5}},{pattern:"*-codex-mini",pricing:{input:1.5,output:6,cached:.75,reasoning:9,cache_creation:1.5}},{pattern:"*-codex-low",pricing:{input:4,output:16,cached:2,reasoning:24,cache_creation:4}},{pattern:"*-codex-none",pricing:{input:3,output:12,cached:1.5,reasoning:18,cache_creation:3}},{pattern:"*-codex-spark",pricing:{input:3,output:12,cached:.3,reasoning:12,cache_creation:3}},{pattern:"codex-*",pricing:{input:3,output:12,cached:1.5,reasoning:18,cache_creation:3}},{pattern:"*-codex",pricing:{input:3,output:12,cached:1.5,reasoning:18,cache_creation:3}},{pattern:"claude-opus-*",pricing:{input:5,output:25,cached:.5,reasoning:25,cache_creation:6.25}},{pattern:"claude-sonnet-*",pricing:{input:3,output:15,cached:.3,reasoning:15,cache_creation:3.75}},{pattern:"claude-haiku-*",pricing:{input:1,output:5,cached:.1,reasoning:5,cache_creation:1.25}},{pattern:"claude-*",pricing:{input:3,output:15,cached:.3,reasoning:15,cache_creation:3.75}},{pattern:"gemini-*-flash-lite",pricing:{input:.15,output:1.25,cached:.015,reasoning:1.875,cache_creation:.15}},{pattern:"gemini-*-flash",pricing:{input:.3,output:2.5,cached:.03,reasoning:3.75,cache_creation:.3}},{pattern:"gemini-*-pro",pricing:{input:2,output:12,cached:.25,reasoning:18,cache_creation:2}},{pattern:"gemini-3-*",pricing:{input:.5,output:3,cached:.03,reasoning:4.5,cache_creation:.5}},{pattern:"gemini-2.5-*",pricing:{input:.3,output:2.5,cached:.03,reasoning:3.75,cache_creation:.3}},{pattern:"gemini-*",pricing:{input:.5,output:3,cached:.03,reasoning:4.5,cache_creation:.5}},{pattern:"gpt-5.3-*",pricing:{input:6,output:24,cached:3,reasoning:36,cache_creation:6}},{pattern:"gpt-5.2-*",pricing:{input:5,output:20,cached:2.5,reasoning:30,cache_creation:5}},{pattern:"gpt-5.1-*",pricing:{input:4,output:16,cached:2,reasoning:24,cache_creation:4}},{pattern:"gpt-5-*",pricing:{input:3,output:12,cached:1.5,reasoning:18,cache_creation:3}},{pattern:"gpt-5*",pricing:{input:3,output:12,cached:1.5,reasoning:18,cache_creation:3}},{pattern:"gpt-4o-*",pricing:{input:.15,output:.6,cached:.075,reasoning:.9,cache_creation:.15}},{pattern:"gpt-4o",pricing:{input:2.5,output:10,cached:1.25,reasoning:15,cache_creation:2.5}},{pattern:"gpt-4*",pricing:{input:2.5,output:10,cached:1.25,reasoning:15,cache_creation:2.5}},{pattern:"o1-*",pricing:{input:3,output:12,cached:1.5,reasoning:18,cache_creation:3}},{pattern:"o1",pricing:{input:15,output:60,cached:7.5,reasoning:90,cache_creation:15}},{pattern:"o3-*",pricing:{input:10,output:40,cached:5,reasoning:60,cache_creation:10}},{pattern:"o4-*",pricing:{input:2,output:8,cached:1,reasoning:12,cache_creation:2}},{pattern:"qwen3-coder-*",pricing:{input:1,output:4,cached:.5,reasoning:6,cache_creation:1}},{pattern:"qwen*-coder-*",pricing:{input:1,output:4,cached:.5,reasoning:6,cache_creation:1}},{pattern:"qwen*",pricing:{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5}},{pattern:"kimi-*-thinking",pricing:{input:1.8,output:7.2,cached:.9,reasoning:10.8,cache_creation:1.8}},{pattern:"kimi-k2*",pricing:{input:1.2,output:4.8,cached:.6,reasoning:7.2,cache_creation:1.2}},{pattern:"kimi-*",pricing:{input:1,output:4,cached:.5,reasoning:6,cache_creation:1}},{pattern:"deepseek-*reasoner*",pricing:{input:.14,output:.28,cached:.0028,reasoning:.28,cache_creation:.14}},{pattern:"deepseek-r*",pricing:{input:.14,output:.28,cached:.0028,reasoning:.28,cache_creation:.14}},{pattern:"deepseek-v*",pricing:{input:.14,output:.28,cached:.0028,reasoning:.28,cache_creation:.14}},{pattern:"deepseek-*",pricing:{input:.14,output:.28,cached:.0028,reasoning:.28,cache_creation:.14}},{pattern:"glm-5*",pricing:{input:1,output:4,cached:.5,reasoning:6,cache_creation:1}},{pattern:"glm-4*",pricing:{input:.75,output:3,cached:.375,reasoning:4.5,cache_creation:.75}},{pattern:"glm-*",pricing:{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5}},{pattern:"MiniMax-*",pricing:{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5}},{pattern:"minimax-*",pricing:{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5}},{pattern:"grok-code-*",pricing:{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5}},{pattern:"grok-*",pricing:{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5}}];function h(a,b){return RegExp("^"+a.split("*").map(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*")+"$","i").test(b)}function i(a,b){if(!b)return null;if(a&&f[a]?.[b])return f[a][b];let c=(0,d.KN)(b),i=function(a){let b=a.includes("/")?a.split("/").pop():a;if(e[b]||e[a])return e[b]||e[a];for(let{pattern:c,pricing:d}of g)if(h(c,b||a))return d;return null}(b);return c&&i?{...i,...c}:c||i}function j(a,b){if(!a||!b)return 0;let c=0,d=a.prompt_tokens||a.input_tokens||0,e=a.cached_tokens||a.cache_read_input_tokens||0,f=a.cache_creation_input_tokens||0;c+=Math.max(0,d-e-f)*(b.input/1e6),e>0&&(c+=e*((b.cached||b.input)/1e6)),c+=(a.completion_tokens||a.output_tokens||0)*(b.output/1e6);let g=a.reasoning_tokens||0;return g>0&&(c+=g*((b.reasoning||b.output)/1e6)),f>0&&(c+=f*((b.cache_creation||b.input)/1e6)),c}},72285:(a,b,c)=>{"use strict";c.d(b,{h:()=>v});var d=c(77598),e=c(67671),f=c(38421),g=c(45431),h=c(98976),i=c(96997),j=c(10342),k=c(13161),l=c(49623),m=c(96930);let n=null;async function o(a="endpoint-proxy-salt"){let b=function(){if(n)return n;try{n=(0,m.machineIdSync)()}catch{n=d.randomUUID()}return n}();return d.createHash("sha256").update(b+a).digest("hex").substring(0,16)}var p=c(97137),q=c(83382);let r=new Set(["model","input","instructions","tools","tool_choice","stream","store","reasoning","include","temperature","top_p","max_output_tokens","parallel_tool_calls","text","metadata","prompt_cache_key"]),s=new Set(["low","medium","high","xhigh"]),t=/^(?:rs|msg|fc)_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function u(a,b){return a._grokCliRequest||(a._grokCliRequest={sessionId:(0,l.oV)({headers:a.rawHeaders,body:b,connectionId:a.connectionId||a.id,workspaceId:a.providerSpecificData?.workspaceId,scope:"grok-cli"}),requestId:d.randomUUID(),agentId:a.providerSpecificData?.deviceId||null,turnIdx:1,model:null}),a._grokCliRequest}class v extends e.Hv{constructor(){super("grok-cli",f.xq["grok-cli"]||g.A.transport)}buildUrl(){return`${q.Nr}/responses`}resolveIdentity(){return q.s2}async refreshCredentials(a,b,c=null){if(!a?.refreshToken)return null;let d=await (0,i.$B)("grok-cli",a,b,c);return(0,h.hJ)("grok-cli",a,d)}needsRefresh(a){return(0,h.fp)("grok-cli",a)}buildHeaders(a,b=!0){let c=super.buildHeaders(a,b),d=u(a,{});c["x-grok-session-id"]=d.sessionId,c["x-grok-conv-id"]=d.sessionId,c["x-grok-req-id"]=d.requestId,c["x-grok-turn-idx"]=String(d.turnIdx),d.agentId&&(c["x-grok-agent-id"]=d.agentId),d.model&&(c["x-grok-model-override"]=d.model);let e=a.providerSpecificData||{};return(e.email||a.email)&&(c["x-email"]=e.email||a.email),(e.userId||a.userId)&&(c["x-userid"]=e.userId||a.userId),c}transformRequest(a,b,c,d){var e;let f=u(d,b),g=(0,j.m)(b.input);g?b.input=g:Array.isArray(b.messages)&&(b.input=b.messages.map(a=>({type:"message",role:a.role||"user",content:"string"==typeof a.content?a.content:JSON.stringify(a.content??"")}))),b.input||(b.input=(0,j.m)("")),Array.isArray(b.input)&&(b.input=b.input.filter(a=>"string"==typeof a?!/^(rs|fc|resp|msg)_/.test(a):!a||"object"!=typeof a||"item_reference"!==a.type&&("string"==typeof a.id&&/^(rs|fc|resp|msg)_/.test(a.id)&&!t.test(a.id)&&delete a.id,!0))),function(a){if(!Array.isArray(a.tools)||0===a.tools.length){delete a.tools,delete a.tool_choice;return}let b=new Set;if(a.tools=a.tools.flatMap(a=>{if(!a||"object"!=typeof a||Array.isArray(a))return[];if(["web_search","x_search","file_search","image_generation","code_interpreter","mcp","local_shell"].includes(a.type))return[a];let c=a.function&&"object"==typeof a.function?a.function:a,d="string"==typeof c.name?c.name.trim().slice(0,128):"";return d?(b.add(d),[{type:"function",name:d,...c.description?{description:String(c.description)}:{},parameters:"custom"===a.type?{type:"object",properties:{input:{type:"string"}},required:["input"]}:c.parameters||{type:"object",properties:{}}}]):[]}),0===a.tools.length)delete a.tools,delete a.tool_choice;else if(a.tool_choice&&"object"==typeof a.tool_choice){let c=a.tool_choice.name||a.tool_choice.function?.name;b.has(c)?a.tool_choice={type:"function",name:c}:delete a.tool_choice}}(b),f.turnIdx=Array.isArray(e=b.input)?Math.max(1,e.filter(a=>a?.role==="user"&&(!a.type||"message"===a.type)).length):1;let h=String(b.model||a||q.to),i=h.match(/-(low|medium|high|xhigh)$/)?.[1]||null,l=i?h.slice(0,-(i.length+1)):h;b.model=(0,k.kt)("gcli",l)||l,f.model=b.model;let m=b.reasoning&&"object"==typeof b.reasoning?b.reasoning:{};if(b.reasoning={...m,summary:m.summary||"concise"},(0,q.Au)(b.model)){let a;b.reasoning.effort="max"===(a=String(m.effort||b.reasoning_effort||i||"").trim().toLowerCase())?"xhigh":s.has(a)?a:"high"}else delete b.reasoning.effort;for(let a of(delete b.reasoning_effort,b.include=Array.isArray(b.include)?b.include:[],b.include.includes("reasoning.encrypted_content")||b.include.push("reasoning.encrypted_content"),b.stream=!0,b.store=!1,delete b.messages,delete b.max_tokens,delete b.max_completion_tokens,delete b.user,delete b.stream_options,delete b.previous_response_id,Object.keys(b)))r.has(a)||delete b[a];return b}async execute(a){var b;let c,d={...a.credentials||{}},e=u(d,a.body);return e.agentId||(b=await o("grok-cli-agent"),c=`${b}${b}`.replace(/[^0-9a-f]/gi,"0").padEnd(32,"0").slice(0,32),e.agentId=`${c.slice(0,8)}-${c.slice(8,12)}-5${c.slice(13,16)}-a${c.slice(17,20)}-${c.slice(20)}`),(0,p.v)({execute:()=>super.execute({...a,credentials:d}),retryConfig:this.config.retry,signal:a.signal,log:a.log,provider:"grok-cli"})}parseError(a,b){if(402===a.status&&b)try{let a=JSON.parse(b);return{status:402,message:a.error||a.message||b,code:a.code}}catch{}return super.parseError(a,b)}}},72345:(a,b,c)=>{"use strict";c(50969);var d=c(38528);c(10793),(0,d.U)("antigravity"),c(82961),c(20012),c(43835),(0,d.U)("minimax").urls,(0,d.U)("minimax-cn").urls,c(15251),c(83382),(0,d.U)("glm").url,(0,d.U)("glm-cn").url,(0,d.U)("vercel-ai-gateway").url},73081:(a,b,c)=>{"use strict";c(68531),c(18101),new TextEncoder},73135:(a,b,c)=>{"use strict";let{addAbortListener:d}=c(84285),{RequestAbortedError:e}=c(61448),f=Symbol("kListener"),g=Symbol("kSignal");function h(a){a.abort?a.abort(a[g]?.reason):a.reason=a[g]?.reason??new e,i(a)}function i(a){a[g]&&("removeEventListener"in a[g]?a[g].removeEventListener("abort",a[f]):a[g].removeListener("abort",a[f]),a[g]=null,a[f]=null)}a.exports={addSignal:function(a,b){if(a.reason=null,a[g]=null,a[f]=null,b){if(b.aborted)return void h(a);a[g]=b,a[f]=()=>{h(a)},d(a[g],a[f])}},removeSignal:i}},73792:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{OJ:()=>w});var e=c(77168),f=c(77326),g=c(82961),h=c(20012),i=c(95695),j=c(50969),k=c(63993),l=c(70906),m=c(78744),n=a([e,i,l]);[e,i,l]=n.then?(await n)():n;let x=m.oc;x.tickIntervalMs;let y={claude:{getUsage:g.g,sendPing:r},codex:{getUsage:h.Tl,sendPing:t}},z=global.__quotaAutoPing??={interval:null,running:!1,resetCache:{},failureCache:{}};function o(a){let b=new Date(a).getTime();return Number.isFinite(b)?new Date(6e4*Math.floor(b/6e4)).toISOString():a}function p(a,b=null){if("number"==typeof a&&Number.isFinite(a))return a;if("string"==typeof a&&a.trim()){let b=Number(a);if(Number.isFinite(b))return b}return b}function q(a){if(!a||!0===a.unlimited)return!1;let b=p(a.remaining);if(null!==b)return b<=0;let c=p(a.used),d=p(a.total);return null!==d&&d>0&&null!==c&&c>=d}async function r(a,b,c,d){return(await d.proxyAwareFetch("https://api.anthropic.com/v1/messages?beta=true",{method:"POST",headers:{Authorization:`Bearer ${a.accessToken}`,"content-type":"application/json"},body:JSON.stringify({model:b.pingModel,max_tokens:b.pingMaxTokens,messages:[{role:"user",content:b.pingText}]}),identity:"claude-cli",provider:"claude",format:"claude",credentialId:a.id,stream:!1,retryCount:0},c)).ok}async function s(a){if("function"==typeof a?.text)return void await a.text();let b=a?.body?.getReader?.();if(b)try{for(;;){let{done:a}=await b.read();if(a)return}}finally{b.releaseLock?.()}}async function t(a,b,c,d){var e;let f=d.getExecutor("codex"),{response:g}=await f.execute({model:b.pingModel,stream:!0,credentials:{accessToken:a.accessToken,connectionId:a.id,providerSpecificData:a.providerSpecificData},proxyOptions:c,log:console,body:{model:b.pingModel,input:(e=b.pingText,[{type:"message",role:"user",content:[{type:"input_text",text:e}]}]),instructions:b.pingInstructions,reasoning:b.pingReasoningEffort?{effort:b.pingReasoningEffort,summary:"auto"}:void 0,store:!1,stream:!0}});if(!g.ok){try{await g.body?.cancel?.()}catch{}return!1}return await s(g),!0}async function u(a,b,c,d,e,f=z){var g,h,i;let j=(g=a.id,`${b}:${g}`),k=f.resetCache[j];if(!c.pingWhenResetAtSlides&&k&&Date.now()<new Date(k).getTime()-x.refreshAheadMs||function(a,b,c=Date.now()){let d=a.failureCache[b];return d&&c-d<x.failureCooldownMs}(f,j))return;let l=(h=await e.resolveConnectionProxyConfig(a.providerSpecificData),{connectionProxyEnabled:!0===h.connectionProxyEnabled,connectionProxyUrl:h.connectionProxyUrl||"",connectionNoProxy:h.connectionNoProxy||"",vercelRelayUrl:h.vercelRelayUrl||"",strictProxy:!1}),m=a;try{m=(await e.refreshAndUpdateCredentials(m,!1,l)).connection}catch(c){f.failureCache[j]=Date.now(),console.warn(`[AutoPing] ${b}:${a.id}: refresh failed: ${c.message}`);return}let n=await d.getUsage(m.accessToken,l),p=n?.quotas||{},r=p?.[c.quotaKey],s=function(a){if(!a||"object"!=typeof a)return null;if(!0===a.unlimited)return 100;let b=Number(a.remainingPercentage);if(Number.isFinite(b))return Math.max(0,Math.min(100,b));let c=Number(a.remaining),d=Number(a.total);return Number.isFinite(c)&&Number.isFinite(d)&&d>0?Math.max(0,Math.min(100,c/d*100)):Number.isFinite(c)?Math.max(0,c):null}(r);if(null!=s)try{await e.updateProviderConnection(m.id,{lastQuota:{remainingPercentage:s,resetAt:r.resetAt??null,at:Date.now()}})}catch{}let t=r?.resetAt;if(!t||(f.resetCache[j]=t,c.skipWhenBlockingQuotaExhausted&&(i=c.quotaKey,Object.entries(p||{}).some(([a,b])=>a!==i&&!String(a).toLowerCase().includes("session")&&q(b)))||q(r)))return;let v=Date.now(),w=o(t),y=m.lastPingedResetKey||o(m.lastPingedResetAt);if(!(!function(a,b,c,d){if(a.pingWhenResetAtSlides){let d,e;return!!b&&(d=new Date(b).getTime(),e=new Date(c).getTime(),(Number.isFinite(d)&&Number.isFinite(e)?e-d:0)>=(a.resetAtDriftMs||0))}let e=new Date(c).getTime();return Number.isFinite(e)&&d>=e-x.pingLeadMs}(c,k,t,v)||function(a,b,c=Date.now()){if(!b)return!1;let d=new Date(a.lastPingAt).getTime();return Number.isFinite(d)&&c-d<b}(m,c.minPingIntervalMs,v))&&y!==w){if(!await d.sendPing(m,c,l,e)){f.failureCache[j]=Date.now(),console.warn(`[AutoPing] ${b}:${m.id}: ping failed (reset ${t})`);return}delete f.failureCache[j],await e.updateProviderConnection(m.id,{lastPingedResetAt:t,lastPingedResetKey:w,lastPingAt:new Date().toISOString(),updatedAt:new Date().toISOString()}),console.log(`[AutoPing] ${b}:${m.id}: ping sent (reset ${t})`)}}async function v(a={getSettings:f.mt,getProviderConnections:f.getProviderConnections,updateProviderConnection:f.updateProviderConnection,resolveConnectionProxyConfig:k.B,refreshAndUpdateCredentials:l.q,proxyAwareFetch:j.Fm,getExecutor:i.SB},b=z){if(!b.running){b.running=!0;try{let d=await a.getSettings();for(let[e,f]of Object.entries(x.providers)){let g=y[e];if(!g)continue;let h=d?.[f.settingsKey]?.connections||{};if(0!==Object.keys(h).length)for(let d of(await a.getProviderConnections({provider:e,isActive:!0})).filter(a=>"oauth"===a.authType&&!0===h[a.id]))try{await u(d,e,f,g,a,b)}catch(a){var c;b.failureCache[c=d.id,`${e}:${c}`]=Date.now(),console.warn(`[AutoPing] ${e}:${d.id}: ${a.message}`)}}}catch(a){console.warn("[AutoPing] tick error:",a.message)}finally{b.running=!1}}}function w(){!z.interval&&(console.log("[AutoPing] scheduler started"),v().catch(()=>{}),z.interval=setInterval(()=>{v().catch(()=>{})},x.tickIntervalMs),z.interval.unref&&z.interval.unref())}d()}catch(a){d(a)}})},74399:(a,b,c)=>{"use strict";let d=c(7344),{InvalidArgumentError:e}=c(61448),{toRawHeaders:f}=c(84285);class g{#at;constructor(a){this.#at=a}onRequestStart(a,b){this.#at.onConnect?.(b=>a.abort(b),b)}onRequestUpgrade(a,b,c,d){let e=a?.rawHeaders??f(c??{});this.#at.onUpgrade?.(b,e,d)}onResponseStart(a,b,c,d){let e=a?.rawHeaders??f(c??{});this.#at.onHeaders?.(b,e,()=>a.resume(),d)===!1&&a.pause()}onResponseData(a,b){this.#at.onData?.(b)===!1&&a.pause()}onResponseEnd(a,b){let c=a?.rawTrailers??f(b??{});this.#at.onComplete?.(c)}onResponseError(a,b){if(!this.#at.onError)throw b;this.#at.onError(b)}onBodySent(a){this.#at.onBodySent?.(a)}onRequestSent(){this.#at.onRequestSent?.()}onResponseStarted(){this.#at.onResponseStarted?.()}}class h extends d{#d;constructor(a){if(super(),!a||"function"!=typeof a.dispatch)throw new e("Argument dispatcher must implement dispatch");this.#d=a}static wrapHandler(a){if(!a||"object"!=typeof a)throw new e("handler must be an object");return"function"==typeof a.onRequestStart?a:new g(a)}dispatch(a,b){return!1!==a.allowH2&&(a={...a,allowH2:!1}),this.#d.dispatch(a,h.wrapHandler(b))}close(...a){return this.#d.close(...a)}destroy(...a){return this.#d.destroy(...a)}}a.exports=h},74570:(a,b,c)=>{"use strict";c.d(b,{Bi:()=>e,Es:()=>i,XP:()=>k,b8:()=>d,d:()=>h,ky:()=>j,w3:()=>l}),c(21820);let d="2023-06-01",e={"Anthropic-Version":d,"Anthropic-Beta":"claude-code-20250219,interleaved-thinking-2025-05-14"},f=["claude-code-20250219","oauth-2025-04-20","interleaved-thinking-2025-05-14","context-management-2025-06-27","prompt-caching-scope-2026-01-05","structured-outputs-2025-12-15","fast-mode-2026-02-01","redact-thinking-2026-02-12","token-efficient-tools-2026-03-28"],g=["advanced-tool-use-2025-11-20","effort-2025-11-24"];function h(a=""){let b=[...f];return/^claude-(opus|sonnet)/.test(a)&&b.push(...g),b.join(",")}let i="https://api.openai.com/v1",j="https://api.anthropic.com/v1",k={clientId:"1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com",clientSecret:"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"},l={clientId:"681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com",clientSecret:"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"}},75371:(a,b,c)=>{"use strict";c(68531),c(96684),c(62457)},76103:(a,b,c)=>{var d=c(45654);c(45518),c(63070),c(88819),c(36105),c(49345),c(56416),c(29984),c(33889),c(65737);var e=d.asn1,f=a.exports=d.pkcs7=d.pkcs7||{};function g(a){var b;if(a.type===d.pki.oids.contentType)b=e.create(e.Class.UNIVERSAL,e.Type.OID,!1,e.oidToDer(a.value).getBytes());else if(a.type===d.pki.oids.messageDigest)b=e.create(e.Class.UNIVERSAL,e.Type.OCTETSTRING,!1,a.value.bytes());else if(a.type===d.pki.oids.signingTime){var c=new Date("1950-01-01T00:00:00Z"),f=new Date("2050-01-01T00:00:00Z"),g=a.value;if("string"==typeof g){var h=Date.parse(g);g=isNaN(h)?13===g.length?e.utcTimeToDate(g):e.generalizedTimeToDate(g):new Date(h)}b=g>=c&&g<f?e.create(e.Class.UNIVERSAL,e.Type.UTCTIME,!1,e.dateToUtcTime(g)):e.create(e.Class.UNIVERSAL,e.Type.GENERALIZEDTIME,!1,e.dateToGeneralizedTime(g))}return e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.OID,!1,e.oidToDer(a.type).getBytes()),e.create(e.Class.UNIVERSAL,e.Type.SET,!0,[b])])}function h(a,b,c){var f={};if(!e.validate(b,c,f,[])){var g=Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message.");throw g.errors=g,g}if(e.derToOid(f.contentType)!==d.pki.oids.data)throw Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported.");if(f.encryptedContent){var h="";if(d.util.isArray(f.encryptedContent))for(var i=0;i<f.encryptedContent.length;++i){if(f.encryptedContent[i].type!==e.Type.OCTETSTRING)throw Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects.");h+=f.encryptedContent[i].value}else h=f.encryptedContent;a.encryptedContent={algorithm:e.derToOid(f.encAlgorithm),parameter:d.util.createBuffer(f.encParameter.value),content:d.util.createBuffer(h)}}if(f.content){var h="";if(d.util.isArray(f.content))for(var i=0;i<f.content.length;++i){if(f.content[i].type!==e.Type.OCTETSTRING)throw Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects.");h+=f.content[i].value}else h=f.content;a.content=d.util.createBuffer(h)}return a.version=f.version.charCodeAt(0),a.rawCapture=f,f}function i(a){if(void 0===a.encryptedContent.key)throw Error("Symmetric key not available.");if(void 0===a.content){var b;switch(a.encryptedContent.algorithm){case d.pki.oids["aes128-CBC"]:case d.pki.oids["aes192-CBC"]:case d.pki.oids["aes256-CBC"]:b=d.aes.createDecryptionCipher(a.encryptedContent.key);break;case d.pki.oids.desCBC:case d.pki.oids["des-EDE3-CBC"]:b=d.des.createDecryptionCipher(a.encryptedContent.key);break;default:throw Error("Unsupported symmetric cipher, OID "+a.encryptedContent.algorithm)}if(b.start(a.encryptedContent.parameter),b.update(a.encryptedContent.content),!b.finish())throw Error("Symmetric decryption failed.");a.content=b.output}}f.messageFromPem=function(a){var b=d.pem.decode(a)[0];if("PKCS7"!==b.type){var c=Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".');throw c.headerType=b.type,c}if(b.procType&&"ENCRYPTED"===b.procType.type)throw Error("Could not convert PKCS#7 message from PEM; PEM is encrypted.");var g=e.fromDer(b.body);return f.messageFromAsn1(g)},f.messageToPem=function(a,b){var c={type:"PKCS7",body:e.toDer(a.toAsn1()).getBytes()};return d.pem.encode(c,{maxline:b})},f.messageFromAsn1=function(a){var b,c={},g=[];if(!e.validate(a,f.asn1.contentInfoValidator,c,g)){var h=Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo.");throw h.errors=g,h}var i=e.derToOid(c.contentType);switch(i){case d.pki.oids.envelopedData:b=f.createEnvelopedData();break;case d.pki.oids.encryptedData:b=f.createEncryptedData();break;case d.pki.oids.signedData:b=f.createSignedData();break;default:throw Error("Cannot read PKCS#7 message. ContentType with OID "+i+" is not (yet) supported.")}return b.fromAsn1(c.content.value[0]),b},f.createSignedData=function(){var a=null;return a={type:d.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(b){if(h(a,b,f.asn1.signedDataValidator),a.certificates=[],a.crls=[],a.digestAlgorithmIdentifiers=[],a.contentInfo=null,a.signerInfos=[],a.rawCapture.certificates)for(var c=a.rawCapture.certificates.value,e=0;e<c.length;++e)a.certificates.push(d.pki.certificateFromAsn1(c[e]))},toAsn1:function(){a.contentInfo||a.sign();for(var b=[],c=0;c<a.certificates.length;++c)b.push(d.pki.certificateToAsn1(a.certificates[c]));var f=[],g=e.create(e.Class.CONTEXT_SPECIFIC,0,!0,[e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.INTEGER,!1,e.integerToDer(a.version).getBytes()),e.create(e.Class.UNIVERSAL,e.Type.SET,!0,a.digestAlgorithmIdentifiers),a.contentInfo])]);return b.length>0&&g.value[0].value.push(e.create(e.Class.CONTEXT_SPECIFIC,0,!0,b)),f.length>0&&g.value[0].value.push(e.create(e.Class.CONTEXT_SPECIFIC,1,!0,f)),g.value[0].value.push(e.create(e.Class.UNIVERSAL,e.Type.SET,!0,a.signerInfos)),e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.OID,!1,e.oidToDer(a.type).getBytes()),g])},addSigner:function(b){var c=b.issuer,e=b.serialNumber;if(b.certificate){var f=b.certificate;"string"==typeof f&&(f=d.pki.certificateFromPem(f)),c=f.issuer.attributes,e=f.serialNumber}var g=b.key;if(!g)throw Error("Could not add PKCS#7 signer; no private key specified.");"string"==typeof g&&(g=d.pki.privateKeyFromPem(g));var h=b.digestAlgorithm||d.pki.oids.sha1;switch(h){case d.pki.oids.sha1:case d.pki.oids.sha256:case d.pki.oids.sha384:case d.pki.oids.sha512:case d.pki.oids.md5:break;default:throw Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+h)}var i=b.authenticatedAttributes||[];if(i.length>0){for(var j=!1,k=!1,l=0;l<i.length;++l){var m=i[l];if(!j&&m.type===d.pki.oids.contentType){if(j=!0,k)break;continue}if(!k&&m.type===d.pki.oids.messageDigest){if(k=!0,j)break;continue}}if(!j||!k)throw Error("Invalid signer.authenticatedAttributes. If signer.authenticatedAttributes is specified, then it must contain at least two attributes, PKCS #9 content-type and PKCS #9 message-digest.")}a.signers.push({key:g,version:1,issuer:c,serialNumber:e,digestAlgorithm:h,signatureAlgorithm:d.pki.oids.rsaEncryption,signature:null,authenticatedAttributes:i,unauthenticatedAttributes:[]})},sign:function(b){if(b=b||{},("object"!=typeof a.content||null===a.contentInfo)&&(a.contentInfo=e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.OID,!1,e.oidToDer(d.pki.oids.data).getBytes())]),"content"in a)){var c;a.content instanceof d.util.ByteBuffer?c=a.content.bytes():"string"==typeof a.content&&(c=d.util.encodeUtf8(a.content)),b.detached?a.detachedContent=e.create(e.Class.UNIVERSAL,e.Type.OCTETSTRING,!1,c):a.contentInfo.value.push(e.create(e.Class.CONTEXT_SPECIFIC,0,!0,[e.create(e.Class.UNIVERSAL,e.Type.OCTETSTRING,!1,c)]))}0!==a.signers.length&&function(b){if(!(c=a.detachedContent?a.detachedContent:(c=a.contentInfo.value[1]).value[0]))throw Error("Could not sign PKCS#7 message; there is no content to sign.");var c,f=e.derToOid(a.contentInfo.value[0].value),h=e.toDer(c);for(var i in h.getByte(),e.getBerValueLength(h),h=h.getBytes(),b)b[i].start().update(h);for(var j=new Date,k=0;k<a.signers.length;++k){var l=a.signers[k];if(0===l.authenticatedAttributes.length){if(f!==d.pki.oids.data)throw Error("Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data.")}else{l.authenticatedAttributesAsn1=e.create(e.Class.CONTEXT_SPECIFIC,0,!0,[]);for(var m=e.create(e.Class.UNIVERSAL,e.Type.SET,!0,[]),n=0;n<l.authenticatedAttributes.length;++n){var o=l.authenticatedAttributes[n];o.type===d.pki.oids.messageDigest?o.value=b[l.digestAlgorithm].digest():o.type!==d.pki.oids.signingTime||o.value||(o.value=j),m.value.push(g(o)),l.authenticatedAttributesAsn1.value.push(g(o))}h=e.toDer(m).getBytes(),l.md.start().update(h)}l.signature=l.key.sign(l.md,"RSASSA-PKCS1-V1_5")}a.signerInfos=function(a){for(var b=[],c=0;c<a.length;++c)b.push(function(a){var b=e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.INTEGER,!1,e.integerToDer(a.version).getBytes()),e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[d.pki.distinguishedNameToAsn1({attributes:a.issuer}),e.create(e.Class.UNIVERSAL,e.Type.INTEGER,!1,d.util.hexToBytes(a.serialNumber))]),e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.OID,!1,e.oidToDer(a.digestAlgorithm).getBytes()),e.create(e.Class.UNIVERSAL,e.Type.NULL,!1,"")])]);if(a.authenticatedAttributesAsn1&&b.value.push(a.authenticatedAttributesAsn1),b.value.push(e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.OID,!1,e.oidToDer(a.signatureAlgorithm).getBytes()),e.create(e.Class.UNIVERSAL,e.Type.NULL,!1,"")])),b.value.push(e.create(e.Class.UNIVERSAL,e.Type.OCTETSTRING,!1,a.signature)),a.unauthenticatedAttributes.length>0){for(var c=e.create(e.Class.CONTEXT_SPECIFIC,1,!0,[]),f=0;f<a.unauthenticatedAttributes.length;++f){var h=a.unauthenticatedAttributes[f];c.values.push(g(h))}b.value.push(c)}return b}(a[c]));return b}(a.signers)}(function(){for(var b={},c=0;c<a.signers.length;++c){var f=a.signers[c],g=f.digestAlgorithm;g in b||(b[g]=d.md[d.pki.oids[g]].create()),0===f.authenticatedAttributes.length?f.md=b[g]:f.md=d.md[d.pki.oids[g]].create()}for(var g in a.digestAlgorithmIdentifiers=[],b)a.digestAlgorithmIdentifiers.push(e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.OID,!1,e.oidToDer(g).getBytes()),e.create(e.Class.UNIVERSAL,e.Type.NULL,!1,"")]));return b}())},verify:function(){throw Error("PKCS#7 signature verification not yet implemented.")},addCertificate:function(b){"string"==typeof b&&(b=d.pki.certificateFromPem(b)),a.certificates.push(b)},addCertificateRevokationList:function(a){throw Error("PKCS#7 CRL support not yet implemented.")}}},f.createEncryptedData=function(){var a=null;return a={type:d.pki.oids.encryptedData,version:0,encryptedContent:{algorithm:d.pki.oids["aes256-CBC"]},fromAsn1:function(b){h(a,b,f.asn1.encryptedDataValidator)},decrypt:function(b){void 0!==b&&(a.encryptedContent.key=b),i(a)}}},f.createEnvelopedData=function(){var a=null;return a={type:d.pki.oids.envelopedData,version:0,recipients:[],encryptedContent:{algorithm:d.pki.oids["aes256-CBC"]},fromAsn1:function(b){var c=h(a,b,f.asn1.envelopedDataValidator);a.recipients=function(a){for(var b=[],c=0;c<a.length;++c)b.push(function(a){var b={},c=[];if(!e.validate(a,f.asn1.recipientInfoValidator,b,c)){var g=Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");throw g.errors=c,g}return{version:b.version.charCodeAt(0),issuer:d.pki.RDNAttributesAsArray(b.issuer),serialNumber:d.util.createBuffer(b.serial).toHex(),encryptedContent:{algorithm:e.derToOid(b.encAlgorithm),parameter:b.encParameter?b.encParameter.value:void 0,content:b.encKey}}}(a[c]));return b}(c.recipientInfos.value)},toAsn1:function(){var b;return e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.OID,!1,e.oidToDer(a.type).getBytes()),e.create(e.Class.CONTEXT_SPECIFIC,0,!0,[e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.INTEGER,!1,e.integerToDer(a.version).getBytes()),e.create(e.Class.UNIVERSAL,e.Type.SET,!0,function(a){for(var b,c=[],f=0;f<a.length;++f)c.push((b=a[f],e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.INTEGER,!1,e.integerToDer(b.version).getBytes()),e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[d.pki.distinguishedNameToAsn1({attributes:b.issuer}),e.create(e.Class.UNIVERSAL,e.Type.INTEGER,!1,d.util.hexToBytes(b.serialNumber))]),e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.OID,!1,e.oidToDer(b.encryptedContent.algorithm).getBytes()),e.create(e.Class.UNIVERSAL,e.Type.NULL,!1,"")]),e.create(e.Class.UNIVERSAL,e.Type.OCTETSTRING,!1,b.encryptedContent.content)])));return c}(a.recipients)),e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,(b=a.encryptedContent,[e.create(e.Class.UNIVERSAL,e.Type.OID,!1,e.oidToDer(d.pki.oids.data).getBytes()),e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.OID,!1,e.oidToDer(b.algorithm).getBytes()),b.parameter?e.create(e.Class.UNIVERSAL,e.Type.OCTETSTRING,!1,b.parameter.getBytes()):void 0]),e.create(e.Class.CONTEXT_SPECIFIC,0,!0,[e.create(e.Class.UNIVERSAL,e.Type.OCTETSTRING,!1,b.content.getBytes())])]))])])])},findRecipient:function(b){for(var c=b.issuer.attributes,d=0;d<a.recipients.length;++d){var e=a.recipients[d],f=e.issuer;if(e.serialNumber===b.serialNumber&&f.length===c.length){for(var g=!0,h=0;h<c.length;++h)if(f[h].type!==c[h].type||f[h].value!==c[h].value){g=!1;break}if(g)return e}}return null},decrypt:function(b,c){if(void 0===a.encryptedContent.key&&void 0!==b&&void 0!==c)switch(b.encryptedContent.algorithm){case d.pki.oids.rsaEncryption:case d.pki.oids.desCBC:var e=c.decrypt(b.encryptedContent.content);a.encryptedContent.key=d.util.createBuffer(e);break;default:throw Error("Unsupported asymmetric cipher, OID "+b.encryptedContent.algorithm)}i(a)},addRecipient:function(b){a.recipients.push({version:0,issuer:b.issuer.attributes,serialNumber:b.serialNumber,encryptedContent:{algorithm:d.pki.oids.rsaEncryption,key:b.publicKey}})},encrypt:function(b,c){if(void 0===a.encryptedContent.content){switch(c=c||a.encryptedContent.algorithm,b=b||a.encryptedContent.key,c){case d.pki.oids["aes128-CBC"]:e=16,f=16,g=d.aes.createEncryptionCipher;break;case d.pki.oids["aes192-CBC"]:e=24,f=16,g=d.aes.createEncryptionCipher;break;case d.pki.oids["aes256-CBC"]:e=32,f=16,g=d.aes.createEncryptionCipher;break;case d.pki.oids["des-EDE3-CBC"]:e=24,f=8,g=d.des.createEncryptionCipher;break;default:throw Error("Unsupported symmetric cipher, OID "+c)}if(void 0===b)b=d.util.createBuffer(d.random.getBytes(e));else if(b.length()!=e)throw Error("Symmetric key has wrong length; got "+b.length()+" bytes, expected "+e+".");a.encryptedContent.algorithm=c,a.encryptedContent.key=b,a.encryptedContent.parameter=d.util.createBuffer(d.random.getBytes(f));var e,f,g,h=g(b);if(h.start(a.encryptedContent.parameter.copy()),h.update(a.content),!h.finish())throw Error("Symmetric encryption failed.");a.encryptedContent.content=h.output}for(var i=0;i<a.recipients.length;++i){var j=a.recipients[i];if(void 0===j.encryptedContent.content)if(j.encryptedContent.algorithm===d.pki.oids.rsaEncryption)j.encryptedContent.content=j.encryptedContent.key.encrypt(a.encryptedContent.key.data);else throw Error("Unsupported asymmetric cipher, OID "+j.encryptedContent.algorithm)}}}}},76316:(a,b,c)=>{"use strict";let{InvalidArgumentError:d,NotSupportedError:e}=c(61448),f=c(34589),{isValidHTTPToken:g,isValidHeaderValue:h,isStream:i,destroy:j,isBuffer:k,isFormDataLike:l,isIterable:m,hasSafeIterator:n,isBlobLike:o,serializePathWithQuery:p,parseHeaders:q,assertRequestHandler:r,getServerName:s,normalizedMethodRecords:t,getProtocolFromUrlString:u}=c(84285),{channels:v}=c(62571),{headerNameLowerCasedRecord:w}=c(28820),x=/[^\u0021-\u00ff]/,y=Symbol("handler"),z=Symbol("controller"),A=Symbol("resume");class B{#bt=!1;#bu=null;#L=!1;#bv;[A]=null;rawHeaders=null;rawTrailers=null;constructor(a){this.#bv=a}pause(){this.#bt=!0}resume(){this.#bt&&(this.#bt=!1,this[A]?.())}abort(a){this.#L||(this.#L=!0,this.#bu=a,this.#bv(a))}get aborted(){return this.#L}get reason(){return this.#bu}get paused(){return this.#bt}}class C{constructor(a,{path:b,method:c,body:e,headers:f,query:q,idempotent:w,blocking:z,upgrade:A,headersTimeout:B,bodyTimeout:C,reset:E,expectContinue:F,servername:G,throwOnError:H,maxRedirections:I,typeOfService:J},K){if("string"!=typeof b)throw new d("path must be a string");if("/"===b[0]||b.startsWith("http://")||b.startsWith("https://")||"CONNECT"===c){if(x.test(b))throw new d("invalid request path")}else throw new d("path must be an absolute URL or start with a slash");if("string"!=typeof c)throw new d("method must be a string");if(void 0===t[c]&&!g(c))throw new d("invalid request method");if(A&&"string"!=typeof A)throw new d("upgrade must be a string");if(A&&!h(A))throw new d("invalid upgrade header");if(null!=B&&(!Number.isFinite(B)||B<0))throw new d("invalid headersTimeout");if(null!=C&&(!Number.isFinite(C)||C<0))throw new d("invalid bodyTimeout");if(null!=E&&"boolean"!=typeof E)throw new d("invalid reset");if(null!=F&&"boolean"!=typeof F)throw new d("invalid expectContinue");if(null!=H)throw new d("invalid throwOnError");if(null!=I&&0!==I)throw new d("maxRedirections is not supported, use the redirect interceptor");if(null!=J&&(!Number.isInteger(J)||J<0||J>255))throw new d("typeOfService must be an integer between 0 and 255");if(this.headersTimeout=B,this.bodyTimeout=C,this.method=c,this.typeOfService=J,this.abort=null,null==e)this.body=null;else if(i(e)){this.body=e;const a=this.body._readableState;a&&a.autoDestroy||(this.endHandler=function(){j(this)},this.body.on("end",this.endHandler)),this.errorHandler=a=>{this.abort?this.abort(a):this.error=a},this.body.on("error",this.errorHandler)}else if(k(e))this.body=e.byteLength?e:null;else if(ArrayBuffer.isView(e))this.body=e.buffer.byteLength?Buffer.from(e.buffer,e.byteOffset,e.byteLength):null;else if(e instanceof ArrayBuffer)this.body=e.byteLength?Buffer.from(e):null;else if("string"==typeof e)this.body=e.length?Buffer.from(e):null;else if(l(e)||m(e)||o(e))this.body=e;else throw new d("body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable");if(this.completed=!1,this.aborted=!1,this.upgrade=A||null,this.path=q?p(b,q):b,this.origin=a,this.protocol=u(a),this.idempotent=null==w?"HEAD"===c||"GET"===c||"QUERY"===c:w,this.blocking=z??"HEAD"!==this.method,this.reset=null==E?null:E,this.host=null,this.contentLength=null,this.contentType=null,this.headers=[],this.expectContinue=null!=F&&F,Array.isArray(f)){if(f.length%2!=0)throw new d("headers array must be even");for(let a=0;a<f.length;a+=2)D(this,f[a],f[a+1])}else if(f&&"object"==typeof f)if(n(f))for(const a of f){if(!Array.isArray(a)||2!==a.length)throw new d("headers must be in key-value pair format");D(this,a[0],a[1])}else{const a=Object.keys(f);for(let b=0;b<a.length;++b)D(this,a[b],f[a[b]])}else if(null!=f)throw new d("headers must be an object or an array");r(K,c,A),this.servername=G||s(this.host)||null,this[y]=K,v.create.hasSubscribers&&v.create.publish({request:this})}onBodySent(a){if(v.bodyChunkSent.hasSubscribers&&v.bodyChunkSent.publish({request:this,chunk:a}),this[y].onBodySent)try{return this[y].onBodySent(a)}catch(a){this.abort(a)}}onRequestSent(){if(v.bodySent.hasSubscribers&&v.bodySent.publish({request:this}),this[y].onRequestSent)try{return this[y].onRequestSent()}catch(a){this.abort(a)}}onRequestStart(a,b){return(f(!this.aborted),f(!this.completed),this[z]=new B(a),this.error)?void this[z].abort(this.error):(this.abort=a,this[y].onRequestStart(this[z],b))}onResponseStarted(){return this[y].onResponseStarted?.()}onResponseStart(a,b,c,d){f(!this.aborted),f(!this.completed),v.headers.hasSubscribers&&v.headers.publish({request:this,response:{statusCode:a,headers:b,statusText:d}});let e=this[z];e&&(e[A]=c,e.rawHeaders=b);let g=Array.isArray(b)?q(b):b;try{return this[y].onResponseStart?.(e,a,g,d),!e?.paused}catch(a){return this.abort(a),!1}}onResponseData(a){f(!this.aborted),f(!this.completed),v.bodyChunkReceived.hasSubscribers&&v.bodyChunkReceived.publish({request:this,chunk:a});let b=this[z];try{return this[y].onResponseData?.(b,a),!b?.paused}catch(a){return this.abort(a),!1}}onRequestUpgrade(a,b,c){f(!this.aborted),f(!this.completed);let d=this[z];d&&(d.rawHeaders=b);let e=Array.isArray(b)?q(b):b;return this[y].onRequestUpgrade?.(d,a,e,c)}onResponseEnd(a){this.onFinally(),f(!this.aborted),f(!this.completed),this.completed=!0,v.trailers.hasSubscribers&&v.trailers.publish({request:this,trailers:a});let b=this[z];b&&(b.rawTrailers=a);let c=Array.isArray(a)?q(a):a;try{return this[y].onResponseEnd?.(b,c)}catch(a){this.onResponseError(a)}}onResponseError(a){if(this.onFinally(),v.error.hasSubscribers&&v.error.publish({request:this,error:a}),this.aborted)return;this.aborted=!0;let b=this[z];return this[y].onResponseError?.(b,a)}onFinally(){this.errorHandler&&(this.body.off("error",this.errorHandler),this.errorHandler=null),this.endHandler&&(this.body.off("end",this.endHandler),this.endHandler=null)}addHeader(a,b){return D(this,a,b),this}}function D(a,b,c){if(c&&"object"==typeof c&&!Array.isArray(c))throw new d(`invalid ${b} header`);if(void 0===c)return;let f=w[b];if(void 0===f&&void 0===w[f=b.toLowerCase()]&&!g(f))throw new d("invalid header key");if(Array.isArray(c)){let a=[];for(let e=0;e<c.length;e++)if("string"==typeof c[e]){if(!h(c[e]))throw new d(`invalid ${b} header`);a.push(c[e])}else if(null===c[e])a.push("");else if("object"==typeof c[e])throw new d(`invalid ${b} header`);else{let f=`${c[e]}`;if(!h(f))throw new d(`invalid ${b} header`);a.push(f)}c=a}else if("string"==typeof c){if(!h(c))throw new d(`invalid ${b} header`)}else if(null===c)c="";else if(!h(c=`${c}`))throw new d(`invalid ${b} header`);if("host"===f){if(null!==a.host)throw new d("duplicate host header");if("string"!=typeof c)throw new d("invalid host header");a.host=c}else if("content-length"===f){if(null!==a.contentLength)throw new d("duplicate content-length header");if(!function(a){if("string"!=typeof a||0===a.length)return!1;for(let b=0;b<a.length;b++){let c=a.charCodeAt(b);if(c<48||c>57)return!1}return!0}(c))throw new d("invalid content-length header");a.contentLength=parseInt(c,10)}else if(null===a.contentType&&"content-type"===f)a.contentType=c,a.headers.push(b,c);else if("transfer-encoding"===f||"keep-alive"===f||"upgrade"===f)throw new d(`invalid ${f} header`);else if("connection"===f){let b="string"==typeof c?c:null;if(null===b)throw new d("invalid connection header");for(let c of b.toLowerCase().split(",")){let b=c.trim();if(!g(b))throw new d("invalid connection header");"close"===b&&(a.reset=!0)}}else if("expect"===f)throw new e("expect header not supported");else a.headers.push(b,c)}a.exports=C},76403:(a,b,c)=>{"use strict";let d,{makeNetworkError:e,makeAppropriateNetworkError:f,filterResponse:g,makeResponse:h,fromInnerResponse:i,getResponseState:j}=c(78196),{HeadersList:k}=c(28665),{Request:l,cloneRequest:m,getRequestDispatcher:n,getRequestState:o,removeRequestAbortListener:p}=c(12600),q=c(38522),{makePolicyContainer:r,clonePolicyContainer:s,requestBadPort:t,TAOCheck:u,appendRequestOriginHeader:v,responseLocationURL:w,requestCurrentURL:x,setRequestReferrerPolicyOnRedirect:y,tryUpgradeRequestToAPotentiallyTrustworthyURL:z,createOpaqueTimingInfo:A,appendFetchMetadata:B,corsCheck:C,crossOriginResourcePolicyCheck:D,determineRequestsReferrer:E,coarsenedSharedCurrentTime:F,sameOrigin:G,isCancelled:H,isAborted:I,isErrorLike:J,fullyReadBody:K,readableStreamClose:L,urlIsLocal:M,urlIsHttpHttpsScheme:N,urlHasHttpsScheme:O,clampAndCoarsenConnectionTimingInfo:P,simpleRangeHeaderValue:Q,buildContentRange:R,createInflate:S,extractMimeType:T,hasAuthenticationEntry:U,includesCredentials:V,isTraversableNavigable:W}=c(42425),X=c(34589),{safelyExtractBody:Y,extractBody:Z}=c(35381),{redirectStatusSet:$,nullBodyStatus:_,safeMethodsSet:aa,requestBodyHeader:ab,subresourceSet:ac}=c(19608),ad=c(78474),{Readable:ae,pipeline:af,finished:ag,isErrored:ah,isReadable:ai}=c(57075),{addAbortListener:aj,bufferToLowerCasedHeaderName:ak}=c(84285),{dataURLProcessor:al,serializeAMimeType:am,minimizeSupportedMimeType:an}=c(16537),{getGlobalDispatcher:ao}=c(59970),{webidl:ap}=c(32984),{STATUS_CODES:aq}=c(37067),{bytesMatch:ar}=c(64371),{isomorphicEncode:as}=c(70745),at=["GET","HEAD"],au="u">typeof __UNDICI_IS_NODE__||"u">typeof esbuildDetection?"node":"undici";function av(a,b,c){if(Array.isArray(c)){for(let b=0;b<c.length;b+=2){let d=ak(c[b]),e=c[b+1];if(Array.isArray(e)&&!Buffer.isBuffer(e))for(let b of e)a.append(d,b.toString("latin1"),!0);else a.append(d,e.toString("latin1"),!0)}return}for(let[c,d]of Object.entries(b??{}))if(Array.isArray(d))for(let b of d)a.append(c,`${b}`,!0);else a.append(c,`${d}`,!0)}class aw extends ad{constructor(a){super(),this.dispatcher=a,this.connection=null,this.dump=!1,this.state="ongoing"}terminate(a){"ongoing"===this.state&&(this.state="terminated",this.connection?.destroy(a),this.emit("terminated",a))}abort(a){"ongoing"===this.state&&(this.state="aborted",a||(a=new DOMException("The operation was aborted.","AbortError")),this.serializedAbortReason=a,this.connection?.destroy(a),this.emit("terminated",a))}}function ax(a,b="other"){if("error"===a.type&&a.aborted||!a.urlList?.length)return;let c=a.urlList[0],d=a.timingInfo,e=a.cacheState;N(c)&&null!==d&&(a.timingAllowPassed||(d=A({startTime:d.startTime}),e=""),d.endTime=F(),a.timingInfo=d,ay(d,c.href,b,globalThis,e,"",a.status))}let ay=performance.markResourceTiming;function az(a,b,c,d,e){if(a&&a.reject(d),b.body?.stream!=null&&ai(b.body.stream)&&b.body.stream.cancel(d).catch(a=>{if("ERR_INVALID_STATE"!==a.code)throw a}),null==c)return;let f=j(c);f.body?.stream!=null&&ai(f.body.stream)&&e.error(d)}function aA({request:a,processRequestBodyChunkLength:b,processRequestEndOfBody:c,processResponse:d,processResponseEndOfBody:e,processResponseConsumeBody:f,useParallelQueue:g=!1,dispatcher:h=ao(),requestObject:i=null}){X(h);let j=null,k=!1;null!=a.client&&(j=a.client.globalObject,k=a.client.crossOriginIsolatedCapability);let l=A({startTime:F(k)}),m={controller:new aw(h),request:a,timingInfo:l,processRequestBodyChunkLength:b,processRequestEndOfBody:c,processResponse:d,processResponseConsumeBody:f,processResponseEndOfBody:e,taskDestination:j,crossOriginIsolatedCapability:k,requestObject:i};return X(!a.body||a.body.stream),"client"===a.window&&(a.window=a.client?.globalObject?.constructor?.name==="Window"?a.client:"no-window"),"client"===a.origin&&(a.origin=a.client.origin),"client"===a.policyContainer&&(null!=a.client?a.policyContainer=s(a.client.policyContainer):a.policyContainer=r()),a.headersList.contains("accept",!0)||a.headersList.append("accept","*/*",!0),a.headersList.contains("accept-language",!0)||a.headersList.append("accept-language","*",!0),a.priority,ac.has(a.destination),aB(m,!1),m.controller}async function aB(a,b){try{let c=a.request,d=null;if(c.localURLsOnly&&!M(x(c))&&(d=e("local URLs only")),z(c),"blocked"===t(c)&&(d=e("bad port")),""===c.referrerPolicy&&(c.referrerPolicy=c.policyContainer.referrerPolicy),"no-referrer"!==c.referrer&&(c.referrer=E(c)),null===d){let b=x(c);G(b,c.url)&&"basic"===c.responseTainting||"data:"===b.protocol||"navigate"===c.mode||"websocket"===c.mode?(c.responseTainting="basic",d=await aC(a)):"same-origin"===c.mode?d=e('request mode cannot be "same-origin"'):"no-cors"===c.mode?"follow"!==c.redirect?d=e('redirect mode cannot be "follow" for "no-cors" request'):(c.responseTainting="opaque",d=await aC(a)):N(x(c))?(c.responseTainting="cors",d=await aE(a)):d=e("URL scheme must be a HTTP(S) scheme")}if(b)return d;0===d.status||d.internalResponse||(c.responseTainting,"basic"===c.responseTainting?d=g(d,"basic"):"cors"===c.responseTainting?d=g(d,"cors"):"opaque"===c.responseTainting?d=g(d,"opaque"):X(!1));let f=0===d.status?d:d.internalResponse;if(0===f.urlList.length&&f.urlList.push(...c.urlList),c.timingAllowFailed||(d.timingAllowPassed=!0),"opaque"===d.type&&206===f.status&&f.rangeRequested&&!c.headers.contains("range",!0)&&(d=f=e()),0!==d.status&&("HEAD"===c.method||"CONNECT"===c.method||_.includes(f.status))&&(f.body=null,a.controller.dump=!0),c.integrity){let b=b=>aD(a,e(b));if("opaque"===c.responseTainting||null==d.body)return void b(d.error);K(d.body,e=>{ar(e,c.integrity)?(d.body=Y(e)[0],aD(a,d)):b("integrity mismatch")},b)}else aD(a,d)}catch(b){a.controller.terminate(b)}}function aC(a){if(H(a)&&0===a.request.redirectCount)return Promise.resolve(f(a));let{request:b}=a,{protocol:g}=x(b);switch(g){case"about:":return Promise.resolve(e("about scheme is not supported"));case"blob:":{d||(d=c(4573).resolveObjectURL);let a=x(b);if(0!==a.search.length)return Promise.resolve(e("NetworkError when attempting to fetch resource."));let f=d(a.toString());if("GET"!==b.method||!ap.is.Blob(f))return Promise.resolve(e("invalid method"));let g=h(),i=f.size,j=as(`${i}`),k=f.type;if(b.headersList.contains("range",!0)){g.rangeRequested=!0;let a=Q(b.headersList.get("range",!0),!0);if("failure"===a)return Promise.resolve(e("failed to fetch the data URL"));let{rangeStartValue:c,rangeEndValue:d}=a;if(null===c)d=(c=i-d)+d-1;else{if(c>=i)return Promise.resolve(e("Range start is greater than the blob's size."));(null===d||d>=i)&&(d=i-1)}let h=f.slice(c,d+1,k);g.body=Z(h)[0];let j=as(`${h.size}`),l=R(c,d,i);g.status=206,g.statusText="Partial Content",g.headersList.set("content-length",j,!0),g.headersList.set("content-type",k,!0),g.headersList.set("content-range",l,!0)}else{let a=Z(f);g.statusText="OK",g.body=a[0],g.headersList.set("content-length",j,!0),g.headersList.set("content-type",k,!0)}return Promise.resolve(g)}case"data:":{let a=al(x(b));if("failure"===a)return Promise.resolve(e("failed to fetch the data URL"));return Promise.resolve(h({statusText:"OK",headersList:[["content-type",{name:"Content-Type",value:am(a.mimeType)}]],body:Y(a.body)[0]}))}case"file:":return Promise.resolve(e("not implemented... yet..."));case"http:":case"https:":return aE(a).catch(a=>e(a));default:return Promise.resolve(e("unknown scheme"))}}function aD(a,b){let c=a.timingInfo,d=()=>{let d=Date.now();"document"===a.request.destination&&(a.controller.fullTimingInfo=c),a.controller.reportTimingSteps=()=>{if(!N(a.request.url))return;c.endTime=d;let e=b.cacheState,f=b.bodyInfo;b.timingAllowPassed||(c=A(c),e="");let g=0;if("navigate"!==a.request.mode||!b.hasCrossOriginRedirects){g=b.status;let a=T(b.headersList);"failure"!==a&&(f.contentType=an(a))}null!=a.request.initiatorType&&ay(c,a.request.url.href,a.request.initiatorType,globalThis,e,f,g)},queueMicrotask(()=>void(a.request.done=!0,null!=a.processResponseEndOfBody&&queueMicrotask(()=>a.processResponseEndOfBody(b)),null!=a.request.initiatorType&&a.controller.reportTimingSteps()))};null!=a.processResponse&&queueMicrotask(()=>{a.processResponse(b),a.processResponse=null});let e="error"===b.type?b:b.internalResponse??b;null==e.body?d():ag(e.body.stream,()=>{d()})}async function aE(a){let b=a.request,c=null,d=null,f=a.timingInfo;if(b.serviceWorkers,null===c){if("follow"===b.redirect&&(b.serviceWorkers="none"),d=c=await aF(a),"cors"===b.responseTainting&&"failure"===C(b,c))return e("cors failure");"failure"===u(b,c)&&(b.timingAllowFailed=!0)}return("opaque"===b.responseTainting||"opaque"===c.type)&&"blocked"===D(b.origin,b.client,b.destination,d)?e("blocked"):($.has(d.status)&&("manual"!==b.redirect&&a.controller.connection.destroy(void 0,!1),"error"===b.redirect?c=e("unexpected redirect"):"manual"===b.redirect?c=d:"follow"===b.redirect?c=await function(a,b){let c,d=a.request,f=b.internalResponse?b.internalResponse:b;try{if(c=w(f,x(d).hash),null==c)return b}catch(a){return Promise.resolve(e(a))}if(!N(c))return Promise.resolve(e("URL scheme must be a HTTP(S) scheme"));if(20===d.redirectCount)return Promise.resolve(e("redirect count exceeded"));if(d.redirectCount+=1,"cors"===d.mode&&(c.username||c.password)&&!G(d,c))return Promise.resolve(e('cross origin not allowed for request mode "cors"'));if("cors"===d.responseTainting&&(c.username||c.password))return Promise.resolve(e('URL cannot contain credentials for request mode "cors"'));if(303!==f.status&&null!=d.body&&null==d.body.source)return Promise.resolve(e());if([301,302].includes(f.status)&&"POST"===d.method||303===f.status&&!at.includes(d.method))for(let a of(d.method="GET",d.body=null,ab))d.headersList.delete(a);G(x(d),c)||(d.headersList.delete("authorization",!0),d.headersList.delete("proxy-authorization",!0),d.headersList.delete("cookie",!0),d.headersList.delete("host",!0)),null!=d.body&&(X(null!=d.body.source),d.body=Y(d.body.source)[0]);let g=a.timingInfo;return g.redirectEndTime=g.postRedirectStartTime=F(a.crossOriginIsolatedCapability),0===g.redirectStartTime&&(g.redirectStartTime=g.startTime),d.urlList.push(c),y(d,f),aB(a,!0)}(a,c):X(!1)),c.timingInfo=f,c)}async function aF(a,b=!1,c=!1){let d=a.request,g=null,h=null,i=null;"no-window"===d.window&&"error"===d.redirect?(g=a,h=d):(d.body?.source!=null?h=m(d):(h=m({...d,body:null})).body=d.body,(g={...a}).request=h);let j="include"===d.credentials||"same-origin"===d.credentials&&"basic"===d.responseTainting,k=h.body?h.body.length:null,l=null;if(null==h.body&&["POST","PUT"].includes(h.method)&&(l="0"),null!=k&&(l=as(`${k}`)),null==l||h.headersList.contains("content-length",!0)||h.headersList.append("content-length",l,!0),null!=k&&h.keepalive,ap.is.URL(h.referrer)&&h.headersList.append("referer",as(h.referrer.href),!0),v(h),B(h),h.headersList.contains("user-agent",!0)||h.headersList.append("user-agent",au,!0),"default"===h.cache&&(h.headersList.contains("if-modified-since",!0)||h.headersList.contains("if-none-match",!0)||h.headersList.contains("if-unmodified-since",!0)||h.headersList.contains("if-match",!0)||h.headersList.contains("if-range",!0))&&(h.cache="no-store"),"no-cache"!==h.cache||h.preventNoCacheCacheControlHeaderModification||h.headersList.contains("cache-control",!0)||h.headersList.append("cache-control","max-age=0",!0),("no-store"===h.cache||"reload"===h.cache)&&(h.headersList.contains("pragma",!0)||h.headersList.append("pragma","no-cache",!0),h.headersList.contains("cache-control",!0)||h.headersList.append("cache-control","no-cache",!0)),h.headersList.contains("range",!0)&&h.headersList.append("accept-encoding","identity",!0),h.headersList.contains("accept-encoding",!0)||(O(x(h))?h.headersList.append("accept-encoding","br, gzip, deflate, zstd",!0):h.headersList.append("accept-encoding","gzip, deflate",!0)),h.headersList.delete("host",!0),j&&!h.headersList.contains("authorization",!0)){let a=null;if(U(h)&&(void 0===h.useURLCredentials||!V(x(h))));else if(V(x(h))&&b){let{username:b,password:c}=x(h);a=`Basic ${Buffer.from(`${b}:${c}`).toString("base64")}`}null!==a&&h.headersList.append("Authorization",a,!1)}if(h.cache="no-store","no-store"!==h.cache&&h.cache,null==i){if("only-if-cached"===h.cache)return e("only if cached");let a=await aG(g,j,c);!aa.has(h.method)&&a.status>=200&&a.status,null==i&&(i=a)}if(i.urlList=[...h.urlList],h.headersList.contains("range",!0)&&(i.rangeRequested=!0),i.requestIncludesCredentials=j,401===i.status&&"cors"!==h.responseTainting&&j&&(void 0!==d.useURLCredentials||W(d.traversableForUserPrompts))){if(null!=d.body){if(null==d.body.source)return i;d.body=Y(d.body.source)[0]}if(void 0===d.useURLCredentials||b)return H(a)?f(a):i;a.controller.connection.destroy(),i=await aF(a,!0)}if(407===i.status)return"no-window"===d.window?e():H(a)?f(a):e("proxy authentication required");if(421===i.status&&!c&&(null==d.body||null!=d.body.source)){if(H(a))return f(a);a.controller.connection.destroy(),i=await aF(a,b,!0)}return i}async function aG(a,b=!1,c=!1){X(!a.controller.connection||a.controller.connection.destroyed),a.controller.connection={abort:null,destroyed:!1,destroy(a,b=!0){!this.destroyed&&(this.destroyed=!0,b&&this.abort?.(a??new DOMException("The operation was aborted.","AbortError")))}};let d=a.request,g=null,i=a.timingInfo;d.cache="no-store",d.mode;let j=null;if(null==d.body&&a.processRequestEndOfBody)queueMicrotask(()=>a.processRequestEndOfBody());else if(null!=d.body){let b=async function*(b){H(a)||(yield b,a.processRequestBodyChunkLength?.(b.byteLength))};j=async function*(){try{for await(let a of d.body.stream)yield*b(a);!H(a)&&a.processRequestEndOfBody&&a.processRequestEndOfBody()}catch(b){H(a)||("AbortError"===b.name?a.controller.abort():a.controller.terminate(b))}}()}try{let{body:b,status:c,statusText:e,headersList:f,socket:l}=await function({body:b}){let c=x(d),e=a.controller.dispatcher,f=c.pathname+c.search,g=0===c.search.length&&"?"===c.href[c.href.length-c.hash.length-1];return function b(h,j){return new Promise((l,m)=>e.dispatch({path:g?`${f}?`:f,origin:c.origin,method:d.method,body:e.isMockActive?d.body&&(d.body.source||d.body.stream):h,__mockAgentBodyForDispatch:h,headers:d.headersList.entries,maxRedirections:0,upgrade:"websocket"===d.mode?"websocket":void 0,...!1===j?{allowH2:j}:null},{body:null,abort:null,onRequestStart(b){let{connection:c}=a.controller;i.finalConnectionTimingInfo=P(void 0,i.postRedirectStartTime,a.crossOriginIsolatedCapability);let d=a=>b.abort(a);c.destroyed?d(new DOMException("The operation was aborted.","AbortError")):(a.controller.on("terminated",d),this.abort=c.abort=d),i.finalNetworkRequestStartTime=F(a.crossOriginIsolatedCapability)},onResponseStarted(){i.finalNetworkResponseStartTime=F(a.crossOriginIsolatedCapability)},onResponseStart(a,b,c,e){if(b<200)return;let f=a?.rawHeaders??[],g=new k;av(g,c,f);let h=g.get("location",!0);this.body=new ae({read:()=>a.resume()});let i=h&&"follow"===d.redirect&&$.has(b),j=[];if("HEAD"!==d.method&&"CONNECT"!==d.method&&!_.includes(b)&&!i){let a=g.get("content-encoding",!0),b=a?a.toLowerCase().split(","):[];if(b.length>5)return void m(Error(`too many content-encodings in response: ${b.length}, maximum allowed is 5`));for(let a=b.length-1;a>=0;--a){let c=b[a].trim();if("x-gzip"===c||"gzip"===c)j.push(q.createGunzip({flush:q.constants.Z_SYNC_FLUSH,finishFlush:q.constants.Z_SYNC_FLUSH}));else if("deflate"===c)j.push(S({flush:q.constants.Z_SYNC_FLUSH,finishFlush:q.constants.Z_SYNC_FLUSH}));else if("br"===c)j.push(q.createBrotliDecompress({flush:q.constants.BROTLI_OPERATION_FLUSH,finishFlush:q.constants.BROTLI_OPERATION_FLUSH}));else if("zstd"===c)j.push(q.createZstdDecompress({flush:q.constants.ZSTD_e_continue,finishFlush:q.constants.ZSTD_e_end}));else{j.length=0;break}}}let n=b=>this.onResponseError(a,b);l({status:b,statusText:e,headersList:g,body:j.length?af(this.body,...j,b=>{b&&this.onResponseError(a,b)}).on("error",n):this.body.on("error",n)})},onResponseData(b,c){a.controller.dump||(i.encodedBodySize+=c.byteLength,!1===this.body.push(c)&&b.pause())},onResponseEnd(){this.abort&&a.controller.off("terminated",this.abort),a.controller.ended=!0,this.body?.push(null)},onResponseError(c,e){(this.abort&&a.controller.off("terminated",this.abort),"websocket"===d.mode&&!1!==j&&e?.code==="UND_ERR_INFO"&&e?.message==="HTTP/2: Extended CONNECT protocol not supported by server")?l(b(h,!1)):(this.body?.destroy(e),a.controller.terminate(e),m(e))},onRequestUpgrade(a,b,c,d){if(null!=d.session&&200!==b||null==d.session&&101!==b)return!1;let e=a?.rawHeaders??[],f=new k;return av(f,c,e),l({status:b,statusText:aq[b],headersList:f,socket:d}),!0}}))}(b)}({body:j});if(l)g=h({status:c,statusText:e,headersList:f,socket:l});else{let d=b[Symbol.asyncIterator]();a.controller.next=()=>d.next(),g=h({status:c,statusText:e,headersList:f})}}catch(b){if("AbortError"===b.name)return a.controller.connection.destroy(),f(a,b);return e(b)}let l=new ReadableStream({start(b){a.controller.controller=b},pull:()=>a.controller.resume(),cancel:b=>{H(a)||a.controller.abort(b)},type:"bytes"});return g.body={stream:l,source:null,length:null},a.controller.resume||a.controller.on("terminated",function(b){I(a)?(g.aborted=!0,ai(l)&&a.controller.controller.error(a.controller.serializedAbortReason)):ai(l)&&a.controller.controller.error(TypeError("terminated",{cause:J(b)?b:void 0})),a.controller.connection.destroy()}),a.controller.resume=async()=>{for(;;){let b,c;try{let{done:c,value:d}=await a.controller.next();if(I(a))break;b=c?void 0:d}catch(d){a.controller.ended&&!i.encodedBodySize?b=void 0:(b=d,c=!0)}if(void 0===b){L(a.controller.controller),function(a,b){a.request.done=!0,null!=a.processResponseDone&&queueMicrotask(()=>a.processResponseDone(b))}(a,g);return}if(i.decodedBodySize+=b?.byteLength??0,c)return void a.controller.terminate(b);let d=new Uint8Array(b);if(d.byteLength&&a.controller.controller.enqueue(d),ah(l))return void a.controller.terminate();if(a.controller.controller.desiredSize<=0)return}},g}a.exports={fetch:function(a,b){let c;ap.argumentLengthCheck(arguments,1,"globalThis.fetch");let d=Promise.withResolvers();try{c=new l(a,b)}catch(a){return d.reject(a),d.promise}let e=o(c);if(c.signal.aborted)return az(d,e,null,c.signal.reason,null),d.promise;let f=e.client.globalObject;f?.constructor?.name==="ServiceWorkerGlobalScope"&&(e.serviceWorkers="none");let g=null,h=!1,j=null,k=aj(c.signal,()=>{h=!0,X(null!=j),j.abort(c.signal.reason);let a=g?.deref();az(d,e,a,c.signal.reason,j.controller)}),m=()=>{k(),p(c)};return j=aA({request:e,processResponseEndOfBody:a=>{ax(a,"fetch"),m()},processResponse:a=>{if(!h){if(a.aborted){az(d,e,g,j.serializedAbortReason,j.controller),m();return}if("error"===a.type){d.reject(TypeError("fetch failed",{cause:a.error})),m();return}g=new WeakRef(i(a,"immutable")),d.resolve(g.deref()),d=null}},dispatcher:n(c),requestObject:c}),d.promise},Fetch:aw,fetching:aA,finalizeAndReportTiming:ax}},76441:(a,b,c)=>{"use strict";c(70625)},76540:(a,b,c)=>{"use strict";c(33873),c(29021);let{MITM_DIR:d}=c(37436),{generateRootCA:e,loadRootCA:f,generateLeafCert:g}=c(1653);a.exports={generateCert:function(){return e()},getCertForDomain:function(a){try{let b=f(),c=g(a,b);return{key:c.key,cert:c.cert}}catch(b){return console.error(`Failed to generate cert for ${a}:`,b.message),null}}}},76558:(a,b,c)=>{"use strict";c.d(b,{Yh:()=>p});var d=c(67671),e=c(38421),f=c(50969),g=c(55511),h=c(21820);let i=e.xq["mimo-free"].baseUrl,j="abcdefghijklmnopqrstuvwxyz0123456789",k=["Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"],l="You are MiMoCode, an interactive CLI tool that helps users with software engineering tasks.",m=null,n=0;async function o(a=null){if(m&&Date.now()<n-3e5)return m;let b=await (0,f.Fm)("https://api.xiaomimimo.com/api/free-ai/bootstrap",{method:"POST",headers:{"Content-Type":"application/json","User-Agent":k[Math.floor(Math.random()*k.length)]},body:JSON.stringify({client:function(){let a="unknown-user";try{a=h.userInfo().username}catch{}let b=(h.cpus()[0]?.model||"unknown-cpu").trim(),c=`${h.hostname()}|${h.platform()}|${h.arch()}|${b}|${a}`;return(0,g.createHash)("sha256").update(c).digest("hex")}()})},a);if(!b.ok)throw Error(`MiMo bootstrap failed: ${b.status}`);let c=await b.json();if(!c.jwt)throw Error("MiMo bootstrap returned no JWT");return m=c.jwt,n=function(a){try{let b=JSON.parse(Buffer.from(a.split(".")[1],"base64").toString());if(b.exp)return 1e3*b.exp}catch{}return Date.now()+3e6}(c.jwt),m}class p extends d.Hv{constructor(){super("mimo-free",e.xq["mimo-free"]),this.sessionId=function(){let a="ses_";for(let b=0;b<24;b++)a+=j[Math.floor(Math.random()*j.length)];return a}()}buildUrl(){return i}buildHeaders(a,b=!0){return{"Content-Type":"application/json","X-Mimo-Source":"mimocode-cli-free","User-Agent":k[Math.floor(Math.random()*k.length)],"x-session-affinity":this.sessionId,Accept:b?"text/event-stream":"application/json"}}transformRequest(a,b){let c;return!Array.isArray(c=b?.messages)||c.some(a=>a?.role==="system"&&"string"==typeof a.content&&a.content.includes(l))?b:{...b,messages:[{role:"system",content:l},...c]}}async execute({model:a,body:b,stream:c,credentials:d,signal:e,log:g,proxyOptions:h=null}){let i;try{i=await o(h)}catch(a){throw g?.error?.("AUTH",`MiMo bootstrap failed: ${a.message}`),a}let j=this.buildUrl(),k=this.transformRequest(a,b),l={...this.buildHeaders(d,c),Authorization:`Bearer ${i}`},p=JSON.stringify(k);g?.debug?.("FETCH",`MIMO-FREE → ${j} | body=${p.length}B`);let q=await (0,f.Fm)(j,{method:"POST",headers:l,body:p,signal:e},h);return 401===q.status||403===q.status?(g?.debug?.("AUTH",`MiMo auth failed (${q.status}), re-bootstrapping...`),m=null,n=0,i=await o(h),l.Authorization=`Bearer ${i}`,{response:await (0,f.Fm)(j,{method:"POST",headers:l,body:p,signal:e},h),url:j,headers:l,transformedBody:k}):{response:q,url:j,headers:l,transformedBody:k}}}},76632:(a,b,c)=>{var d=c(45654);c(1277),c(33889),(a.exports=d.hmac=d.hmac||{}).create=function(){var a=null,b=null,c=null,e=null,f={};return f.start=function(f,g){if(null!==f)if("string"==typeof f)if((f=f.toLowerCase())in d.md.algorithms)b=d.md.algorithms[f].create();else throw Error('Unknown hash algorithm "'+f+'"');else b=f;if(null===g)g=a;else{if("string"==typeof g)g=d.util.createBuffer(g);else if(d.util.isArray(g)){var h=g;g=d.util.createBuffer();for(var i=0;i<h.length;++i)g.putByte(h[i])}var j=g.length();j>b.blockLength&&(b.start(),b.update(g.bytes()),g=b.digest()),c=d.util.createBuffer(),e=d.util.createBuffer(),j=g.length();for(var i=0;i<j;++i){var h=g.at(i);c.putByte(54^h),e.putByte(92^h)}if(j<b.blockLength)for(var h=b.blockLength-j,i=0;i<h;++i)c.putByte(54),e.putByte(92);a=g,c=c.bytes(),e=e.bytes()}b.start(),b.update(c)},f.update=function(a){b.update(a)},f.getMac=function(){var a=b.digest().bytes();return b.start(),b.update(e),b.update(a),b.digest()},f.digest=f.getMac,f}},77168:(a,b,c)=>{"use strict";c.a(a,async(a,b)=>{try{c(50969),c(38421),c(10793),c(82689),c(13161),c(68531),c(87350),c(22884),c(86538),c(1654),c(96997),c(98976);var d=c(69641);c(20830);var e=c(95695);c(80152),c(18762);var f=a([d,e]);[d,e]=f.then?(await f)():f,b()}catch(a){b(a)}})},77321:(a,b,c)=>{"use strict";c.d(b,{Z:()=>h});var d=c(38421);let e=[{match:a=>/^kimi-/i.test(a||""),scope:"toolCalls"},{match:a=>/deepseek/i.test(a||""),scope:"all"}],f="deepseek-v4-pro",g={[`${f}-max`]:{thinkingType:"enabled",reasoningEffort:"max"},[`${f}-none`]:{thinkingType:"disabled",reasoningEffort:null}};function h({provider:a,model:b,body:c}){let i=d.xq[a]?.reasoningInject,j=e.find(a=>a.match(b));var k=function({provider:a,model:b,body:c}){let d=g[b];if("deepseek"!==a||!d||!c)return c;let e={...c,model:f,thinking:{type:d.thinkingType}};if(e.extra_body?.thinking){let{thinking:a,...b}=e.extra_body;0===Object.keys(b).length?delete e.extra_body:e.extra_body=b}return d.reasoningEffort?e.reasoning_effort=d.reasoningEffort:delete e.reasoning_effort,e}({provider:a,model:b,body:c}),l=i||j;if(!l||!k?.messages||function(a){if("string"==typeof a.system||Array.isArray(a.system))return!0;if(!Array.isArray(a.messages))return!1;for(let b of a.messages)if(Array.isArray(b.content)){for(let a of b.content)if(a?.type==="tool_use"||a?.type==="tool_result"||a?.type==="thinking")return!0}return!1}(k))return k;let m=k.messages.map(a=>!function(a,b){if(a?.role!=="assistant")return!1;let c=a.reasoning_content;return("string"!=typeof c||!(c.length>0))&&("toolCalls"!==b||Array.isArray(a.tool_calls)&&a.tool_calls.length>0)}(a,l.scope)?a:{...a,reasoning_content:" "});return{...k,messages:m}}},77326:(a,b,c)=>{"use strict";c.d(b,{E5:()=>E,SB:()=>G,ui:()=>H.ui,bI:()=>e.cleanupProviderConnections,Iq:()=>g.createApiKey,jd:()=>l,iE:()=>e.createProviderConnection,eh:()=>I.eh,PX:()=>g.getApiKeys,Dj:()=>k,getProviderConnections:()=>e.getProviderConnections,mt:()=>f.getSettings,ox:()=>F.ox,sZ:()=>D,o5:()=>o.o5,uw:()=>C,oG:()=>n,updateProviderConnection:()=>e.updateProviderConnection,Xx:()=>f.Xx});var d=c(24081),e=c(92216);c(20639);var f=c(45874);c(7044);var g=c(57431),h=c(27137),i=c(50743);function j(a){return a?{id:a.id,name:a.name,kind:a.kind,models:(0,i.q)(a.models,[]),createdAt:a.createdAt,updatedAt:a.updatedAt}:null}async function k(a){return j((await (0,d.c)()).get("SELECT * FROM combos WHERE name = ?",[a]))}async function l(a){let b=await (0,d.c)(),c=new Date().toISOString(),e={id:(0,h.A)(),name:a.name,kind:a.kind||null,models:a.models||[],createdAt:c,updatedAt:c};return b.run("INSERT INTO combos(id, name, kind, models, createdAt, updatedAt) VALUES(?, ?, ?, ?, ?, ?)",[e.id,e.name,e.kind,(0,i.s)(e.models),e.createdAt,e.updatedAt]),e}let m=["name","kind","models"];async function n(a,b){let c=await (0,d.c)(),e=null;return c.transaction(()=>{let d=c.get("SELECT * FROM combos WHERE id = ?",[a]);if(!d)return;let f={...j(d),updatedAt:new Date().toISOString()};for(let a of m)b&&Object.prototype.hasOwnProperty.call(b,a)&&(f[a]=b[a]);c.run("UPDATE combos SET name = ?, kind = ?, models = ?, updatedAt = ? WHERE id = ?",[f.name,f.kind,(0,i.s)(f.models||[]),f.updatedAt,a]),e=f}),e}var o=c(37703);c(90181);var p=c(94735),q=c(15904),r=c(77397),s=c(15738);global._pendingRequests||(global._pendingRequests={byModel:{},byAccount:{}}),global._lastErrorProvider||(global._lastErrorProvider={provider:"",ts:0}),global._statsEmitter||(global._statsEmitter=new p.EventEmitter,global._statsEmitter.setMaxListeners(50)),global._recentRing||(global._recentRing={items:[],initialized:!1}),global._connectionMapCache||(global._connectionMapCache={map:{},ts:0}),global._statsEmitTimers||(global._statsEmitTimers={pending:null,update:null});let t=global._pendingRequests,u=global._lastErrorProvider,v=global._recentRing;global._connectionMapCache;let w=global._statsEmitTimers,x=global._statsEmitter;function y(a,b=150){let c="update"===a?"update":"pending";w[c]||(w[c]=setTimeout(()=>{w[c]=null,x.emit(a)},b),w[c]?.unref?.())}function z(a){if(!a||null!==Object.getPrototypeOf(a)){let b=Object.create(null);return a&&Object.assign(b,a),b}return a}function A(a,b,c){let d=function(a){if(null==a)return null;let b=String(a);return"__proto__"===b||"constructor"===b||"prototype"===b?`__safe_${b}`:b}(b);null!=d&&(a[d]||(a[d]={requests:0,promptTokens:0,completionTokens:0,cachedTokens:0,cost:0}),a[d].requests+=c.requests||1,a[d].promptTokens+=c.promptTokens||0,a[d].completionTokens+=c.completionTokens||0,a[d].cachedTokens+=c.cachedTokens||0,a[d].cost+=c.cost||0,c.meta&&Object.assign(a[d],c.meta))}async function B(a,b,d){if(!d||!a||!b)return 0;try{let{getPricingForModel:e}=await Promise.resolve().then(c.bind(c,90181)),f=await e(a,b);if(!f)return 0;let{calculateCostFromTokens:g}=await Promise.resolve().then(c.bind(c,71253));return g(d,f)}catch(a){return console.error("Error calculating cost:",a),0}}function C(a,b,c,d,e=!1){let f=b?`${a} (${b})`:a;t.byModel[f]||(t.byModel[f]=0),t.byModel[f]=Math.max(0,t.byModel[f]+(d?1:-1)),0===t.byModel[f]&&delete t.byModel[f],c&&(t.byAccount[c]||(t.byAccount[c]={}),t.byAccount[c][f]||(t.byAccount[c][f]=0),t.byAccount[c][f]=Math.max(0,t.byAccount[c][f]+(d?1:-1)),0===t.byAccount[c][f]&&(delete t.byAccount[c][f],0===Object.keys(t.byAccount[c]).length&&delete t.byAccount[c])),!d&&e&&b&&(u.provider=b.toLowerCase(),u.ts=Date.now());let g=new Date().toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"});console.log(`[${g}] [PENDING] ${d?"START":"END"}${e?" (ERROR)":""} | provider=${b} | model=${a}`),y("pending")}async function D(a){try{let b=await (0,d.c)();a.timestamp||(a.timestamp=new Date().toISOString()),a.cost=await B(a.provider,a.model,a.tokens);let c=a.tokens||{},e=(0,r.T)(c.prompt_tokens||c.input_tokens||0,"usage.promptTokens",{integer:!0}),f=(0,r.T)(c.completion_tokens||c.output_tokens||0,"usage.completionTokens",{integer:!0}),g=(0,r.T)(c.cached_tokens||c.cache_read_input_tokens||0,"usage.cachedTokens",{integer:!0}),h=(0,r.T)(a.cost,"usage.cost"),j=!1;(b.transaction(()=>{var d;let k,l,m,n,o,p,r,t,u,v,w,x,y=a.requestId||null;if(y&&b.get("SELECT id FROM usageHistory WHERE requestId = ?",[y]))return;b.run("INSERT INTO usageHistory(timestamp, provider, model, connectionId, clientKeyId, endpoint, promptTokens, completionTokens, cost, status, tokens, meta, requestId) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[a.timestamp,a.provider||null,a.model||null,a.connectionId||null,a.clientKeyId||null,a.endpoint||null,e,f,a.cost||0,a.status||"ok",(0,i.s)(c),(0,i.s)({}),y]),a.clientKeyId&&b.run("UPDATE apiKeys SET spentUsd = spentUsd + ? WHERE id = ?",[Number(a.cost||0),a.clientKeyId]);let B=parseInt(process.env.USAGE_HISTORY_MAX||"50000",10),C=b.get("SELECT value FROM _meta WHERE key = 'usageHistoryCount'");if(k=C?.value!=null?parseInt(C.value,10)+1:b.get("SELECT COUNT(*) as c FROM usageHistory")?.c||0,Number.isFinite(B)&&B>0&&k>B){let a=k-B;b.run("DELETE FROM usageHistory WHERE id IN (SELECT id FROM usageHistory ORDER BY id ASC LIMIT ?)",[a]),k=B}b.run("INSERT INTO _meta(key, value) VALUES('usageHistoryCount', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",[String(k)]);let D=(l=(d=a.timestamp)?new Date(d):new Date,`${l.getFullYear()}-${String(l.getMonth()+1).padStart(2,"0")}-${String(l.getDate()).padStart(2,"0")}`),E=b.get("SELECT data FROM usageDaily WHERE dateKey = ?",[D]),F=E?(0,i.q)(E.data,{}):{requests:0,promptTokens:0,completionTokens:0,cost:0,byProvider:{},byModel:{},byAccount:{},byClientKey:{},byEndpoint:{}};m=a.tokens?.prompt_tokens||a.tokens?.input_tokens||0,n=a.tokens?.completion_tokens||a.tokens?.output_tokens||0,o=a.tokens?.cached_tokens||a.tokens?.cache_read_input_tokens||0,p=a.cost||0,r={promptTokens:m,completionTokens:n,cachedTokens:o,cost:p},F.requests=(F.requests||0)+1,F.promptTokens=(F.promptTokens||0)+m,F.completionTokens=(F.completionTokens||0)+n,F.cachedTokens=(F.cachedTokens||0)+o,F.cost=(F.cost||0)+p,F.byProvider=z(F.byProvider||{}),F.byModel=z(F.byModel||{}),F.byAccount=z(F.byAccount||{}),F.byClientKey=z(F.byClientKey||{}),F.byEndpoint=z(F.byEndpoint||{}),a.provider&&A(F.byProvider,a.provider,r),t=a.provider?`${a.model}|${a.provider}`:a.model,A(F.byModel,t,{...r,meta:{rawModel:a.model,provider:a.provider}}),a.connectionId&&A(F.byAccount,a.connectionId,{...r,meta:{rawModel:a.model,provider:a.provider}}),u=a.clientKeyId&&"string"==typeof a.clientKeyId?a.clientKeyId:null,v=`${u||"local-no-key"}|${a.model}|${a.provider||"unknown"}`,A(F.byClientKey,v,{...r,meta:{rawModel:a.model,provider:a.provider,clientKeyId:u}}),w=a.endpoint||"Unknown",x=`${w}|${a.model}|${a.provider||"unknown"}`,A(F.byEndpoint,x,{...r,meta:{endpoint:w,rawModel:a.model,provider:a.provider}}),b.run("INSERT INTO usageDaily(dateKey, data) VALUES(?, ?) ON CONFLICT(dateKey) DO UPDATE SET data = excluded.data",[D,(0,i.s)(F)]),(0,q.Bq)(b,()=>{let c=(0,s.ry)(b,a.provider)?a.provider:"unknown",d=b.get(`SELECT provider, requests, promptTokens, completionTokens, cachedTokens, cost
|
|
397
|
+
WHERE vault_chunks.conversationId = ? AND vault_entries.expiresAt > ?${c?" AND vault_chunks.entryId = ?":""} AND (${b}) LIMIT ?`,d),o=Array.isArray(h)&&Array.isArray(l)?h.map(a=>({...a,score:l.reduce((b,c)=>b+Number(String(a?.text||"").toLowerCase().includes(c)),0)})).sort((a,b)=>b.score-a.score).slice(0,i):[]}let p=function(a,b){if(!Array.isArray(b))return[];let c=new Map;for(let d of b.slice(0,20)){let b=d?.entryId;if(!(!b||c.has(b)))try{c.set(b,a.get("SELECT toolName FROM vault_entries WHERE id = ?",[b])?.toolName??null)}catch{c.set(b,null)}}return b.map(a=>({entryId:a.entryId,chunkIndex:a.chunkIndex,text:a.text,toolName:c.get(a.entryId)??null}))}(m,o.slice(0,i));var j=[...new Set(p.map(a=>a.entryId))],k=new Date().toISOString();if(Array.isArray(j)&&k)for(let a of j.slice(0,20))try{m.run("UPDATE vault_entries SET lastAccessedAt = ? WHERE id = ?",[k,a])}catch{}return p}catch{return[]}}async function j(a){try{if("string"!=typeof a||!a)return null;let b=await (0,d.c)(),c=b.get("SELECT id, conversationId, toolName, content, expiresAt FROM vault_entries WHERE id = ?",[a]);if(!c)return null;let f=new Date().toISOString();if(c.expiresAt<f){try{b.run("DELETE FROM vault_chunks WHERE entryId = ?",[a]),g(b)&&b.run(`DELETE FROM ${e} WHERE entryId = ?`,[a]),b.run("DELETE FROM vault_entries WHERE id = ?",[a])}catch{}return null}try{b.run("UPDATE vault_entries SET lastAccessedAt = ? WHERE id = ?",[f,a])}catch{}return{id:c.id,conversationId:c.conversationId,toolName:c.toolName,content:c.content}}catch{return null}}async function k(){try{var a=await (0,d.c)(),b=new Date().toISOString();if("string"!=typeof b||!b)return 0;let c="SELECT id FROM vault_entries WHERE expiresAt < ?";if(a.run(`DELETE FROM vault_chunks WHERE entryId IN (${c})`,[b]),g(a))try{a.run(`DELETE FROM ${e} WHERE entryId IN (${c})`,[b])}catch{}return a.run("DELETE FROM vault_entries WHERE expiresAt < ?",[b])?.changes??0}catch{return 0}}},70906:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{q:()=>i});var e=c(77168),f=c(77326);c(72345);var g=c(95695);c(63995);var h=a([e,g]);async function i(a,b=!1,c=null){let d=(0,g.SB)(a.provider),e={accessToken:a.accessToken,refreshToken:a.refreshToken,idToken:a.idToken,expiresAt:a.expiresAt||a.tokenExpiresAt,lastRefreshAt:a.lastRefreshAt,connectionId:a.id,providerSpecificData:a.providerSpecificData,copilotToken:a.providerSpecificData?.copilotToken,copilotTokenExpiresAt:a.providerSpecificData?.copilotTokenExpiresAt};if(!(b||d.needsRefresh(e)))return{connection:a,refreshed:!1};let h=await d.refreshCredentials(e,console,c);if(!h){if(a.accessToken)return{connection:a,refreshed:!1};throw Error("Failed to refresh credentials. Please re-authorize the connection.")}let j={updatedAt:new Date().toISOString()};h.accessToken&&(j.accessToken=h.accessToken),h.refreshToken&&(j.refreshToken=h.refreshToken),h.idToken&&(j.idToken=h.idToken),h.lastRefreshAt&&(j.lastRefreshAt=h.lastRefreshAt),h.expiresIn?(j.expiresAt=new Date(Date.now()+1e3*h.expiresIn).toISOString(),j.expiresIn=h.expiresIn):h.expiresAt&&(j.expiresAt=h.expiresAt);let k={...h.providerSpecificData||{},...h.copilotToken?{copilotToken:h.copilotToken}:{},...h.copilotTokenExpiresAt?{copilotTokenExpiresAt:h.copilotTokenExpiresAt}:{}};return Object.keys(k).length>0&&(j.providerSpecificData={...a.providerSpecificData||{},...k}),await (0,f.updateProviderConnection)(a.id,j),{connection:{...a,...j,providerSpecificData:j.providerSpecificData||a.providerSpecificData},refreshed:!0}}[e,g]=h.then?(await h)():h,d()}catch(a){d(a)}})},71137:(a,b,c)=>{"use strict";c.d(b,{CP:()=>p,yI:()=>m});var d=c(27137),e=c(74075);let f="1"===process.env.CURSOR_PROTOBUF_DEBUG,g=(a,...b)=>f&&console.log(`[PROTOBUF:${a}]`,...b);new TextDecoder;let h="1.1.3",i=new Set([1,2,3,9,10,11,27,1,25]);function j(a){let b=[];for(;a>=128;)b.push(127&a|128),a>>>=7;return b.push(127&a),new Uint8Array(b)}function k(a,b,c){let d=j(a<<3|b);if(0===b)return l(d,j(c));if(2===b){let a="string"==typeof c?new TextEncoder().encode(c):c instanceof Uint8Array?c:Buffer.isBuffer(c)?new Uint8Array(c):new Uint8Array(0);return l(d,j(a.length),a)}return new Uint8Array(0)}function l(...a){let b=new Uint8Array(a.reduce((a,b)=>a+b.length,0)),c=0;for(let d of a)b.set(d,c),c+=d.length;return b}function m(a,b,c=[],f=null,h=!1){g("BODY",`Generating: ${a.length} msgs, model=${b}, tools=${c.length}, reasoning=${f||"none"}, forceAgentMode=${h}`);let i=function(a,b,c=[],e=null,f=!1){return k(1,2,function(a,b,c=[],e=null,f=!1){let h,i=c?.length>0,m=i||f,n=[],o=[],p=[];for(let b=0;b<a.length;b++){let c=a[b],d=Array.isArray(c?.tool_calls)&&c.tool_calls.length>0,e=Array.isArray(c?.tool_results)&&c.tool_results.length>0;if(c?.role==="assistant"&&d&&e){g("ENCODE",`normalizing mixed assistant tool payload at msg[${b}] (calls=${c.tool_calls.length}, results=${c.tool_results.length})`),p.push({...c,tool_results:[]});let d=a[b+1],e=d?.role==="assistant"&&Array.isArray(d?.tool_results)&&d.tool_results.length>0,f=new Set(c.tool_results.map(a=>a?.tool_call_id).filter(a=>"string"==typeof a)),h=new Set((d?.tool_results||[]).map(a=>a?.tool_call_id).filter(a=>"string"==typeof a)),i=f.size>0&&f.size===h.size;if(i){for(let a of f)if(!h.has(a)){i=!1;break}}e&&i||p.push({role:"assistant",content:"",tool_results:c.tool_results});continue}p.push(c)}for(let a=0;a<p.length;a++){let b=p[a],c="user"===b.role?1:2,e=(0,d.A)(),f=a===p.length-1;n.push({content:b.content,role:c,messageId:e,isLast:f,hasTools:i,toolResults:b.tool_results||[]}),o.push({messageId:e,role:c})}let q=0;return"medium"===e?q=1:"high"===e&&(q=2),l(...n.map(a=>k(1,2,function(a,b,c,d=!1,e=!1,f=[],g=null){let h=f.length>0;return l(k(1,2,a),k(2,0,b),k(13,2,c),...g?[k(32,2,g)]:[],...h?f.map(a=>k(18,2,function(a){var b;let c,d,e=function(a){let b="string"==typeof a&&a.length>0?a:"tool";if(b.startsWith("mcp__")){let a=b.slice(5),c=a.indexOf("__");if(c>=0){let b=a.slice(0,c)||"custom",d=a.slice(c+2)||"tool";return`mcp_${b}_${d}`}return`mcp_custom_${a||"tool"}`}return b.startsWith("mcp_")?b:`mcp_custom_${b}`}(a.tool_name||a.name||""),f=a.raw_args||"{}",g=a.result_content||a.result||"",{toolCallId:h,modelCallId:i}=(b=a.tool_call_id||"",c="\nmc_",(d=b.indexOf(c))>=0?{toolCallId:b.slice(0,d),modelCallId:b.slice(d+c.length)}:{toolCallId:b,modelCallId:null}),j=a.tool_index||a.index||1,{serverName:m,selectedTool:n}=function(a){if("string"!=typeof a||!a.startsWith("mcp_"))return{serverName:"custom",selectedTool:a||"tool"};let b=a.slice(4),c=b.indexOf("_");return c<0?{serverName:"custom",selectedTool:b||"tool"}:{serverName:b.slice(0,c)||"custom",selectedTool:b.slice(c+1)||"tool"}}(e);return l(k(1,2,h),k(2,2,e),k(3,0,j>0?j:1),...i?[k(12,2,i)]:[],k(5,2,f),k(8,2,function(a,b,c,d,e=1){return l(k(1,0,19),k(28,2,l(k(1,2,c),k(2,2,d))),k(35,2,a),...b?[k(48,2,b)]:[],k(49,0,e>0?e:1))}(h,i,n,g,j)),k(11,2,function(a,b,c,d,e,f,g=1){let h;return l(k(1,0,19),k(27,2,(h=l(k(1,2,c),k(3,2,e),k(4,2,d)),k(1,2,h))),k(3,2,a),k(9,2,b),k(10,2,e),k(48,0,g>0?g:1),...f?[k(49,2,f)]:[])}(h,e,n,m,f,i,j)))}(a))):[],k(29,0,+!!e),k(47,0,e?2:1),...d&&e?[k(51,2,j(1))]:[])}(a.content,a.role,a.messageId,a.isLast,a.hasTools,a.toolResults))),k(2,0,1),k(3,2,new Uint8Array(0)),k(4,0,1),k(5,2,l(k(1,2,b),k(4,2,new Uint8Array(0)))),k(8,2,""),k(13,0,1),k(15,2,(h=l(k(1,2,new Uint8Array(0)),k(2,2,new Uint8Array(0))),l(k(1,2,"cursor\\aisettings"),k(3,2,new Uint8Array(0)),k(6,2,h),k(8,0,1),k(9,0,1)))),k(19,0,1),k(23,2,(0,d.A)()),k(26,2,l(k(1,2,process.platform||"linux"),k(2,2,process.arch||"x64"),k(3,2,process.version||"v20.0.0"),k(4,2,process.cwd?.()||"/"),k(5,2,new Date().toISOString()))),k(27,0,+!!m),...m?[k(29,2,j(1))]:[],...o.map(a=>k(30,2,function(a,b,c=null){return l(k(1,2,a),...c?[k(2,2,c)]:[],k(3,0,b))}(a.messageId,a.role))),...c?.length>0?c.map(a=>{let b,c,d;return k(34,2,(b=a.function?.name||a.name||"",c=a.function?.description||a.description||"",d=a.function?.parameters||a.input_schema||{},l(...b?[k(1,2,b)]:[],...c?[k(2,2,c)]:[],...Object.keys(d).length>0?[k(3,2,JSON.stringify(d))]:[],k(4,2,"custom"))))}):[],k(35,0,0),k(38,0,0),k(46,0,m?2:1),k(47,2,""),k(48,0,+!m),k(49,0,q),k(51,0,0),k(53,0,1),k(54,2,m?"Agent":"Ask"))}(a,b,c,e,f))}(a,b,c,f,h),n=function(a,b=!1){let c=a,d=0;b&&(c=new Uint8Array(e.gzipSync(Buffer.from(a))),d=1);let f=new Uint8Array(5+c.length);return f[0]=d,f[1]=c.length>>24&255,f[2]=c.length>>16&255,f[3]=c.length>>8&255,f[4]=255&c.length,f.set(c,5),f}(i,!1);return g("BODY",`Protobuf=${i.length}B, Framed=${n.length}B`),n}function n(a,b){let c=0,d=0,e=b;for(;e<a.length;){let b=a[e];if(c|=(127&b)<<d,e++,!(128&b))break;d+=7}return[c,e]}function o(a){let b=new Map,c=0;for(;c<a.length;){let[d,e,f,g]=function(a,b){let c;if(b>=a.length)return[null,null,null,b];let[d,e]=n(a,b),f=7&d,g=e;if(0===f)[c,g]=n(a,g);else if(2===f){let[b,d]=n(a,g);c=a.slice(d,d+b),g=d+b}else 1===f?(c=a.slice(g,g+8),g+=8):5===f?(c=a.slice(g,g+4),g+=4):c=null;return[d>>3,f,c,g]}(a,c);if(null===d)break;b.has(d)||b.set(d,[]),b.get(d).push({wireType:e,value:f}),c=g}return b}function p(a){try{let b=o(a);for(let a of b.keys())i.has(a)||g("SCHEMA",`Unknown response field #${a} detected. Schema v${h} may be outdated.`);if(b.has(1)){let a=function(a){let b=o(a),c="",d="",e="",f=!1;if(b.has(3)&&(c=new TextDecoder().decode(b.get(3)[0].value).split("\n")[0]),b.has(9)&&(d=new TextDecoder().decode(b.get(9)[0].value)),b.has(11)&&(f=0!==b.get(11)[0].value),b.has(27))try{let a=o(b.get(27)[0].value);if(a.has(1)){let b=o(a.get(1)[0].value);b.has(1)&&(d=new TextDecoder().decode(b.get(1)[0].value)),b.has(3)&&(e=new TextDecoder().decode(b.get(3)[0].value))}}catch(a){g("EXTRACT",`MCP parse error: ${a.message}`)}return(!e&&b.has(10)&&(e=new TextDecoder().decode(b.get(10)[0].value)),c&&d)?{id:c,type:"function",function:{name:d,arguments:e||"{}"},isLast:f}:null}(b.get(1)[0].value);if(a)return g("EXTRACT",`Tool call: ${a.function.name}`),{text:null,error:null,toolCall:a,thinking:null}}if(b.has(2)){let{text:a,thinking:c}=function(a){let b=o(a),c=null,d=null;if(b.has(1)&&(c=new TextDecoder().decode(b.get(1)[0].value)),b.has(25))try{let a=o(b.get(25)[0].value);a.has(1)&&(d=new TextDecoder().decode(a.get(1)[0].value))}catch(a){g("EXTRACT",`Thinking parse error: ${a.message}`)}return{text:c,thinking:d}}(b.get(2)[0].value);if(a||c)return{text:a,error:null,toolCall:null,thinking:c}}return{text:null,error:null,toolCall:null,thinking:null}}catch(b){return g("EXTRACT",`Decode failed (schema v${h}): ${b.message}`),{text:null,error:null,toolCall:null,thinking:null,raw:Buffer.from(a).toString("base64"),decodeError:b.message}}}},71253:(a,b,c)=>{"use strict";c.d(b,{PROVIDER_PRICING:()=>f,calculateCostFromTokens:()=>j,gH:()=>h,getPricingForModel:()=>i});var d=c(57690);let e={"claude-opus-4-6":{input:5,output:25,cached:.5,reasoning:25,cache_creation:6.25},"claude-opus-4-5-20251101":{input:5,output:25,cached:.5,reasoning:25,cache_creation:6.25},"claude-sonnet-4-6":{input:3,output:15,cached:.3,reasoning:15,cache_creation:3.75},"claude-sonnet-4-5-20250929":{input:3,output:15,cached:.3,reasoning:15,cache_creation:3.75},"claude-haiku-4-5-20251001":{input:1,output:5,cached:.1,reasoning:5,cache_creation:1.25},"claude-sonnet-4-20250514":{input:3,output:15,cached:1.5,reasoning:15,cache_creation:3},"claude-opus-4-20250514":{input:15,output:25,cached:7.5,reasoning:112.5,cache_creation:15},"claude-3-5-sonnet-20241022":{input:3,output:15,cached:1.5,reasoning:15,cache_creation:3},"claude-haiku-4.5":{input:.5,output:2.5,cached:.05,reasoning:3.75,cache_creation:.5},"claude-opus-4.1":{input:5,output:25,cached:.5,reasoning:37.5,cache_creation:5},"claude-opus-4.5":{input:5,output:25,cached:.5,reasoning:37.5,cache_creation:5},"claude-opus-4.6":{input:5,output:25,cached:.5,reasoning:37.5,cache_creation:5},"claude-sonnet-4":{input:3,output:15,cached:.3,reasoning:22.5,cache_creation:3},"claude-sonnet-4.5":{input:3,output:15,cached:.3,reasoning:22.5,cache_creation:3},"claude-sonnet-4.6":{input:3,output:15,cached:.3,reasoning:22.5,cache_creation:3},"claude-opus-4-5-thinking":{input:5,output:25,cached:.5,reasoning:37.5,cache_creation:5},"claude-opus-4-6-thinking":{input:5,output:25,cached:.5,reasoning:37.5,cache_creation:5},"gpt-3.5-turbo":{input:.5,output:1.5,cached:.25,reasoning:2.25,cache_creation:.5},"gpt-4":{input:2.5,output:10,cached:1.25,reasoning:15,cache_creation:2.5},"gpt-4-turbo":{input:10,output:30,cached:5,reasoning:45,cache_creation:10},"gpt-4o":{input:2.5,output:10,cached:1.25,reasoning:15,cache_creation:2.5},"gpt-4o-mini":{input:.15,output:.6,cached:.075,reasoning:.9,cache_creation:.15},"gpt-4.1":{input:2.5,output:10,cached:1.25,reasoning:15,cache_creation:2.5},"gpt-5":{input:3,output:12,cached:1.5,reasoning:18,cache_creation:3},"gpt-5-mini":{input:.75,output:3,cached:.375,reasoning:4.5,cache_creation:.75},"gpt-5-codex":{input:3,output:12,cached:1.5,reasoning:18,cache_creation:3},"gpt-5.1":{input:4,output:16,cached:2,reasoning:24,cache_creation:4},"gpt-5.1-codex":{input:4,output:16,cached:2,reasoning:24,cache_creation:4},"gpt-5.1-codex-mini":{input:1.5,output:6,cached:.75,reasoning:9,cache_creation:1.5},"gpt-5.1-codex-mini-high":{input:2,output:8,cached:1,reasoning:12,cache_creation:2},"gpt-5.1-codex-max":{input:8,output:32,cached:4,reasoning:48,cache_creation:8},"gpt-5.2":{input:5,output:20,cached:2.5,reasoning:30,cache_creation:5},"gpt-5.2-codex":{input:5,output:20,cached:2.5,reasoning:30,cache_creation:5},"gpt-5.3-codex":{input:6,output:24,cached:3,reasoning:36,cache_creation:6},"gpt-5.3-codex-spark":{input:3,output:12,cached:.3,reasoning:12,cache_creation:3},o1:{input:15,output:60,cached:7.5,reasoning:90,cache_creation:15},"o1-mini":{input:3,output:12,cached:1.5,reasoning:18,cache_creation:3},"gemini-3-flash-preview":{input:.5,output:3,cached:.03,reasoning:4.5,cache_creation:.5},"gemini-3-pro-preview":{input:2,output:12,cached:.25,reasoning:18,cache_creation:2},"gemini-3.1-pro-low":{input:2,output:12,cached:.25,reasoning:18,cache_creation:2},"gemini-3.1-pro-high":{input:4,output:18,cached:.5,reasoning:27,cache_creation:4},"gemini-pro-agent":{input:4,output:18,cached:.5,reasoning:27,cache_creation:4},"gemini-3-flash-agent":{input:.5,output:3,cached:.03,reasoning:4.5,cache_creation:.5},"gemini-3.5-flash-low":{input:.5,output:3,cached:.03,reasoning:4.5,cache_creation:.5},"gemini-3.5-flash-extra-low":{input:.5,output:3,cached:.03,reasoning:4.5,cache_creation:.5},"gemini-3-flash":{input:.5,output:3,cached:.03,reasoning:4.5,cache_creation:.5},"gemini-2.5-pro":{input:2,output:12,cached:.25,reasoning:18,cache_creation:2},"gemini-2.5-flash":{input:.3,output:2.5,cached:.03,reasoning:3.75,cache_creation:.3},"gemini-2.5-flash-lite":{input:.15,output:1.25,cached:.015,reasoning:1.875,cache_creation:.15},"qwen3-coder-plus":{input:1,output:4,cached:.5,reasoning:6,cache_creation:1},"qwen3-coder-flash":{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5},"kimi-k2":{input:1,output:4,cached:.5,reasoning:6,cache_creation:1},"kimi-k2-thinking":{input:1.5,output:6,cached:.75,reasoning:9,cache_creation:1.5},"kimi-k2.5":{input:1.2,output:4.8,cached:.6,reasoning:7.2,cache_creation:1.2},"kimi-k2.5-thinking":{input:1.8,output:7.2,cached:.9,reasoning:10.8,cache_creation:1.8},"kimi-latest":{input:1,output:4,cached:.5,reasoning:6,cache_creation:1},"deepseek-chat":{input:.14,output:.28,cached:.0028,reasoning:.28,cache_creation:.14},"deepseek-reasoner":{input:.14,output:.28,cached:.0028,reasoning:.28,cache_creation:.14},"deepseek-r1":{input:.14,output:.28,cached:.0028,reasoning:.28,cache_creation:.14},"deepseek-v3.2-chat":{input:.14,output:.28,cached:.0028,reasoning:.28,cache_creation:.14},"deepseek-v3.2-reasoner":{input:.14,output:.28,cached:.0028,reasoning:.28,cache_creation:.14},"deepseek-v4-flash":{input:.14,output:.28,cached:.0028,reasoning:.28,cache_creation:.14},"deepseek-v4-pro":{input:.435,output:.87,cached:.003625,reasoning:.87,cache_creation:.435},"glm-4.6":{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5},"glm-4.6v":{input:.75,output:3,cached:.375,reasoning:4.5,cache_creation:.75},"glm-4.7":{input:.75,output:3,cached:.375,reasoning:4.5,cache_creation:.75},"glm-5":{input:1,output:4,cached:.5,reasoning:6,cache_creation:1},"MiniMax-M3":{input:.3,output:1.2,cached:.06,reasoning:1.8,cache_creation:.3},"MiniMax-M2.1":{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5},"MiniMax-M2.5":{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5},"MiniMax-M2.7":{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5},"minimax-m2.1":{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5},"minimax-m2.5":{input:.6,output:2.4,cached:.3,reasoning:3.6,cache_creation:.6},"grok-code-fast-1":{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5},auto:{input:2,output:8,cached:1,reasoning:12,cache_creation:2},"oswe-vscode-prime":{input:1,output:4,cached:.5,reasoning:6,cache_creation:1},"gpt-oss-120b-medium":{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5},"vision-model":{input:1.5,output:6,cached:.75,reasoning:9,cache_creation:1.5},"coder-model":{input:1.5,output:6,cached:.75,reasoning:9,cache_creation:1.5}},f={gh:{"gpt-5.3-codex":{input:1.75,output:14,cached:.175,reasoning:14,cache_creation:1.75}}},g=[{pattern:"*-codex-xhigh",pricing:{input:10,output:40,cached:5,reasoning:60,cache_creation:10}},{pattern:"*-codex-high",pricing:{input:8,output:32,cached:4,reasoning:48,cache_creation:8}},{pattern:"*-codex-max",pricing:{input:8,output:32,cached:4,reasoning:48,cache_creation:8}},{pattern:"*-codex-mini-*",pricing:{input:1.5,output:6,cached:.75,reasoning:9,cache_creation:1.5}},{pattern:"*-codex-mini",pricing:{input:1.5,output:6,cached:.75,reasoning:9,cache_creation:1.5}},{pattern:"*-codex-low",pricing:{input:4,output:16,cached:2,reasoning:24,cache_creation:4}},{pattern:"*-codex-none",pricing:{input:3,output:12,cached:1.5,reasoning:18,cache_creation:3}},{pattern:"*-codex-spark",pricing:{input:3,output:12,cached:.3,reasoning:12,cache_creation:3}},{pattern:"codex-*",pricing:{input:3,output:12,cached:1.5,reasoning:18,cache_creation:3}},{pattern:"*-codex",pricing:{input:3,output:12,cached:1.5,reasoning:18,cache_creation:3}},{pattern:"claude-opus-*",pricing:{input:5,output:25,cached:.5,reasoning:25,cache_creation:6.25}},{pattern:"claude-sonnet-*",pricing:{input:3,output:15,cached:.3,reasoning:15,cache_creation:3.75}},{pattern:"claude-haiku-*",pricing:{input:1,output:5,cached:.1,reasoning:5,cache_creation:1.25}},{pattern:"claude-*",pricing:{input:3,output:15,cached:.3,reasoning:15,cache_creation:3.75}},{pattern:"gemini-*-flash-lite",pricing:{input:.15,output:1.25,cached:.015,reasoning:1.875,cache_creation:.15}},{pattern:"gemini-*-flash",pricing:{input:.3,output:2.5,cached:.03,reasoning:3.75,cache_creation:.3}},{pattern:"gemini-*-pro",pricing:{input:2,output:12,cached:.25,reasoning:18,cache_creation:2}},{pattern:"gemini-3-*",pricing:{input:.5,output:3,cached:.03,reasoning:4.5,cache_creation:.5}},{pattern:"gemini-2.5-*",pricing:{input:.3,output:2.5,cached:.03,reasoning:3.75,cache_creation:.3}},{pattern:"gemini-*",pricing:{input:.5,output:3,cached:.03,reasoning:4.5,cache_creation:.5}},{pattern:"gpt-5.3-*",pricing:{input:6,output:24,cached:3,reasoning:36,cache_creation:6}},{pattern:"gpt-5.2-*",pricing:{input:5,output:20,cached:2.5,reasoning:30,cache_creation:5}},{pattern:"gpt-5.1-*",pricing:{input:4,output:16,cached:2,reasoning:24,cache_creation:4}},{pattern:"gpt-5-*",pricing:{input:3,output:12,cached:1.5,reasoning:18,cache_creation:3}},{pattern:"gpt-5*",pricing:{input:3,output:12,cached:1.5,reasoning:18,cache_creation:3}},{pattern:"gpt-4o-*",pricing:{input:.15,output:.6,cached:.075,reasoning:.9,cache_creation:.15}},{pattern:"gpt-4o",pricing:{input:2.5,output:10,cached:1.25,reasoning:15,cache_creation:2.5}},{pattern:"gpt-4*",pricing:{input:2.5,output:10,cached:1.25,reasoning:15,cache_creation:2.5}},{pattern:"o1-*",pricing:{input:3,output:12,cached:1.5,reasoning:18,cache_creation:3}},{pattern:"o1",pricing:{input:15,output:60,cached:7.5,reasoning:90,cache_creation:15}},{pattern:"o3-*",pricing:{input:10,output:40,cached:5,reasoning:60,cache_creation:10}},{pattern:"o4-*",pricing:{input:2,output:8,cached:1,reasoning:12,cache_creation:2}},{pattern:"qwen3-coder-*",pricing:{input:1,output:4,cached:.5,reasoning:6,cache_creation:1}},{pattern:"qwen*-coder-*",pricing:{input:1,output:4,cached:.5,reasoning:6,cache_creation:1}},{pattern:"qwen*",pricing:{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5}},{pattern:"kimi-*-thinking",pricing:{input:1.8,output:7.2,cached:.9,reasoning:10.8,cache_creation:1.8}},{pattern:"kimi-k2*",pricing:{input:1.2,output:4.8,cached:.6,reasoning:7.2,cache_creation:1.2}},{pattern:"kimi-*",pricing:{input:1,output:4,cached:.5,reasoning:6,cache_creation:1}},{pattern:"deepseek-*reasoner*",pricing:{input:.14,output:.28,cached:.0028,reasoning:.28,cache_creation:.14}},{pattern:"deepseek-r*",pricing:{input:.14,output:.28,cached:.0028,reasoning:.28,cache_creation:.14}},{pattern:"deepseek-v*",pricing:{input:.14,output:.28,cached:.0028,reasoning:.28,cache_creation:.14}},{pattern:"deepseek-*",pricing:{input:.14,output:.28,cached:.0028,reasoning:.28,cache_creation:.14}},{pattern:"glm-5*",pricing:{input:1,output:4,cached:.5,reasoning:6,cache_creation:1}},{pattern:"glm-4*",pricing:{input:.75,output:3,cached:.375,reasoning:4.5,cache_creation:.75}},{pattern:"glm-*",pricing:{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5}},{pattern:"MiniMax-*",pricing:{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5}},{pattern:"minimax-*",pricing:{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5}},{pattern:"grok-code-*",pricing:{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5}},{pattern:"grok-*",pricing:{input:.5,output:2,cached:.25,reasoning:3,cache_creation:.5}}];function h(a,b){return RegExp("^"+a.split("*").map(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*")+"$","i").test(b)}function i(a,b){if(!b)return null;if(a&&f[a]?.[b])return f[a][b];let c=(0,d.KN)(b),i=function(a){let b=a.includes("/")?a.split("/").pop():a;if(e[b]||e[a])return e[b]||e[a];for(let{pattern:c,pricing:d}of g)if(h(c,b||a))return d;return null}(b);return c&&i?{...i,...c}:c||i}function j(a,b){if(!a||!b)return 0;let c=0,d=a.prompt_tokens||a.input_tokens||0,e=a.cached_tokens||a.cache_read_input_tokens||0,f=a.cache_creation_input_tokens||0;c+=Math.max(0,d-e-f)*(b.input/1e6),e>0&&(c+=e*((b.cached||b.input)/1e6)),c+=(a.completion_tokens||a.output_tokens||0)*(b.output/1e6);let g=a.reasoning_tokens||0;return g>0&&(c+=g*((b.reasoning||b.output)/1e6)),f>0&&(c+=f*((b.cache_creation||b.input)/1e6)),c}},72285:(a,b,c)=>{"use strict";c.d(b,{h:()=>v});var d=c(77598),e=c(67671),f=c(38421),g=c(45431),h=c(98976),i=c(96997),j=c(10342),k=c(13161),l=c(49623),m=c(96930);let n=null;async function o(a="endpoint-proxy-salt"){let b=function(){if(n)return n;try{n=(0,m.machineIdSync)()}catch{n=d.randomUUID()}return n}();return d.createHash("sha256").update(b+a).digest("hex").substring(0,16)}var p=c(97137),q=c(83382);let r=new Set(["model","input","instructions","tools","tool_choice","stream","store","reasoning","include","temperature","top_p","max_output_tokens","parallel_tool_calls","text","metadata","prompt_cache_key"]),s=new Set(["low","medium","high","xhigh"]),t=/^(?:rs|msg|fc)_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function u(a,b){return a._grokCliRequest||(a._grokCliRequest={sessionId:(0,l.oV)({headers:a.rawHeaders,body:b,connectionId:a.connectionId||a.id,workspaceId:a.providerSpecificData?.workspaceId,scope:"grok-cli"}),requestId:d.randomUUID(),agentId:a.providerSpecificData?.deviceId||null,turnIdx:1,model:null}),a._grokCliRequest}class v extends e.Hv{constructor(){super("grok-cli",f.xq["grok-cli"]||g.A.transport)}buildUrl(){return`${q.Nr}/responses`}resolveIdentity(){return q.s2}async refreshCredentials(a,b,c=null){if(!a?.refreshToken)return null;let d=await (0,i.$B)("grok-cli",a,b,c);return(0,h.hJ)("grok-cli",a,d)}needsRefresh(a){return(0,h.fp)("grok-cli",a)}buildHeaders(a,b=!0){let c=super.buildHeaders(a,b),d=u(a,{});c["x-grok-session-id"]=d.sessionId,c["x-grok-conv-id"]=d.sessionId,c["x-grok-req-id"]=d.requestId,c["x-grok-turn-idx"]=String(d.turnIdx),d.agentId&&(c["x-grok-agent-id"]=d.agentId),d.model&&(c["x-grok-model-override"]=d.model);let e=a.providerSpecificData||{};return(e.email||a.email)&&(c["x-email"]=e.email||a.email),(e.userId||a.userId)&&(c["x-userid"]=e.userId||a.userId),c}transformRequest(a,b,c,d){var e;let f=u(d,b),g=(0,j.m)(b.input);g?b.input=g:Array.isArray(b.messages)&&(b.input=b.messages.map(a=>({type:"message",role:a.role||"user",content:"string"==typeof a.content?a.content:JSON.stringify(a.content??"")}))),b.input||(b.input=(0,j.m)("")),Array.isArray(b.input)&&(b.input=b.input.filter(a=>"string"==typeof a?!/^(rs|fc|resp|msg)_/.test(a):!a||"object"!=typeof a||"item_reference"!==a.type&&("string"==typeof a.id&&/^(rs|fc|resp|msg)_/.test(a.id)&&!t.test(a.id)&&delete a.id,!0))),function(a){if(!Array.isArray(a.tools)||0===a.tools.length){delete a.tools,delete a.tool_choice;return}let b=new Set;if(a.tools=a.tools.flatMap(a=>{if(!a||"object"!=typeof a||Array.isArray(a))return[];if(["web_search","x_search","file_search","image_generation","code_interpreter","mcp","local_shell"].includes(a.type))return[a];let c=a.function&&"object"==typeof a.function?a.function:a,d="string"==typeof c.name?c.name.trim().slice(0,128):"";return d?(b.add(d),[{type:"function",name:d,...c.description?{description:String(c.description)}:{},parameters:"custom"===a.type?{type:"object",properties:{input:{type:"string"}},required:["input"]}:c.parameters||{type:"object",properties:{}}}]):[]}),0===a.tools.length)delete a.tools,delete a.tool_choice;else if(a.tool_choice&&"object"==typeof a.tool_choice){let c=a.tool_choice.name||a.tool_choice.function?.name;b.has(c)?a.tool_choice={type:"function",name:c}:delete a.tool_choice}}(b),f.turnIdx=Array.isArray(e=b.input)?Math.max(1,e.filter(a=>a?.role==="user"&&(!a.type||"message"===a.type)).length):1;let h=String(b.model||a||q.to),i=h.match(/-(low|medium|high|xhigh)$/)?.[1]||null,l=i?h.slice(0,-(i.length+1)):h;b.model=(0,k.kt)("gcli",l)||l,f.model=b.model;let m=b.reasoning&&"object"==typeof b.reasoning?b.reasoning:{};if(b.reasoning={...m,summary:m.summary||"concise"},(0,q.Au)(b.model)){let a;b.reasoning.effort="max"===(a=String(m.effort||b.reasoning_effort||i||"").trim().toLowerCase())?"xhigh":s.has(a)?a:"high"}else delete b.reasoning.effort;for(let a of(delete b.reasoning_effort,b.include=Array.isArray(b.include)?b.include:[],b.include.includes("reasoning.encrypted_content")||b.include.push("reasoning.encrypted_content"),b.stream=!0,b.store=!1,delete b.messages,delete b.max_tokens,delete b.max_completion_tokens,delete b.user,delete b.stream_options,delete b.previous_response_id,Object.keys(b)))r.has(a)||delete b[a];return b}async execute(a){var b;let c,d={...a.credentials||{}},e=u(d,a.body);return e.agentId||(b=await o("grok-cli-agent"),c=`${b}${b}`.replace(/[^0-9a-f]/gi,"0").padEnd(32,"0").slice(0,32),e.agentId=`${c.slice(0,8)}-${c.slice(8,12)}-5${c.slice(13,16)}-a${c.slice(17,20)}-${c.slice(20)}`),(0,p.v)({execute:()=>super.execute({...a,credentials:d}),retryConfig:this.config.retry,signal:a.signal,log:a.log,provider:"grok-cli"})}parseError(a,b){if(402===a.status&&b)try{let a=JSON.parse(b);return{status:402,message:a.error||a.message||b,code:a.code}}catch{}return super.parseError(a,b)}}},72345:(a,b,c)=>{"use strict";c(50969);var d=c(38528);c(10793),(0,d.U)("antigravity"),c(82961),c(20012),c(43835),(0,d.U)("minimax").urls,(0,d.U)("minimax-cn").urls,c(15251),c(83382),(0,d.U)("glm").url,(0,d.U)("glm-cn").url,(0,d.U)("vercel-ai-gateway").url},73081:(a,b,c)=>{"use strict";c.d(b,{nu:()=>e}),c(68531),c(18101);let d=new Set(["response.completed","response.done","response.failed","error"]);function e(a,b){let c=a||(b&&"string"==typeof b.type?b.type:null);if(d.has(c))return!0;let e=b?.response?.status;return"completed"===e||"failed"===e}new TextEncoder},73135:(a,b,c)=>{"use strict";let{addAbortListener:d}=c(84285),{RequestAbortedError:e}=c(61448),f=Symbol("kListener"),g=Symbol("kSignal");function h(a){a.abort?a.abort(a[g]?.reason):a.reason=a[g]?.reason??new e,i(a)}function i(a){a[g]&&("removeEventListener"in a[g]?a[g].removeEventListener("abort",a[f]):a[g].removeListener("abort",a[f]),a[g]=null,a[f]=null)}a.exports={addSignal:function(a,b){if(a.reason=null,a[g]=null,a[f]=null,b){if(b.aborted)return void h(a);a[g]=b,a[f]=()=>{h(a)},d(a[g],a[f])}},removeSignal:i}},73792:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{OJ:()=>w});var e=c(77168),f=c(77326),g=c(82961),h=c(20012),i=c(95695),j=c(50969),k=c(63993),l=c(70906),m=c(78744),n=a([e,i,l]);[e,i,l]=n.then?(await n)():n;let x=m.oc;x.tickIntervalMs;let y={claude:{getUsage:g.g,sendPing:r},codex:{getUsage:h.Tl,sendPing:t}},z=global.__quotaAutoPing??={interval:null,running:!1,resetCache:{},failureCache:{}};function o(a){let b=new Date(a).getTime();return Number.isFinite(b)?new Date(6e4*Math.floor(b/6e4)).toISOString():a}function p(a,b=null){if("number"==typeof a&&Number.isFinite(a))return a;if("string"==typeof a&&a.trim()){let b=Number(a);if(Number.isFinite(b))return b}return b}function q(a){if(!a||!0===a.unlimited)return!1;let b=p(a.remaining);if(null!==b)return b<=0;let c=p(a.used),d=p(a.total);return null!==d&&d>0&&null!==c&&c>=d}async function r(a,b,c,d){return(await d.proxyAwareFetch("https://api.anthropic.com/v1/messages?beta=true",{method:"POST",headers:{Authorization:`Bearer ${a.accessToken}`,"content-type":"application/json"},body:JSON.stringify({model:b.pingModel,max_tokens:b.pingMaxTokens,messages:[{role:"user",content:b.pingText}]}),identity:"claude-cli",provider:"claude",format:"claude",credentialId:a.id,stream:!1,retryCount:0},c)).ok}async function s(a){if("function"==typeof a?.text)return void await a.text();let b=a?.body?.getReader?.();if(b)try{for(;;){let{done:a}=await b.read();if(a)return}}finally{b.releaseLock?.()}}async function t(a,b,c,d){var e;let f=d.getExecutor("codex"),{response:g}=await f.execute({model:b.pingModel,stream:!0,credentials:{accessToken:a.accessToken,connectionId:a.id,providerSpecificData:a.providerSpecificData},proxyOptions:c,log:console,body:{model:b.pingModel,input:(e=b.pingText,[{type:"message",role:"user",content:[{type:"input_text",text:e}]}]),instructions:b.pingInstructions,reasoning:b.pingReasoningEffort?{effort:b.pingReasoningEffort,summary:"auto"}:void 0,store:!1,stream:!0}});if(!g.ok){try{await g.body?.cancel?.()}catch{}return!1}return await s(g),!0}async function u(a,b,c,d,e,f=z){var g,h,i;let j=(g=a.id,`${b}:${g}`),k=f.resetCache[j];if(!c.pingWhenResetAtSlides&&k&&Date.now()<new Date(k).getTime()-x.refreshAheadMs||function(a,b,c=Date.now()){let d=a.failureCache[b];return d&&c-d<x.failureCooldownMs}(f,j))return;let l=(h=await e.resolveConnectionProxyConfig(a.providerSpecificData),{connectionProxyEnabled:!0===h.connectionProxyEnabled,connectionProxyUrl:h.connectionProxyUrl||"",connectionNoProxy:h.connectionNoProxy||"",vercelRelayUrl:h.vercelRelayUrl||"",strictProxy:!1}),m=a;try{m=(await e.refreshAndUpdateCredentials(m,!1,l)).connection}catch(c){f.failureCache[j]=Date.now(),console.warn(`[AutoPing] ${b}:${a.id}: refresh failed: ${c.message}`);return}let n=await d.getUsage(m.accessToken,l),p=n?.quotas||{},r=p?.[c.quotaKey],s=function(a){if(!a||"object"!=typeof a)return null;if(!0===a.unlimited)return 100;let b=Number(a.remainingPercentage);if(Number.isFinite(b))return Math.max(0,Math.min(100,b));let c=Number(a.remaining),d=Number(a.total);return Number.isFinite(c)&&Number.isFinite(d)&&d>0?Math.max(0,Math.min(100,c/d*100)):Number.isFinite(c)?Math.max(0,c):null}(r);if(null!=s)try{await e.updateProviderConnection(m.id,{lastQuota:{remainingPercentage:s,resetAt:r.resetAt??null,at:Date.now()}})}catch{}let t=r?.resetAt;if(!t||(f.resetCache[j]=t,c.skipWhenBlockingQuotaExhausted&&(i=c.quotaKey,Object.entries(p||{}).some(([a,b])=>a!==i&&!String(a).toLowerCase().includes("session")&&q(b)))||q(r)))return;let v=Date.now(),w=o(t),y=m.lastPingedResetKey||o(m.lastPingedResetAt);if(!(!function(a,b,c,d){if(a.pingWhenResetAtSlides){let d,e;return!!b&&(d=new Date(b).getTime(),e=new Date(c).getTime(),(Number.isFinite(d)&&Number.isFinite(e)?e-d:0)>=(a.resetAtDriftMs||0))}let e=new Date(c).getTime();return Number.isFinite(e)&&d>=e-x.pingLeadMs}(c,k,t,v)||function(a,b,c=Date.now()){if(!b)return!1;let d=new Date(a.lastPingAt).getTime();return Number.isFinite(d)&&c-d<b}(m,c.minPingIntervalMs,v))&&y!==w){if(!await d.sendPing(m,c,l,e)){f.failureCache[j]=Date.now(),console.warn(`[AutoPing] ${b}:${m.id}: ping failed (reset ${t})`);return}delete f.failureCache[j],await e.updateProviderConnection(m.id,{lastPingedResetAt:t,lastPingedResetKey:w,lastPingAt:new Date().toISOString(),updatedAt:new Date().toISOString()}),console.log(`[AutoPing] ${b}:${m.id}: ping sent (reset ${t})`)}}async function v(a={getSettings:f.mt,getProviderConnections:f.getProviderConnections,updateProviderConnection:f.updateProviderConnection,resolveConnectionProxyConfig:k.B,refreshAndUpdateCredentials:l.q,proxyAwareFetch:j.Fm,getExecutor:i.SB},b=z){if(!b.running){b.running=!0;try{let d=await a.getSettings();for(let[e,f]of Object.entries(x.providers)){let g=y[e];if(!g)continue;let h=d?.[f.settingsKey]?.connections||{};if(0!==Object.keys(h).length)for(let d of(await a.getProviderConnections({provider:e,isActive:!0})).filter(a=>"oauth"===a.authType&&!0===h[a.id]))try{await u(d,e,f,g,a,b)}catch(a){var c;b.failureCache[c=d.id,`${e}:${c}`]=Date.now(),console.warn(`[AutoPing] ${e}:${d.id}: ${a.message}`)}}}catch(a){console.warn("[AutoPing] tick error:",a.message)}finally{b.running=!1}}}function w(){!z.interval&&(console.log("[AutoPing] scheduler started"),v().catch(()=>{}),z.interval=setInterval(()=>{v().catch(()=>{})},x.tickIntervalMs),z.interval.unref&&z.interval.unref())}d()}catch(a){d(a)}})},74399:(a,b,c)=>{"use strict";let d=c(7344),{InvalidArgumentError:e}=c(61448),{toRawHeaders:f}=c(84285);class g{#at;constructor(a){this.#at=a}onRequestStart(a,b){this.#at.onConnect?.(b=>a.abort(b),b)}onRequestUpgrade(a,b,c,d){let e=a?.rawHeaders??f(c??{});this.#at.onUpgrade?.(b,e,d)}onResponseStart(a,b,c,d){let e=a?.rawHeaders??f(c??{});this.#at.onHeaders?.(b,e,()=>a.resume(),d)===!1&&a.pause()}onResponseData(a,b){this.#at.onData?.(b)===!1&&a.pause()}onResponseEnd(a,b){let c=a?.rawTrailers??f(b??{});this.#at.onComplete?.(c)}onResponseError(a,b){if(!this.#at.onError)throw b;this.#at.onError(b)}onBodySent(a){this.#at.onBodySent?.(a)}onRequestSent(){this.#at.onRequestSent?.()}onResponseStarted(){this.#at.onResponseStarted?.()}}class h extends d{#d;constructor(a){if(super(),!a||"function"!=typeof a.dispatch)throw new e("Argument dispatcher must implement dispatch");this.#d=a}static wrapHandler(a){if(!a||"object"!=typeof a)throw new e("handler must be an object");return"function"==typeof a.onRequestStart?a:new g(a)}dispatch(a,b){return!1!==a.allowH2&&(a={...a,allowH2:!1}),this.#d.dispatch(a,h.wrapHandler(b))}close(...a){return this.#d.close(...a)}destroy(...a){return this.#d.destroy(...a)}}a.exports=h},74570:(a,b,c)=>{"use strict";c.d(b,{Bi:()=>e,Es:()=>i,XP:()=>k,b8:()=>d,d:()=>h,ky:()=>j,w3:()=>l}),c(21820);let d="2023-06-01",e={"Anthropic-Version":d,"Anthropic-Beta":"claude-code-20250219,interleaved-thinking-2025-05-14"},f=["claude-code-20250219","oauth-2025-04-20","interleaved-thinking-2025-05-14","context-management-2025-06-27","prompt-caching-scope-2026-01-05","structured-outputs-2025-12-15","fast-mode-2026-02-01","redact-thinking-2026-02-12","token-efficient-tools-2026-03-28"],g=["advanced-tool-use-2025-11-20","effort-2025-11-24"];function h(a=""){let b=[...f];return/^claude-(opus|sonnet)/.test(a)&&b.push(...g),b.join(",")}let i="https://api.openai.com/v1",j="https://api.anthropic.com/v1",k={clientId:"1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com",clientSecret:"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"},l={clientId:"681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com",clientSecret:"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"}},75371:(a,b,c)=>{"use strict";c(68531),c(96684),c(62457)},76103:(a,b,c)=>{var d=c(45654);c(45518),c(63070),c(88819),c(36105),c(49345),c(56416),c(29984),c(33889),c(65737);var e=d.asn1,f=a.exports=d.pkcs7=d.pkcs7||{};function g(a){var b;if(a.type===d.pki.oids.contentType)b=e.create(e.Class.UNIVERSAL,e.Type.OID,!1,e.oidToDer(a.value).getBytes());else if(a.type===d.pki.oids.messageDigest)b=e.create(e.Class.UNIVERSAL,e.Type.OCTETSTRING,!1,a.value.bytes());else if(a.type===d.pki.oids.signingTime){var c=new Date("1950-01-01T00:00:00Z"),f=new Date("2050-01-01T00:00:00Z"),g=a.value;if("string"==typeof g){var h=Date.parse(g);g=isNaN(h)?13===g.length?e.utcTimeToDate(g):e.generalizedTimeToDate(g):new Date(h)}b=g>=c&&g<f?e.create(e.Class.UNIVERSAL,e.Type.UTCTIME,!1,e.dateToUtcTime(g)):e.create(e.Class.UNIVERSAL,e.Type.GENERALIZEDTIME,!1,e.dateToGeneralizedTime(g))}return e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.OID,!1,e.oidToDer(a.type).getBytes()),e.create(e.Class.UNIVERSAL,e.Type.SET,!0,[b])])}function h(a,b,c){var f={};if(!e.validate(b,c,f,[])){var g=Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message.");throw g.errors=g,g}if(e.derToOid(f.contentType)!==d.pki.oids.data)throw Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported.");if(f.encryptedContent){var h="";if(d.util.isArray(f.encryptedContent))for(var i=0;i<f.encryptedContent.length;++i){if(f.encryptedContent[i].type!==e.Type.OCTETSTRING)throw Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects.");h+=f.encryptedContent[i].value}else h=f.encryptedContent;a.encryptedContent={algorithm:e.derToOid(f.encAlgorithm),parameter:d.util.createBuffer(f.encParameter.value),content:d.util.createBuffer(h)}}if(f.content){var h="";if(d.util.isArray(f.content))for(var i=0;i<f.content.length;++i){if(f.content[i].type!==e.Type.OCTETSTRING)throw Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects.");h+=f.content[i].value}else h=f.content;a.content=d.util.createBuffer(h)}return a.version=f.version.charCodeAt(0),a.rawCapture=f,f}function i(a){if(void 0===a.encryptedContent.key)throw Error("Symmetric key not available.");if(void 0===a.content){var b;switch(a.encryptedContent.algorithm){case d.pki.oids["aes128-CBC"]:case d.pki.oids["aes192-CBC"]:case d.pki.oids["aes256-CBC"]:b=d.aes.createDecryptionCipher(a.encryptedContent.key);break;case d.pki.oids.desCBC:case d.pki.oids["des-EDE3-CBC"]:b=d.des.createDecryptionCipher(a.encryptedContent.key);break;default:throw Error("Unsupported symmetric cipher, OID "+a.encryptedContent.algorithm)}if(b.start(a.encryptedContent.parameter),b.update(a.encryptedContent.content),!b.finish())throw Error("Symmetric decryption failed.");a.content=b.output}}f.messageFromPem=function(a){var b=d.pem.decode(a)[0];if("PKCS7"!==b.type){var c=Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".');throw c.headerType=b.type,c}if(b.procType&&"ENCRYPTED"===b.procType.type)throw Error("Could not convert PKCS#7 message from PEM; PEM is encrypted.");var g=e.fromDer(b.body);return f.messageFromAsn1(g)},f.messageToPem=function(a,b){var c={type:"PKCS7",body:e.toDer(a.toAsn1()).getBytes()};return d.pem.encode(c,{maxline:b})},f.messageFromAsn1=function(a){var b,c={},g=[];if(!e.validate(a,f.asn1.contentInfoValidator,c,g)){var h=Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo.");throw h.errors=g,h}var i=e.derToOid(c.contentType);switch(i){case d.pki.oids.envelopedData:b=f.createEnvelopedData();break;case d.pki.oids.encryptedData:b=f.createEncryptedData();break;case d.pki.oids.signedData:b=f.createSignedData();break;default:throw Error("Cannot read PKCS#7 message. ContentType with OID "+i+" is not (yet) supported.")}return b.fromAsn1(c.content.value[0]),b},f.createSignedData=function(){var a=null;return a={type:d.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(b){if(h(a,b,f.asn1.signedDataValidator),a.certificates=[],a.crls=[],a.digestAlgorithmIdentifiers=[],a.contentInfo=null,a.signerInfos=[],a.rawCapture.certificates)for(var c=a.rawCapture.certificates.value,e=0;e<c.length;++e)a.certificates.push(d.pki.certificateFromAsn1(c[e]))},toAsn1:function(){a.contentInfo||a.sign();for(var b=[],c=0;c<a.certificates.length;++c)b.push(d.pki.certificateToAsn1(a.certificates[c]));var f=[],g=e.create(e.Class.CONTEXT_SPECIFIC,0,!0,[e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.INTEGER,!1,e.integerToDer(a.version).getBytes()),e.create(e.Class.UNIVERSAL,e.Type.SET,!0,a.digestAlgorithmIdentifiers),a.contentInfo])]);return b.length>0&&g.value[0].value.push(e.create(e.Class.CONTEXT_SPECIFIC,0,!0,b)),f.length>0&&g.value[0].value.push(e.create(e.Class.CONTEXT_SPECIFIC,1,!0,f)),g.value[0].value.push(e.create(e.Class.UNIVERSAL,e.Type.SET,!0,a.signerInfos)),e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.OID,!1,e.oidToDer(a.type).getBytes()),g])},addSigner:function(b){var c=b.issuer,e=b.serialNumber;if(b.certificate){var f=b.certificate;"string"==typeof f&&(f=d.pki.certificateFromPem(f)),c=f.issuer.attributes,e=f.serialNumber}var g=b.key;if(!g)throw Error("Could not add PKCS#7 signer; no private key specified.");"string"==typeof g&&(g=d.pki.privateKeyFromPem(g));var h=b.digestAlgorithm||d.pki.oids.sha1;switch(h){case d.pki.oids.sha1:case d.pki.oids.sha256:case d.pki.oids.sha384:case d.pki.oids.sha512:case d.pki.oids.md5:break;default:throw Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+h)}var i=b.authenticatedAttributes||[];if(i.length>0){for(var j=!1,k=!1,l=0;l<i.length;++l){var m=i[l];if(!j&&m.type===d.pki.oids.contentType){if(j=!0,k)break;continue}if(!k&&m.type===d.pki.oids.messageDigest){if(k=!0,j)break;continue}}if(!j||!k)throw Error("Invalid signer.authenticatedAttributes. If signer.authenticatedAttributes is specified, then it must contain at least two attributes, PKCS #9 content-type and PKCS #9 message-digest.")}a.signers.push({key:g,version:1,issuer:c,serialNumber:e,digestAlgorithm:h,signatureAlgorithm:d.pki.oids.rsaEncryption,signature:null,authenticatedAttributes:i,unauthenticatedAttributes:[]})},sign:function(b){if(b=b||{},("object"!=typeof a.content||null===a.contentInfo)&&(a.contentInfo=e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.OID,!1,e.oidToDer(d.pki.oids.data).getBytes())]),"content"in a)){var c;a.content instanceof d.util.ByteBuffer?c=a.content.bytes():"string"==typeof a.content&&(c=d.util.encodeUtf8(a.content)),b.detached?a.detachedContent=e.create(e.Class.UNIVERSAL,e.Type.OCTETSTRING,!1,c):a.contentInfo.value.push(e.create(e.Class.CONTEXT_SPECIFIC,0,!0,[e.create(e.Class.UNIVERSAL,e.Type.OCTETSTRING,!1,c)]))}0!==a.signers.length&&function(b){if(!(c=a.detachedContent?a.detachedContent:(c=a.contentInfo.value[1]).value[0]))throw Error("Could not sign PKCS#7 message; there is no content to sign.");var c,f=e.derToOid(a.contentInfo.value[0].value),h=e.toDer(c);for(var i in h.getByte(),e.getBerValueLength(h),h=h.getBytes(),b)b[i].start().update(h);for(var j=new Date,k=0;k<a.signers.length;++k){var l=a.signers[k];if(0===l.authenticatedAttributes.length){if(f!==d.pki.oids.data)throw Error("Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data.")}else{l.authenticatedAttributesAsn1=e.create(e.Class.CONTEXT_SPECIFIC,0,!0,[]);for(var m=e.create(e.Class.UNIVERSAL,e.Type.SET,!0,[]),n=0;n<l.authenticatedAttributes.length;++n){var o=l.authenticatedAttributes[n];o.type===d.pki.oids.messageDigest?o.value=b[l.digestAlgorithm].digest():o.type!==d.pki.oids.signingTime||o.value||(o.value=j),m.value.push(g(o)),l.authenticatedAttributesAsn1.value.push(g(o))}h=e.toDer(m).getBytes(),l.md.start().update(h)}l.signature=l.key.sign(l.md,"RSASSA-PKCS1-V1_5")}a.signerInfos=function(a){for(var b=[],c=0;c<a.length;++c)b.push(function(a){var b=e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.INTEGER,!1,e.integerToDer(a.version).getBytes()),e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[d.pki.distinguishedNameToAsn1({attributes:a.issuer}),e.create(e.Class.UNIVERSAL,e.Type.INTEGER,!1,d.util.hexToBytes(a.serialNumber))]),e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.OID,!1,e.oidToDer(a.digestAlgorithm).getBytes()),e.create(e.Class.UNIVERSAL,e.Type.NULL,!1,"")])]);if(a.authenticatedAttributesAsn1&&b.value.push(a.authenticatedAttributesAsn1),b.value.push(e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.OID,!1,e.oidToDer(a.signatureAlgorithm).getBytes()),e.create(e.Class.UNIVERSAL,e.Type.NULL,!1,"")])),b.value.push(e.create(e.Class.UNIVERSAL,e.Type.OCTETSTRING,!1,a.signature)),a.unauthenticatedAttributes.length>0){for(var c=e.create(e.Class.CONTEXT_SPECIFIC,1,!0,[]),f=0;f<a.unauthenticatedAttributes.length;++f){var h=a.unauthenticatedAttributes[f];c.values.push(g(h))}b.value.push(c)}return b}(a[c]));return b}(a.signers)}(function(){for(var b={},c=0;c<a.signers.length;++c){var f=a.signers[c],g=f.digestAlgorithm;g in b||(b[g]=d.md[d.pki.oids[g]].create()),0===f.authenticatedAttributes.length?f.md=b[g]:f.md=d.md[d.pki.oids[g]].create()}for(var g in a.digestAlgorithmIdentifiers=[],b)a.digestAlgorithmIdentifiers.push(e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.OID,!1,e.oidToDer(g).getBytes()),e.create(e.Class.UNIVERSAL,e.Type.NULL,!1,"")]));return b}())},verify:function(){throw Error("PKCS#7 signature verification not yet implemented.")},addCertificate:function(b){"string"==typeof b&&(b=d.pki.certificateFromPem(b)),a.certificates.push(b)},addCertificateRevokationList:function(a){throw Error("PKCS#7 CRL support not yet implemented.")}}},f.createEncryptedData=function(){var a=null;return a={type:d.pki.oids.encryptedData,version:0,encryptedContent:{algorithm:d.pki.oids["aes256-CBC"]},fromAsn1:function(b){h(a,b,f.asn1.encryptedDataValidator)},decrypt:function(b){void 0!==b&&(a.encryptedContent.key=b),i(a)}}},f.createEnvelopedData=function(){var a=null;return a={type:d.pki.oids.envelopedData,version:0,recipients:[],encryptedContent:{algorithm:d.pki.oids["aes256-CBC"]},fromAsn1:function(b){var c=h(a,b,f.asn1.envelopedDataValidator);a.recipients=function(a){for(var b=[],c=0;c<a.length;++c)b.push(function(a){var b={},c=[];if(!e.validate(a,f.asn1.recipientInfoValidator,b,c)){var g=Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");throw g.errors=c,g}return{version:b.version.charCodeAt(0),issuer:d.pki.RDNAttributesAsArray(b.issuer),serialNumber:d.util.createBuffer(b.serial).toHex(),encryptedContent:{algorithm:e.derToOid(b.encAlgorithm),parameter:b.encParameter?b.encParameter.value:void 0,content:b.encKey}}}(a[c]));return b}(c.recipientInfos.value)},toAsn1:function(){var b;return e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.OID,!1,e.oidToDer(a.type).getBytes()),e.create(e.Class.CONTEXT_SPECIFIC,0,!0,[e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.INTEGER,!1,e.integerToDer(a.version).getBytes()),e.create(e.Class.UNIVERSAL,e.Type.SET,!0,function(a){for(var b,c=[],f=0;f<a.length;++f)c.push((b=a[f],e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.INTEGER,!1,e.integerToDer(b.version).getBytes()),e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[d.pki.distinguishedNameToAsn1({attributes:b.issuer}),e.create(e.Class.UNIVERSAL,e.Type.INTEGER,!1,d.util.hexToBytes(b.serialNumber))]),e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.OID,!1,e.oidToDer(b.encryptedContent.algorithm).getBytes()),e.create(e.Class.UNIVERSAL,e.Type.NULL,!1,"")]),e.create(e.Class.UNIVERSAL,e.Type.OCTETSTRING,!1,b.encryptedContent.content)])));return c}(a.recipients)),e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,(b=a.encryptedContent,[e.create(e.Class.UNIVERSAL,e.Type.OID,!1,e.oidToDer(d.pki.oids.data).getBytes()),e.create(e.Class.UNIVERSAL,e.Type.SEQUENCE,!0,[e.create(e.Class.UNIVERSAL,e.Type.OID,!1,e.oidToDer(b.algorithm).getBytes()),b.parameter?e.create(e.Class.UNIVERSAL,e.Type.OCTETSTRING,!1,b.parameter.getBytes()):void 0]),e.create(e.Class.CONTEXT_SPECIFIC,0,!0,[e.create(e.Class.UNIVERSAL,e.Type.OCTETSTRING,!1,b.content.getBytes())])]))])])])},findRecipient:function(b){for(var c=b.issuer.attributes,d=0;d<a.recipients.length;++d){var e=a.recipients[d],f=e.issuer;if(e.serialNumber===b.serialNumber&&f.length===c.length){for(var g=!0,h=0;h<c.length;++h)if(f[h].type!==c[h].type||f[h].value!==c[h].value){g=!1;break}if(g)return e}}return null},decrypt:function(b,c){if(void 0===a.encryptedContent.key&&void 0!==b&&void 0!==c)switch(b.encryptedContent.algorithm){case d.pki.oids.rsaEncryption:case d.pki.oids.desCBC:var e=c.decrypt(b.encryptedContent.content);a.encryptedContent.key=d.util.createBuffer(e);break;default:throw Error("Unsupported asymmetric cipher, OID "+b.encryptedContent.algorithm)}i(a)},addRecipient:function(b){a.recipients.push({version:0,issuer:b.issuer.attributes,serialNumber:b.serialNumber,encryptedContent:{algorithm:d.pki.oids.rsaEncryption,key:b.publicKey}})},encrypt:function(b,c){if(void 0===a.encryptedContent.content){switch(c=c||a.encryptedContent.algorithm,b=b||a.encryptedContent.key,c){case d.pki.oids["aes128-CBC"]:e=16,f=16,g=d.aes.createEncryptionCipher;break;case d.pki.oids["aes192-CBC"]:e=24,f=16,g=d.aes.createEncryptionCipher;break;case d.pki.oids["aes256-CBC"]:e=32,f=16,g=d.aes.createEncryptionCipher;break;case d.pki.oids["des-EDE3-CBC"]:e=24,f=8,g=d.des.createEncryptionCipher;break;default:throw Error("Unsupported symmetric cipher, OID "+c)}if(void 0===b)b=d.util.createBuffer(d.random.getBytes(e));else if(b.length()!=e)throw Error("Symmetric key has wrong length; got "+b.length()+" bytes, expected "+e+".");a.encryptedContent.algorithm=c,a.encryptedContent.key=b,a.encryptedContent.parameter=d.util.createBuffer(d.random.getBytes(f));var e,f,g,h=g(b);if(h.start(a.encryptedContent.parameter.copy()),h.update(a.content),!h.finish())throw Error("Symmetric encryption failed.");a.encryptedContent.content=h.output}for(var i=0;i<a.recipients.length;++i){var j=a.recipients[i];if(void 0===j.encryptedContent.content)if(j.encryptedContent.algorithm===d.pki.oids.rsaEncryption)j.encryptedContent.content=j.encryptedContent.key.encrypt(a.encryptedContent.key.data);else throw Error("Unsupported asymmetric cipher, OID "+j.encryptedContent.algorithm)}}}}},76316:(a,b,c)=>{"use strict";let{InvalidArgumentError:d,NotSupportedError:e}=c(61448),f=c(34589),{isValidHTTPToken:g,isValidHeaderValue:h,isStream:i,destroy:j,isBuffer:k,isFormDataLike:l,isIterable:m,hasSafeIterator:n,isBlobLike:o,serializePathWithQuery:p,parseHeaders:q,assertRequestHandler:r,getServerName:s,normalizedMethodRecords:t,getProtocolFromUrlString:u}=c(84285),{channels:v}=c(62571),{headerNameLowerCasedRecord:w}=c(28820),x=/[^\u0021-\u00ff]/,y=Symbol("handler"),z=Symbol("controller"),A=Symbol("resume");class B{#bt=!1;#bu=null;#L=!1;#bv;[A]=null;rawHeaders=null;rawTrailers=null;constructor(a){this.#bv=a}pause(){this.#bt=!0}resume(){this.#bt&&(this.#bt=!1,this[A]?.())}abort(a){this.#L||(this.#L=!0,this.#bu=a,this.#bv(a))}get aborted(){return this.#L}get reason(){return this.#bu}get paused(){return this.#bt}}class C{constructor(a,{path:b,method:c,body:e,headers:f,query:q,idempotent:w,blocking:z,upgrade:A,headersTimeout:B,bodyTimeout:C,reset:E,expectContinue:F,servername:G,throwOnError:H,maxRedirections:I,typeOfService:J},K){if("string"!=typeof b)throw new d("path must be a string");if("/"===b[0]||b.startsWith("http://")||b.startsWith("https://")||"CONNECT"===c){if(x.test(b))throw new d("invalid request path")}else throw new d("path must be an absolute URL or start with a slash");if("string"!=typeof c)throw new d("method must be a string");if(void 0===t[c]&&!g(c))throw new d("invalid request method");if(A&&"string"!=typeof A)throw new d("upgrade must be a string");if(A&&!h(A))throw new d("invalid upgrade header");if(null!=B&&(!Number.isFinite(B)||B<0))throw new d("invalid headersTimeout");if(null!=C&&(!Number.isFinite(C)||C<0))throw new d("invalid bodyTimeout");if(null!=E&&"boolean"!=typeof E)throw new d("invalid reset");if(null!=F&&"boolean"!=typeof F)throw new d("invalid expectContinue");if(null!=H)throw new d("invalid throwOnError");if(null!=I&&0!==I)throw new d("maxRedirections is not supported, use the redirect interceptor");if(null!=J&&(!Number.isInteger(J)||J<0||J>255))throw new d("typeOfService must be an integer between 0 and 255");if(this.headersTimeout=B,this.bodyTimeout=C,this.method=c,this.typeOfService=J,this.abort=null,null==e)this.body=null;else if(i(e)){this.body=e;const a=this.body._readableState;a&&a.autoDestroy||(this.endHandler=function(){j(this)},this.body.on("end",this.endHandler)),this.errorHandler=a=>{this.abort?this.abort(a):this.error=a},this.body.on("error",this.errorHandler)}else if(k(e))this.body=e.byteLength?e:null;else if(ArrayBuffer.isView(e))this.body=e.buffer.byteLength?Buffer.from(e.buffer,e.byteOffset,e.byteLength):null;else if(e instanceof ArrayBuffer)this.body=e.byteLength?Buffer.from(e):null;else if("string"==typeof e)this.body=e.length?Buffer.from(e):null;else if(l(e)||m(e)||o(e))this.body=e;else throw new d("body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable");if(this.completed=!1,this.aborted=!1,this.upgrade=A||null,this.path=q?p(b,q):b,this.origin=a,this.protocol=u(a),this.idempotent=null==w?"HEAD"===c||"GET"===c||"QUERY"===c:w,this.blocking=z??"HEAD"!==this.method,this.reset=null==E?null:E,this.host=null,this.contentLength=null,this.contentType=null,this.headers=[],this.expectContinue=null!=F&&F,Array.isArray(f)){if(f.length%2!=0)throw new d("headers array must be even");for(let a=0;a<f.length;a+=2)D(this,f[a],f[a+1])}else if(f&&"object"==typeof f)if(n(f))for(const a of f){if(!Array.isArray(a)||2!==a.length)throw new d("headers must be in key-value pair format");D(this,a[0],a[1])}else{const a=Object.keys(f);for(let b=0;b<a.length;++b)D(this,a[b],f[a[b]])}else if(null!=f)throw new d("headers must be an object or an array");r(K,c,A),this.servername=G||s(this.host)||null,this[y]=K,v.create.hasSubscribers&&v.create.publish({request:this})}onBodySent(a){if(v.bodyChunkSent.hasSubscribers&&v.bodyChunkSent.publish({request:this,chunk:a}),this[y].onBodySent)try{return this[y].onBodySent(a)}catch(a){this.abort(a)}}onRequestSent(){if(v.bodySent.hasSubscribers&&v.bodySent.publish({request:this}),this[y].onRequestSent)try{return this[y].onRequestSent()}catch(a){this.abort(a)}}onRequestStart(a,b){return(f(!this.aborted),f(!this.completed),this[z]=new B(a),this.error)?void this[z].abort(this.error):(this.abort=a,this[y].onRequestStart(this[z],b))}onResponseStarted(){return this[y].onResponseStarted?.()}onResponseStart(a,b,c,d){f(!this.aborted),f(!this.completed),v.headers.hasSubscribers&&v.headers.publish({request:this,response:{statusCode:a,headers:b,statusText:d}});let e=this[z];e&&(e[A]=c,e.rawHeaders=b);let g=Array.isArray(b)?q(b):b;try{return this[y].onResponseStart?.(e,a,g,d),!e?.paused}catch(a){return this.abort(a),!1}}onResponseData(a){f(!this.aborted),f(!this.completed),v.bodyChunkReceived.hasSubscribers&&v.bodyChunkReceived.publish({request:this,chunk:a});let b=this[z];try{return this[y].onResponseData?.(b,a),!b?.paused}catch(a){return this.abort(a),!1}}onRequestUpgrade(a,b,c){f(!this.aborted),f(!this.completed);let d=this[z];d&&(d.rawHeaders=b);let e=Array.isArray(b)?q(b):b;return this[y].onRequestUpgrade?.(d,a,e,c)}onResponseEnd(a){this.onFinally(),f(!this.aborted),f(!this.completed),this.completed=!0,v.trailers.hasSubscribers&&v.trailers.publish({request:this,trailers:a});let b=this[z];b&&(b.rawTrailers=a);let c=Array.isArray(a)?q(a):a;try{return this[y].onResponseEnd?.(b,c)}catch(a){this.onResponseError(a)}}onResponseError(a){if(this.onFinally(),v.error.hasSubscribers&&v.error.publish({request:this,error:a}),this.aborted)return;this.aborted=!0;let b=this[z];return this[y].onResponseError?.(b,a)}onFinally(){this.errorHandler&&(this.body.off("error",this.errorHandler),this.errorHandler=null),this.endHandler&&(this.body.off("end",this.endHandler),this.endHandler=null)}addHeader(a,b){return D(this,a,b),this}}function D(a,b,c){if(c&&"object"==typeof c&&!Array.isArray(c))throw new d(`invalid ${b} header`);if(void 0===c)return;let f=w[b];if(void 0===f&&void 0===w[f=b.toLowerCase()]&&!g(f))throw new d("invalid header key");if(Array.isArray(c)){let a=[];for(let e=0;e<c.length;e++)if("string"==typeof c[e]){if(!h(c[e]))throw new d(`invalid ${b} header`);a.push(c[e])}else if(null===c[e])a.push("");else if("object"==typeof c[e])throw new d(`invalid ${b} header`);else{let f=`${c[e]}`;if(!h(f))throw new d(`invalid ${b} header`);a.push(f)}c=a}else if("string"==typeof c){if(!h(c))throw new d(`invalid ${b} header`)}else if(null===c)c="";else if(!h(c=`${c}`))throw new d(`invalid ${b} header`);if("host"===f){if(null!==a.host)throw new d("duplicate host header");if("string"!=typeof c)throw new d("invalid host header");a.host=c}else if("content-length"===f){if(null!==a.contentLength)throw new d("duplicate content-length header");if(!function(a){if("string"!=typeof a||0===a.length)return!1;for(let b=0;b<a.length;b++){let c=a.charCodeAt(b);if(c<48||c>57)return!1}return!0}(c))throw new d("invalid content-length header");a.contentLength=parseInt(c,10)}else if(null===a.contentType&&"content-type"===f)a.contentType=c,a.headers.push(b,c);else if("transfer-encoding"===f||"keep-alive"===f||"upgrade"===f)throw new d(`invalid ${f} header`);else if("connection"===f){let b="string"==typeof c?c:null;if(null===b)throw new d("invalid connection header");for(let c of b.toLowerCase().split(",")){let b=c.trim();if(!g(b))throw new d("invalid connection header");"close"===b&&(a.reset=!0)}}else if("expect"===f)throw new e("expect header not supported");else a.headers.push(b,c)}a.exports=C},76403:(a,b,c)=>{"use strict";let d,{makeNetworkError:e,makeAppropriateNetworkError:f,filterResponse:g,makeResponse:h,fromInnerResponse:i,getResponseState:j}=c(78196),{HeadersList:k}=c(28665),{Request:l,cloneRequest:m,getRequestDispatcher:n,getRequestState:o,removeRequestAbortListener:p}=c(12600),q=c(38522),{makePolicyContainer:r,clonePolicyContainer:s,requestBadPort:t,TAOCheck:u,appendRequestOriginHeader:v,responseLocationURL:w,requestCurrentURL:x,setRequestReferrerPolicyOnRedirect:y,tryUpgradeRequestToAPotentiallyTrustworthyURL:z,createOpaqueTimingInfo:A,appendFetchMetadata:B,corsCheck:C,crossOriginResourcePolicyCheck:D,determineRequestsReferrer:E,coarsenedSharedCurrentTime:F,sameOrigin:G,isCancelled:H,isAborted:I,isErrorLike:J,fullyReadBody:K,readableStreamClose:L,urlIsLocal:M,urlIsHttpHttpsScheme:N,urlHasHttpsScheme:O,clampAndCoarsenConnectionTimingInfo:P,simpleRangeHeaderValue:Q,buildContentRange:R,createInflate:S,extractMimeType:T,hasAuthenticationEntry:U,includesCredentials:V,isTraversableNavigable:W}=c(42425),X=c(34589),{safelyExtractBody:Y,extractBody:Z}=c(35381),{redirectStatusSet:$,nullBodyStatus:_,safeMethodsSet:aa,requestBodyHeader:ab,subresourceSet:ac}=c(19608),ad=c(78474),{Readable:ae,pipeline:af,finished:ag,isErrored:ah,isReadable:ai}=c(57075),{addAbortListener:aj,bufferToLowerCasedHeaderName:ak}=c(84285),{dataURLProcessor:al,serializeAMimeType:am,minimizeSupportedMimeType:an}=c(16537),{getGlobalDispatcher:ao}=c(59970),{webidl:ap}=c(32984),{STATUS_CODES:aq}=c(37067),{bytesMatch:ar}=c(64371),{isomorphicEncode:as}=c(70745),at=["GET","HEAD"],au="u">typeof __UNDICI_IS_NODE__||"u">typeof esbuildDetection?"node":"undici";function av(a,b,c){if(Array.isArray(c)){for(let b=0;b<c.length;b+=2){let d=ak(c[b]),e=c[b+1];if(Array.isArray(e)&&!Buffer.isBuffer(e))for(let b of e)a.append(d,b.toString("latin1"),!0);else a.append(d,e.toString("latin1"),!0)}return}for(let[c,d]of Object.entries(b??{}))if(Array.isArray(d))for(let b of d)a.append(c,`${b}`,!0);else a.append(c,`${d}`,!0)}class aw extends ad{constructor(a){super(),this.dispatcher=a,this.connection=null,this.dump=!1,this.state="ongoing"}terminate(a){"ongoing"===this.state&&(this.state="terminated",this.connection?.destroy(a),this.emit("terminated",a))}abort(a){"ongoing"===this.state&&(this.state="aborted",a||(a=new DOMException("The operation was aborted.","AbortError")),this.serializedAbortReason=a,this.connection?.destroy(a),this.emit("terminated",a))}}function ax(a,b="other"){if("error"===a.type&&a.aborted||!a.urlList?.length)return;let c=a.urlList[0],d=a.timingInfo,e=a.cacheState;N(c)&&null!==d&&(a.timingAllowPassed||(d=A({startTime:d.startTime}),e=""),d.endTime=F(),a.timingInfo=d,ay(d,c.href,b,globalThis,e,"",a.status))}let ay=performance.markResourceTiming;function az(a,b,c,d,e){if(a&&a.reject(d),b.body?.stream!=null&&ai(b.body.stream)&&b.body.stream.cancel(d).catch(a=>{if("ERR_INVALID_STATE"!==a.code)throw a}),null==c)return;let f=j(c);f.body?.stream!=null&&ai(f.body.stream)&&e.error(d)}function aA({request:a,processRequestBodyChunkLength:b,processRequestEndOfBody:c,processResponse:d,processResponseEndOfBody:e,processResponseConsumeBody:f,useParallelQueue:g=!1,dispatcher:h=ao(),requestObject:i=null}){X(h);let j=null,k=!1;null!=a.client&&(j=a.client.globalObject,k=a.client.crossOriginIsolatedCapability);let l=A({startTime:F(k)}),m={controller:new aw(h),request:a,timingInfo:l,processRequestBodyChunkLength:b,processRequestEndOfBody:c,processResponse:d,processResponseConsumeBody:f,processResponseEndOfBody:e,taskDestination:j,crossOriginIsolatedCapability:k,requestObject:i};return X(!a.body||a.body.stream),"client"===a.window&&(a.window=a.client?.globalObject?.constructor?.name==="Window"?a.client:"no-window"),"client"===a.origin&&(a.origin=a.client.origin),"client"===a.policyContainer&&(null!=a.client?a.policyContainer=s(a.client.policyContainer):a.policyContainer=r()),a.headersList.contains("accept",!0)||a.headersList.append("accept","*/*",!0),a.headersList.contains("accept-language",!0)||a.headersList.append("accept-language","*",!0),a.priority,ac.has(a.destination),aB(m,!1),m.controller}async function aB(a,b){try{let c=a.request,d=null;if(c.localURLsOnly&&!M(x(c))&&(d=e("local URLs only")),z(c),"blocked"===t(c)&&(d=e("bad port")),""===c.referrerPolicy&&(c.referrerPolicy=c.policyContainer.referrerPolicy),"no-referrer"!==c.referrer&&(c.referrer=E(c)),null===d){let b=x(c);G(b,c.url)&&"basic"===c.responseTainting||"data:"===b.protocol||"navigate"===c.mode||"websocket"===c.mode?(c.responseTainting="basic",d=await aC(a)):"same-origin"===c.mode?d=e('request mode cannot be "same-origin"'):"no-cors"===c.mode?"follow"!==c.redirect?d=e('redirect mode cannot be "follow" for "no-cors" request'):(c.responseTainting="opaque",d=await aC(a)):N(x(c))?(c.responseTainting="cors",d=await aE(a)):d=e("URL scheme must be a HTTP(S) scheme")}if(b)return d;0===d.status||d.internalResponse||(c.responseTainting,"basic"===c.responseTainting?d=g(d,"basic"):"cors"===c.responseTainting?d=g(d,"cors"):"opaque"===c.responseTainting?d=g(d,"opaque"):X(!1));let f=0===d.status?d:d.internalResponse;if(0===f.urlList.length&&f.urlList.push(...c.urlList),c.timingAllowFailed||(d.timingAllowPassed=!0),"opaque"===d.type&&206===f.status&&f.rangeRequested&&!c.headers.contains("range",!0)&&(d=f=e()),0!==d.status&&("HEAD"===c.method||"CONNECT"===c.method||_.includes(f.status))&&(f.body=null,a.controller.dump=!0),c.integrity){let b=b=>aD(a,e(b));if("opaque"===c.responseTainting||null==d.body)return void b(d.error);K(d.body,e=>{ar(e,c.integrity)?(d.body=Y(e)[0],aD(a,d)):b("integrity mismatch")},b)}else aD(a,d)}catch(b){a.controller.terminate(b)}}function aC(a){if(H(a)&&0===a.request.redirectCount)return Promise.resolve(f(a));let{request:b}=a,{protocol:g}=x(b);switch(g){case"about:":return Promise.resolve(e("about scheme is not supported"));case"blob:":{d||(d=c(4573).resolveObjectURL);let a=x(b);if(0!==a.search.length)return Promise.resolve(e("NetworkError when attempting to fetch resource."));let f=d(a.toString());if("GET"!==b.method||!ap.is.Blob(f))return Promise.resolve(e("invalid method"));let g=h(),i=f.size,j=as(`${i}`),k=f.type;if(b.headersList.contains("range",!0)){g.rangeRequested=!0;let a=Q(b.headersList.get("range",!0),!0);if("failure"===a)return Promise.resolve(e("failed to fetch the data URL"));let{rangeStartValue:c,rangeEndValue:d}=a;if(null===c)d=(c=i-d)+d-1;else{if(c>=i)return Promise.resolve(e("Range start is greater than the blob's size."));(null===d||d>=i)&&(d=i-1)}let h=f.slice(c,d+1,k);g.body=Z(h)[0];let j=as(`${h.size}`),l=R(c,d,i);g.status=206,g.statusText="Partial Content",g.headersList.set("content-length",j,!0),g.headersList.set("content-type",k,!0),g.headersList.set("content-range",l,!0)}else{let a=Z(f);g.statusText="OK",g.body=a[0],g.headersList.set("content-length",j,!0),g.headersList.set("content-type",k,!0)}return Promise.resolve(g)}case"data:":{let a=al(x(b));if("failure"===a)return Promise.resolve(e("failed to fetch the data URL"));return Promise.resolve(h({statusText:"OK",headersList:[["content-type",{name:"Content-Type",value:am(a.mimeType)}]],body:Y(a.body)[0]}))}case"file:":return Promise.resolve(e("not implemented... yet..."));case"http:":case"https:":return aE(a).catch(a=>e(a));default:return Promise.resolve(e("unknown scheme"))}}function aD(a,b){let c=a.timingInfo,d=()=>{let d=Date.now();"document"===a.request.destination&&(a.controller.fullTimingInfo=c),a.controller.reportTimingSteps=()=>{if(!N(a.request.url))return;c.endTime=d;let e=b.cacheState,f=b.bodyInfo;b.timingAllowPassed||(c=A(c),e="");let g=0;if("navigate"!==a.request.mode||!b.hasCrossOriginRedirects){g=b.status;let a=T(b.headersList);"failure"!==a&&(f.contentType=an(a))}null!=a.request.initiatorType&&ay(c,a.request.url.href,a.request.initiatorType,globalThis,e,f,g)},queueMicrotask(()=>void(a.request.done=!0,null!=a.processResponseEndOfBody&&queueMicrotask(()=>a.processResponseEndOfBody(b)),null!=a.request.initiatorType&&a.controller.reportTimingSteps()))};null!=a.processResponse&&queueMicrotask(()=>{a.processResponse(b),a.processResponse=null});let e="error"===b.type?b:b.internalResponse??b;null==e.body?d():ag(e.body.stream,()=>{d()})}async function aE(a){let b=a.request,c=null,d=null,f=a.timingInfo;if(b.serviceWorkers,null===c){if("follow"===b.redirect&&(b.serviceWorkers="none"),d=c=await aF(a),"cors"===b.responseTainting&&"failure"===C(b,c))return e("cors failure");"failure"===u(b,c)&&(b.timingAllowFailed=!0)}return("opaque"===b.responseTainting||"opaque"===c.type)&&"blocked"===D(b.origin,b.client,b.destination,d)?e("blocked"):($.has(d.status)&&("manual"!==b.redirect&&a.controller.connection.destroy(void 0,!1),"error"===b.redirect?c=e("unexpected redirect"):"manual"===b.redirect?c=d:"follow"===b.redirect?c=await function(a,b){let c,d=a.request,f=b.internalResponse?b.internalResponse:b;try{if(c=w(f,x(d).hash),null==c)return b}catch(a){return Promise.resolve(e(a))}if(!N(c))return Promise.resolve(e("URL scheme must be a HTTP(S) scheme"));if(20===d.redirectCount)return Promise.resolve(e("redirect count exceeded"));if(d.redirectCount+=1,"cors"===d.mode&&(c.username||c.password)&&!G(d,c))return Promise.resolve(e('cross origin not allowed for request mode "cors"'));if("cors"===d.responseTainting&&(c.username||c.password))return Promise.resolve(e('URL cannot contain credentials for request mode "cors"'));if(303!==f.status&&null!=d.body&&null==d.body.source)return Promise.resolve(e());if([301,302].includes(f.status)&&"POST"===d.method||303===f.status&&!at.includes(d.method))for(let a of(d.method="GET",d.body=null,ab))d.headersList.delete(a);G(x(d),c)||(d.headersList.delete("authorization",!0),d.headersList.delete("proxy-authorization",!0),d.headersList.delete("cookie",!0),d.headersList.delete("host",!0)),null!=d.body&&(X(null!=d.body.source),d.body=Y(d.body.source)[0]);let g=a.timingInfo;return g.redirectEndTime=g.postRedirectStartTime=F(a.crossOriginIsolatedCapability),0===g.redirectStartTime&&(g.redirectStartTime=g.startTime),d.urlList.push(c),y(d,f),aB(a,!0)}(a,c):X(!1)),c.timingInfo=f,c)}async function aF(a,b=!1,c=!1){let d=a.request,g=null,h=null,i=null;"no-window"===d.window&&"error"===d.redirect?(g=a,h=d):(d.body?.source!=null?h=m(d):(h=m({...d,body:null})).body=d.body,(g={...a}).request=h);let j="include"===d.credentials||"same-origin"===d.credentials&&"basic"===d.responseTainting,k=h.body?h.body.length:null,l=null;if(null==h.body&&["POST","PUT"].includes(h.method)&&(l="0"),null!=k&&(l=as(`${k}`)),null==l||h.headersList.contains("content-length",!0)||h.headersList.append("content-length",l,!0),null!=k&&h.keepalive,ap.is.URL(h.referrer)&&h.headersList.append("referer",as(h.referrer.href),!0),v(h),B(h),h.headersList.contains("user-agent",!0)||h.headersList.append("user-agent",au,!0),"default"===h.cache&&(h.headersList.contains("if-modified-since",!0)||h.headersList.contains("if-none-match",!0)||h.headersList.contains("if-unmodified-since",!0)||h.headersList.contains("if-match",!0)||h.headersList.contains("if-range",!0))&&(h.cache="no-store"),"no-cache"!==h.cache||h.preventNoCacheCacheControlHeaderModification||h.headersList.contains("cache-control",!0)||h.headersList.append("cache-control","max-age=0",!0),("no-store"===h.cache||"reload"===h.cache)&&(h.headersList.contains("pragma",!0)||h.headersList.append("pragma","no-cache",!0),h.headersList.contains("cache-control",!0)||h.headersList.append("cache-control","no-cache",!0)),h.headersList.contains("range",!0)&&h.headersList.append("accept-encoding","identity",!0),h.headersList.contains("accept-encoding",!0)||(O(x(h))?h.headersList.append("accept-encoding","br, gzip, deflate, zstd",!0):h.headersList.append("accept-encoding","gzip, deflate",!0)),h.headersList.delete("host",!0),j&&!h.headersList.contains("authorization",!0)){let a=null;if(U(h)&&(void 0===h.useURLCredentials||!V(x(h))));else if(V(x(h))&&b){let{username:b,password:c}=x(h);a=`Basic ${Buffer.from(`${b}:${c}`).toString("base64")}`}null!==a&&h.headersList.append("Authorization",a,!1)}if(h.cache="no-store","no-store"!==h.cache&&h.cache,null==i){if("only-if-cached"===h.cache)return e("only if cached");let a=await aG(g,j,c);!aa.has(h.method)&&a.status>=200&&a.status,null==i&&(i=a)}if(i.urlList=[...h.urlList],h.headersList.contains("range",!0)&&(i.rangeRequested=!0),i.requestIncludesCredentials=j,401===i.status&&"cors"!==h.responseTainting&&j&&(void 0!==d.useURLCredentials||W(d.traversableForUserPrompts))){if(null!=d.body){if(null==d.body.source)return i;d.body=Y(d.body.source)[0]}if(void 0===d.useURLCredentials||b)return H(a)?f(a):i;a.controller.connection.destroy(),i=await aF(a,!0)}if(407===i.status)return"no-window"===d.window?e():H(a)?f(a):e("proxy authentication required");if(421===i.status&&!c&&(null==d.body||null!=d.body.source)){if(H(a))return f(a);a.controller.connection.destroy(),i=await aF(a,b,!0)}return i}async function aG(a,b=!1,c=!1){X(!a.controller.connection||a.controller.connection.destroyed),a.controller.connection={abort:null,destroyed:!1,destroy(a,b=!0){!this.destroyed&&(this.destroyed=!0,b&&this.abort?.(a??new DOMException("The operation was aborted.","AbortError")))}};let d=a.request,g=null,i=a.timingInfo;d.cache="no-store",d.mode;let j=null;if(null==d.body&&a.processRequestEndOfBody)queueMicrotask(()=>a.processRequestEndOfBody());else if(null!=d.body){let b=async function*(b){H(a)||(yield b,a.processRequestBodyChunkLength?.(b.byteLength))};j=async function*(){try{for await(let a of d.body.stream)yield*b(a);!H(a)&&a.processRequestEndOfBody&&a.processRequestEndOfBody()}catch(b){H(a)||("AbortError"===b.name?a.controller.abort():a.controller.terminate(b))}}()}try{let{body:b,status:c,statusText:e,headersList:f,socket:l}=await function({body:b}){let c=x(d),e=a.controller.dispatcher,f=c.pathname+c.search,g=0===c.search.length&&"?"===c.href[c.href.length-c.hash.length-1];return function b(h,j){return new Promise((l,m)=>e.dispatch({path:g?`${f}?`:f,origin:c.origin,method:d.method,body:e.isMockActive?d.body&&(d.body.source||d.body.stream):h,__mockAgentBodyForDispatch:h,headers:d.headersList.entries,maxRedirections:0,upgrade:"websocket"===d.mode?"websocket":void 0,...!1===j?{allowH2:j}:null},{body:null,abort:null,onRequestStart(b){let{connection:c}=a.controller;i.finalConnectionTimingInfo=P(void 0,i.postRedirectStartTime,a.crossOriginIsolatedCapability);let d=a=>b.abort(a);c.destroyed?d(new DOMException("The operation was aborted.","AbortError")):(a.controller.on("terminated",d),this.abort=c.abort=d),i.finalNetworkRequestStartTime=F(a.crossOriginIsolatedCapability)},onResponseStarted(){i.finalNetworkResponseStartTime=F(a.crossOriginIsolatedCapability)},onResponseStart(a,b,c,e){if(b<200)return;let f=a?.rawHeaders??[],g=new k;av(g,c,f);let h=g.get("location",!0);this.body=new ae({read:()=>a.resume()});let i=h&&"follow"===d.redirect&&$.has(b),j=[];if("HEAD"!==d.method&&"CONNECT"!==d.method&&!_.includes(b)&&!i){let a=g.get("content-encoding",!0),b=a?a.toLowerCase().split(","):[];if(b.length>5)return void m(Error(`too many content-encodings in response: ${b.length}, maximum allowed is 5`));for(let a=b.length-1;a>=0;--a){let c=b[a].trim();if("x-gzip"===c||"gzip"===c)j.push(q.createGunzip({flush:q.constants.Z_SYNC_FLUSH,finishFlush:q.constants.Z_SYNC_FLUSH}));else if("deflate"===c)j.push(S({flush:q.constants.Z_SYNC_FLUSH,finishFlush:q.constants.Z_SYNC_FLUSH}));else if("br"===c)j.push(q.createBrotliDecompress({flush:q.constants.BROTLI_OPERATION_FLUSH,finishFlush:q.constants.BROTLI_OPERATION_FLUSH}));else if("zstd"===c)j.push(q.createZstdDecompress({flush:q.constants.ZSTD_e_continue,finishFlush:q.constants.ZSTD_e_end}));else{j.length=0;break}}}let n=b=>this.onResponseError(a,b);l({status:b,statusText:e,headersList:g,body:j.length?af(this.body,...j,b=>{b&&this.onResponseError(a,b)}).on("error",n):this.body.on("error",n)})},onResponseData(b,c){a.controller.dump||(i.encodedBodySize+=c.byteLength,!1===this.body.push(c)&&b.pause())},onResponseEnd(){this.abort&&a.controller.off("terminated",this.abort),a.controller.ended=!0,this.body?.push(null)},onResponseError(c,e){(this.abort&&a.controller.off("terminated",this.abort),"websocket"===d.mode&&!1!==j&&e?.code==="UND_ERR_INFO"&&e?.message==="HTTP/2: Extended CONNECT protocol not supported by server")?l(b(h,!1)):(this.body?.destroy(e),a.controller.terminate(e),m(e))},onRequestUpgrade(a,b,c,d){if(null!=d.session&&200!==b||null==d.session&&101!==b)return!1;let e=a?.rawHeaders??[],f=new k;return av(f,c,e),l({status:b,statusText:aq[b],headersList:f,socket:d}),!0}}))}(b)}({body:j});if(l)g=h({status:c,statusText:e,headersList:f,socket:l});else{let d=b[Symbol.asyncIterator]();a.controller.next=()=>d.next(),g=h({status:c,statusText:e,headersList:f})}}catch(b){if("AbortError"===b.name)return a.controller.connection.destroy(),f(a,b);return e(b)}let l=new ReadableStream({start(b){a.controller.controller=b},pull:()=>a.controller.resume(),cancel:b=>{H(a)||a.controller.abort(b)},type:"bytes"});return g.body={stream:l,source:null,length:null},a.controller.resume||a.controller.on("terminated",function(b){I(a)?(g.aborted=!0,ai(l)&&a.controller.controller.error(a.controller.serializedAbortReason)):ai(l)&&a.controller.controller.error(TypeError("terminated",{cause:J(b)?b:void 0})),a.controller.connection.destroy()}),a.controller.resume=async()=>{for(;;){let b,c;try{let{done:c,value:d}=await a.controller.next();if(I(a))break;b=c?void 0:d}catch(d){a.controller.ended&&!i.encodedBodySize?b=void 0:(b=d,c=!0)}if(void 0===b){L(a.controller.controller),function(a,b){a.request.done=!0,null!=a.processResponseDone&&queueMicrotask(()=>a.processResponseDone(b))}(a,g);return}if(i.decodedBodySize+=b?.byteLength??0,c)return void a.controller.terminate(b);let d=new Uint8Array(b);if(d.byteLength&&a.controller.controller.enqueue(d),ah(l))return void a.controller.terminate();if(a.controller.controller.desiredSize<=0)return}},g}a.exports={fetch:function(a,b){let c;ap.argumentLengthCheck(arguments,1,"globalThis.fetch");let d=Promise.withResolvers();try{c=new l(a,b)}catch(a){return d.reject(a),d.promise}let e=o(c);if(c.signal.aborted)return az(d,e,null,c.signal.reason,null),d.promise;let f=e.client.globalObject;f?.constructor?.name==="ServiceWorkerGlobalScope"&&(e.serviceWorkers="none");let g=null,h=!1,j=null,k=aj(c.signal,()=>{h=!0,X(null!=j),j.abort(c.signal.reason);let a=g?.deref();az(d,e,a,c.signal.reason,j.controller)}),m=()=>{k(),p(c)};return j=aA({request:e,processResponseEndOfBody:a=>{ax(a,"fetch"),m()},processResponse:a=>{if(!h){if(a.aborted){az(d,e,g,j.serializedAbortReason,j.controller),m();return}if("error"===a.type){d.reject(TypeError("fetch failed",{cause:a.error})),m();return}g=new WeakRef(i(a,"immutable")),d.resolve(g.deref()),d=null}},dispatcher:n(c),requestObject:c}),d.promise},Fetch:aw,fetching:aA,finalizeAndReportTiming:ax}},76441:(a,b,c)=>{"use strict";c(70625)},76540:(a,b,c)=>{"use strict";c(33873),c(29021);let{MITM_DIR:d}=c(37436),{generateRootCA:e,loadRootCA:f,generateLeafCert:g}=c(1653);a.exports={generateCert:function(){return e()},getCertForDomain:function(a){try{let b=f(),c=g(a,b);return{key:c.key,cert:c.cert}}catch(b){return console.error(`Failed to generate cert for ${a}:`,b.message),null}}}},76558:(a,b,c)=>{"use strict";c.d(b,{Yh:()=>p});var d=c(67671),e=c(38421),f=c(50969),g=c(55511),h=c(21820);let i=e.xq["mimo-free"].baseUrl,j="abcdefghijklmnopqrstuvwxyz0123456789",k=["Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"],l="You are MiMoCode, an interactive CLI tool that helps users with software engineering tasks.",m=null,n=0;async function o(a=null){if(m&&Date.now()<n-3e5)return m;let b=await (0,f.Fm)("https://api.xiaomimimo.com/api/free-ai/bootstrap",{method:"POST",headers:{"Content-Type":"application/json","User-Agent":k[Math.floor(Math.random()*k.length)]},body:JSON.stringify({client:function(){let a="unknown-user";try{a=h.userInfo().username}catch{}let b=(h.cpus()[0]?.model||"unknown-cpu").trim(),c=`${h.hostname()}|${h.platform()}|${h.arch()}|${b}|${a}`;return(0,g.createHash)("sha256").update(c).digest("hex")}()})},a);if(!b.ok)throw Error(`MiMo bootstrap failed: ${b.status}`);let c=await b.json();if(!c.jwt)throw Error("MiMo bootstrap returned no JWT");return m=c.jwt,n=function(a){try{let b=JSON.parse(Buffer.from(a.split(".")[1],"base64").toString());if(b.exp)return 1e3*b.exp}catch{}return Date.now()+3e6}(c.jwt),m}class p extends d.Hv{constructor(){super("mimo-free",e.xq["mimo-free"]),this.sessionId=function(){let a="ses_";for(let b=0;b<24;b++)a+=j[Math.floor(Math.random()*j.length)];return a}()}buildUrl(){return i}buildHeaders(a,b=!0){return{"Content-Type":"application/json","X-Mimo-Source":"mimocode-cli-free","User-Agent":k[Math.floor(Math.random()*k.length)],"x-session-affinity":this.sessionId,Accept:b?"text/event-stream":"application/json"}}transformRequest(a,b){let c;return!Array.isArray(c=b?.messages)||c.some(a=>a?.role==="system"&&"string"==typeof a.content&&a.content.includes(l))?b:{...b,messages:[{role:"system",content:l},...c]}}async execute({model:a,body:b,stream:c,credentials:d,signal:e,log:g,proxyOptions:h=null}){let i;try{i=await o(h)}catch(a){throw g?.error?.("AUTH",`MiMo bootstrap failed: ${a.message}`),a}let j=this.buildUrl(),k=this.transformRequest(a,b),l={...this.buildHeaders(d,c),Authorization:`Bearer ${i}`},p=JSON.stringify(k);g?.debug?.("FETCH",`MIMO-FREE → ${j} | body=${p.length}B`);let q=await (0,f.Fm)(j,{method:"POST",headers:l,body:p,signal:e},h);return 401===q.status||403===q.status?(g?.debug?.("AUTH",`MiMo auth failed (${q.status}), re-bootstrapping...`),m=null,n=0,i=await o(h),l.Authorization=`Bearer ${i}`,{response:await (0,f.Fm)(j,{method:"POST",headers:l,body:p,signal:e},h),url:j,headers:l,transformedBody:k}):{response:q,url:j,headers:l,transformedBody:k}}}},76632:(a,b,c)=>{var d=c(45654);c(1277),c(33889),(a.exports=d.hmac=d.hmac||{}).create=function(){var a=null,b=null,c=null,e=null,f={};return f.start=function(f,g){if(null!==f)if("string"==typeof f)if((f=f.toLowerCase())in d.md.algorithms)b=d.md.algorithms[f].create();else throw Error('Unknown hash algorithm "'+f+'"');else b=f;if(null===g)g=a;else{if("string"==typeof g)g=d.util.createBuffer(g);else if(d.util.isArray(g)){var h=g;g=d.util.createBuffer();for(var i=0;i<h.length;++i)g.putByte(h[i])}var j=g.length();j>b.blockLength&&(b.start(),b.update(g.bytes()),g=b.digest()),c=d.util.createBuffer(),e=d.util.createBuffer(),j=g.length();for(var i=0;i<j;++i){var h=g.at(i);c.putByte(54^h),e.putByte(92^h)}if(j<b.blockLength)for(var h=b.blockLength-j,i=0;i<h;++i)c.putByte(54),e.putByte(92);a=g,c=c.bytes(),e=e.bytes()}b.start(),b.update(c)},f.update=function(a){b.update(a)},f.getMac=function(){var a=b.digest().bytes();return b.start(),b.update(e),b.update(a),b.digest()},f.digest=f.getMac,f}},77168:(a,b,c)=>{"use strict";c.a(a,async(a,b)=>{try{c(50969),c(38421),c(10793),c(82689),c(13161),c(68531),c(87350),c(22884),c(86538),c(1654),c(96997),c(98976);var d=c(69641);c(20830);var e=c(95695);c(80152),c(18762);var f=a([d,e]);[d,e]=f.then?(await f)():f,b()}catch(a){b(a)}})},77321:(a,b,c)=>{"use strict";c.d(b,{Z:()=>h});var d=c(38421);let e=[{match:a=>/^kimi-/i.test(a||""),scope:"toolCalls"},{match:a=>/deepseek/i.test(a||""),scope:"all"}],f="deepseek-v4-pro",g={[`${f}-max`]:{thinkingType:"enabled",reasoningEffort:"max"},[`${f}-none`]:{thinkingType:"disabled",reasoningEffort:null}};function h({provider:a,model:b,body:c}){let i=d.xq[a]?.reasoningInject,j=e.find(a=>a.match(b));var k=function({provider:a,model:b,body:c}){let d=g[b];if("deepseek"!==a||!d||!c)return c;let e={...c,model:f,thinking:{type:d.thinkingType}};if(e.extra_body?.thinking){let{thinking:a,...b}=e.extra_body;0===Object.keys(b).length?delete e.extra_body:e.extra_body=b}return d.reasoningEffort?e.reasoning_effort=d.reasoningEffort:delete e.reasoning_effort,e}({provider:a,model:b,body:c}),l=i||j;if(!l||!k?.messages||function(a){if("string"==typeof a.system||Array.isArray(a.system))return!0;if(!Array.isArray(a.messages))return!1;for(let b of a.messages)if(Array.isArray(b.content)){for(let a of b.content)if(a?.type==="tool_use"||a?.type==="tool_result"||a?.type==="thinking")return!0}return!1}(k))return k;let m=k.messages.map(a=>!function(a,b){if(a?.role!=="assistant")return!1;let c=a.reasoning_content;return("string"!=typeof c||!(c.length>0))&&("toolCalls"!==b||Array.isArray(a.tool_calls)&&a.tool_calls.length>0)}(a,l.scope)?a:{...a,reasoning_content:" "});return{...k,messages:m}}},77326:(a,b,c)=>{"use strict";c.d(b,{E5:()=>E,SB:()=>G,ui:()=>H.ui,bI:()=>e.cleanupProviderConnections,Iq:()=>g.createApiKey,jd:()=>l,iE:()=>e.createProviderConnection,eh:()=>I.eh,PX:()=>g.getApiKeys,Dj:()=>k,getProviderConnections:()=>e.getProviderConnections,mt:()=>f.getSettings,ox:()=>F.ox,sZ:()=>D,o5:()=>o.o5,uw:()=>C,oG:()=>n,updateProviderConnection:()=>e.updateProviderConnection,Xx:()=>f.Xx});var d=c(24081),e=c(92216);c(20639);var f=c(45874);c(7044);var g=c(57431),h=c(27137),i=c(50743);function j(a){return a?{id:a.id,name:a.name,kind:a.kind,models:(0,i.q)(a.models,[]),createdAt:a.createdAt,updatedAt:a.updatedAt}:null}async function k(a){return j((await (0,d.c)()).get("SELECT * FROM combos WHERE name = ?",[a]))}async function l(a){let b=await (0,d.c)(),c=new Date().toISOString(),e={id:(0,h.A)(),name:a.name,kind:a.kind||null,models:a.models||[],createdAt:c,updatedAt:c};return b.run("INSERT INTO combos(id, name, kind, models, createdAt, updatedAt) VALUES(?, ?, ?, ?, ?, ?)",[e.id,e.name,e.kind,(0,i.s)(e.models),e.createdAt,e.updatedAt]),e}let m=["name","kind","models"];async function n(a,b){let c=await (0,d.c)(),e=null;return c.transaction(()=>{let d=c.get("SELECT * FROM combos WHERE id = ?",[a]);if(!d)return;let f={...j(d),updatedAt:new Date().toISOString()};for(let a of m)b&&Object.prototype.hasOwnProperty.call(b,a)&&(f[a]=b[a]);c.run("UPDATE combos SET name = ?, kind = ?, models = ?, updatedAt = ? WHERE id = ?",[f.name,f.kind,(0,i.s)(f.models||[]),f.updatedAt,a]),e=f}),e}var o=c(37703);c(90181);var p=c(94735),q=c(15904),r=c(77397),s=c(15738);global._pendingRequests||(global._pendingRequests={byModel:{},byAccount:{}}),global._lastErrorProvider||(global._lastErrorProvider={provider:"",ts:0}),global._statsEmitter||(global._statsEmitter=new p.EventEmitter,global._statsEmitter.setMaxListeners(50)),global._recentRing||(global._recentRing={items:[],initialized:!1}),global._connectionMapCache||(global._connectionMapCache={map:{},ts:0}),global._statsEmitTimers||(global._statsEmitTimers={pending:null,update:null});let t=global._pendingRequests,u=global._lastErrorProvider,v=global._recentRing;global._connectionMapCache;let w=global._statsEmitTimers,x=global._statsEmitter;function y(a,b=150){let c="update"===a?"update":"pending";w[c]||(w[c]=setTimeout(()=>{w[c]=null,x.emit(a)},b),w[c]?.unref?.())}function z(a){if(!a||null!==Object.getPrototypeOf(a)){let b=Object.create(null);return a&&Object.assign(b,a),b}return a}function A(a,b,c){let d=function(a){if(null==a)return null;let b=String(a);return"__proto__"===b||"constructor"===b||"prototype"===b?`__safe_${b}`:b}(b);null!=d&&(a[d]||(a[d]={requests:0,promptTokens:0,completionTokens:0,cachedTokens:0,cost:0}),a[d].requests+=c.requests||1,a[d].promptTokens+=c.promptTokens||0,a[d].completionTokens+=c.completionTokens||0,a[d].cachedTokens+=c.cachedTokens||0,a[d].cost+=c.cost||0,c.meta&&Object.assign(a[d],c.meta))}async function B(a,b,d){if(!d||!a||!b)return 0;try{let{getPricingForModel:e}=await Promise.resolve().then(c.bind(c,90181)),f=await e(a,b);if(!f)return 0;let{calculateCostFromTokens:g}=await Promise.resolve().then(c.bind(c,71253));return g(d,f)}catch(a){return console.error("Error calculating cost:",a),0}}function C(a,b,c,d,e=!1){let f=b?`${a} (${b})`:a;t.byModel[f]||(t.byModel[f]=0),t.byModel[f]=Math.max(0,t.byModel[f]+(d?1:-1)),0===t.byModel[f]&&delete t.byModel[f],c&&(t.byAccount[c]||(t.byAccount[c]={}),t.byAccount[c][f]||(t.byAccount[c][f]=0),t.byAccount[c][f]=Math.max(0,t.byAccount[c][f]+(d?1:-1)),0===t.byAccount[c][f]&&(delete t.byAccount[c][f],0===Object.keys(t.byAccount[c]).length&&delete t.byAccount[c])),!d&&e&&b&&(u.provider=b.toLowerCase(),u.ts=Date.now());let g=new Date().toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"});console.log(`[${g}] [PENDING] ${d?"START":"END"}${e?" (ERROR)":""} | provider=${b} | model=${a}`),y("pending")}async function D(a){try{let b=await (0,d.c)();a.timestamp||(a.timestamp=new Date().toISOString()),a.cost=await B(a.provider,a.model,a.tokens);let c=a.tokens||{},e=(0,r.T)(c.prompt_tokens||c.input_tokens||0,"usage.promptTokens",{integer:!0}),f=(0,r.T)(c.completion_tokens||c.output_tokens||0,"usage.completionTokens",{integer:!0}),g=(0,r.T)(c.cached_tokens||c.cache_read_input_tokens||0,"usage.cachedTokens",{integer:!0}),h=(0,r.T)(a.cost,"usage.cost"),j=!1;(b.transaction(()=>{var d;let k,l,m,n,o,p,r,t,u,v,w,x,y=a.requestId||null;if(y&&b.get("SELECT id FROM usageHistory WHERE requestId = ?",[y]))return;b.run("INSERT INTO usageHistory(timestamp, provider, model, connectionId, clientKeyId, endpoint, promptTokens, completionTokens, cost, status, tokens, meta, requestId) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[a.timestamp,a.provider||null,a.model||null,a.connectionId||null,a.clientKeyId||null,a.endpoint||null,e,f,a.cost||0,a.status||"ok",(0,i.s)(c),(0,i.s)({}),y]),a.clientKeyId&&b.run("UPDATE apiKeys SET spentUsd = spentUsd + ? WHERE id = ?",[Number(a.cost||0),a.clientKeyId]);let B=parseInt(process.env.USAGE_HISTORY_MAX||"50000",10),C=b.get("SELECT value FROM _meta WHERE key = 'usageHistoryCount'");if(k=C?.value!=null?parseInt(C.value,10)+1:b.get("SELECT COUNT(*) as c FROM usageHistory")?.c||0,Number.isFinite(B)&&B>0&&k>B){let a=k-B;b.run("DELETE FROM usageHistory WHERE id IN (SELECT id FROM usageHistory ORDER BY id ASC LIMIT ?)",[a]),k=B}b.run("INSERT INTO _meta(key, value) VALUES('usageHistoryCount', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",[String(k)]);let D=(l=(d=a.timestamp)?new Date(d):new Date,`${l.getFullYear()}-${String(l.getMonth()+1).padStart(2,"0")}-${String(l.getDate()).padStart(2,"0")}`),E=b.get("SELECT data FROM usageDaily WHERE dateKey = ?",[D]),F=E?(0,i.q)(E.data,{}):{requests:0,promptTokens:0,completionTokens:0,cost:0,byProvider:{},byModel:{},byAccount:{},byClientKey:{},byEndpoint:{}};m=a.tokens?.prompt_tokens||a.tokens?.input_tokens||0,n=a.tokens?.completion_tokens||a.tokens?.output_tokens||0,o=a.tokens?.cached_tokens||a.tokens?.cache_read_input_tokens||0,p=a.cost||0,r={promptTokens:m,completionTokens:n,cachedTokens:o,cost:p},F.requests=(F.requests||0)+1,F.promptTokens=(F.promptTokens||0)+m,F.completionTokens=(F.completionTokens||0)+n,F.cachedTokens=(F.cachedTokens||0)+o,F.cost=(F.cost||0)+p,F.byProvider=z(F.byProvider||{}),F.byModel=z(F.byModel||{}),F.byAccount=z(F.byAccount||{}),F.byClientKey=z(F.byClientKey||{}),F.byEndpoint=z(F.byEndpoint||{}),a.provider&&A(F.byProvider,a.provider,r),t=a.provider?`${a.model}|${a.provider}`:a.model,A(F.byModel,t,{...r,meta:{rawModel:a.model,provider:a.provider}}),a.connectionId&&A(F.byAccount,a.connectionId,{...r,meta:{rawModel:a.model,provider:a.provider}}),u=a.clientKeyId&&"string"==typeof a.clientKeyId?a.clientKeyId:null,v=`${u||"local-no-key"}|${a.model}|${a.provider||"unknown"}`,A(F.byClientKey,v,{...r,meta:{rawModel:a.model,provider:a.provider,clientKeyId:u}}),w=a.endpoint||"Unknown",x=`${w}|${a.model}|${a.provider||"unknown"}`,A(F.byEndpoint,x,{...r,meta:{endpoint:w,rawModel:a.model,provider:a.provider}}),b.run("INSERT INTO usageDaily(dateKey, data) VALUES(?, ?) ON CONFLICT(dateKey) DO UPDATE SET data = excluded.data",[D,(0,i.s)(F)]),(0,q.Bq)(b,()=>{let c=(0,s.ry)(b,a.provider)?a.provider:"unknown",d=b.get(`SELECT provider, requests, promptTokens, completionTokens, cachedTokens, cost
|
|
395
398
|
FROM prometheusUsageTotals WHERE provider = ?`,[c]);d&&(0,q.Kd)(d),d&&(0,q.Kd)({provider:c,requests:d.requests+1,promptTokens:d.promptTokens+e,completionTokens:d.completionTokens+f,cachedTokens:d.cachedTokens+g,cost:d.cost+h}),b.run(`INSERT INTO prometheusUsageTotals(provider, requests, promptTokens, completionTokens, cachedTokens, cost)
|
|
396
399
|
VALUES(?, 1, ?, ?, ?, ?)
|
|
397
400
|
ON CONFLICT(provider) DO UPDATE SET
|
|
@@ -485,7 +488,7 @@ ${b}`:b),"string"==typeof a.encrypted_content&&(m=a.encrypted_content);continue}
|
|
|
485
488
|
fi
|
|
486
489
|
fi
|
|
487
490
|
done
|
|
488
|
-
`;return new Promise(a=>{f(d,{shell:"/bin/bash"},()=>a())})}async function y(a,b){if(!h()){k(`🔐 Cert: cannot install to system store without sudo — trust this file on clients: ${b}`),await x(b,"add");return}let c=p(),d=`${c.dir}/switchboard-root-ca.crt`,e=`cp "${b}" "${d}" && (${c.cmd} 2>/dev/null || true)`;try{await g(e,a),await x(b,"add"),k(`🔐 Cert: ✅ installed to Linux trust store (${c.dir}) and user browser databases`)}catch(a){throw Error(`Certificate install failed: ${a.message}`)}}async function z(a){if(await x(null,"delete"),!h())return;let b=p(),c=`${b.dir}/switchboard-root-ca.crt`,d=`rm -f "${c}" && (${b.cmd} 2>/dev/null || true)`;try{await g(d,a),k("\uD83D\uDD10 Cert: ✅ uninstalled from Linux trust store and user browser databases")}catch(a){throw Error("Failed to uninstall certificate")}}a.exports={installCert:async function a(a,b){if(!d.existsSync(b))throw Error(`Certificate file not found: ${b}`);await s(b)?k("\uD83D\uDD10 Cert: already trusted ✅"):m?await u(b):n?await t(a,b):await y(a,b)},uninstallCert:async function a(a,b){await s(b)?m?await w():n?await v(a,b):await z(a):k("\uD83D\uDD10 Cert: not found in system store")},checkCertInstalled:s}},94463:(a,b,c)=>{var d=c(45654);c(63070),c(36105),c(20308),c(49345),c(70710),c(15873),c(87981),c(10401),c(33889),c(65737);var e=d.asn1,f=a.exports=d.pki=d.pki||{};f.pemToDer=function(a){var b=d.pem.decode(a)[0];if(b.procType&&"ENCRYPTED"===b.procType.type)throw Error("Could not convert PEM to DER; PEM is encrypted.");return d.util.createBuffer(b.body)},f.privateKeyFromPem=function(a){var b=d.pem.decode(a)[0];if("PRIVATE KEY"!==b.type&&"RSA PRIVATE KEY"!==b.type){var c=Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".');throw c.headerType=b.type,c}if(b.procType&&"ENCRYPTED"===b.procType.type)throw Error("Could not convert private key from PEM; PEM is encrypted.");var g=e.fromDer(b.body);return f.privateKeyFromAsn1(g)},f.privateKeyToPem=function(a,b){var c={type:"RSA PRIVATE KEY",body:e.toDer(f.privateKeyToAsn1(a)).getBytes()};return d.pem.encode(c,{maxline:b})},f.privateKeyInfoToPem=function(a,b){var c={type:"PRIVATE KEY",body:e.toDer(a).getBytes()};return d.pem.encode(c,{maxline:b})}},95095:(a,b,c)=>{"use strict";let d=c(7344),e=c(31825);class f extends d{#bR=null;#bS=null;constructor(a,b={}){super(b),this.#bR=a,this.#bS=b}dispatch(a,b){let c=new e({...a,retryOptions:this.#bS},{dispatch:this.#bR.dispatch.bind(this.#bR),handler:b});return this.#bR.dispatch(a,c)}close(){return this.#bR.close()}destroy(){return this.#bR.destroy()}}a.exports=f},95695:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{SB:()=>B});var e=c(65369),f=c(30322),g=c(59529),h=c(4620),i=c(16542),j=c(33113),k=c(62692),l=c(84263),m=c(37071),n=c(51171),o=c(41883),p=c(99120),q=c(67594),r=c(49209),s=c(37606),t=c(18205),u=c(94107),v=c(14071),w=c(76558),x=c(16276),y=c(46248),z=c(72285);c(67671);var A=a([n]);n=(A.then?(await A)():A)[0];let C={antigravity:new e.c,azure:new f.P,"gemini-cli":new g.V,github:new h.x,iflow:new i.r,qoder:new j.DH,kiro:new k.B,kimchi:new l.BL,codex:new m.T,cursor:new n.o,cu:new n.o,vertex:new o.w("vertex"),"vertex-partner":new o.w("vertex-partner"),qwen:new p.R,opencode:new q.j,"grok-web":new r.$,"perplexity-web":new s.Ay,"ollama-local":new t.D,commandcode:new u.A,"xiaomi-tokenplan":new v.F,"mimo-free":new w.Yh,mmf:new w.Yh,"codebuddy-cn":new x.v,"grok-cli":new z.h},D=new Map;function B(a){return C[a]?C[a]:(D.has(a)||D.set(a,new y.L(a)),D.get(a))}d()}catch(a){d(a)}})},96684:(a,b,c)=>{"use strict";c.d(b,{F:()=>e,Q:()=>f});var d=c(62457);function e(a,b){switch(b){case"claude":switch(a){case d.Ut.END_TURN:return d.bC.STOP;case d.Ut.MAX_TOKENS:return d.bC.LENGTH;case d.Ut.TOOL_USE:return d.bC.TOOL_CALLS;case d.Ut.STOP_SEQUENCE:default:return d.bC.STOP}case"commandcode":switch(a){case"stop":case"error":return d.bC.STOP;case"length":return d.bC.LENGTH;case"tool-calls":case"tool_use":return d.bC.TOOL_CALLS;case"content-filter":return d.bC.CONTENT_FILTER;default:return a||d.bC.STOP}case"gemini":{let b=String(a).toUpperCase();if(d.lW.has(b))return d.bC.ERROR;if(d.zh.has(b))return d.bC.CONTENT_FILTER;switch(b){case d.a_.STOP:return d.bC.STOP;case d.a_.MAX_TOKENS:return d.bC.LENGTH;default:return d.bC.STOP}}case"kiro":case"ollama":switch(a){case"tool_calls":case"tool_use":return d.bC.TOOL_CALLS;case"length":case"max_tokens":return d.bC.LENGTH;default:return d.bC.STOP}default:return a||d.bC.STOP}}function f(a,b){if("claude"!==b)return a;switch(a){case d.bC.STOP:return d.Ut.END_TURN;case d.bC.LENGTH:return d.Ut.MAX_TOKENS;case d.bC.TOOL_CALLS:return d.Ut.TOOL_USE;case d.bC.ERROR:default:return d.Ut.END_TURN}}},96997:(a,b,c)=>{"use strict";c.d(b,{oD:()=>z,Og:()=>B,jT:()=>A,Sc:()=>C,jR:()=>x,I9:()=>q,AH:()=>v,Ql:()=>u,$B:()=>H,pb:()=>E});var d=c(38421),e=c(10793),f=c(50969);let g=new Map;function h(a,b){g.get(a)===b&&(g.delete(a),b.cleanupTimer&&clearTimeout(b.cleanupTimer))}async function i(a,b,c,d){if(!b)return c();let e=`${a}:${b}`,f=g.get(e);if(f){if(f.promise)return d?.info?.("TOKEN_REFRESH",`Reusing in-flight refresh for ${a}`),f.promise;if(f.expiresAt>Date.now())return d?.info?.("TOKEN_REFRESH",`Reusing recent refresh result for ${a}`),f.result;h(e,f)}let i={promise:null},j=(async()=>{try{let a=await c();if(a&&(a.accessToken||a.copilotToken||a.refreshToken)){let b;(b={result:a,expiresAt:Date.now()+1e4,cleanupTimer:null}).cleanupTimer=setTimeout(()=>{g.get(e)===b&&(g.delete(e),b.cleanupTimer=null)},1e4),b.cleanupTimer.unref?.(),g.set(e,b)}else h(e,i);return a}catch(a){throw h(e,i),a}})();return i.promise=j,g.set(e,i),j}var j=c(17438),k=c(85513);function l(a="",b=0){let c="";try{let b=a?JSON.parse(a):null;c=b?.error||b?.error_code||b?.code||""}catch{}return{status:b,errorCode:c||void 0,bodyLen:a?.length||0}}let m=null;async function n(a,b){return a?i("xai",a,async()=>{try{if(!m){let a=(0,j.oC)().createXaiService;if(!a)return b?.warn?.("TOKEN_REFRESH","xAI service not wired (setOpenSseDeps)"),null;m=await a()}let c=await m.refreshAccessToken(a);return{accessToken:c.access_token,refreshToken:c.refresh_token||a,expiresIn:c.expires_in,idToken:c.id_token}}catch(d){let a=String(d?.message||""),c=a.includes("invalid_grant")?"invalid_grant":a.includes("invalid_request")?"invalid_request":null;if(b?.warn?.("TOKEN_REFRESH","xai refresh failed",c?{errorCode:c}:void 0),c)return{error:c};return null}},b):null}async function o(a,b,c,e,g=null){let h=d.xq[a],j=h?.refreshUrl||d.sr[a]?.refreshUrl||d.sr[a]?.tokenUrl;return h&&j?b?i(a,b,async()=>{try{let c=new URLSearchParams({grant_type:"refresh_token",refresh_token:b,client_id:h.clientId});h.clientSecret&&c.set("client_secret",h.clientSecret);let d=await (0,f.Fm)(j,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:c,identity:h.identity,provider:a,format:h.format},g);if(!d.ok){let b=await d.text();return e?.error?.("TOKEN_REFRESH",`Failed to refresh token for ${a}`,{status:d.status,error:l(b,d.status)}),null}let i=await d.json();return e?.info?.("TOKEN_REFRESH",`Successfully refreshed token for ${a}`,{hasNewAccessToken:!!i.access_token,hasNewRefreshToken:!!i.refresh_token,expiresIn:i.expires_in}),{accessToken:i.access_token,refreshToken:i.refresh_token||b,expiresIn:i.expires_in}}catch(b){return e?.error?.("TOKEN_REFRESH",`Error refreshing token for ${a}`,{error:b.message}),null}},e):(e?.warn?.("TOKEN_REFRESH",`No refresh token available for provider: ${a}`),null):(e?.warn?.("TOKEN_REFRESH",`No refresh URL configured for provider: ${a}`),null)}async function p(a,b){return a?i("claude",a,async()=>{try{let c=await (0,f.Fm)(e.NA.anthropic.token,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:a,client_id:d.xq.claude.clientId}),identity:d.xq.claude?.identity,provider:"claude",format:d.xq.claude?.format});if(!c.ok){let a=await c.text();return b?.error?.("TOKEN_REFRESH","Failed to refresh Claude OAuth token",{status:c.status,error:l(a,c.status)}),null}let g=await c.json();return b?.info?.("TOKEN_REFRESH","Successfully refreshed Claude OAuth token",{hasNewAccessToken:!!g.access_token,expiresIn:g.expires_in}),{accessToken:g.access_token,refreshToken:g.refresh_token||a,expiresIn:g.expires_in}}catch(a){return b?.error?.("TOKEN_REFRESH",`Network error refreshing Claude token: ${a.message}`),null}},b):null}async function q(a,b,c,g,h=null,j=null){if(!a)return null;let k=h||(b===d.xq.antigravity?.clientId?"antigravity":"gemini-cli"),m=d.xq[k];return i(`google:${b}`,a,async()=>{try{let d=await (0,f.Fm)(e.NA.google.token,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:a,client_id:b,client_secret:c}),identity:m?.identity,provider:k,format:m?.format},j);if(!d.ok){let a=await d.text();return g?.error?.("TOKEN_REFRESH","Failed to refresh Google token",{status:d.status,error:l(a,d.status)}),null}let h=await d.json();return g?.info?.("TOKEN_REFRESH","Successfully refreshed Google token",{hasNewAccessToken:!!h.access_token,expiresIn:h.expires_in}),{accessToken:h.access_token,refreshToken:h.refresh_token||a,expiresIn:h.expires_in}}catch(a){return g?.error?.("TOKEN_REFRESH",`Network error refreshing Google token: ${a.message}`),null}},g)}async function r(a,b){return a?i("qwen",a,async()=>{let c=e.NA.qwen.token;try{let e=await (0,f.Fm)(c,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:a,client_id:d.xq.qwen.clientId}),identity:d.xq.qwen?.identity,provider:"qwen",format:d.xq.qwen?.format});if(200===e.status){let c=await e.json();return b?.info?.("TOKEN_REFRESH","Successfully refreshed Qwen token",{hasNewAccessToken:!!c.access_token,hasNewRefreshToken:!!c.refresh_token,expiresIn:c.expires_in}),{accessToken:c.access_token,refreshToken:c.refresh_token||a,expiresIn:c.expires_in,providerSpecificData:c.resource_url?{resourceUrl:c.resource_url}:void 0}}{let a=await e.text().catch(()=>"");b?.warn?.("TOKEN_REFRESH","Error with Qwen endpoint",{status:e.status,error:l(a,e.status)})}}catch(a){b?.warn?.("TOKEN_REFRESH","Network error trying Qwen endpoint",{error:a.message})}return b?.error?.("TOKEN_REFRESH","Failed to refresh Qwen token"),null},b):null}async function s(a,b){return a?i("codex",a,async()=>{try{let c=await (0,f.Fm)(e.NA.openai.token,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:d.xq.codex.clientId,grant_type:"refresh_token",refresh_token:a}),identity:d.xq.codex?.identity,provider:"codex",format:d.xq.codex?.format});if(!c.ok){let a=await c.text(),d=function(a="",b=0){let c=null;try{c=a?JSON.parse(a):null}catch{c=null}let d=c?.error?.code||c?.error||c?.error_code||"",e=c?.error_description||c?.message||a||"",f=`${d} ${e}`.toLowerCase();return{status:b,code:d,description:e,permanent:["refresh_token_expired","refresh_token_reused","refresh_token_invalidated","invalid_grant"].some(a=>f.includes(a))}}(a,c.status);if(d.permanent)return b?.error?.("TOKEN_REFRESH","Codex refresh token already used or invalid. Re-auth required.",{status:c.status,code:d.code}),{error:"unrecoverable_refresh_error",code:d.code};return b?.error?.("TOKEN_REFRESH","Failed to refresh Codex token",{status:c.status,error:l(a,c.status),code:d.code,permanent:d.permanent}),null}let g=await c.json();return b?.info?.("TOKEN_REFRESH","Successfully refreshed Codex token",{hasNewAccessToken:!!g.access_token,hasNewRefreshToken:!!g.refresh_token,hasIdToken:!!g.id_token,expiresIn:g.expires_in}),{accessToken:g.access_token,refreshToken:g.refresh_token||a,idToken:g.id_token,expiresIn:g.expires_in}}catch(a){return b?.error?.("TOKEN_REFRESH",`Network error refreshing Codex token: ${a.message}`),null}},b):null}async function t(a,b,c){if(a?.profileArn)return{};let d=c?.trim?.()||null;if(!d){let c=(0,j.oC)().fetchKiroProfileArn;c&&(d=await c(b,a?.region))}return d?{providerSpecificData:{profileArn:d}}:{}}async function u(a,b,c,e=null){return a?i("kiro",a,async()=>{let g=b?.authMethod,h=b?.clientId,i=b?.clientSecret,m=b?.region;if("external_idp"===g){let g;try{let c=(0,j.oC)().buildExternalIdpRefreshParams;if(!c)throw Error("buildExternalIdpRefreshParams not wired");g=await c(a,b)}catch(a){return c?.warn?.("TOKEN_REFRESH",`Invalid Kiro external_idp refresh config: ${a.message}`),null}let h=await (0,f.Fm)(g.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:g.body,identity:d.xq.kiro?.identity,provider:"kiro",format:d.xq.kiro?.format},e);if(!h.ok){let a=await h.text();return c?.error?.("TOKEN_REFRESH","Failed to refresh Kiro external_idp token",{status:h.status,error:l(a,h.status)}),null}let i=await h.json();return c?.info?.("TOKEN_REFRESH","Successfully refreshed Kiro external_idp token",{hasNewAccessToken:!!i.access_token,hasNewRefreshToken:!!i.refresh_token,expiresIn:i.expires_in}),{accessToken:i.access_token,refreshToken:i.refresh_token||a,expiresIn:i.expires_in,providerSpecificData:g.providerSpecificData}}if(h&&i){let j="idc"===g&&(0,k.i7)(m)?`https://oidc.${m}.amazonaws.com/token`:"https://oidc.us-east-1.amazonaws.com/token",n=await (0,f.Fm)(j,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({clientId:h,clientSecret:i,refreshToken:a,grantType:"refresh_token"}),identity:d.xq.kiro?.identity,provider:"kiro",format:d.xq.kiro?.format},e);if(!n.ok){let a=await n.text();return c?.error?.("TOKEN_REFRESH","Failed to refresh Kiro AWS token",{status:n.status,error:l(a,n.status)}),null}let o=await n.json();return c?.info?.("TOKEN_REFRESH","Successfully refreshed Kiro AWS token",{hasNewAccessToken:!!o.accessToken,expiresIn:o.expiresIn}),{accessToken:o.accessToken,refreshToken:o.refreshToken||a,expiresIn:o.expiresIn,...await t(b,o.accessToken,o.profileArn)}}let n=await (0,f.Fm)(d.xq.kiro.tokenUrl,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","User-Agent":"kiro-cli/1.0.0"},body:JSON.stringify({refreshToken:a}),identity:d.xq.kiro?.identity,provider:"kiro",format:d.xq.kiro?.format},e);if(!n.ok){let a=await n.text();return c?.error?.("TOKEN_REFRESH","Failed to refresh Kiro social token",{status:n.status,error:l(a,n.status)}),null}let o=await n.json();return c?.info?.("TOKEN_REFRESH","Successfully refreshed Kiro social token",{hasNewAccessToken:!!o.accessToken,expiresIn:o.expiresIn}),{accessToken:o.accessToken,refreshToken:o.refreshToken||a,expiresIn:o.expiresIn,...await t(b,o.accessToken,o.profileArn)}},c):null}async function v(a,b){return a?i("iflow",a,async()=>{let c=btoa(`${d.xq.iflow.clientId}:${d.xq.iflow.clientSecret}`),g=await (0,f.Fm)(e.NA.iflow.token,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json",Authorization:`Basic ${c}`},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:a,client_id:d.xq.iflow.clientId,client_secret:d.xq.iflow.clientSecret}),identity:d.xq.iflow?.identity,provider:"iflow",format:d.xq.iflow?.format});if(!g.ok){let a=await g.text();return b?.error?.("TOKEN_REFRESH","Failed to refresh iFlow token",{status:g.status,error:l(a,g.status)}),null}let h=await g.json();return b?.info?.("TOKEN_REFRESH","Successfully refreshed iFlow token",{hasNewAccessToken:!!h.access_token,hasNewRefreshToken:!!h.refresh_token,expiresIn:h.expires_in}),{accessToken:h.access_token,refreshToken:h.refresh_token||a,expiresIn:h.expires_in}},b):null}async function w(a,b){return a?i("github",a,async()=>{let c={grant_type:"refresh_token",refresh_token:a,client_id:d.xq.github.clientId};d.xq.github.clientSecret&&(c.client_secret=d.xq.github.clientSecret);let g=await (0,f.Fm)(e.NA.github.token,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams(c),identity:d.xq.github?.identity,provider:"github",format:d.xq.github?.format});if(!g.ok){let a=await g.text();return b?.error?.("TOKEN_REFRESH","Failed to refresh GitHub token",{status:g.status,error:l(a,g.status)}),null}let h=await g.json();return b?.info?.("TOKEN_REFRESH","Successfully refreshed GitHub token",{hasNewAccessToken:!!h.access_token,hasNewRefreshToken:!!h.refresh_token,expiresIn:h.expires_in}),{accessToken:h.access_token,refreshToken:h.refresh_token||a,expiresIn:h.expires_in}},b):null}async function x(a,b){return a?i("copilot",a,async()=>{try{let c=await (0,f.Fm)(d.sr.github?.copilotTokenUrl,{headers:{Authorization:`token ${a}`,Accept:"application/json"},identity:d.xq.github?.identity,provider:"github",format:d.xq.github?.format});if(!c.ok){let a=await c.text();return b?.error?.("TOKEN_REFRESH","Failed to refresh Copilot token",{status:c.status,error:l(a,c.status)}),null}let e=await c.json();return b?.info?.("TOKEN_REFRESH","Successfully refreshed Copilot token",{hasToken:!!e.token,expiresAt:e.expires_at}),{token:e.token,expiresAt:e.expires_at}}catch(a){return b?.error?.("TOKEN_REFRESH","Error refreshing Copilot token",{error:a.message}),null}},b):null}async function y(a,b){return a?i("codebuddy-cn",a,async()=>{let c=d.sr["codebuddy-cn"]||{},e=await (0,f.Fm)(c.refreshUrl,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","User-Agent":c.userAgent,"X-Requested-With":"XMLHttpRequest","X-Domain":"copilot.tencent.com","X-Refresh-Token":a},body:JSON.stringify({refreshToken:a}),identity:d.xq["codebuddy-cn"]?.identity,provider:"codebuddy-cn",format:d.xq["codebuddy-cn"]?.format});if(!e.ok){let a=await e.text();return b?.error?.("TOKEN_REFRESH","Failed to refresh CodeBuddy token",{status:e.status,error:l(a,e.status)}),null}let g=await e.json();return 0===g.code&&g.data?.accessToken?(b?.info?.("TOKEN_REFRESH","Successfully refreshed CodeBuddy token",{hasNewAccessToken:!!g.data.accessToken,hasNewRefreshToken:!!g.data.refreshToken,expiresIn:g.data.expiresIn}),{accessToken:g.data.accessToken,refreshToken:g.data.refreshToken||a,expiresIn:g.data.expiresIn}):(b?.error?.("TOKEN_REFRESH","CodeBuddy token refresh returned no token",{code:g.code,msg:g.msg}),null)},b):null}let z=3e5;function A(a){return a&&"object"==typeof a&&("unrecoverable_refresh_error"===a.error||"refresh_token_reused"===a.error||"invalid_request"===a.error||"invalid_grant"===a.error)}function B(a){return e.Wu[a]||z}function C(a){if("string"!=typeof a)return null;try{let b=JSON.parse(a);if("service_account"===b.type&&b.client_email&&b.private_key&&b.project_id)return b;return null}catch{return null}}let D=new Map;async function E(a,b,g="vertex",h=null){let i=a.client_email,j=D.get(i);if(j&&j.expiresAt-Date.now()>3e5)return{accessToken:j.token,expiresAt:j.expiresAt};try{let{SignJWT:j,importPKCS8:k}=await c.e(3675).then(c.bind(c,3675));b?.debug?.("TOKEN_REFRESH",`Vertex minting token for ${a.client_email}`);let l=await k(a.private_key.replace(/\\n/g,"\n"),"RS256"),m=Math.floor(Date.now()/1e3),n=await new j({scope:"https://www.googleapis.com/auth/cloud-platform"}).setProtectedHeader({alg:"RS256"}).setIssuer(a.client_email).setAudience(e.NA.google.token).setIssuedAt(m).setExpirationTime(m+3600).sign(l),o=d.xq[g]||d.xq.vertex,p=await (0,f.Fm)(e.NA.google.token,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:n}),identity:o.identity,provider:g,format:o.format},h);if(!p.ok){let a=await p.text();return b?.error?.("TOKEN_REFRESH",`Vertex token mint failed: ${a}`),null}let{access_token:q,expires_in:r}=await p.json(),s=Date.now()+(r??3600)*1e3;return D.set(i,{token:q,expiresAt:s}),b?.info?.("TOKEN_REFRESH",`Vertex token minted for ${a.client_email}`),{accessToken:q,expiresAt:s}}catch(a){return b?.error?.("TOKEN_REFRESH",`Vertex token error: ${a.message}`),null}}function F(a,b,c="vertex"){let d=C(a.apiKey);if(d)return E(d,b,c);try{let d="string"==typeof a.apiKey?JSON.parse(a.apiKey):null;if(d?.type==="authorized_user"&&d.refresh_token&&d.client_id&&d.client_secret)return q(d.refresh_token,d.client_id,d.client_secret,b,c)}catch{}return null}let G={"gemini-cli":(a,b)=>q(a.refreshToken,d.xq["gemini-cli"].clientId,d.xq["gemini-cli"].clientSecret,b),antigravity:(a,b)=>q(a.refreshToken,d.xq.antigravity.clientId,d.xq.antigravity.clientSecret,b),claude:(a,b)=>p(a.refreshToken,b),codex:(a,b)=>s(a.refreshToken,b),qwen:(a,b)=>r(a.refreshToken,b),iflow:(a,b)=>v(a.refreshToken,b),github:(a,b)=>w(a.refreshToken,b),kiro:(a,b)=>u(a.refreshToken,a.providerSpecificData,b),xai:(a,b)=>n(a.refreshToken,b),"grok-cli":(a,b,c)=>o("grok-cli",a.refreshToken,a,b,c),"codebuddy-cn":(a,b)=>y(a.refreshToken,b),vertex:(a,b)=>F(a,b,"vertex"),"vertex-partner":(a,b)=>F(a,b,"vertex-partner")};async function H(a,b,c,d=null){let e="vertex"===a||"vertex-partner"===a;if(!b.refreshToken&&!(e&&b?.apiKey))return null;let f=G[a];return f?f(b,c,d):o(a,b.refreshToken,b,c,d)}},97137:(a,b,c)=>{"use strict";c.d(b,{v:()=>j});var d=c(82689);let e=["server_is_overloaded","service_unavailable_error"];function f(a){let b=Error(a?.reason?.message||"Request aborted");return b.name="AbortError",b}function g(a){let b="",c=[];for(let d of a.split(/\r?\n/))d.startsWith("event:")?b=d.slice(6).trim():d.startsWith("data:")&&c.push(d.slice(5).trimStart());let d=c.join("\n"),e=null;try{e=JSON.parse(d)}catch{}return{event:b,parsed:e,rawData:d}}function h({event:a,parsed:b,rawData:c}){let d=b?.type||a,f=b?.error||b?.response?.error;if(!("error"===a||"error"===d||"response.failed"===d||d?.endsWith?.(".error")||f))return null;let g=b?JSON.stringify(f||b):c;return e.find(a=>g.includes(a))||null}async function i(a){let b;if(!a?.ok||!a.body)return{matched:null,replacementBody:null};let c=a.body.getReader(),d=new TextDecoder,e=[],f=0,i="",j=!1,k=null;try{for(;f<4096&&!k&&!j;){let{done:a,value:b}=await c.read();if(a)break;e.push(b),f+=b.byteLength;let l=(i+=d.decode(b,{stream:!0})).split(/\r?\n\r?\n/);for(let a of(i=l.pop()||"",l)){let b=g(a);(function({event:a,parsed:b}){let c=b?.type||a;return!(!c||"error"===c||"response.failed"===c||c?.endsWith?.(".error")||b?.error||b?.response?.error)&&(c.startsWith("response.output_")||c.startsWith("response.content_part.")||c.startsWith("response.function_call")||c.startsWith("response.reasoning")||c.startsWith("response.refusal")||c.startsWith("response.image_generation_call."))})(b)&&(j=!0);let c=h(b);if(c&&!j){k=c;break}}}k||j||(k=h(g(i)))}catch{}return{matched:k,replacementBody:(b=0,new ReadableStream({async pull(a){if(b<e.length)return void a.enqueue(e[b++]);try{let{done:b,value:d}=await c.read();b?a.close():a.enqueue(d)}catch(b){a.error(b)}},cancel:a=>c.cancel(a)}))}}async function j({execute:a,retryConfig:b,signal:c,log:e,provider:g="UPSTREAM"}){let h={...d.cI,...b},{attempts:k,delayMs:l}=(0,d.DR)(h[503]);for(let b=0;;b++){var m;if(c?.aborted)throw f(c);let d=await a(),h=await i(d.response),j=(m=h.replacementBody)?{...d,response:new Response(m,{status:d.response.status,statusText:d.response.statusText,headers:d.response.headers})}:d;if(!h.matched)return j;if(b>=k)return e?.warn?.("RETRY",`${g.toUpperCase()} | SSE transient "${h.matched}" — retries exhausted (${b}/${k})`),j;e?.debug?.("RETRY",`${g.toUpperCase()} | SSE "${h.matched}" retry ${b+1}/${k} after ${l/1e3}s`);try{await j.response.body?.cancel?.("retrying transient SSE error")}catch{}await function(a,b){return b?.aborted?Promise.reject(f(b)):a<=0?Promise.resolve():new Promise((c,d)=>{let e=()=>{clearTimeout(g),b?.removeEventListener?.("abort",e),d(f(b))},g=setTimeout(()=>{clearTimeout(g),b?.removeEventListener?.("abort",e),c()},a);b?.addEventListener?.("abort",e,{once:!0})})}(l,c)}}},97210:(a,b,c)=>{"use strict";let{createInflateRaw:d,Z_DEFAULT_WINDOWBITS:e}=c(38522),{isValidClientWindowBits:f}=c(94050),{MessageSizeExceededError:g}=c(61448),h=Buffer.from([0,0,255,255]),i=Symbol("kBuffer"),j=Symbol("kLength");class k{#bT;#bS={};#br=0;constructor(a,b){this.#bS.serverNoContextTakeover=a.has("server_no_context_takeover"),this.#bS.serverMaxWindowBits=a.get("server_max_window_bits"),this.#br=b.maxPayloadSize}decompress(a,b,c){if(!this.#bT){let a=e;if(this.#bS.serverMaxWindowBits){if(!f(this.#bS.serverMaxWindowBits))return void c(Error("Invalid server_max_window_bits"));a=Number.parseInt(this.#bS.serverMaxWindowBits)}try{this.#bT=d({windowBits:a})}catch(a){c(a);return}this.#bT[i]=[],this.#bT[j]=0,this.#bT.on("data",a=>{if(this.#bT[j]+=a.length,this.#br>0&&this.#bT[j]>this.#br){c(new g),this.#bT.removeAllListeners(),this.#bT=null;return}this.#bT[i].push(a)}),this.#bT.on("error",a=>{this.#bT=null,c(a)})}this.#bT.write(a),b&&this.#bT.write(h),this.#bT.flush(()=>{if(!this.#bT)return;let a=Buffer.concat(this.#bT[i],this.#bT[j]);this.#bT[i].length=0,this.#bT[j]=0,c(null,a)})}}a.exports={PerMessageDeflate:k}},97356:(a,b,c)=>{"use strict";let{Transform:d}=c(57075),{isASCIINumber:e,isValidLastEventId:f}=c(26376),g=Buffer.from("data"),h=Buffer.from("event"),i=Buffer.from("id"),j=Buffer.from("retry");function k(a,b,c){if(b!==c.length)return!1;for(let d=0;d<b;d++)if(a[d]!==c[d])return!1;return!0}class l extends d{state;checkBOM=!0;crlfCheck=!1;eventEndCheck=!1;chunks=[];chunkIndex=0;pos=0;lineChunkIndex=0;linePos=0;event={data:void 0,event:void 0,id:void 0,retry:void 0};constructor(a={}){a.readableObjectMode=!0,super(a),this.state=a.eventSourceSettings||{},a.push&&(this.push=a.push)}_transform(a,b,c){if(0===a.length||(this.chunks.push(a),this.checkBOM&&this.handleBOM()))return void c();for(;this.hasCurrentByte();){let a=this.currentByte();if(this.eventEndCheck){if(this.crlfCheck){if(10===a){this.crlfCheck=!1,this.consumeCurrentByte();continue}this.crlfCheck=!1}if(10===a||13===a){13===a&&(this.crlfCheck=!0),this.consumeCurrentByte(),this.hasPendingEvent()&&this.processEvent(this.event),this.clearEvent();continue}this.eventEndCheck=!1;continue}if(10===a||13===a){13===a&&(this.crlfCheck=!0),this.parseLine(this.readLine(),this.event),this.consumeCurrentByte(),this.eventEndCheck=!0;continue}this.advanceCursor()}c()}parseLine(a,b){if(0===a.length)return;let c=a.indexOf(58);if(0===c)return;let d=a.length,e=a.length;if(-1!==c&&(d=c,32===a[e=c+1]&&++e),k(a,d,g)){let c=a.toString("utf8",e);void 0===b.data?b.data=c:b.data+=`
|
|
491
|
+
`;return new Promise(a=>{f(d,{shell:"/bin/bash"},()=>a())})}async function y(a,b){if(!h()){k(`🔐 Cert: cannot install to system store without sudo — trust this file on clients: ${b}`),await x(b,"add");return}let c=p(),d=`${c.dir}/switchboard-root-ca.crt`,e=`cp "${b}" "${d}" && (${c.cmd} 2>/dev/null || true)`;try{await g(e,a),await x(b,"add"),k(`🔐 Cert: ✅ installed to Linux trust store (${c.dir}) and user browser databases`)}catch(a){throw Error(`Certificate install failed: ${a.message}`)}}async function z(a){if(await x(null,"delete"),!h())return;let b=p(),c=`${b.dir}/switchboard-root-ca.crt`,d=`rm -f "${c}" && (${b.cmd} 2>/dev/null || true)`;try{await g(d,a),k("\uD83D\uDD10 Cert: ✅ uninstalled from Linux trust store and user browser databases")}catch(a){throw Error("Failed to uninstall certificate")}}a.exports={installCert:async function a(a,b){if(!d.existsSync(b))throw Error(`Certificate file not found: ${b}`);await s(b)?k("\uD83D\uDD10 Cert: already trusted ✅"):m?await u(b):n?await t(a,b):await y(a,b)},uninstallCert:async function a(a,b){await s(b)?m?await w():n?await v(a,b):await z(a):k("\uD83D\uDD10 Cert: not found in system store")},checkCertInstalled:s}},94463:(a,b,c)=>{var d=c(45654);c(63070),c(36105),c(20308),c(49345),c(70710),c(15873),c(87981),c(10401),c(33889),c(65737);var e=d.asn1,f=a.exports=d.pki=d.pki||{};f.pemToDer=function(a){var b=d.pem.decode(a)[0];if(b.procType&&"ENCRYPTED"===b.procType.type)throw Error("Could not convert PEM to DER; PEM is encrypted.");return d.util.createBuffer(b.body)},f.privateKeyFromPem=function(a){var b=d.pem.decode(a)[0];if("PRIVATE KEY"!==b.type&&"RSA PRIVATE KEY"!==b.type){var c=Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".');throw c.headerType=b.type,c}if(b.procType&&"ENCRYPTED"===b.procType.type)throw Error("Could not convert private key from PEM; PEM is encrypted.");var g=e.fromDer(b.body);return f.privateKeyFromAsn1(g)},f.privateKeyToPem=function(a,b){var c={type:"RSA PRIVATE KEY",body:e.toDer(f.privateKeyToAsn1(a)).getBytes()};return d.pem.encode(c,{maxline:b})},f.privateKeyInfoToPem=function(a,b){var c={type:"PRIVATE KEY",body:e.toDer(a).getBytes()};return d.pem.encode(c,{maxline:b})}},95095:(a,b,c)=>{"use strict";let d=c(7344),e=c(31825);class f extends d{#bR=null;#bS=null;constructor(a,b={}){super(b),this.#bR=a,this.#bS=b}dispatch(a,b){let c=new e({...a,retryOptions:this.#bS},{dispatch:this.#bR.dispatch.bind(this.#bR),handler:b});return this.#bR.dispatch(a,c)}close(){return this.#bR.close()}destroy(){return this.#bR.destroy()}}a.exports=f},95695:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{SB:()=>B});var e=c(65369),f=c(30322),g=c(59529),h=c(4620),i=c(16542),j=c(33113),k=c(62692),l=c(84263),m=c(40404),n=c(51171),o=c(41883),p=c(99120),q=c(67594),r=c(49209),s=c(37606),t=c(18205),u=c(94107),v=c(14071),w=c(76558),x=c(16276),y=c(46248),z=c(72285);c(67671);var A=a([n]);n=(A.then?(await A)():A)[0];let C={antigravity:new e.c,azure:new f.P,"gemini-cli":new g.V,github:new h.x,iflow:new i.r,qoder:new j.DH,kiro:new k.B,kimchi:new l.BL,codex:new m.T,cursor:new n.o,cu:new n.o,vertex:new o.w("vertex"),"vertex-partner":new o.w("vertex-partner"),qwen:new p.R,opencode:new q.j,"grok-web":new r.$,"perplexity-web":new s.Ay,"ollama-local":new t.D,commandcode:new u.A,"xiaomi-tokenplan":new v.F,"mimo-free":new w.Yh,mmf:new w.Yh,"codebuddy-cn":new x.v,"grok-cli":new z.h},D=new Map;function B(a){return C[a]?C[a]:(D.has(a)||D.set(a,new y.L(a)),D.get(a))}d()}catch(a){d(a)}})},96684:(a,b,c)=>{"use strict";c.d(b,{F:()=>e,Q:()=>f});var d=c(62457);function e(a,b){switch(b){case"claude":switch(a){case d.Ut.END_TURN:return d.bC.STOP;case d.Ut.MAX_TOKENS:return d.bC.LENGTH;case d.Ut.TOOL_USE:return d.bC.TOOL_CALLS;case d.Ut.STOP_SEQUENCE:default:return d.bC.STOP}case"commandcode":switch(a){case"stop":case"error":return d.bC.STOP;case"length":return d.bC.LENGTH;case"tool-calls":case"tool_use":return d.bC.TOOL_CALLS;case"content-filter":return d.bC.CONTENT_FILTER;default:return a||d.bC.STOP}case"gemini":{let b=String(a).toUpperCase();if(d.lW.has(b))return d.bC.ERROR;if(d.zh.has(b))return d.bC.CONTENT_FILTER;switch(b){case d.a_.STOP:return d.bC.STOP;case d.a_.MAX_TOKENS:return d.bC.LENGTH;default:return d.bC.STOP}}case"kiro":case"ollama":switch(a){case"tool_calls":case"tool_use":return d.bC.TOOL_CALLS;case"length":case"max_tokens":return d.bC.LENGTH;default:return d.bC.STOP}default:return a||d.bC.STOP}}function f(a,b){if("claude"!==b)return a;switch(a){case d.bC.STOP:return d.Ut.END_TURN;case d.bC.LENGTH:return d.Ut.MAX_TOKENS;case d.bC.TOOL_CALLS:return d.Ut.TOOL_USE;case d.bC.ERROR:default:return d.Ut.END_TURN}}},96997:(a,b,c)=>{"use strict";c.d(b,{oD:()=>z,Og:()=>B,jT:()=>A,Sc:()=>C,jR:()=>x,I9:()=>q,AH:()=>v,Ql:()=>u,$B:()=>H,pb:()=>E});var d=c(38421),e=c(10793),f=c(50969);let g=new Map;function h(a,b){g.get(a)===b&&(g.delete(a),b.cleanupTimer&&clearTimeout(b.cleanupTimer))}async function i(a,b,c,d){if(!b)return c();let e=`${a}:${b}`,f=g.get(e);if(f){if(f.promise)return d?.info?.("TOKEN_REFRESH",`Reusing in-flight refresh for ${a}`),f.promise;if(f.expiresAt>Date.now())return d?.info?.("TOKEN_REFRESH",`Reusing recent refresh result for ${a}`),f.result;h(e,f)}let i={promise:null},j=(async()=>{try{let a=await c();if(a&&(a.accessToken||a.copilotToken||a.refreshToken)){let b;(b={result:a,expiresAt:Date.now()+1e4,cleanupTimer:null}).cleanupTimer=setTimeout(()=>{g.get(e)===b&&(g.delete(e),b.cleanupTimer=null)},1e4),b.cleanupTimer.unref?.(),g.set(e,b)}else h(e,i);return a}catch(a){throw h(e,i),a}})();return i.promise=j,g.set(e,i),j}var j=c(17438),k=c(85513);function l(a="",b=0){let c="";try{let b=a?JSON.parse(a):null;c=b?.error||b?.error_code||b?.code||""}catch{}return{status:b,errorCode:c||void 0,bodyLen:a?.length||0}}let m=null;async function n(a,b){return a?i("xai",a,async()=>{try{if(!m){let a=(0,j.oC)().createXaiService;if(!a)return b?.warn?.("TOKEN_REFRESH","xAI service not wired (setOpenSseDeps)"),null;m=await a()}let c=await m.refreshAccessToken(a);return{accessToken:c.access_token,refreshToken:c.refresh_token||a,expiresIn:c.expires_in,idToken:c.id_token}}catch(d){let a=String(d?.message||""),c=a.includes("invalid_grant")?"invalid_grant":a.includes("invalid_request")?"invalid_request":null;if(b?.warn?.("TOKEN_REFRESH","xai refresh failed",c?{errorCode:c}:void 0),c)return{error:c};return null}},b):null}async function o(a,b,c,e,g=null){let h=d.xq[a],j=h?.refreshUrl||d.sr[a]?.refreshUrl||d.sr[a]?.tokenUrl;return h&&j?b?i(a,b,async()=>{try{let c=new URLSearchParams({grant_type:"refresh_token",refresh_token:b,client_id:h.clientId});h.clientSecret&&c.set("client_secret",h.clientSecret);let d=await (0,f.Fm)(j,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:c,identity:h.identity,provider:a,format:h.format},g);if(!d.ok){let b=await d.text();return e?.error?.("TOKEN_REFRESH",`Failed to refresh token for ${a}`,{status:d.status,error:l(b,d.status)}),null}let i=await d.json();return e?.info?.("TOKEN_REFRESH",`Successfully refreshed token for ${a}`,{hasNewAccessToken:!!i.access_token,hasNewRefreshToken:!!i.refresh_token,expiresIn:i.expires_in}),{accessToken:i.access_token,refreshToken:i.refresh_token||b,expiresIn:i.expires_in}}catch(b){return e?.error?.("TOKEN_REFRESH",`Error refreshing token for ${a}`,{error:b.message}),null}},e):(e?.warn?.("TOKEN_REFRESH",`No refresh token available for provider: ${a}`),null):(e?.warn?.("TOKEN_REFRESH",`No refresh URL configured for provider: ${a}`),null)}async function p(a,b){return a?i("claude",a,async()=>{try{let c=await (0,f.Fm)(e.NA.anthropic.token,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:a,client_id:d.xq.claude.clientId}),identity:d.xq.claude?.identity,provider:"claude",format:d.xq.claude?.format});if(!c.ok){let a=await c.text();return b?.error?.("TOKEN_REFRESH","Failed to refresh Claude OAuth token",{status:c.status,error:l(a,c.status)}),null}let g=await c.json();return b?.info?.("TOKEN_REFRESH","Successfully refreshed Claude OAuth token",{hasNewAccessToken:!!g.access_token,expiresIn:g.expires_in}),{accessToken:g.access_token,refreshToken:g.refresh_token||a,expiresIn:g.expires_in}}catch(a){return b?.error?.("TOKEN_REFRESH",`Network error refreshing Claude token: ${a.message}`),null}},b):null}async function q(a,b,c,g,h=null,j=null){if(!a)return null;let k=h||(b===d.xq.antigravity?.clientId?"antigravity":"gemini-cli"),m=d.xq[k];return i(`google:${b}`,a,async()=>{try{let d=await (0,f.Fm)(e.NA.google.token,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:a,client_id:b,client_secret:c}),identity:m?.identity,provider:k,format:m?.format},j);if(!d.ok){let a=await d.text();return g?.error?.("TOKEN_REFRESH","Failed to refresh Google token",{status:d.status,error:l(a,d.status)}),null}let h=await d.json();return g?.info?.("TOKEN_REFRESH","Successfully refreshed Google token",{hasNewAccessToken:!!h.access_token,expiresIn:h.expires_in}),{accessToken:h.access_token,refreshToken:h.refresh_token||a,expiresIn:h.expires_in}}catch(a){return g?.error?.("TOKEN_REFRESH",`Network error refreshing Google token: ${a.message}`),null}},g)}async function r(a,b){return a?i("qwen",a,async()=>{let c=e.NA.qwen.token;try{let e=await (0,f.Fm)(c,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:a,client_id:d.xq.qwen.clientId}),identity:d.xq.qwen?.identity,provider:"qwen",format:d.xq.qwen?.format});if(200===e.status){let c=await e.json();return b?.info?.("TOKEN_REFRESH","Successfully refreshed Qwen token",{hasNewAccessToken:!!c.access_token,hasNewRefreshToken:!!c.refresh_token,expiresIn:c.expires_in}),{accessToken:c.access_token,refreshToken:c.refresh_token||a,expiresIn:c.expires_in,providerSpecificData:c.resource_url?{resourceUrl:c.resource_url}:void 0}}{let a=await e.text().catch(()=>"");b?.warn?.("TOKEN_REFRESH","Error with Qwen endpoint",{status:e.status,error:l(a,e.status)})}}catch(a){b?.warn?.("TOKEN_REFRESH","Network error trying Qwen endpoint",{error:a.message})}return b?.error?.("TOKEN_REFRESH","Failed to refresh Qwen token"),null},b):null}async function s(a,b){return a?i("codex",a,async()=>{try{let c=await (0,f.Fm)(e.NA.openai.token,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:d.xq.codex.clientId,grant_type:"refresh_token",refresh_token:a}),identity:d.xq.codex?.identity,provider:"codex",format:d.xq.codex?.format});if(!c.ok){let a=await c.text(),d=function(a="",b=0){let c=null;try{c=a?JSON.parse(a):null}catch{c=null}let d=c?.error?.code||c?.error||c?.error_code||"",e=c?.error_description||c?.message||a||"",f=`${d} ${e}`.toLowerCase();return{status:b,code:d,description:e,permanent:["refresh_token_expired","refresh_token_reused","refresh_token_invalidated","invalid_grant"].some(a=>f.includes(a))}}(a,c.status);if(d.permanent)return b?.error?.("TOKEN_REFRESH","Codex refresh token already used or invalid. Re-auth required.",{status:c.status,code:d.code}),{error:"unrecoverable_refresh_error",code:d.code};return b?.error?.("TOKEN_REFRESH","Failed to refresh Codex token",{status:c.status,error:l(a,c.status),code:d.code,permanent:d.permanent}),null}let g=await c.json();return b?.info?.("TOKEN_REFRESH","Successfully refreshed Codex token",{hasNewAccessToken:!!g.access_token,hasNewRefreshToken:!!g.refresh_token,hasIdToken:!!g.id_token,expiresIn:g.expires_in}),{accessToken:g.access_token,refreshToken:g.refresh_token||a,idToken:g.id_token,expiresIn:g.expires_in}}catch(a){return b?.error?.("TOKEN_REFRESH",`Network error refreshing Codex token: ${a.message}`),null}},b):null}async function t(a,b,c){if(a?.profileArn)return{};let d=c?.trim?.()||null;if(!d){let c=(0,j.oC)().fetchKiroProfileArn;c&&(d=await c(b,a?.region))}return d?{providerSpecificData:{profileArn:d}}:{}}async function u(a,b,c,e=null){return a?i("kiro",a,async()=>{let g=b?.authMethod,h=b?.clientId,i=b?.clientSecret,m=b?.region;if("external_idp"===g){let g;try{let c=(0,j.oC)().buildExternalIdpRefreshParams;if(!c)throw Error("buildExternalIdpRefreshParams not wired");g=await c(a,b)}catch(a){return c?.warn?.("TOKEN_REFRESH",`Invalid Kiro external_idp refresh config: ${a.message}`),null}let h=await (0,f.Fm)(g.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:g.body,identity:d.xq.kiro?.identity,provider:"kiro",format:d.xq.kiro?.format},e);if(!h.ok){let a=await h.text();return c?.error?.("TOKEN_REFRESH","Failed to refresh Kiro external_idp token",{status:h.status,error:l(a,h.status)}),null}let i=await h.json();return c?.info?.("TOKEN_REFRESH","Successfully refreshed Kiro external_idp token",{hasNewAccessToken:!!i.access_token,hasNewRefreshToken:!!i.refresh_token,expiresIn:i.expires_in}),{accessToken:i.access_token,refreshToken:i.refresh_token||a,expiresIn:i.expires_in,providerSpecificData:g.providerSpecificData}}if(h&&i){let j="idc"===g&&(0,k.i7)(m)?`https://oidc.${m}.amazonaws.com/token`:"https://oidc.us-east-1.amazonaws.com/token",n=await (0,f.Fm)(j,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({clientId:h,clientSecret:i,refreshToken:a,grantType:"refresh_token"}),identity:d.xq.kiro?.identity,provider:"kiro",format:d.xq.kiro?.format},e);if(!n.ok){let a=await n.text();return c?.error?.("TOKEN_REFRESH","Failed to refresh Kiro AWS token",{status:n.status,error:l(a,n.status)}),null}let o=await n.json();return c?.info?.("TOKEN_REFRESH","Successfully refreshed Kiro AWS token",{hasNewAccessToken:!!o.accessToken,expiresIn:o.expiresIn}),{accessToken:o.accessToken,refreshToken:o.refreshToken||a,expiresIn:o.expiresIn,...await t(b,o.accessToken,o.profileArn)}}let n=await (0,f.Fm)(d.xq.kiro.tokenUrl,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","User-Agent":"kiro-cli/1.0.0"},body:JSON.stringify({refreshToken:a}),identity:d.xq.kiro?.identity,provider:"kiro",format:d.xq.kiro?.format},e);if(!n.ok){let a=await n.text();return c?.error?.("TOKEN_REFRESH","Failed to refresh Kiro social token",{status:n.status,error:l(a,n.status)}),null}let o=await n.json();return c?.info?.("TOKEN_REFRESH","Successfully refreshed Kiro social token",{hasNewAccessToken:!!o.accessToken,expiresIn:o.expiresIn}),{accessToken:o.accessToken,refreshToken:o.refreshToken||a,expiresIn:o.expiresIn,...await t(b,o.accessToken,o.profileArn)}},c):null}async function v(a,b){return a?i("iflow",a,async()=>{let c=btoa(`${d.xq.iflow.clientId}:${d.xq.iflow.clientSecret}`),g=await (0,f.Fm)(e.NA.iflow.token,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json",Authorization:`Basic ${c}`},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:a,client_id:d.xq.iflow.clientId,client_secret:d.xq.iflow.clientSecret}),identity:d.xq.iflow?.identity,provider:"iflow",format:d.xq.iflow?.format});if(!g.ok){let a=await g.text();return b?.error?.("TOKEN_REFRESH","Failed to refresh iFlow token",{status:g.status,error:l(a,g.status)}),null}let h=await g.json();return b?.info?.("TOKEN_REFRESH","Successfully refreshed iFlow token",{hasNewAccessToken:!!h.access_token,hasNewRefreshToken:!!h.refresh_token,expiresIn:h.expires_in}),{accessToken:h.access_token,refreshToken:h.refresh_token||a,expiresIn:h.expires_in}},b):null}async function w(a,b){return a?i("github",a,async()=>{let c={grant_type:"refresh_token",refresh_token:a,client_id:d.xq.github.clientId};d.xq.github.clientSecret&&(c.client_secret=d.xq.github.clientSecret);let g=await (0,f.Fm)(e.NA.github.token,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams(c),identity:d.xq.github?.identity,provider:"github",format:d.xq.github?.format});if(!g.ok){let a=await g.text();return b?.error?.("TOKEN_REFRESH","Failed to refresh GitHub token",{status:g.status,error:l(a,g.status)}),null}let h=await g.json();return b?.info?.("TOKEN_REFRESH","Successfully refreshed GitHub token",{hasNewAccessToken:!!h.access_token,hasNewRefreshToken:!!h.refresh_token,expiresIn:h.expires_in}),{accessToken:h.access_token,refreshToken:h.refresh_token||a,expiresIn:h.expires_in}},b):null}async function x(a,b){return a?i("copilot",a,async()=>{try{let c=await (0,f.Fm)(d.sr.github?.copilotTokenUrl,{headers:{Authorization:`token ${a}`,Accept:"application/json"},identity:d.xq.github?.identity,provider:"github",format:d.xq.github?.format});if(!c.ok){let a=await c.text();return b?.error?.("TOKEN_REFRESH","Failed to refresh Copilot token",{status:c.status,error:l(a,c.status)}),null}let e=await c.json();return b?.info?.("TOKEN_REFRESH","Successfully refreshed Copilot token",{hasToken:!!e.token,expiresAt:e.expires_at}),{token:e.token,expiresAt:e.expires_at}}catch(a){return b?.error?.("TOKEN_REFRESH","Error refreshing Copilot token",{error:a.message}),null}},b):null}async function y(a,b){return a?i("codebuddy-cn",a,async()=>{let c=d.sr["codebuddy-cn"]||{},e=await (0,f.Fm)(c.refreshUrl,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","User-Agent":c.userAgent,"X-Requested-With":"XMLHttpRequest","X-Domain":"copilot.tencent.com","X-Refresh-Token":a},body:JSON.stringify({refreshToken:a}),identity:d.xq["codebuddy-cn"]?.identity,provider:"codebuddy-cn",format:d.xq["codebuddy-cn"]?.format});if(!e.ok){let a=await e.text();return b?.error?.("TOKEN_REFRESH","Failed to refresh CodeBuddy token",{status:e.status,error:l(a,e.status)}),null}let g=await e.json();return 0===g.code&&g.data?.accessToken?(b?.info?.("TOKEN_REFRESH","Successfully refreshed CodeBuddy token",{hasNewAccessToken:!!g.data.accessToken,hasNewRefreshToken:!!g.data.refreshToken,expiresIn:g.data.expiresIn}),{accessToken:g.data.accessToken,refreshToken:g.data.refreshToken||a,expiresIn:g.data.expiresIn}):(b?.error?.("TOKEN_REFRESH","CodeBuddy token refresh returned no token",{code:g.code,msg:g.msg}),null)},b):null}let z=3e5;function A(a){return a&&"object"==typeof a&&("unrecoverable_refresh_error"===a.error||"refresh_token_reused"===a.error||"invalid_request"===a.error||"invalid_grant"===a.error)}function B(a){return e.Wu[a]||z}function C(a){if("string"!=typeof a)return null;try{let b=JSON.parse(a);if("service_account"===b.type&&b.client_email&&b.private_key&&b.project_id)return b;return null}catch{return null}}let D=new Map;async function E(a,b,g="vertex",h=null){let i=a.client_email,j=D.get(i);if(j&&j.expiresAt-Date.now()>3e5)return{accessToken:j.token,expiresAt:j.expiresAt};try{let{SignJWT:j,importPKCS8:k}=await c.e(3675).then(c.bind(c,3675));b?.debug?.("TOKEN_REFRESH",`Vertex minting token for ${a.client_email}`);let l=await k(a.private_key.replace(/\\n/g,"\n"),"RS256"),m=Math.floor(Date.now()/1e3),n=await new j({scope:"https://www.googleapis.com/auth/cloud-platform"}).setProtectedHeader({alg:"RS256"}).setIssuer(a.client_email).setAudience(e.NA.google.token).setIssuedAt(m).setExpirationTime(m+3600).sign(l),o=d.xq[g]||d.xq.vertex,p=await (0,f.Fm)(e.NA.google.token,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:n}),identity:o.identity,provider:g,format:o.format},h);if(!p.ok){let a=await p.text();return b?.error?.("TOKEN_REFRESH",`Vertex token mint failed: ${a}`),null}let{access_token:q,expires_in:r}=await p.json(),s=Date.now()+(r??3600)*1e3;return D.set(i,{token:q,expiresAt:s}),b?.info?.("TOKEN_REFRESH",`Vertex token minted for ${a.client_email}`),{accessToken:q,expiresAt:s}}catch(a){return b?.error?.("TOKEN_REFRESH",`Vertex token error: ${a.message}`),null}}function F(a,b,c="vertex"){let d=C(a.apiKey);if(d)return E(d,b,c);try{let d="string"==typeof a.apiKey?JSON.parse(a.apiKey):null;if(d?.type==="authorized_user"&&d.refresh_token&&d.client_id&&d.client_secret)return q(d.refresh_token,d.client_id,d.client_secret,b,c)}catch{}return null}let G={"gemini-cli":(a,b)=>q(a.refreshToken,d.xq["gemini-cli"].clientId,d.xq["gemini-cli"].clientSecret,b),antigravity:(a,b)=>q(a.refreshToken,d.xq.antigravity.clientId,d.xq.antigravity.clientSecret,b),claude:(a,b)=>p(a.refreshToken,b),codex:(a,b)=>s(a.refreshToken,b),qwen:(a,b)=>r(a.refreshToken,b),iflow:(a,b)=>v(a.refreshToken,b),github:(a,b)=>w(a.refreshToken,b),kiro:(a,b)=>u(a.refreshToken,a.providerSpecificData,b),xai:(a,b)=>n(a.refreshToken,b),"grok-cli":(a,b,c)=>o("grok-cli",a.refreshToken,a,b,c),"codebuddy-cn":(a,b)=>y(a.refreshToken,b),vertex:(a,b)=>F(a,b,"vertex"),"vertex-partner":(a,b)=>F(a,b,"vertex-partner")};async function H(a,b,c,d=null){let e="vertex"===a||"vertex-partner"===a;if(!b.refreshToken&&!(e&&b?.apiKey))return null;let f=G[a];return f?f(b,c,d):o(a,b.refreshToken,b,c,d)}},97137:(a,b,c)=>{"use strict";c.d(b,{v:()=>j});var d=c(82689);let e=["server_is_overloaded","service_unavailable_error"];function f(a){let b=Error(a?.reason?.message||"Request aborted");return b.name="AbortError",b}function g(a){let b="",c=[];for(let d of a.split(/\r?\n/))d.startsWith("event:")?b=d.slice(6).trim():d.startsWith("data:")&&c.push(d.slice(5).trimStart());let d=c.join("\n"),e=null;try{e=JSON.parse(d)}catch{}return{event:b,parsed:e,rawData:d}}function h({event:a,parsed:b,rawData:c}){let d=b?.type||a,f=b?.error||b?.response?.error;if(!("error"===a||"error"===d||"response.failed"===d||d?.endsWith?.(".error")||f))return null;let g=b?JSON.stringify(f||b):c;return e.find(a=>g.includes(a))||null}async function i(a){let b;if(!a?.ok||!a.body)return{matched:null,replacementBody:null};let c=a.body.getReader(),d=new TextDecoder,e=[],f=0,i="",j=!1,k=null;try{for(;f<4096&&!k&&!j;){let{done:a,value:b}=await c.read();if(a)break;e.push(b),f+=b.byteLength;let l=(i+=d.decode(b,{stream:!0})).split(/\r?\n\r?\n/);for(let a of(i=l.pop()||"",l)){let b=g(a);(function({event:a,parsed:b}){let c=b?.type||a;return!(!c||"error"===c||"response.failed"===c||c?.endsWith?.(".error")||b?.error||b?.response?.error)&&(c.startsWith("response.output_")||c.startsWith("response.content_part.")||c.startsWith("response.function_call")||c.startsWith("response.reasoning")||c.startsWith("response.refusal")||c.startsWith("response.image_generation_call."))})(b)&&(j=!0);let c=h(b);if(c&&!j){k=c;break}}}k||j||(k=h(g(i)))}catch{}return{matched:k,replacementBody:(b=0,new ReadableStream({async pull(a){if(b<e.length)return void a.enqueue(e[b++]);try{let{done:b,value:d}=await c.read();b?a.close():a.enqueue(d)}catch(b){a.error(b)}},cancel:a=>c.cancel(a)}))}}async function j({execute:a,retryConfig:b,signal:c,log:e,provider:g="UPSTREAM"}){let h={...d.cI,...b},{attempts:k,delayMs:l}=(0,d.DR)(h[503]);for(let b=0;;b++){var m;if(c?.aborted)throw f(c);let d=await a(),h=await i(d.response),j=(m=h.replacementBody)?{...d,response:new Response(m,{status:d.response.status,statusText:d.response.statusText,headers:d.response.headers})}:d;if(!h.matched)return j;if(b>=k)return e?.warn?.("RETRY",`${g.toUpperCase()} | SSE transient "${h.matched}" — retries exhausted (${b}/${k})`),j;e?.debug?.("RETRY",`${g.toUpperCase()} | SSE "${h.matched}" retry ${b+1}/${k} after ${l/1e3}s`);try{await j.response.body?.cancel?.("retrying transient SSE error")}catch{}await function(a,b){return b?.aborted?Promise.reject(f(b)):a<=0?Promise.resolve():new Promise((c,d)=>{let e=()=>{clearTimeout(g),b?.removeEventListener?.("abort",e),d(f(b))},g=setTimeout(()=>{clearTimeout(g),b?.removeEventListener?.("abort",e),c()},a);b?.addEventListener?.("abort",e,{once:!0})})}(l,c)}}},97210:(a,b,c)=>{"use strict";let{createInflateRaw:d,Z_DEFAULT_WINDOWBITS:e}=c(38522),{isValidClientWindowBits:f}=c(94050),{MessageSizeExceededError:g}=c(61448),h=Buffer.from([0,0,255,255]),i=Symbol("kBuffer"),j=Symbol("kLength");class k{#bT;#bS={};#br=0;constructor(a,b){this.#bS.serverNoContextTakeover=a.has("server_no_context_takeover"),this.#bS.serverMaxWindowBits=a.get("server_max_window_bits"),this.#br=b.maxPayloadSize}decompress(a,b,c){if(!this.#bT){let a=e;if(this.#bS.serverMaxWindowBits){if(!f(this.#bS.serverMaxWindowBits))return void c(Error("Invalid server_max_window_bits"));a=Number.parseInt(this.#bS.serverMaxWindowBits)}try{this.#bT=d({windowBits:a})}catch(a){c(a);return}this.#bT[i]=[],this.#bT[j]=0,this.#bT.on("data",a=>{if(this.#bT[j]+=a.length,this.#br>0&&this.#bT[j]>this.#br){c(new g),this.#bT.removeAllListeners(),this.#bT=null;return}this.#bT[i].push(a)}),this.#bT.on("error",a=>{this.#bT=null,c(a)})}this.#bT.write(a),b&&this.#bT.write(h),this.#bT.flush(()=>{if(!this.#bT)return;let a=Buffer.concat(this.#bT[i],this.#bT[j]);this.#bT[i].length=0,this.#bT[j]=0,c(null,a)})}}a.exports={PerMessageDeflate:k}},97356:(a,b,c)=>{"use strict";let{Transform:d}=c(57075),{isASCIINumber:e,isValidLastEventId:f}=c(26376),g=Buffer.from("data"),h=Buffer.from("event"),i=Buffer.from("id"),j=Buffer.from("retry");function k(a,b,c){if(b!==c.length)return!1;for(let d=0;d<b;d++)if(a[d]!==c[d])return!1;return!0}class l extends d{state;checkBOM=!0;crlfCheck=!1;eventEndCheck=!1;chunks=[];chunkIndex=0;pos=0;lineChunkIndex=0;linePos=0;event={data:void 0,event:void 0,id:void 0,retry:void 0};constructor(a={}){a.readableObjectMode=!0,super(a),this.state=a.eventSourceSettings||{},a.push&&(this.push=a.push)}_transform(a,b,c){if(0===a.length||(this.chunks.push(a),this.checkBOM&&this.handleBOM()))return void c();for(;this.hasCurrentByte();){let a=this.currentByte();if(this.eventEndCheck){if(this.crlfCheck){if(10===a){this.crlfCheck=!1,this.consumeCurrentByte();continue}this.crlfCheck=!1}if(10===a||13===a){13===a&&(this.crlfCheck=!0),this.consumeCurrentByte(),this.hasPendingEvent()&&this.processEvent(this.event),this.clearEvent();continue}this.eventEndCheck=!1;continue}if(10===a||13===a){13===a&&(this.crlfCheck=!0),this.parseLine(this.readLine(),this.event),this.consumeCurrentByte(),this.eventEndCheck=!0;continue}this.advanceCursor()}c()}parseLine(a,b){if(0===a.length)return;let c=a.indexOf(58);if(0===c)return;let d=a.length,e=a.length;if(-1!==c&&(d=c,32===a[e=c+1]&&++e),k(a,d,g)){let c=a.toString("utf8",e);void 0===b.data?b.data=c:b.data+=`
|
|
489
492
|
${c}`;return}if(k(a,d,j)){(function(a,b){if(b>=a.length)return!1;for(let c=b;c<a.length;c++)if(a[c]<48||a[c]>57)return!1;return!0})(a,e)&&(b.retry=a.toString("utf8",e));return}if(k(a,d,i)){(function(a,b){for(let c=b;c<a.length;c++)if(0===a[c])return!1;return!0})(a,e)&&(b.id=a.toString("utf8",e));return}if(k(a,d,h)){let c=a.toString("utf8",e);c.length>0&&(b.event=c)}}processEvent(a){a.retry&&e(a.retry)&&(this.state.reconnectionTime=parseInt(a.retry,10)),void 0!==a.id&&f(a.id)&&(this.state.lastEventId=a.id),void 0!==a.data&&this.push({type:a.event||"message",options:{data:a.data,lastEventId:this.state.lastEventId,origin:this.state.origin}})}clearEvent(){this.event.data=void 0,this.event.event=void 0,this.event.id=void 0,this.event.retry=void 0}hasPendingEvent(){return void 0!==this.event.data||void 0!==this.event.event||void 0!==this.event.id||void 0!==this.event.retry}hasCurrentByte(){return this.chunkIndex<this.chunks.length&&this.pos<this.chunks[this.chunkIndex].length}currentByte(){return this.chunks[this.chunkIndex][this.pos]}consumeCurrentByte(){this.advanceCursor(),this.syncLineStartToCursor()}advanceCursor(){for(this.pos++;this.chunkIndex<this.chunks.length&&this.pos>=this.chunks[this.chunkIndex].length;)this.chunkIndex++,this.pos=0}syncLineStartToCursor(){this.lineChunkIndex=this.chunkIndex,this.linePos=this.pos,this.dropConsumedChunks()}dropConsumedChunks(){for(;this.lineChunkIndex>0;)this.chunks.shift(),this.lineChunkIndex--,this.chunkIndex--;this.chunkIndex===this.chunks.length&&(this.chunks.length=0,this.chunkIndex=0,this.pos=0,this.lineChunkIndex=0,this.linePos=0)}readLine(){if(this.lineChunkIndex===this.chunkIndex)return this.chunks[this.chunkIndex].subarray(this.linePos,this.pos);let a=[],b=0;for(let c=this.lineChunkIndex;c<=this.chunkIndex;c++){let d=this.chunks[c],e=c===this.lineChunkIndex?this.linePos:0,f=c===this.chunkIndex?this.pos:d.length,g=d.subarray(e,f);b+=g.length,a.push(g)}return Buffer.concat(a,b)}peekBufferedByte(a){let b=this.lineChunkIndex,c=this.linePos;for(;b<this.chunks.length;){let d=this.chunks[b],e=d.length-c;if(a<e)return d[c+a];a-=e,b++,c=0}}discardLeadingBytes(a){for(;a>0&&this.lineChunkIndex<this.chunks.length;){let b=this.chunks[this.lineChunkIndex].length-this.linePos;a<b?(this.linePos+=a,a=0):(a-=b,this.lineChunkIndex++,this.linePos=0)}this.chunkIndex=this.lineChunkIndex,this.pos=this.linePos,this.dropConsumedChunks()}handleBOM(){let a=this.peekBufferedByte(0),b=this.peekBufferedByte(1),c=this.peekBufferedByte(2);return void 0===b?239===a||(this.checkBOM=!1,!0):void 0===c?239===a&&187===b||(this.checkBOM=!1,!1):(239===a&&187===b&&191===c&&this.discardLeadingBytes(3),this.checkBOM=!1,!this.hasCurrentByte())}}a.exports={EventSourceStream:l}},97465:(a,b,c)=>{"use strict";let d=c(34589),{AsyncResource:e}=c(16698),{InvalidArgumentError:f,SocketError:g}=c(61448),h=c(84285),{addSignal:i,removeSignal:j}=c(73135);class k extends e{constructor(a,b){if(!a||"object"!=typeof a)throw new f("invalid opts");if("function"!=typeof b)throw new f("invalid callback");const{signal:c,opaque:d,responseHeaders:e}=a;if(c&&"function"!=typeof c.on&&"function"!=typeof c.addEventListener)throw new f("signal must be an EventEmitter or EventTarget");super("UNDICI_CONNECT"),this.opaque=d||null,this.responseHeaders=e||null,this.callback=b,this.abort=null,i(this,c)}onRequestStart(a,b){this.reason?a.abort(this.reason):(d(this.callback),this.abort=b=>a.abort(b),this.context=b)}onResponseStart(){throw new g("bad connect",null)}onRequestUpgrade(a,b,c,d){let{callback:e,opaque:f,context:g}=this;j(this),this.callback=null;let i=c,k=a?.rawHeaders;null!=i&&(i="raw"===this.responseHeaders?h.parseRawHeaders(k):c),this.runInAsyncScope(e,null,null,{statusCode:b,headers:i,socket:d,opaque:f,context:g})}onResponseError(a,b){let{callback:c,opaque:d}=this;j(this),c&&(this.callback=null,queueMicrotask(()=>{this.runInAsyncScope(c,null,b,{opaque:d})}))}}a.exports=function a(b,c){if(void 0===c)return new Promise((c,d)=>{a.call(this,b,(a,b)=>a?d(a):c(b))});try{let a=new k(b,c),d={...b,method:"CONNECT"};this.dispatch(d,a)}catch(d){if("function"!=typeof c)throw d;let a=b?.opaque;queueMicrotask(()=>c(d,{opaque:a}))}}},97678:(a,b,c)=>{"use strict";let d,e=c(34589),f=c(84285),{channels:g}=c(62571),h=c(64704),{RequestContentLengthMismatchError:i,ResponseContentLengthMismatchError:j,RequestAbortedError:k,InvalidArgumentError:l,HeadersTimeoutError:m,HeadersOverflowError:n,SocketError:o,InformationalError:p,BodyTimeoutError:q,HTTPParserError:r,ResponseExceededMaxSizeError:s}=c(61448),{kUrl:t,kReset:u,kClient:v,kParser:w,kBlocking:x,kRunning:y,kPending:z,kSize:A,kWriting:B,kQueue:C,kNoRef:D,kKeepAliveDefaultTimeout:E,kHostHeader:F,kPendingIdx:G,kRunningIdx:H,kError:I,kPipelining:J,kSocket:K,kKeepAliveTimeoutValue:L,kMaxHeadersSize:M,kKeepAliveMaxTimeout:N,kKeepAliveTimeoutThreshold:O,kHeadersTimeout:P,kBodyTimeout:Q,kStrictContentLength:R,kMaxRequests:S,kCounter:T,kMaxResponseSize:U,kOnError:V,kResume:W,kHTTPContext:X,kClosed:Y}=c(49176),Z=c(65429),$=Buffer.alloc(0),_=Buffer[Symbol.species],aa=f.removeAllListeners,ab=Symbol("kIdleSocketValidation"),ac=Symbol("kIdleSocketValidationTimeout"),ad=Symbol("kSocketUsed"),ae=Symbol("kTypeOfService"),af=null,ag=null,ah=null,ai=0,aj=null,ak=null;class al{constructor(a,b,{exports:c}){this.llhttp=c,this.ptr=this.llhttp.llhttp_alloc(Z.TYPE.RESPONSE),this.client=a,this.socket=b,this.timeout=null,this.timeoutWeakRef=new WeakRef(this),this.timeoutValue=null,this.timeoutType=null,this.statusCode=0,this.statusText="",this.upgrade=!1,this.headers=[],this.headersSize=0,this.headersMaxSize=a[M],this.shouldKeepAlive=!1,this.paused=!1,this.resume=this.resume.bind(this),this.bytesRead=0,this.keepAlive="",this.contentLength=-1,this.connectionKeepAlive=!1,this.maxResponseSize=a[U]}setTimeout(a,b){a!==this.timeoutValue||1&b^1&this.timeoutType?(this.timeout&&(h.clearTimeout(this.timeout),this.timeout=null),a&&(1&b?this.timeout=h.setFastTimeout(am,a,this.timeoutWeakRef):(this.timeout=setTimeout(am,a,this.timeoutWeakRef),this.timeout?.unref())),this.timeoutValue=a):this.timeout&&this.timeout.refresh&&this.timeout.refresh(),this.timeoutType=b}resume(){!this.socket.destroyed&&this.paused&&(e(null!=this.ptr),e(null===ag),this.llhttp.llhttp_resume(this.ptr),e(5===this.timeoutType),this.timeout&&this.timeout.refresh&&this.timeout.refresh(),this.paused=!1,this.execute(this.socket.read()||$),this.readMore())}readMore(){for(;!this.paused&&this.ptr;){let a=this.socket.read();if(null===a)break;this.execute(a)}}execute(a){e(null===ag),e(null!=this.ptr),e(!this.paused);let{socket:b,llhttp:c}=this;a.length>ai&&(aj&&c.free(aj),ai=4096*Math.ceil(a.length/4096),aj=c.malloc(ai)),(null===ak||ak.buffer!==c.memory.buffer||ak.byteOffset!==aj||ak.byteLength!==ai)&&(ak=new Uint8Array(c.memory.buffer,aj,ai)),ak.set(a);try{let d;try{ah=a,ag=this,d=c.llhttp_execute(this.ptr,aj,a.length)}finally{ag=null,ah=null}if(d!==Z.ERROR.OK){let e=a.subarray(c.llhttp_get_error_pos(this.ptr)-aj);if(d===Z.ERROR.PAUSED_UPGRADE)this.onUpgrade(e);else if(d===Z.ERROR.PAUSED)this.paused=!0,b.unshift(e);else throw this.createError(d,e)}}catch(a){f.destroy(b,a)}}finish(){let a;e(null===ag),e(null!=this.ptr);let{llhttp:b}=this;if(this.paused){let a;do b.llhttp_resume(this.ptr),this.paused=!1,a=this.socket.read()||$,this.execute(a);while(this.paused&&a.length>0);this.paused&&(b.llhttp_resume(this.ptr),this.paused=!1)}try{ag=this,a=b.llhttp_finish(this.ptr)}finally{ag=null}return a===Z.ERROR.OK?null:a===Z.ERROR.PAUSED||a===Z.ERROR.PAUSED_UPGRADE?(this.paused=!0,null):this.createError(a,$)}createError(a,b){let{llhttp:c,contentLength:d,bytesRead:e}=this;if(-1!==d&&e!==d)return new j;let f=c.llhttp_get_error_reason(this.ptr),g="";if(f){let a=new Uint8Array(c.memory.buffer,f).indexOf(0);g="Response does not match the HTTP/1.1 protocol ("+Buffer.from(c.memory.buffer,f,a).toString()+")"}return new r(g,Z.ERROR[a],b)}destroy(){e(null===ag),e(null!=this.ptr),this.llhttp.llhttp_free(this.ptr),this.ptr=null,this.timeout&&h.clearTimeout(this.timeout),this.timeout=null,this.timeoutValue=null,this.timeoutType=null,this.paused=!1}onStatus(a){return this.statusText=a.toString(),0}onMessageBegin(){let{socket:a,client:b}=this;if(a.destroyed)return -1;if(0===b[y])return f.destroy(a,new o("bad response",f.getSocketInfo(a))),-1;let c=b[C][b[H]];return c?(c.onResponseStarted(),0):-1}onHeaderField(a){let b=this.headers.length;return(1&b)==0?this.headers.push(a):this.headers[b-1]=Buffer.concat([this.headers[b-1],a]),this.trackHeader(a.length),0}onHeaderValue(a){let b=this.headers.length;(1&b)==1?(this.headers.push(a),b+=1):this.headers[b-1]=Buffer.concat([this.headers[b-1],a]);let c=this.headers[b-2];if(10===c.length){let d=f.bufferToLowerCasedHeaderName(c);"keep-alive"===d?this.keepAlive+=a.toString():"connection"===d&&(this.connectionKeepAlive=10===this.headers[b-1].length&&"keep-alive"===f.bufferToLowerCasedHeaderName(this.headers[b-1]))}else if(14===c.length&&"content-length"===f.bufferToLowerCasedHeaderName(c)){-1===this.contentLength&&(this.contentLength=0);for(let b=0;b<a.length;b++)this.contentLength=10*this.contentLength+(a[b]-48)}return this.trackHeader(a.length),0}trackHeader(a){this.headersSize+=a,this.headersSize>=this.headersMaxSize&&f.destroy(this.socket,new n)}onUpgrade(a){let{upgrade:b,client:c,socket:d,headers:g,statusCode:h}=this;e(b),e(c[K]===d),e(!d.destroyed),e(!this.paused),e((1&g.length)==0);let i=c[C][c[H]];e(i),e(i.upgrade||"CONNECT"===i.method),this.statusCode=0,this.statusText="",this.shouldKeepAlive=!1,this.headers=[],this.headersSize=0,d.unshift(a),d[w].destroy(),d[w]=null,d[v]=null,d[I]=null,aa(d),c[K]=null,c[X]=null,c[C][c[H]++]=null,c.emit("disconnect",c[t],[c],new p("upgrade"));try{i.onRequestUpgrade(h,g,d)}catch(a){f.destroy(d,a)}c[W]()}onHeadersComplete(a,b,c){let{client:d,socket:g,headers:h,statusText:i}=this;if(g.destroyed)return -1;if(0===d[y])return f.destroy(g,new o("bad response",f.getSocketInfo(g))),-1;let j=d[C][d[H]];if(!j)return -1;if(e(!this.upgrade),e(this.statusCode<200),100===a)return f.destroy(g,new o("bad response",f.getSocketInfo(g))),-1;if(b&&!j.upgrade)return f.destroy(g,new o("bad upgrade",f.getSocketInfo(g))),-1;if(e(3===this.timeoutType),this.statusCode=a,this.shouldKeepAlive=c||"HEAD"===j.method&&!g[u]&&this.connectionKeepAlive,this.statusCode>=200){let a=null!=j.bodyTimeout?j.bodyTimeout:d[Q];this.setTimeout(a,5)}else this.timeout&&this.timeout.refresh&&this.timeout.refresh();if("CONNECT"===j.method||b)return e(1===d[y]),this.upgrade=!0,2;if(e((1&this.headers.length)==0),this.headers=[],this.headersSize=0,this.shouldKeepAlive&&d[J]){let a=this.keepAlive?f.parseKeepAliveTimeout(this.keepAlive):null;if(null!=a){let b=Math.min(a-d[O],d[N]);b<=0?g[u]=!0:d[L]=b}else d[L]=d[E]}else g[u]=!0;let k=!1===j.onResponseStart(a,h,this.resume,i);return j.aborted?-1:"HEAD"===j.method||a<200?1:(g[x]&&(g[x]=!1,d[W]()),k?Z.ERROR.PAUSED:0)}onBody(a){let{client:b,socket:c,statusCode:d,maxResponseSize:g}=this;if(c.destroyed)return -1;let h=b[C][b[H]];return(e(h),e(5===this.timeoutType),this.timeout&&this.timeout.refresh&&this.timeout.refresh(),e(d>=200),g>-1&&this.bytesRead+a.length>g)?(f.destroy(c,new s),-1):(this.bytesRead+=a.length,!1===h.onResponseData(a))?Z.ERROR.PAUSED:0}onMessageComplete(){let{client:a,socket:b,statusCode:c,upgrade:d,headers:g,contentLength:h,bytesRead:i,shouldKeepAlive:k}=this;if(b.destroyed&&(!c||k))return -1;if(d)return 0;e(c>=100),e((1&this.headers.length)==0);let l=a[C][a[H]];return(e(l),this.statusCode=0,this.statusText="",this.bytesRead=0,this.contentLength=-1,this.keepAlive="",this.connectionKeepAlive=!1,this.headers=[],this.headersSize=0,c<200)?0:"HEAD"!==l.method&&-1!==h&&i!==h?(f.destroy(b,new j),-1):(l.onResponseEnd(g),a[C][a[H]++]=null,b[ad]=0===a[z],b[B])?(e(0===a[y]),f.destroy(b,new p("reset")),Z.ERROR.PAUSED):k?b[u]&&0===a[y]?(f.destroy(b,new p("reset")),Z.ERROR.PAUSED):(null==a[J]||1===a[J]?setImmediate(a[W]):a[W](),0):(f.destroy(b,new p("reset")),Z.ERROR.PAUSED)}}function am(a){let b=a.deref();if(!b)return;let{socket:c,timeoutType:d,client:g,paused:h}=b;3===d?(!c[B]||c.writableNeedDrain||g[y]>1)&&(e(!h,"cannot be paused while waiting for headers"),f.destroy(c,new m)):5===d?h||f.destroy(c,new q):8===d&&(e(0===g[y]&&g[L]),f.destroy(c,new p("socket idle timeout")))}function an(a){e("ERR_TLS_CERT_ALTNAME_INVALID"!==a.code);let b=this[w];if("ECONNRESET"===a.code&&b.statusCode&&!b.shouldKeepAlive){let a=b.finish();a&&(this[I]=a,this[v][V](a));return}this[I]=a,this[v][V](a)}function ao(){this[w]?.readMore()}function ap(){let a=this[w];if(a.statusCode&&!a.shouldKeepAlive){let b=a.finish();b&&f.destroy(this,b);return}f.destroy(this,new o("other side closed",f.getSocketInfo(this)))}function aq(){let a=this[w];as(this),a&&(this[I]||!a.statusCode||a.shouldKeepAlive||(this[I]=a.finish()||this[I]),this[w].destroy(),this[w]=null);let b=this[I]||new o("closed",f.getSocketInfo(this)),c=this[v];if(c[K]=null,c[X]=null,c.destroyed){e(0===c[z]);let a=c[C].splice(c[H]);for(let d=0;d<a.length;d++){let e=a[d];f.errorRequest(c,e,b)}}else if(c[y]>0&&"UND_ERR_INFO"!==b.code){let a=c[C][c[H]];c[C][c[H]++]=null,f.errorRequest(c,a,b)}c[G]=c[H],e(0===c[y]),c.emit("disconnect",c[t],[c],b),c[W]()}function ar(){this[Y]=!0}function as(a){a[ac]&&(clearTimeout(a[ac]),a[ac]=null),a[ab]=0}function at(a,b,c,d,g,h,i,j){try{b?f.isBuffer(b)&&(e(h===b.byteLength,"buffer body must have content length"),g.cork(),g.write(`${i}content-length: ${h}\r
|
|
490
493
|
\r
|
|
491
494
|
`,"latin1"),g.write(b),g.uncork(),d.onBodySent(b),j||!1===d.reset||(g[u]=!0)):0===h?g.write(`${i}content-length: 0\r
|