@cortexkit/opencode-openai-auth 1.19.0 → 1.19.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +2 -2
- package/dist/{index-cawk490s.js → index-1ttg64ny.js} +2 -2
- package/dist/index-34r6y4jf.js +64 -0
- package/dist/{index-gqnca0gh.js → index-3wr1ebxp.js} +2 -2
- package/dist/{index-hrv1msdb.js → index-62xhtkv8.js} +1 -1
- package/dist/{index-raj3tyyz.js → index-663p60em.js} +1 -1
- package/dist/{index-aew7mcfy.js → index-8km6f9bq.js} +2 -2
- package/dist/{index-6tgra34y.js → index-977gx5br.js} +2 -2
- package/dist/{index-r3vc66vz.js → index-ckkhe4r4.js} +19 -19
- package/dist/{index-3b9e26wv.js → index-hsrx1pkq.js} +2 -2
- package/dist/{index-a4cgsngv.js → index-jk0zyyny.js} +2 -2
- package/dist/{index-12gxtre8.js → index-kgzevj7y.js} +1 -1
- package/dist/{index-hnb97ydy.js → index-mbxq1g4n.js} +1 -1
- package/dist/{index-v2wvavef.js → index-nrkvrvpw.js} +2 -2
- package/dist/{index-h7xxfm12.js → index-r6k6hh93.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/token-util-kwahm03g.js +1 -0
- package/dist/{token-kdjmv82a.js → token-y3kre94n.js} +1 -1
- package/dist/tui-preferences.js +1 -1
- package/dist/v2/server.js +4 -4
- package/package.json +8 -8
- package/src/tui-compiled/raw/shared/a75d0d866c227b3f-index.tsx +129 -18
- package/src/tui-compiled/runtime/shared/a75d0d866c227b3f-index.js +324 -187
- package/dist/index-7ztbemxe.js +0 -64
- package/dist/token-util-71r7z2vr.js +0 -1
package/dist/index-7ztbemxe.js
DELETED
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import{$a as AY,$b as x6,Aa as MZ,Ab as F4,Ac as yZ,Bb as D4,Bc as fZ,Ca as dz,Cb as D3,Cc as aZ,Da as iz,Dc as jW,Ea as QY,Ec as tZ,Fa as GY,Fb as wZ,Fc as eZ,Ga as OW,Gb as O3,Gc as _W,Ha as I7,Ia as vY,Ja as S7,Ka as b7,Lb as GW,Mb as b2,Nb as j4,Ob as k2,Pa as k7,Pb as x2,Qa as x7,Ra as v7,Rb as IZ,Sa as h7,Ta as UW,Tb as c6,Ua as V8,Va as $4,Vb as F8,Wa as W6,Xa as PY,Xb as uX,Ya as R6,Yb as IY,Za as MY,Zb as K8,_a as EY,_b as bZ,ab as TY,bb as RY,bc as f7,cb as TZ,cc as B7,db as RZ,dc as K7,eb as VJ,ec as g7,fb as NJ,fc as kZ,gc as l3,hb as YW,hc as xZ,ib as JW,ic as a8,jb as L3,jc as zY,kb as F3,kc as q4,lb as CZ,lc as P4,mb as O4,mc as Z8,nc as r2,oa as W8,ob as BJ,oc as t8,pa as d8,pb as D8,pc as d3,qa as VZ,qb as l2,qc as m7,ra as O1,rb as d2,sa as pz,sb as i2,ta as s2,tb as n2,tc as vZ,ub as o2,uc as g6,va as n,vb as XW,wa as DW,wb as $W,xb as QW,yb as L8,yc as hZ,zb as S2}from"./index-r3vc66vz.js";import{Kc as C3,Mc as v2,Oc as u1,Pc as gZ,Sc as mZ,Wc as RW,Xc as cZ,Yc as uZ,Zc as i3,cd as WY,dd as ZY,ed as pZ,fd as lZ,id as dZ,jd as iZ,kd as nZ,md as _4,nd as U9,od as oZ,pd as rZ,qd as P6,rd as sZ}from"./index-gqnca0gh.js";import{$e as o1,Ae as A7,Af as t0,Bd as z8,Be as T7,Bf as S6,Ce as R7,Cf as xY,De as C7,Ee as w7,Fe as G4,Ff as PZ,Ge as a1,Gf as B8,Hd as _8,He as w8,Hf as V1,Id as uz,Ie as Iz,If as C1,Je as u0,Jf as nz,Ke as NZ,Kf as C9,Le as S9,Lf as EZ,Md as B3,Me as e8,Ne as LZ,Nf as oz,Of as rz,Pd as mX,Pe as FZ,Qe as G1,Qf as AZ,Re as m8,Rf as sz,Se as Z6,Sf as K3,Te as p9,Tf as az,Ue as J8,Uf as tz,Ve as c8,Vf as ez,Wd as I2,We as l9,Wf as R3,Xd as O7,Xe as EX,Yd as _7,Ye as w6,Zd as Q4,Ze as Q8,_e as hX,af as r8,bf as KW,cf as y1,df as cX,ef as o0,fe as q7,ff as X8,gf as DZ,jf as V7,kf as k6,lf as OZ,mf as z4,ne as H7,of as j3,pe as Z9,pf as b9,qe as KZ,qf as N3,re as s1,rf as o6,se as p3,sf as K4,te as jZ,tf as U6,ue as P7,uf as l1,ve as M7,vf as _Z,we as W1,wf as qZ,xe as Z1,xf as p2,ye as b6,yf as lz,zd as t1,ze as E7,zf as f1}from"./index-a4cgsngv.js";import{$f as N4,eg as gX}from"./index-v2wvavef.js";import{jg as B2,kg as K2,lg as j2,mg as gW,ng as BZ,og as g1,pg as mW,qg as cW}from"./index-6tgra34y.js";import{Dg as A8,Fg as y7}from"./index-12gxtre8.js";import{Gg as a7,Jg as B4,Lg as W0}from"./index-cawk490s.js";import{Mg as m1,Ng as J9,Rg as n7,Sg as o7,Tg as mY,Ug as r7,Xg as s7}from"./index-aew7mcfy.js";import{$g as SZ,Zg as N2}from"./index-hrv1msdb.js";import{bh as OJ}from"./index-h7xxfm12.js";import{randomUUID as QZ}from"node:crypto";import{statSync as $F}from"node:fs";import g3 from"node:os";import{isDeepStrictEqual as vU}from"node:util";var AX={hosts:"OpenCode 1, OpenCode 2 and Pi",project:"user-only"},v1={...AX,overrides:{host:!0}},h1={hosts:"OpenCode 1 and OpenCode 2",project:"user-only"},g8={hosts:"OpenCode 1 only",project:"user-only"},TX=(Y,J)=>Y.flatMap((X)=>J.map(($)=>({source:X,path:$}))),q1=(...Y)=>TX(["opencode-store","pi-store"],Y),n0=(...Y)=>TX(["opencode-store"],Y),q0=EX({plugin:"openai-auth",settings:{routing_mode:{...v1,value:J8(["ordered","main-first","fallback-first","sticky-balanced"]),default:"main-first",legacy:q1(["routing","mode"])},max_same_account_wait:{...v1,value:J8(["off","15m","cache"]),default:"15m",legacy:q1(["routing","maxSameAccountWait"])},fallback_on:{...v1,hosts:"OpenCode 1 and Pi; not read by OpenCode 2",value:c8(m8()),default:[401,403,429],legacy:q1(["fallbackOn"])},refresh_enabled:{...g8,hosts:"OpenCode 1 legacy fallback refresh only",value:G1(),default:!0,legacy:n0(["refresh","enabled"])},refresh_before_expiry_minutes:{...v1,value:Z6(),default:240,legacy:q1(["refresh","refreshBeforeExpiryMinutes"])},quota_enabled:{...v1,value:G1(),default:!0,legacy:q1(["quota","enabled"])},quota_check_interval_minutes:{...g8,hosts:"OpenCode 1 legacy quota freshness and polling only",value:Z6({min:1}),default:5,legacy:n0(["quota","checkIntervalMinutes"])},quota_minimum_remaining:{...v1,value:c8(l9({window:J8(["primary","secondary"]),floor:Z6()})),default:[],legacy:q1(["quota","minimumRemaining","primary"],["quota","minimumRemaining","5h"],["quota","minimumRemaining","secondary"],["quota","minimumRemaining","1w"])},quota_fail_closed_on_unknown:{...v1,value:G1(),default:!1,legacy:q1(["quota","failClosedOnUnknownQuota"])},cost_zeroing:{...g8,value:G1(),default:!0,legacy:n0(["costZeroing","enabled"])},killswitch_enabled:{...v1,value:G1(),default:!1,legacy:q1(["killswitch","enabled"])},killswitch_default_primary:{...v1,value:Z6(),default:5,legacy:q1(["killswitch","defaults","primary"],["killswitch","main","primary"],["killswitch","main","5h"])},killswitch_default_secondary:{...v1,value:Z6(),default:10,legacy:q1(["killswitch","defaults","secondary"],["killswitch","main","secondary"],["killswitch","main","1w"])},killswitch_account_floors:{...AX,value:c8(l9({account:p9(),host:J8(["opencode","pi","both"]),primary:Z6(),secondary:Z6()})),default:[],legacy:q1(["killswitch","accounts"])},cache_keep_enabled:{...h1,value:G1(),default:!1,legacy:n0(["cacheKeep","enabled"],["cachekeep","enabled"])},cache_keep_subagents:{...h1,value:G1(),default:!1,legacy:n0(["cacheKeep","subagents"],["cachekeep","subagents"])},cache_keep_sustain:{...h1,value:G1(),default:!1,legacy:n0(["cacheKeep","sustain"],["cachekeep","sustain"])},cache_keep_window:{...h1,value:c8(l9({start_hour:m8({min:0,max:23}),end_hour:m8({min:0,max:23})})),default:[],legacy:n0(["cacheKeep","startHour"],["cacheKeep","endHour"],["cachekeep","startHour"],["cachekeep","endHour"])},log_level:{...h1,value:J8(["error","warn","info","debug","trace","default"]),default:"default",legacy:n0(["logging","level"])},request_dumps:{...h1,value:G1(),default:!1,legacy:n0(["dump"],["dump","enabled"])},dump_dir:{...h1,value:p9(),default:"",legacy:n0(["dumpDir"])},dump_max_bytes:{...h1,value:m8({min:0,max:Number.MAX_SAFE_INTEGER}),default:536870912,legacy:n0(["dumpMaxBytes"])},web_sockets:{...g8,value:G1(),default:!1,legacy:n0(["webSockets"])},raw_web_socket:{...g8,value:G1(),default:!1,legacy:n0(["rawWebSocket"])},responses_lite:{...h1,value:G1(),default:!1,legacy:n0(["responsesLite"])},codex_api_endpoint:{...h1,value:p9(),default:"https://chatgpt.com/backend-api/codex/responses",legacy:n0(["codexApiEndpoint"])}}});import{chmod as wU,mkdir as IU}from"node:fs/promises";import{join as SU}from"node:path";import{existsSync as wX,readFileSync as FU}from"node:fs";import{readFileSync as jU}from"node:fs";var RX="Settings moved to ";function NU(Y){let J=Y.split(/\r?\n/,1)[0]??"";if(!J.startsWith(RX)||!J.endsWith("."))return;return J.slice(RX.length,-1)}function LU(Y){try{return NU(jU(`${Y}.MOVED_READPLEASE`,"utf8"))}catch{return}}function CX(Y,J){let X=LU(Y);return X!==void 0&&o1(X)===o1(J)}function DU(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function OU(Y,J){let X=Y;for(let[$,Q]of J.entries()){if(!DU(X)||!Object.hasOwn(X,Q))return!1;if($===J.length-1)return!0;X=X[Q]}return!1}function _U(Y,J){return Object.values(q0.settings).some((X)=>X.legacy.some(($)=>$.source===`${J}-store`&&OU(Y,$.path)))}function qU(Y){try{return _U(JSON.parse(FU(Y.configPath,"utf8")),Y.host)}catch{return!1}}function d9(Y){let J=wX(Y.target),X=Y.sources.some((W)=>CX(W.configPath,Y.target)),$=Y.sources.filter((W)=>wX(W.configPath)),Q=$.length>0,G=X&&!J,z=J&&!X&&$.some(qU);return{kind:J?"target-exists":X?"target-removed":Q?"move-needed":"no-source",completed:J||X,targetExists:J,noteNamesTarget:X,sourcePresent:Q,preExistingFile:z,removedFile:G}}function i9(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function IX(Y){try{let J=Number(Y);return Number.isFinite(J)?Math.min(100,Math.max(0,J)):0}catch{return 0}}function CY(Y,J){let X=U6(Y,J);return{primary:IX(X.primary),secondary:IX(X.secondary)}}function SX(Y,J,X,$){if(!i9(Y))return;for(let Q of["primary","secondary","5h","1w"])if(Y[Q]===null)$.push({source:X,key:`${J}.${Q}`,reason:"invalid"})}function bX(Y){let J={entries:[],unmapped:[]},X=[],$=[];Y.forEach((z,W)=>{if(!z.present)return;if(z.host!=="opencode"&&z.host!=="pi")throw Error("Unsupported killswitch floors source host");let U=z.host,H=i9(z.value)?z.value:{},V=i9(H.killswitch)?H.killswitch:void 0,F={killswitch:H.killswitch},j=V?.schema===X8,K=j?CY({killswitch:{...V,accounts:void 0}}):CY(F);if(X.push({source:W,floors:K}),!j)SX(V?.main,"killswitch.main",W,J.unmapped);if(!i9(V?.accounts))return;for(let L of Object.keys(V.accounts)){let O=`killswitch.accounts.${L}`;if(!j&&L==="main"){J.unmapped.push({source:W,key:O,reason:"shadowed"});continue}if(!j)SX(V.accounts[L],O,W,J.unmapped);$.push({account:L,host:U,...CY(F,L==="main"?void 0:L)})}});for(let[z,W]of[["primary",5],["secondary",10]]){if(X.every(({floors:U})=>U[z]===W))continue;for(let{source:U,floors:H}of X)J.entries.push({source:U,setting:`killswitch_default_${z}`,value:H[z]})}let Q=[];for(let z of $){let W=z.account.startsWith("vault:")?Q.find((U)=>U.account===z.account&&U.host!==z.host&&U.primary===z.primary&&U.secondary===z.secondary):void 0;if(W)W.host="both";else Q.push(z)}let G=X[0];if(G&&Q.length>0)J.entries.push({source:G.source,setting:"killswitch_account_floors",value:Q});return J}function H6(Y){if(Y===null||typeof Y!=="object"||Array.isArray(Y))return!1;let J=Object.getPrototypeOf(Y);return J===Object.prototype||J===null}function kX(Y){let J;try{J=JSON.parse(Y)}catch{throw Error("Settings source is not JSON")}if(!H6(J))throw Error("Settings source is not an object");return J}function $8(Y,J){let X=Y;for(let $ of J){if(!H6(X)||!Object.hasOwn(X,$))return;X=X[$]}return X}function u8(Y,J,X=!1){switch(Y.kind){case"boolean":return typeof J==="boolean";case"string":return typeof J==="string";case"integer":case"number":return typeof J==="number"&&Number.isFinite(J)&&(Y.kind!=="integer"||Number.isInteger(J))&&(Y.min===void 0||J>=Y.min)&&(Y.max===void 0||J<=Y.max);case"oneOf":return typeof J==="string"&&Y.values.includes(J);case"list":return Array.isArray(J)&&Array.from(J).every(($)=>u8(Y.item,$,!0));case"object":return H6(J)&&Object.entries(J).every(([$,Q])=>{let G=Y.fields[$];return Object.hasOwn(Y.fields,$)&&G!==void 0&&u8(G,Q,X)})&&(!X||Object.keys(Y.fields).every(($)=>Object.hasOwn(J,$)));case"record":return H6(J)&&Object.values(J).every(($)=>u8(Y.value,$,!0))}}class o9 extends Error{setting;key;constructor(Y,J){super(`Cannot move setting ${Y}${J?` (${J})`:""}`);this.setting=Y;this.key=J;this.name="CannotMoveSettingError"}}function n9(Y,J){throw new o9(Y,J)}function xX(Y,J,X){try{let $=Number(Y);if(Number.isFinite($))return $}catch{}return n9(J,X)}function PU(Y,J){let X=[];for(let[$,Q]of[["primary","5h"],["secondary","1w"]]){let G=["quota","minimumRemaining"],z=$8(Y,[...G,$]),W=$8(Y,[...G,Q]);for(let[H,V]of[[$,z],[Q,W]])if(V===null)J([...G,H].join("."),"invalid");if(z!=null&&W!=null)J([...G,Q].join("."),"shadowed");let U=z??W;if(U==null)continue;X.push({window:$,floor:xX(U,"quota_minimum_remaining",[...G,$].join("."))})}return X}function MU(Y,J,X){let $=$8(Y,[J,"startHour"]),Q=$8(Y,[J,"endHour"]);if($===void 0&&Q===void 0)return[];let G,z;try{G=Number($),z=Number(Q)}catch{G=Number.NaN,z=Number.NaN}if(Number.isInteger(G)&&G>=0&&G<=23&&Number.isInteger(z)&&z>=0&&z<=23&&G!==z)return[{start_hour:G,end_hour:z}];if($!==void 0)X(`${J}.startHour`,"invalid");if(Q!==void 0)X(`${J}.endHour`,"invalid");return[]}function EU(Y,J,X){let $=q0.settings[Y],Q=$.default;if(Y==="quota_minimum_remaining")return PU(J,X);let G=H6(J.cacheKeep)?"cacheKeep":"cachekeep";if(Y==="cache_keep_window")return MU(J,G,X);let z=$.legacy[0];if(!z)return n9(Y);let W=z.path;if(Y.startsWith("cache_keep_"))W=[G,...W.slice(1)];if(Y==="request_dumps")W=typeof J.dump==="boolean"?["dump"]:["dump","enabled"];let U=$8(J,W),H=W.join(".");if(U===void 0)return Q;if(Y==="max_same_account_wait"){if(U===0)return"off";if(U===15)return"15m";if(U==="max")return"cache"}else if(Y==="fallback_on"){if(Array.isArray(U)){let V=U.filter((F)=>Number.isInteger(F));if(V.length!==U.length)X(H,"invalid");return V.length?V:Q}}else if(Y==="refresh_before_expiry_minutes"||Y==="quota_check_interval_minutes"){if(U!=null){let V=xX(U,Y,H);return Y==="quota_check_interval_minutes"?Math.max(1,V):V}}else if(Y==="quota_fail_closed_on_unknown"){if(U!=null)return Boolean(U)}else if(Y==="dump_dir"||Y==="codex_api_endpoint"){if(typeof U==="string"&&U.trim())return U.trim()}else if(u8($.value,U))return U;return X(H,"invalid"),Q}var AU=new Set(["version","accounts","main","commonAuthPool","commonAuthLimits","openaiAuthPool","mainAccountId","reset","claustrum"]),TU=new Set(["refresh.mainLastRefreshError","refresh.mainRefreshLeaseId","refresh.mainRefreshLeaseUntil","refresh.mainRefreshLeaseTokenHash","quota.mainQuota","quota.mainQuotaCheckedAt","quota.mainQuotaToken","quota.mainLastQuotaApiError"]);function RU(Y,J,X){let $=new Set;for(let G of Object.values(q0.settings))for(let z of G.legacy){let W=z.path.join(".");if($.add(W),J==="pi"&&!G.legacy.some((U)=>U.source==="pi-store")&&$8(Y,z.path)!==void 0){if(W==="dump.enabled"&&Object.hasOwn(Y,"dump"))continue;X(W,"other-host")}}let Q=(G,z="")=>{for(let[W,U]of Object.entries(G)){let H=z?`${z}.${W}`:W;if(!z&&AU.has(W)||TU.has(H)||H==="killswitch.schema")continue;if($.has(H))continue;if([...$].some((V)=>V.startsWith(`${H}.`)))if(H6(U))Q(U,H);else X(H,"invalid");else X(H,"retired")}};if(Q(Y),J==="opencode"&&H6(Y.cacheKeep)&&Y.cachekeep!==void 0)X("cachekeep","shadowed")}function vX(Y){let J={entries:[],unmapped:[]},X=Y.flatMap((Q,G)=>{if(!Q.present)return[];if(Q.host!=="opencode"&&Q.host!=="pi")throw Error("Unsupported settings source host");if(!H6(Q.value))throw Error("Settings source is not an object");let z=(W,U)=>{if(!J.unmapped.some((H)=>H.source===G&&H.key===W&&H.reason===U))J.unmapped.push({source:G,key:W,reason:U})};return RU(Q.value,Q.host,z),[{source:G,host:Q.host,store:Q.value,report:z}]});for(let Q of Object.keys(q0.settings)){if(Q.startsWith("killswitch_default_")||Q==="killswitch_account_floors")continue;let G=q0.settings[Q],z=X.filter((W)=>G.legacy.some((U)=>U.source===`${W.host}-store`)).map((W)=>({source:W.source,value:EU(Q,W.store,W.report)}));if(z.every((W)=>JSON.stringify(W.value)===JSON.stringify(G.default)))continue;for(let W of z)J.entries.push({...W,setting:Q})}let $=bX(Y);J.entries.push(...$.entries),J.unmapped.push(...$.unmapped);for(let Q of J.entries){if(!Object.hasOwn(q0.settings,Q.setting))n9(Q.setting);if(!u8(q0.settings[Q.setting].value,Q.value))n9(Q.setting)}return J}class wY extends Error{host;path;code;constructor(Y,J,X){super(`Settings source ${Y} ${J}: ${X}`);this.host=Y;this.path=J;this.code=X}}function yX(Y){let J=Y?.code;return typeof J==="string"&&/^[A-Z][A-Z0-9_]*$/.test(J)?J:"SETTINGS_MOVE_FAILED"}function CU(Y,J){if(Y instanceof wY)return{kind:"cause",host:Y.host,path:Y.path,code:Y.code};if(Y instanceof o9)return{kind:"setting",setting:Y.setting};let X=Y?.path,$=J.find((G)=>G.path===X),Q=yX(Y);if($)return{kind:"cause",host:$.host,path:$.path,code:Q};return{kind:"cause",code:Q}}async function fX({install:Y,fence:J,log:X}){if(Y.separate||Y.sources.length===0)return;let $=[...Y.sources].sort((G,z)=>Number(G.host==="pi")-Number(z.host==="pi")).map((G)=>({host:G.host,path:G.configPath,locks:[{path:G.configPath,name:"save"},{path:G.statePath,name:"save"}],read(z){try{return kX(z)}catch(W){throw new wY(G.host,G.configPath,W instanceof Error&&W.message==="Settings source is not JSON"?"SOURCE_NOT_JSON":"SOURCE_NOT_OBJECT")}}})),Q=await hX({definition:q0,target:Y.target,separateInstall:!1,sources:$,map:vX,fence:J,log:{warn(){},info(){}}});for(let G of Q.unmapped)X.warn(`Settings move: ${$[G.source]?.host??"unknown"} ${G.key}: ${G.reason}`);for(let G of Q.noteFailures){let z=$.find((W)=>`${W.path}.MOVED_READPLEASE`===G.path);X.warn(`Settings move note: ${z?.host??"unknown"} ${G.path}: ${yX(G.error)}`)}if(Q.outcome==="failed"){Q.failure=CU(Q.cause,$);let G=Q.failure;X.warn(G.kind==="setting"?`Settings move failed: cannot move setting ${G.setting}`:("host"in G)?`Settings move failed: ${G.host} ${G.path}: ${G.code}`:`Settings move failed: ${G.code}`)}return Q}class s9 extends Error{folder;constructor(Y,J){let X=J instanceof Error?J.message:String(J);super(`Cannot record settings authority in ${Y}: ${X}`,{cause:J});this.folder=Y;this.name="SettingsAuthorityRefusal"}}var pX=Symbol.for("@cortexkit/openai-auth/settings-authority"),lX=globalThis,r9=lX[pX]??new Map;lX[pX]=r9;function p8(Y){return r9.get(o1(Y))}function dX(Y){let J=o1(Y.install.configIdentity),X=r9.get(J);if(X)return X;let $=Promise.resolve().then(()=>bU(Y));return r9.set(J,$),$}async function bU({install:Y,stateHome:J,record:X,log:$,fenceOptions:Q}){let G={decision:Y.separate?"separate":"shared",install:Y,ranMove:!1},z=()=>{return cX(Y.configIdentity,G.decision),G};if(Y.separate){try{await X("separate")}catch{}return z()}let W=uX(J),U=()=>{return G.completion=d9(Y),G.completion},H=(V)=>V.completed||!V.sourcePresent;try{return await IU(W,{recursive:!0,mode:448}),await wU(W,448),await gX(SU(W,"settings-authority"),{name:"settings-authority",...mX},async(V)=>{if(!H(U()))if(G.fence=await IY({...Q,stateHome:J}),G.fence.open){G.ranMove=!0;try{G.move=await fX({install:Y,log:$,async fence(){let K=await IY({...Q,stateHome:J});if(!K.open)G.fence=K;return K.open}})}catch(K){G.move={outcome:"failed",cause:K,unmapped:[],differing:[],noteFailures:[],postPublishFailures:[],failure:{kind:"cause",code:"SETTINGS_MOVE_FAILED"}}}let F=G.move?.outcome,j=U();G.decision=F==="moved"||F==="done-already"||F==="aborted-target-appeared"||j.completed?"shared":"legacy"}else G.decision="legacy";await V.assertOwned(),await X(G.decision)}),z()}catch(V){if(!H(U()))throw new s9(W,V);return G.decision="shared",z()}}var C6=Object.freeze({file:(Y)=>`Settings file: ${Y}`,separate:"Settings stay in this install's account store.",legacyProcess:"Settings stay in the old account store because another process still uses it.",legacyBusy:"Settings stay in the old account store because the stores were busy.",legacySetting:(Y)=>`Settings stay in the old account store because ${Y} couldn't be moved.`,legacyFailed:(Y)=>`Settings stay in the old account store because the move failed: ${Y}.`,sharedMissing:"No settings file, so defaults are in use.",sharedMoved:"Settings were moved to the settings file in this process.",sharedFound:"Settings file found.",preExistingFile:(Y)=>`Settings come from ${Y}. Preferences in the old account store weren't copied, because this file already existed.`,removedFile:(Y)=>`The settings file ${Y} was removed, so defaults are in use. Old preferences aren't copied again.`,refused:(Y,J)=>`openai-auth didn't start. Process records folder: ${Y}. Cause: ${J}`,report:{"unknown-key":(Y)=>`Unknown settings key: ${Y}.`,"override-not-allowed":(Y)=>`Settings override not allowed: ${Y}.`,"user-only-in-project":(Y)=>`User-only setting found in a project file: ${Y}.`,"invalid-value":(Y)=>`Invalid settings value: ${Y}.`,"invalid-schema-version":(Y)=>`Invalid settings schema version: ${Y}.`,"newer-version-key-ignored":(Y)=>`Settings key from a newer version ignored: ${Y}.`,"duplicate-key":(Y)=>`Duplicate settings key: ${Y}.`,unparseable:(Y)=>`The settings file ${Y} can't be parsed.`,unreadable:(Y)=>`The settings file ${Y} can't be read.`},checks:{duplicateFloors:"Invalid killswitch_account_floors: duplicate account and host pair.",localBoth:"Invalid killswitch_account_floors: only vault accounts may use host both.",duplicateQuota:"Invalid quota_minimum_remaining: duplicate quota window.",warmWindow:"Invalid cache_keep_window: use at most one window with unequal hours."},refusal:{"settings-unparseable":"The settings file can't be read. Fix it or remove it, then try again.","settings-newer-version":"The settings file is from a newer openai-auth. Update openai-auth to change settings.","settings-invalid-value":"That value isn't allowed for this setting.","settings-busy":"The settings file is busy. Try again.","settings-unavailable":"Settings can't be saved for this install."}});function a9(Y){return C6.refusal[Y]}function kU(Y){let J=C6;if(Y.reason==="invalid-value"&&Y.keyPath.length===1)switch(Y.keyPath[0]){case"killswitch_account_floors":if(Y.detail==="Duplicate account and host pair")return J.checks.duplicateFloors;if(Y.detail==="Only vault accounts may use host both")return J.checks.localBoth;break;case"quota_minimum_remaining":if(Y.detail==="Duplicate quota window")return J.checks.duplicateQuota;break;case"cache_keep_window":if(Y.detail==="Use at most one window with unequal hours")return J.checks.warmWindow}let X=Y.reason==="unparseable"||Y.reason==="unreadable"?Y.file.path:Y.keyPath.length?Y.keyPath.join("."):Y.file.path;return J.report[Y.reason](X)}function xU(Y,J,X=!1){let $=C6;if(Y.decision==="separate")return $.separate;if(Y.decision==="shared"){if(!J?.targetExists)return $.sharedMissing;return Y.ranMove&&Y.move?.outcome==="moved"&&!X?$.sharedMoved:$.sharedFound}if(Y.move?.outcome==="busy")return $.legacyBusy;if(Y.move?.outcome==="fence-closed"||Y.fence?.open===!1)return $.legacyProcess;let Q=Y.move?.failure;if(Q?.kind==="setting")return $.legacySetting(Q.setting);let G=Q?.kind==="cause"?"path"in Q?`${Q.host} ${Q.path}: ${Q.code}`:Q.code:"SETTINGS_MOVE_FAILED";return $.legacyFailed(G)}var iX=Symbol.for("@cortexkit/openai-auth/settings-diagnostics"),nX=globalThis,l8=nX[iX]??{logged:new Set,sawTargetMissing:new Set};nX[iX]=l8;async function oX({configPath:Y,snapshot:J,log:X}){let $=p8(Y);if(!$)throw Error("Settings authority has not been decided");let Q;try{Q=await $}catch(U){if(U instanceof s9||U instanceof Error&&U.name==="SettingsAuthorityRefusal"&&"folder"in U&&typeof U.folder==="string"){let H=U.cause;return{lines:[C6.refused(String(U.folder),H instanceof Error?H.message:String(H))]}}throw U}if(Q.decision==="separate")return{lines:[C6.separate]};let G=Q.decision==="shared"?d9(Q.install):Q.completion,z=o1(Q.install.target);if(Q.decision==="shared"&&!G?.targetExists)l8.sawTargetMissing.add(z);let W=[C6.file(Q.install.target),xU(Q,G,l8.sawTargetMissing.has(z))];if(Q.decision==="shared"&&G){for(let U of["preExistingFile","removedFile"]){if(!G[U])continue;let H=C6[U](Q.install.target);W.push(H);let V=`${U}:${o1(Q.install.target)}`;if(!l8.logged.has(V))l8.logged.add(V),X.warn(H)}await J?.refresh(),W.push(...J?.report().map(kU)??[])}return{lines:W}}var P1=(Y)=>n(Y)?Y:{};function rX(Y){let{routing:J,killswitch:X}=Y.view(),$=Object.fromEntries(Object.entries(X?.accounts??{}).map(([Q,G])=>[Q,Object.fromEntries(Object.entries(P1(G)).filter(([,z])=>z!==0))]));for(let{account:Q}of Y.get("killswitch_account_floors"))if(!Object.hasOwn($,Q))Object.defineProperty($,Q,{value:{},enumerable:!0,writable:!0,configurable:!0});return{routing:J,killswitch:{...X,accounts:$}}}function hU(Y){let J=new Set,X=!1,$=!0,Q=(z)=>{if(!$)return;if(z[0]!=="killswitch"||z[1]!=="accounts")return;if(X=!0,z[2]!==void 0)J.add(z[2])},G=(z,W)=>new Proxy(z,{ownKeys(U){return Q(W),Reflect.ownKeys(U)},get(U,H){let V=Reflect.get(U,H);return typeof H==="string"&&n(V)?G(V,[...W,H]):V},set(U,H,V){if(typeof H==="string")Q([...W,H]);return Reflect.set(U,H,V)},deleteProperty(U,H){if(typeof H==="string")Q([...W,H]);return Reflect.deleteProperty(U,H)}});return{value:G(Y,[]),accounts:J,touched:()=>X,finish:()=>{$=!1}}}function i8(Y){let{host:J,snapshot:X}=Y,$=Y.writer??Q8(q0,{file:Y.file,log:Y.log,separateInstall:!1,createMissing:!0});return{async read(){return await X.refresh(),rX(X)},async update(Q){try{await X.refresh();let G=rX(X),z=hU(structuredClone(G)),W=await Q(z.value)??z.value;z.finish();let U=JSON.parse(JSON.stringify(W)),H=[],V=P1(U.routing),F=P1(G.routing);if(V.mode!==F.mode)H.push({setting:"routing_mode",value:V.mode});if(V.maxSameAccountWait!==F.maxSameAccountWait)H.push({setting:"max_same_account_wait",value:V.maxSameAccountWait===0?"off":V.maxSameAccountWait==="max"?"cache":"15m"});let j=P1(U.killswitch);if(j.enabled!==P1(G.killswitch).enabled)H.push({setting:"killswitch_enabled",value:j.enabled});let K=P1(P1(G.killswitch).accounts),L=P1(j.accounts);for(let q of new Set([...Object.keys(K),...Object.keys(L)]))if(!vU(K[q],L[q]))z.accounts.add(q);let O=z.touched()||z.accounts.size>0;if(O){if(X.report().some((q)=>q.keyPath[0]==="killswitch_account_floors"||q.reason==="unreadable"||q.reason==="unparseable"))throw new w6("settings-invalid-value",Y.file)}await $.update((q)=>{let x=[...H];if(O){let P=q.status==="ready"&&Object.hasOwn(q.document,"killswitch_account_floors")?q.document.killswitch_account_floors:q0.settings.killswitch_account_floors.default;if(!Array.isArray(P))throw new w6("settings-invalid-value",Y.file);let b=P;for(let M of z.accounts){b=b.filter((S)=>P1(S).account!==M||!M.startsWith("vault:")&&P1(S).host!==J);let w=P1(L[M]);if(Object.keys(w).length>0)b.push({account:M,host:M.startsWith("vault:")?"both":J,primary:w.primary??0,secondary:w.secondary??0})}x.push({setting:"killswitch_account_floors",value:b})}return x},{host:J}),await X.refresh()}catch(G){if(G instanceof w6)throw new d8(G.code,a9(G.code));throw G}}}}import{readFile as eU}from"node:fs/promises";import{readFileSync as yU,statSync as fU}from"node:fs";import{homedir as gU,tmpdir as mU}from"node:os";import{join as t9}from"node:path";var cU="https://chatgpt.com/backend-api/codex/responses",sX=536870912,tX=W0("config"),aX=!1,uU="openai-auth.json",z1={webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",responsesLite:"CORTEXKIT_OPENAI_AUTH_RESPONSES_LITE",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",dumpMaxBytes:"OPENCODE_OPENAI_AUTH_DUMP_MAX_BYTES",codexApiEndpoint:"CORTEXKIT_OPENAI_AUTH_CODEX_ENDPOINT",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function pU(){let Y=process.env[z1.configDir]?.trim();if(Y)return Y;return t9(process.env.XDG_CONFIG_HOME||t9(gU(),".config"),"opencode")}function F1(){return process.env[z1.configFile]?.trim()||t9(pU(),uU)}function eX(Y){try{let J=JSON.parse(yU(Y,"utf8"));return J!=null&&typeof J==="object"&&!Array.isArray(J)?J:{}}catch{return{}}}var Y7=Symbol.for("@cortexkit/openai-auth/opencode-settings-snapshots"),J7=Symbol.for("@cortexkit/openai-auth/opencode-settings-snapshot-warnings"),e9=globalThis,n8=e9[Y7]??new Map;e9[Y7]=n8;var SY=e9[J7]??new Set;e9[J7]=SY;function X7(Y,J){let X=r8(Y),$=n8.get(X)??new Set;if($.size===0)o8.delete(X);n8.set(X,$),$.add(J);let Q=J.onChange(()=>{$.delete(J),$.add(J)}),G=!0;return()=>{if(!G)return;if(G=!1,Q(),$.delete(J),$.size===0)n8.delete(X),o8.delete(X)}}function $7(Y){let J=r8(Y),X=n8.get(J),$;for(let Q of X??[])$=Q;if(!$&&!SY.has(J))SY.add(J),tX.warn("Shared settings snapshot is not registered; using declared defaults",{configPath:J});return $}function Q7(Y){let J=q0.settings;return{version:1,accounts:Y?.accounts??[],main:Y?.main,routing:{mode:J.routing_mode.default,maxSameAccountWait:{off:0,"15m":15,cache:"max"}[J.max_same_account_wait.default]},fallbackOn:[...J.fallback_on.default],refresh:{enabled:J.refresh_enabled.default,refreshBeforeExpiryMinutes:J.refresh_before_expiry_minutes.default,mainLastRefreshError:Y?.refresh?.mainLastRefreshError,mainRefreshLeaseId:Y?.refresh?.mainRefreshLeaseId,mainRefreshLeaseUntil:Y?.refresh?.mainRefreshLeaseUntil,mainRefreshLeaseTokenHash:Y?.refresh?.mainRefreshLeaseTokenHash},quota:{enabled:J.quota_enabled.default,checkIntervalMinutes:J.quota_check_interval_minutes.default,minimumRemaining:{},failClosedOnUnknownQuota:J.quota_fail_closed_on_unknown.default,mainQuota:Y?.quota?.mainQuota,mainQuotaCheckedAt:Y?.quota?.mainQuotaCheckedAt,mainQuotaToken:Y?.quota?.mainQuotaToken,mainLastQuotaApiError:Y?.quota?.mainLastQuotaApiError},killswitch:{schema:X8,enabled:J.killswitch_enabled.default,defaults:{primary:J.killswitch_default_primary.default,secondary:J.killswitch_default_secondary.default},accounts:{}},costZeroing:{enabled:J.cost_zeroing.default},logging:{},cacheKeep:{enabled:J.cache_keep_enabled.default,subagents:J.cache_keep_subagents.default,sustain:J.cache_keep_sustain.default},dump:{enabled:J.request_dumps.default},dumpDir:J.dump_dir.default,dumpMaxBytes:J.dump_max_bytes.default,webSockets:J.web_sockets.default,rawWebSocket:J.raw_web_socket.default,responsesLite:J.responses_lite.default,codexApiEndpoint:J.codex_api_endpoint.default}}function M1(Y,J=F1()){if(y1(J)!=="shared")return Y??{version:1,accounts:[]};return $7(J)?.view(Y)??Q7(Y)}function G7(Y){if(y1(Y)!=="shared")return eX(Y);return $7(Y)?.view()??Q7(null)}function z7(Y){let J=process.env[Y];if(J===void 0)return;let X=J.trim().toLowerCase();if(X==="1"||X==="true"||X==="yes"||X==="on")return!0;if(X===""||X==="0"||X==="false"||X==="no"||X==="off")return!1;return}function G8(Y,J,X){let $=z7(Y);if($!==void 0)return $;if(typeof J==="boolean")return J;return X}function lU(Y){let J=process.env[z1.dumpMaxBytes],X=J??Y;if(X===void 0)return sX;let $=J?.trim()?Number(J):X;if(typeof $==="number"&&Number.isSafeInteger($)&&$>=0)return $;if(!aX)aX=!0,tX.warn("Invalid dumpMaxBytes; using the default 512 MiB cap",{env:z1.dumpMaxBytes});return sX}function bY(Y){if(typeof Y.dump==="boolean")return Y.dump;if(Y.dump&&typeof Y.dump==="object")return Y.dump.enabled;return}var I6;function s8(Y=F1()){let J=z7(z1.dump);if(J!==void 0)return J;if(y1(Y)==="shared")return G8(z1.dump,bY(G7(Y)),!1);let X=Y,$;try{$=fU(X)}catch{}if(I6?.path===X&&I6.mtimeMs===$?.mtimeMs&&I6.ctimeMs===$?.ctimeMs&&I6.size===$?.size)return I6.enabled;let Q=G8(z1.dump,bY(eX(X)),!1);return I6={path:X,mtimeMs:$?.mtimeMs,ctimeMs:$?.ctimeMs,size:$?.size,enabled:Q},Q}function dU(Y){let J=G7(Y);return{webSockets:G8(z1.webSockets,J.webSockets,!1),rawWebSocket:G8(z1.rawWebSocket,J.rawWebSocket,!1),responsesLite:G8(z1.responsesLite,J.responsesLite,!1),dump:G8(z1.dump,bY(J),!1),dumpDir:process.env[z1.dumpDir]?.trim()||(typeof J.dumpDir==="string"&&J.dumpDir.trim()?J.dumpDir.trim():t9(mU(),"opencode-openai-auth-dumps")),dumpMaxBytes:lU(J.dumpMaxBytes),codexApiEndpoint:process.env[z1.codexApiEndpoint]?.trim()||(typeof J.codexApiEndpoint==="string"&&J.codexApiEndpoint.trim()?J.codexApiEndpoint.trim():cU)}}var o8=new Map;function D1(Y=F1()){let J=r8(Y),X=y1(Y)==="shared",$=o8.get(J);if(!$||$.shared!==X)$={shared:X,settings:dU(Y)},o8.set(J,$);return $.settings}function W7(Y=F1()){return o8.delete(r8(Y)),I6=void 0,D1(Y)}import{readFileSync as iU}from"node:fs";var nU="The `main` account holds the login OpenCode signs in with (its login slot only points at it), so it cannot be removed. Sign in with another account through `opencode auth login` to replace it.";function oU(Y){return`The account-pool migration is moving OpenCode's login into \`${Y}\` right now, so it cannot be removed yet. Try again once the migration has finished.`}function U8(Y,J={}){return W8({provider:"openai",configPath:Y.configPath,statePath:Y.statePath,quota:z8,...J})}function kY(Y){try{let J=JSON.parse(iU(Y,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return!1;return a8(J).migratedAt!==void 0}catch{return!1}}async function Y4(Y,J){if(!kY(Y.configPath))return;let X=await J.read();return X.status==="ready"?X.rows:void 0}function J4(Y,J){if(Y===f1)return nU;if(a8(J.config).pending?.rowId===Y)return oU(Y);return}function rU(Y,J){return Z8(Y,f1,J.legacyLocks).filter((X)=>X.name===t8)}function r1(Y,J={}){return rU(Y,J)}var H8="This setup has no OpenAI login in its account store. Sign in for this setup with opencode auth login, or point OPENCODE_OPENAI_AUTH_FILE and OPENCODE_OPENAI_AUTH_STATE_FILE at the store that holds the login.";class V6 extends Error{constructor(){super("The main OpenAI account lives in the account pool");this.name="MainAccountInPoolError"}}async function Z7(Y){let J=Y.storage,X=S6(J);if(!J||!X||u0(X))return;let $=X,Q=Y.now(),G=(M1(J,Y.configPath).refresh?.refreshBeforeExpiryMinutes??240)*60000;if((!$.access||!$.expires||$.expires-Q<=G)&&!s1($.lastRefreshError,$.refresh,Q))try{$=await Y.refreshAccount($,J)}catch(U){Y.warn?.("pool main row refresh failed",{error:U instanceof Error?U.message:String(U)})}let W=$.access?.trim();if(!W)return;if(typeof $.expires!=="number"||$.expires<=Y.now())return;return{account:$,token:W}}import{readFile as j7}from"node:fs/promises";function X4(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}async function N7(Y){let J=await V7(Y.configPath),X=[];try{let Q=JSON.parse(await j7(Y.statePath,"utf8"));if(X4(Q)){let G=Q.accounts;if(X4(G))X=Object.keys(G)}}catch(Q){if(Q.code!=="ENOENT")throw Q}return{rosterIds:J?[...J]:[],stateIds:X,orphanStateIds:J?X.filter((Q)=>!J.has(Q)):[]}}async function sU(Y){try{let J=JSON.parse(await j7(Y.configPath,"utf8"));return X4(J)&&X4(J.claustrum)&&J.claustrum.mode==="claustrum"}catch{return!1}}var U7="Connect this host to the Claustrum vault (`opencode auth login` > Connect to the Claustrum vault, or the Vault section of `/openai`) if the vault holds the account, or sign in to the account again.";function L7(Y){if(!Y)return;let J=Y.accounts.find((X)=>X.id==="main"&&o0(X));if(J)return J;if(!Y.mainAccountId)return;return Y.accounts.find((X)=>o0(X)&&X.accountId===Y.mainAccountId)}function aU(Y,J){let X=Y.lastRefreshError;return s1(X,Y.refresh,J)&&X!==void 0&&X.nextRetryAt!==void 0&&X.nextRetryAt-X.checkedAt>=H7}function tU(Y){let J=[],X=[],$=Y.now??Date.now(),Q=L7(Y.storage),G=!1;if(u0(Y.auth))J.push({code:"tombstoned-host-slot",message:`OpenCode's OpenAI slot holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${U7}`});else if(t0(Y.auth)){if(!S6(Y.storage))J.push({code:"main-pool-row-missing",message:"The main account was moved into the account pool, but the pool has no usable `main` row."})}else if(!Y.auth)J.push({code:"auth-slot-missing",message:"OpenCode's OpenAI auth slot is missing."}),G=!0;else if(Y.auth.type!=="oauth")J.push({code:"auth-slot-not-oauth",message:"OpenCode's OpenAI auth slot is not OAuth."}),G=!0;else if(Q&&(!Y.auth.refresh||Q.refresh!==Y.auth.refresh))J.push({code:"main-refresh-not-in-store",message:"OpenCode's main credential does not match the copy in the account store."}),G=!0;if(G&&Q){let U={type:"restore-main-credential"};X.push(U);let H=J.find((V)=>V.code==="auth-slot-missing"||V.code==="auth-slot-not-oauth"||V.code==="main-refresh-not-in-store");if(H)H.repair=U}let z=Y.storage?.accounts??[];if(z.length===0)J.push({code:"no-accounts",message:"The account store has no accounts."});else if(!z.some((U)=>U.enabled!==!1))J.push({code:"no-enabled-accounts",message:"The account store has no enabled accounts."});for(let U of z){if(!o0(U)||!u0(U))continue;J.push({code:"tombstoned-account",accountId:U.id,message:`Account ${U.id} holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${U7}`})}if(Y.retiredCustodyMode)J.push({code:"retired-custody-mode",message:"The config still selects the vault custody mode of an older version (`claustrum.mode`). It is ignored, and dropped at the next settings write; vault accounts are served once this host is connected to the Claustrum vault."});for(let U of z){if(!o0(U))continue;if(!aU(U,$))continue;let H={type:"clear-refresh-backoff",accountId:U.id};X.push(H),J.push({code:"armed-non-transient-refresh-backoff",accountId:U.id,message:`Account ${U.id} has an armed non-transient refresh backoff.`,repair:H})}let W=[...Y.orphanStateIds??[]];if(W.length>0){let U={type:"prune-orphan-state-ids",ids:W};X.push(U),J.push({code:"orphan-state-ids",message:`State contains ids absent from the config roster: ${W.join(", ")}.`,repair:U})}return{findings:J,repairs:X}}function F7(Y){let J=(X)=>{if(X.type==="restore-main-credential")return{label:"Copy the stored main credential back into OpenCode's slot",apply:async()=>{if(t0(await Y.readAuth()))return;let $=L7(await Y.loadAccounts(Y.paths));if(!$)return;await Y.setMainAuth({refresh:$.refresh,access:$.access??"",expires:$.expires??0})}};if(Y.migrated)return;if(X.type==="prune-orphan-state-ids")return{label:`Drop the state entries of ${X.ids.join(", ")}`,apply:async()=>{await Y.mutateAccounts(($)=>$,Y.paths)}};return{label:`Clear the refresh backoff of ${X.accountId}`,apply:async()=>{await Y.mutateAccounts(($)=>{let Q=$.accounts.find((G)=>G.id===X.accountId&&o0(G));if(Q)Q.lastRefreshError=void 0;return $},Y.paths)}}};return[{id:"openai-auth",run:async()=>{let[X,$,Q,G]=await Promise.all([Y.loadAccounts(Y.paths),Y.readStoreIds(Y.paths),Y.readAuth(),sU(Y.paths)]),z=tU({auth:Q.type==="missing"?void 0:Q,storage:X,orphanStateIds:$.orphanStateIds,retiredCustodyMode:G,now:Y.now()}),W=await W8({provider:"openai",quota:z8,configPath:Y.paths.configPath,statePath:Y.paths.statePath}).read();if(W.status==="ready")for(let U of W.rows){if(U.disabledReason!==B7)continue;z.findings.push({code:"slot-transfer-origin-unknown",accountId:U.id,message:`Account ${U.id} was preserved disabled after an interrupted transfer with an untagged placeholder; sole ownership could not be established. ${K7}`})}return z.findings.map((U)=>{let H=U.repair?J(U.repair):void 0;return{code:U.code,message:U.message,...U.accountId!==void 0?{accountId:U.accountId}:{},...H?{repair:H}:{}}})}}]}var YH=y7,D7="OpenAI accounts",JH="ChatGPT accounts in the vault",XH="Uses the ChatGPT accounts in the Claustrum vault, with no sign-in. This works only while this host is connected to the vault and OpenCode has no OpenAI login stored; otherwise it fails and changes nothing.";async function $H(){let{redirectUri:Y}=await T7(),J=await M7(),X=P7(crypto.getRandomValues(new Uint8Array(32)).buffer),$=E7(Y,J,X),Q=R7(J,X);return{url:$,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let G=await Q;return{type:"success",refresh:G.refresh_token,access:G.access_token,expires:Date.now()+(G.expires_in??3600)*1000,accountId:b6(G)}}finally{A7(X)}}}}async function QH(Y){let{deviceData:J,url:X,instructions:$}=await C7(Y);return{url:X,instructions:$,method:"auto",async callback(){try{let Q=await w7(J,Y);return{type:"success",refresh:Q.refresh_token,access:Q.access_token,expires:Date.now()+(Q.expires_in??3600)*1000,accountId:b6(Q)}}catch{return{type:"failed"}}}}}function c7({client:Y,getAuth:J,getPaths:X=()=>x6(F1()),fetchImpl:$=fetch,packageVersion:Q=g1,dependencies:G,onMainSlotWritten:z,vault:W}){let U={authorizeBrowser:G?.authorizeBrowser??$H,authorizeHeadless:G?.authorizeHeadless??(()=>QH(Q)),beginAccountLogin:G?.beginAccountLogin??G4,loadAccounts:G?.loadAccounts??k6,mutateAccounts:G?.mutateAccounts??z4,readStoreIds:G?.readStoreIds??N7,openBrowser:G?.openBrowser??YH,now:G?.now??Date.now,openAccountPool:G?.openAccountPool??U8,migrationBlockers:G?.migrationBlockers??(async()=>{let M=await K8({currentVersion:Q});return M.open?[]:M.blockers.map((w)=>({pid:w.pid,version:w.version}))}),...G?.terminal?{terminal:G.terminal}:{},...G?.vaultWait?{vaultWait:G.vaultWait}:{}},H=async()=>await J?.().catch(()=>{return})??{type:"missing"},V=async()=>{if(W&&await W.authority()!=="local")return!0;if((await H()).type!=="missing")return!0;let M=X(),w=U.openAccountPool(M);if((await w.read()).status==="ready")return x7(w);return((await U.loadAccounts(M))?.accounts.length??0)>0},F=async(M)=>{if(await g7(X().configPath,async()=>{if(W&&await W.authority()!=="local")return!1;if(t0(await H()))return!1;return await Y.auth.set({path:{id:"openai"},body:{type:"oauth",...M}}),!0}))await z?.().catch(()=>{})},j=(M)=>({begin:async({headless:w,signal:S})=>{if(W&&await W.authority()!=="local")throw Error(V8);let E=await U.beginAccountLogin({version:Q,headless:w,...S?{signal:S}:{}});return{url:E.url,instructions:E.instructions,completion:E.completion.then(async(v)=>{if(W&&await W.authority()!=="local")throw Error(V8);let u=await M.read(),c=u.status==="ready"?u.rows.find((J0)=>J0.id===f1)?.identity:void 0;if(v.accountId&&c&&v.accountId===c)throw Error("that account is already the OpenCode main credential");return{id:v.id,credential:{type:"oauth",refresh:v.refresh,...v.access!==void 0?{access:v.access}:{},...v.expires!==void 0?{expires:v.expires}:{}},...v.accountId!==void 0?{identity:v.accountId}:{},...v.label!==void 0?{label:v.label}:{}}})}},openBrowser:(w)=>U.openBrowser(w)}),K=async(M)=>{if(W&&await W.authority()!=="local")throw Error(V8);let w=M.credential;if(w?.type!=="oauth"||!w.access)throw Error("no usable access token for a quota check");let S=await e8({accessToken:w.access,fetchImpl:$,now:U.now,...M.identity?{accountId:M.identity}:{},accountKey:M.id});return B8(S,U.now(),!0)},L=(M)=>F7({paths:X(),migrated:M,readAuth:H,loadAccounts:U.loadAccounts,readStoreIds:U.readStoreIds,mutateAccounts:U.mutateAccounts,setMainAuth:F,now:U.now}),O=(M,w)=>({title:D7,store:PY(w,{rowLocks:(S)=>Z8(M,S)}),...U.terminal?{terminal:U.terminal}:{},login:j(w),protect:(S,E)=>J4(S,E),extraLocks:r1(M),pollQuota:K,doctor:L(!0),status:async()=>{if(W&&await W.authority()==="host")return[O7];let S=await W?.status();if(W&&await W.authority()!=="local"&&S)return[vY(W.host,W.name,S.enrollment)];return[`Routing: ${(await U.loadAccounts(M))?.routing?.mode??"main-first"}`,...W?[vY(W.host,W.name,(await W.status()).enrollment)]:[]]},...W&&!Q4()?{extraActions:[q(W)]}:{}}),q=(M)=>{let w=M.enrolled();return{id:w?"vault-disconnect":"vault-connect",label:w?"Disconnect from the Claustrum vault":"Connect to the Claustrum vault",hint:"serve OpenAI accounts held in the vault",run:async(S)=>{let E=await M.authority();if(E==="host"){S.print(_7);return}if(w){if(E!=="local")await M.disconnect();S.print("Disconnected from the Claustrum vault.");return}if(E!=="local"){S.print("Nothing was changed: this host is already connected or its enrollment is unreadable. Reopen the menu to disconnect.");return}S.print(`Asking the Claustrum vault to enroll ${M.name}…`);let v,u=await M.waitForApproval({...U.vaultWait,onPending:(c)=>{let r=c.state==="pending"?c.requestId??c.retryCode??"":c.state;if(r===v)return;v=r;for(let J0 of I7(M.name,c))S.print(J0);S.print("Waiting for the approval… (stop with Ctrl-C; Connect picks the request up again)")}});S.print(S7(M,u).text)}}},x=async()=>{let M=await U.migrationBlockers();return k7({title:D7,status:["Accounts move to the new account layout once every OpenCode process on this machine runs this version of OpenAI auth. Account management opens after the move.",...M.length>0?["These processes still hold the move back:",...M.map((w)=>` ${w.pid==="unknown"?"processes that could not be read":`pid ${w.pid}`}: version ${w.version}`)]:[]],actions:[b7({checks:L(!1)})],...U.terminal?{terminal:U.terminal}:{}})},P=async(M)=>{let w=X(),S=U.openAccountPool(w);if(W&&await W.authority()!=="local")return $4(O(w,S),W);if(await Y4(w,S)===void 0)return x();let E=O(w,S);return W?$4(E,W):v7(E)},b=(M)=>async()=>{if(W&&await W.authority()!=="local")throw Error(V8);let w=await M();if(w.method!=="auto")return w;return{...w,callback:async()=>{let S=await w.callback();if(W&&await W.authority()!=="local")return{type:"failed"};return S}}};return[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:h7({hasCredential:V,openMenu:P,login:b(()=>U.authorizeBrowser())})},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:b(()=>U.authorizeHeadless())},{label:"Manually enter API Key",type:"api"},...W?.enrolled()?[{label:JH,type:"oauth",authorize:async()=>({url:"",instructions:XH,method:"auto",callback:async()=>{let M=await q7(W.paths,W.name);if(M!=="vault"&&M!=="host")return{type:"failed"};try{let w=JSON.parse(await eU(m7(),"utf8"));if(!w||typeof w!=="object"||Array.isArray(w)||Object.hasOwn(w,"openai"))return{type:"failed"}}catch(w){if(w.code!=="ENOENT")return{type:"failed"}}return{...f7,type:"success"}}})}]:[]]}import{createHash as hH}from"node:crypto";var hY=["type","model","instructions","previous_response_id","input","tools","tool_choice","parallel_tool_calls","reasoning","store","stream","include","prompt_cache_key","text","generate","client_metadata"];function v6(Y){let J={};for(let X of hY)if(X in Y)J[X]=Y[X];for(let X of Object.keys(Y))if(!(X in J))J[X]=Y[X];return J}import{createHash as MH}from"node:crypto";import{createHash as GH,randomBytes as u7}from"node:crypto";import{chmod as zH,lstat as p7,mkdir as WH,open as ZH,readdir as t7,rename as UH,unlink as cY,writeFile as HH}from"node:fs/promises";import{join as W4,resolve as yY}from"node:path";var VH=100,fY="session-unknown",BH=300000,KH=60000,jH=600000,NH=/\.(body|meta|request|response)\.json$/,LH=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-\d+-\d{6,}-[a-zA-Z0-9._-]+$/,FH=/\.[a-f0-9]{24}\.partial$/;function e7(Y){let J=Y.replace(NH,"");if(J===Y||!LH.test(J))return;return J}function DH(Y){let J=Y.replace(FH,"");return J!==Y&&e7(J)!==void 0}async function l7(Y){let{dir:J,maxBytes:X}=Y,$=Y.now??Date.now(),Q=Y.minAgeMs??KH,G=Y.partialStaleMs??jH,z={removed:0,freedBytes:0};if(!(X>0))return z;try{if(m1)await n7(J,"directory");if((await p7(J)).isSymbolicLink())return z;let W=new Set((Y.protectedPaths??[]).map((q)=>yY(q))),U=await t7(J,{withFileTypes:!0}),H=[];await Promise.all(U.map(async(q)=>{if(!q.isFile())return;let x=DH(q.name),P=x?void 0:e7(q.name);if(!x&&P===void 0)return;let b=W4(J,q.name);try{let M=await p7(b);if(!M.isFile())return;H.push({path:b,size:M.size,mtimeMs:M.mtimeMs,group:P})}catch{}}));let V=H.reduce((q,x)=>q+x.size,0),F=0,j=0,K=async(q)=>{try{await cY(q.path),V-=q.size,j+=q.size,F+=1}catch{}};for(let q of H){if(q.group!==void 0)continue;if(W.has(yY(q.path)))continue;if($-q.mtimeMs<G)continue;await K(q)}let L=new Map;for(let q of H){if(q.group===void 0)continue;let x=L.get(q.group)??{files:[],newest:0};x.files.push(q),x.newest=Math.max(x.newest,q.mtimeMs),L.set(q.group,x)}let O=[...L.entries()].sort(([q,x],[P,b])=>x.newest-b.newest||q.localeCompare(P));for(let[,q]of O){if(V<=X)break;if($-q.newest<Q)continue;if(q.files.some((x)=>W.has(yY(x.path))))continue;for(let x of q.files)await K(x)}if(F>0)Y.logger?.debug("removed old dump files",{removed:F,freedBytes:j});return{removed:F,freedBytes:j}}catch(W){if(W instanceof J9&&W.code==="ERR_PRIVATE_FILES_SECURITY")throw W;return z}}async function OH(Y,J,X){if(m1)return s7(Y,J,{stagePath:`${Y}.${X?X():u7(12).toString("hex")}.partial`});for(let $=0;;$+=1){let Q=`${Y}.${X?X():u7(12).toString("hex")}.partial`,G=!1,z;try{z=await ZH(Q,"wx",384),G=!0,await z.writeFile(J,"utf8"),await z.chmod(384),await z.close(),z=void 0,await UH(Q,Y);return}catch(W){if(await z?.close().catch(()=>{}),G)await cY(Q).catch(()=>{});if(W.code==="EEXIST"&&$===0)continue;throw W}}}function gY(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function Y9(Y,J){let X=Y.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!X)return J;return X.slice(0,80)}function d7(Y){return GH("sha256").update(Y).digest("hex")}function _H(Y){return Y.toLowerCase().replace(/[-_]/g,"")}function i7(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function qH(Y,J){if(Y===void 0)return null;if(Y===J)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:Y.length,currentBytes:J.length};let X=0;while(X<Y.length&&X<J.length&&Y[X]===J[X])X++;let $=Y.length-1,Q=J.length-1;while($>=X&&Q>=X&&Y[$]===J[Q])$--,Q--;return{changed:!0,firstByte:X,lastPreviousByte:$,lastCurrentByte:Q,changedPreviousBytes:$-X+1,changedCurrentBytes:Q-X+1,previousBytes:Y.length,currentBytes:J.length}}var PH=0;function Y2(Y){let J=Y.enabled===!0,X=Y.pid??process.pid,$=Y.now??Date.now,Q=Y.logger,G=new Set((Y.secretKeys??[]).map(_H)),z=a7({extraSecretKeys:(E)=>G.has(E),extraValuePatterns:[...Y.secretPatterns??[]]}),W=new Set(Y.schemaKeys??["tools"]),U=new Map,H=()=>typeof Y.dir==="function"?Y.dir():Y.dir;function V(E){let v=z.redact({[E]:null})[E];return v===null?void 0:v}function F(E){if(Array.isArray(E))return E.map(F);if(i7(E)){let v={};for(let[u,c]of Object.entries(E)){let r=V(u);if(W.has(u))v[u]=z.redactStrings(c);else if(r!==void 0)v[u]=r;else v[u]=F(c)}return v}return z.redactStrings(E)}function j(E){let v;try{v=JSON.parse(E)}catch{return{text:z.redactStrings(E),parsed:void 0}}let u=F(v),c=JSON.stringify(u);return{text:JSON.stringify(v)===c?E:c,parsed:i7(u)?u:void 0}}async function K(E,v,u,c){let r=`-${Y9(v,fY)}-${Y9(u,"channel")}`,J0;try{J0=await t7(E)}catch{return}let l=J0.filter((T)=>T.endsWith(".meta.json")&&T.includes(r)).sort().reverse();for(let T of l)try{if(JSON.parse(await mY(W4(E,T),m1))?.baselineKey!==c)continue;return await mY(W4(E,T.replace(/\.meta\.json$/,".body.json")),m1)}catch(B0){if(B0 instanceof J9&&(m1||B0.code==="ERR_PRIVATE_FILES_SECURITY"))throw B0}return}function L(E,v){if(!U.has(E))while(U.size>=VH){let u=U.keys().next().value;if(u===void 0)break;U.delete(u)}U.set(E,v)}async function O(E){if(!J)return;let v=++PH,u=E.session?.trim()||fY,c=H(),r=new Date($()).toISOString(),J0=[r.replace(/[:.]/g,"-"),String(X),String(v).padStart(6,"0"),Y9(u,fY),Y9(E.channel,"channel"),...E.phase?[Y9(E.phase,"phase")]:[]].join("-"),l=W4(c,J0),T={body:`${l}.body.json`,metadata:`${l}.meta.json`,request:`${l}.request.json`},B0=d7(`${E.channel}\x00${u}`);try{if(m1)await o7(c);else await WH(c,{recursive:!0,mode:448}),await zH(c,448);let P0=U.get(B0),d=P0===void 0?void 0:"memory";if(P0===void 0){if(P0=await K(c,u,E.channel,B0),P0!==void 0)d="disk"}let k0=j(E.bodyText),T0={id:J0,createdAt:r,pid:X,session:gY(u),channel:E.channel,...E.phase?{phase:E.phase}:{},accountId:E.accountId,status:E.status,error:E.error===void 0?void 0:z.redactStrings(E.error),baselineKey:B0,bodyBytes:Buffer.byteLength(E.bodyText,"utf8"),bodyHash:d7(E.bodyText),diff:qH(P0,k0.text),baselineSource:d,body:k0.parsed?{parseable:!0,...Y.summarize?.(k0.parsed)}:{parseable:!1},...E.meta?{extra:F(E.meta)}:{},files:T},m=F({url:E.url,method:E.method,accountId:E.accountId,headers:E.headers===void 0?void 0:Object.fromEntries(new Headers(E.headers).entries())}),Z0=(O0,e)=>m1?r7(O0,e):HH(O0,e,{encoding:"utf8",mode:384,flag:"wx"}),p=[[T.body,k0.text],[T.metadata,`${JSON.stringify(T0,null,2)}
|
|
2
|
-
`],[T.request,`${JSON.stringify(m,null,2)}
|
|
3
|
-
`]],M0=await Promise.allSettled(p.map(([O0,e])=>Z0(O0,e))),l0=M0.find((O0)=>O0.status==="rejected");if(l0){if(Y.cleanupFailedDumps)await q(p,M0);throw l0.reason}return L(B0,k0.text),Q?.debug("dumped request",{id:J0,session:gY(u),body:T.body}),w(c,Object.values(T)),{id:J0,files:T,responseFile:`${l}.response.json`}}catch(P0){if(P0 instanceof J9&&(m1||P0.code==="ERR_PRIVATE_FILES_SECURITY"))throw P0;Q?.warn("request dump failed",{session:gY(u),error:P0 instanceof Error?P0.message:String(P0)});return}}async function q(E,v){await Promise.all(E.map(async([u],c)=>{let r=v[c];if(r?.status==="rejected"&&r.reason?.code==="EEXIST")return;await cY(u).catch(()=>{})}))}let x=Y.maxBytes??0,P=Y.sweepIntervalMs??BH,b=0;function M(E,v){return{dir:E,maxBytes:x,protectedPaths:v,now:$(),minAgeMs:Y.sweepMinAgeMs,partialStaleMs:Y.partialStaleMs,logger:Q}}function w(E,v){if(!(x>0))return;let u=$();if(u-b<P)return;b=u,l7(M(E,v))}async function S(E,v){if(!E)return;let u=F({status:v.status,requestId:v.requestId,usage:v.usage,...v.fields,complete:v.complete??!0});try{return await OH(E.responseFile,`${JSON.stringify(u,null,2)}
|
|
4
|
-
`,Y.stageName),E.responseFile}catch(c){if(c instanceof J9&&(m1||c.code==="ERR_PRIVATE_FILES_SECURITY"))throw c;Q?.warn("response dump failed",{id:E.id,error:c instanceof Error?c.message:String(c)});return}}return{isEnabled:()=>J,setEnabled:(E)=>{J=E},dump:O,dumpResponse:S,sweep:(E)=>l7(M(H(),E))}}var J2=W0("dump"),B6="x-cortexkit-openai-auth-dump-session",EH=["chatgpt-account-id","email","org_name","organization_name"],AH=["tools"];function uY(Y){return MH("sha256").update(JSON.stringify(Y)).digest("hex")}function TH(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function RH(Y){let J=Array.isArray(Y.input)?Y.input:[],X=Array.isArray(Y.tools)?Y.tools:[],$=Y.client_metadata!=null&&typeof Y.client_metadata==="object"&&!Array.isArray(Y.client_metadata)?Y.client_metadata:void 0;return{model:typeof Y.model==="string"?Y.model:void 0,stream:Y.stream,generate:Y.generate,store:Y.store,previousResponseID:typeof Y.previous_response_id==="string"?Y.previous_response_id:void 0,promptCacheKey:typeof Y.prompt_cache_key==="string"?Y.prompt_cache_key:void 0,reasoning:Y.reasoning,inputCount:J.length,inputHash:uY(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:uY(J[0]),toolsCount:X.length,toolTypes:X.map(TH),toolsHash:uY(X),clientMetadataKeys:$?Object.keys($).sort():[]}}var pY;function X2(){return pY=D1().dumpMaxBytes,Y2({dir:()=>D1().dumpDir,maxBytes:pY,logger:J2,secretKeys:EH,schemaKeys:AH,summarize:RH})}var Z4=X2();async function j8(Y){if(!s8()){Z4.setEnabled(!1);return}if(D1().dumpMaxBytes!==pY)Z4=X2();Z4.setEnabled(!0);let J=typeof Y.bodyText==="function"?Y.bodyText():Y.bodyText;await Z4.dump({session:Y.sessionID,channel:Y.transport,phase:Y.phase,bodyText:J,accountId:Y.accountId,url:Y.url,method:Y.method,headers:Y.headers,status:Y.status,error:Y.error})}async function h6(Y){if(!s8())return;J2.debug("diagnostic",Y)}function N8(Y){return JSON.stringify(lY(Y))??"undefined"}function lY(Y){if(Array.isArray(Y))return Y.map(lY);if(!n(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((J)=>[J,lY(Y[J])]))}var CH=512,wH=2097152;function dY(Y,J){if(typeof Y==="function"||typeof J==="function")return!1;if(J!==null&&typeof J==="object"&&Object.hasOwn(J,"toJSON")&&typeof J.toJSON==="function")return!1;if(Y===J)return!0;if(Array.isArray(Y))return Array.isArray(J)&&Y.length===J.length&&Y.every((G,z)=>dY(G,J[z]));if(Y===null||J===null||typeof Y!=="object"||typeof J!=="object"||Array.isArray(J))return!1;let X=Y,$=J,Q=Object.keys(X);return Q.length===Object.keys($).length&&Q.every((G)=>Object.prototype.propertyIsEnumerable.call($,G)&&dY(X[G],$[G]))}function y6(Y,J){let X=[],$=[],Q=0;for(let G=0;G<Y.length;G++){let z=J?.texts[G],W=z!==void 0&&dY(J?.snapshots[G],Y[G]),U=W?z:N8(Y[G]);X.push(U),$.push(W?J?.snapshots[G]:U==="undefined"?void 0:JSON.parse(U)),Q+=U.length}return{texts:X,snapshots:$,retainable:Y.length<=CH&&Q<=wH}}function X9(Y){return Y.retainable?Y:void 0}function $9(Y,J){if(Y.texts.length>J.texts.length)return;for(let X=0;X<Y.texts.length;X++)if(Y.texts[X]!==J.texts[X])return;return Y.texts.length}var $2=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-6-astra","gpt-6-sol","gpt-6-luna","gpt-6.1-sol","gpt-6.1-terra","gpt-6.2-sol","gpt-6.2-astra"]),IH="terminal_resize_reflow",U4="0.166.0",Q2=`codex_exec/${U4} (Debian 12.0.0; aarch64) unknown (codex_exec; ${U4})`,SH="seccomp",f6="x-openai-auth-agent";function bH(Y){if(typeof Y!=="string")return;try{let J=JSON.parse(Y);return typeof J==="object"&&J!==null&&!Array.isArray(J)?J:void 0}catch{return}}function Q9(Y,J){return n(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===J}function kH(Y,J,X){if(!Y.input)return J.length>0;let $=Y.canonicalInput??y6(Y.input);if($9($,X)===void 0)return!0;return J.slice(Y.input.length).some((G)=>Q9(G,"user")||Q9(G,"developer"))}function xH(Y,J,X){let $=Array.isArray(J?.input)?J.input:void 0,Q=$?y6($,Y.canonicalInput):void 0;if($&&Q&&(kH(Y,$,Q)||!Y.turnID))Y.turnID=(X?.uuid??g6)(),Y.turnStartedAt=(X?.now??Date.now)();else if(!Y.turnStartedAt)Y.turnStartedAt=(X?.now??Date.now)();if($&&Q)Y.input=$.slice(),Y.canonicalInput=X9(Q)}function G2(Y){let J=Y.headers.get(f6);if(Y.headers.delete(f6),!Y.metadata)return{init:Y.init};let X=bH(Y.init?.body),$=Y.runtime?.now??Date.now;if(!Y.skipTurnUpdate){if(!Y.websocket)xH(Y.metadata,X,Y.runtime);else if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=$();if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=$()}let Q=JSON.stringify({session_id:Y.metadata.threadID,thread_id:Y.metadata.threadID,thread_source:"user",turn_id:Y.metadata.turnID,sandbox:SH,turn_started_at_unix_ms:Y.metadata.turnStartedAt,request_kind:"turn",window_id:Y.metadata.windowID});if(Y.headers.set("originator","codex_exec"),Y.websocket)Y.headers.delete("accept"),Y.headers.delete("content-type");else Y.headers.set("accept","text/event-stream");if(Y.headers.set("session-id",Y.metadata.threadID),Y.headers.delete("x-session-id"),Y.headers.delete("x-session-affinity"),Y.headers.set("thread-id",Y.metadata.threadID),Y.headers.set("x-codex-window-id",Y.metadata.windowID),Y.headers.set("x-client-request-id",Y.metadata.threadID),Y.headers.set("x-codex-beta-features",IH),Y.headers.set("x-codex-turn-metadata",Q),Y.headers.set("user-agent",Q2),Y.headers.set("version",U4),Y.dumpSessionID)Y.headers.set(B6,Y.dumpSessionID);let G=X;if(!G)return{init:Y.init};let z=Y.responsesLite&&typeof G.model==="string"&&$2.has(G.model);if(z&&!Y.websocket)Y.headers.set("x-openai-internal-codex-responses-lite","true");if(G.prompt_cache_key=Y.metadata.threadID,G.parallel_tool_calls??=!0,Array.isArray(G.tools))G.tools=G.tools.map(vH);if(Y.applyEffort?.(G,Y.metadata,J),z)Y.rewriteLite(G);let W={...typeof G.client_metadata==="object"&&G.client_metadata!==null?G.client_metadata:{},"x-codex-installation-id":Y.installationID,"x-codex-window-id":Y.metadata.windowID};if(Y.websocket){if(W["x-codex-turn-metadata"]=Q,W["x-codex-ws-stream-request-start-ms"]=String($()),z)W.ws_request_header_x_openai_internal_codex_responses_lite="true"}return G.client_metadata=W,Y.headers.delete("content-length"),Y.headers.delete("Content-Length"),{init:{...Y.init,body:JSON.stringify(v6(G))}}}function vH(Y){if(!n(Y)||Y.type!=="function")return Y;let J=n(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:U,...H}=Y.parameters;return H})():Y.parameters,{type:X,name:$,description:Q,strict:G,parameters:z,...W}=Y;return{type:X,name:$,description:Q,strict:G??!1,parameters:J,...W}}var z2=new Set(["gpt-6-astra","gpt-6-sol","gpt-6-luna","gpt-6.1-sol"]),yH=new Set(["title","compaction","summary"]);function W2(Y,J,X){if(X!==null&&yH.has(X))return;let $=typeof Y.model==="string"?Y.model:"";if(!z2.has($))return;let Q=n(Y.reasoning)?Y.reasoning:void 0,G=typeof Q?.effort==="string"?Q.effort:void 0;if(!G)return;let z=Array.isArray(Y.input)?Y.input:void 0;J.effortUpdates??=[];let W=J.effortUpdates,U=(j)=>hH("sha256").update(N8(j)).digest("hex").slice(0,16);if(J.pinnedEffort===void 0||W.some((j)=>!z||!Q9(z[j.anchor],"user")||U(z[j.anchor])!==j.fingerprint)){J.pinnedEffort=G,J.effortUpdates=[];return}if(!z||z.length===0)return;let H=z.findLastIndex((j)=>Q9(j,"user")),V=W.at(-1),F=V?.effort??J.pinnedEffort;if(H>=0&&G!==F)if(V?.anchor===H){let j=W.at(-2)?.effort??J.pinnedEffort;if(G===j)W.pop();else V.effort=G}else W.push({anchor:H,fingerprint:U(z[H]),effort:G});else if(H<0&&G!==F)return;if(W.some((j,K)=>K>0&&j.anchor<=(W[K-1]?.anchor??-1))){J.pinnedEffort=G,J.effortUpdates=[];return}Y.reasoning={...Q,effort:J.pinnedEffort};for(let j=W.length-1;j>=0;j--){let K=W[j];if(!K)continue;z.splice(K.anchor,0,{type:"configuration_update",reasoning:{effort:K.effort}})}}function iY(Y){if(Array.isArray(Y)){let X=Y;for(let $=0;$<Y.length;$++){let Q=iY(Y[$]);if(Q===Y[$])continue;if(X===Y)X=Y.slice();X[$]=Q}return X}if(!n(Y))return Y;let J=Y;for(let X of Object.keys(Y)){if(Y.type==="input_image"&&X==="detail"){if(J===Y)J={...Y};delete J[X];continue}let $=iY(Y[X]);if($===Y[X])continue;if(J===Y)J={...Y};J[X]=$}return J}function nY(Y){let J=n(Y.reasoning)?{...Y.reasoning}:{};J.context="all_turns",Y.reasoning=J,Y.parallel_tool_calls=!1;let X=iY(Array.isArray(Y.input)?Y.input:[]),Q=[{type:"additional_tools",role:"developer",tools:Array.isArray(Y.tools)?Y.tools.filter((G)=>!(n(G)&&G.type==="web_search")):[]}];if(typeof Y.instructions==="string"&&Y.instructions.length>0)Q.push({type:"message",role:"developer",content:[{type:"input_text",text:Y.instructions}]});Y.input=[...Q,...X],delete Y.tools,delete Y.instructions}var Z2=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),U2=new Set(["gpt-5.6","gpt-6","gpt-6.1","gpt-6.2"]);function oY(Y){if(Z2.has(Y))return!0;if(U2.has(Y))return!1;let X=Y.match(/^gpt-(\d+(?:\.\d+)?)/)?.[1];return X?parseFloat(X)>5.4:!1}function rY(Y){if(Y.includes("gpt-5.5"))return{context:400000,input:272000,output:128000};if(Y.includes("gpt-5.6")||Y.includes("gpt-6-astra")||Y.includes("gpt-6-sol")||Y.includes("gpt-6-luna")||Y.includes("gpt-6.2-astra"))return{context:872000,input:744000,output:128000};if(Y.includes("gpt-6.1-sol")||Y.includes("gpt-6.1-terra")||Y.includes("gpt-6.2-sol"))return{context:500000,input:372000,output:128000};return}function sY(Y){return Y==="gpt-6.1-terra"?"gpt-6.1-sol":void 0}import{lstat as H2,opendir as fH}from"node:fs/promises";import{join as gH}from"node:path";async function V2(Y){try{if(!(await H2(Y)).isDirectory())return;let J=0,X=!1,$=[],Q=async(G)=>{try{let z=await H2(gH(Y,G));if(z.isFile())J+=z.size}catch(z){if(z.code!=="ENOENT")X=!0}};for await(let G of await fH(Y)){if(!G.isFile())continue;if($.push(Q(G.name)),$.length===32)await Promise.all($),$=[]}return await Promise.all($),X?void 0:J}catch(J){return J.code==="ENOENT"?0:void 0}}function aY(Y){let J=["B","KiB","MiB","GiB","TiB","PiB"],X=0,$=Y;while($>=1024&&X<J.length-1)$/=1024,X++;return`${Number($.toFixed(1))} ${J[X]}`}var tY={rpcRoot:"openai-auth",directoryPrefix:N2,registrationSessionId:"process"},H4=new Map;function sO(Y,J){if(J?.aborted)return Promise.resolve(!1);if(eY(Y))return Promise.resolve(!0);return new Promise((X)=>{let $=(W)=>{if(clearTimeout(G),J?.removeEventListener("abort",Q),z.delete($),z.size===0)H4.delete(Y);X(W)},Q=()=>$(!1),G=setTimeout(()=>$(!1),2000),z=H4.get(Y)??new Set;H4.set(Y,z),z.add($),J?.addEventListener("abort",Q,{once:!0})})}function V4(Y,J){B2(tY,Y,J)}function L2(Y=0,J){let X=K2(tY,Y,J);if(J!==void 0)for(let $ of H4.get(J)??[])$(!0);return X}function eY(Y){return j2(tY,Y)}var K6=W0("commands");function m6(Y){return{configPath:Y.accountStoragePath,statePath:Y.accountStatePath}}function D2(Y){return Y.configPath??m6(Y).configPath}async function G9(Y){let J=Y.settingsSnapshot,X=D2(Y);if(!J||y1(X)!=="shared")return;let $=await p8(X);if($?.decision!=="shared")return;let Q=$.install.target;return{snapshot:J,file:Q,writer:Q8(q0,{file:Q,log:K6,separateInstall:!1,createMissing:!0})}}async function JJ(Y,J,X){let $=await G9(Y);if(!$){await X();return}try{if(J.setting==="cache_keep_window"){if(await $.snapshot.refresh(),$.snapshot.report().some((Q)=>Q.reason==="invalid-value"&&Q.keyPath[0]===J.setting||Q.reason==="unreadable"||Q.reason==="unparseable"))throw new w6("settings-invalid-value",$.file)}await $.writer.update([J],{host:"opencode"}),await $.snapshot.refresh()}catch(Q){if(Q instanceof w6)throw new d8(Q.code,a9(Q.code));throw Q}}function YJ(Y){return`${String(Y.startHour).padStart(2,"0")}-${String(Y.endHour).padStart(2,"0")}`}function mH(Y){let J=/^(\d{1,2})-(\d{1,2})$/.exec(Y.trim());if(!J)return{ok:!1,reason:"expected HH-HH, e.g. 9-18 or 22-6"};let X=Number(J[1]),$=Number(J[2]);if(X>23||$>23||X===$)return{ok:!1,reason:"hours must be integers 0-23 and start ≠ end"};return{ok:!0,startHour:X,endHour:$}}var cH="Sustain keeps main-agent sessions warming past the idle cap for this process. Clock windows still apply.\n\nBefore enabling sustain with Magic Context, set a non-expiring `cache_ttl` for models used by main sessions; elapsed-time cold-cache assumptions are no longer valid.";function uH(Y){let J=(X,$,Q)=>JJ(Y,{setting:X,value:$},()=>R6(Y.store(),r1(m6(Y)),(G)=>{let z={...G.cacheKeep??{}};Q(z),G.cacheKeep=z}));return{title:"Cache",build:async()=>{let X=Y.cacheKeepManager;if(!X)return{lines:["Keep-warm unavailable"]};let $=await G9(Y);await $?.snapshot.refresh();let Q=K4($?$.snapshot.view():await Y.loadAccounts(m6(Y))),G=Q?.enabled===!0,z=Q?.subagents===!0,W=X.status(),U=W.window?YJ(W.window):"always (no window)";return{lines:[`Keep-warm ${G?"on":"off"} · ${W.tracked===0?"no sessions":`${W.tracked} session${W.tracked===1?"":"s"}`}`,`Timer ${W.running?"armed":"idle"} · subagents ${z?"on":"off"} · sustain ${W.sustain?"on":"off"}`,`Window ${U}`,...Y.cacheKeepNotice?[Y.cacheKeepNotice]:[],`TTL ${Math.round(W.ttlMs/1000)}s · lead ${Math.round(W.leadMs/1000)}s · idle cap ${Math.round(W.maxIdleWarmMs/60000)}min (subagents ${Math.round(W.maxSubagentIdleMs/60000)}min)`],items:W.targets.map((H)=>({id:H.sessionKey,label:H.sessionKey,group:"Sessions",detail:[H.accountId??"main",`expires in ${Math.ceil((H.cacheExpiresAt-W.generatedAt)/1000)}s`,...H.lastWarmedAt?[`last warm ${Math.ceil((W.generatedAt-H.lastWarmedAt)/1000)}s ago`]:[],...H.backoffUntil&&H.backoffUntil>W.generatedAt?[`backoff ${Math.ceil((H.backoffUntil-W.generatedAt)/1000)}s`]:[]].join(" · ")})),actions:[{id:"enabled",label:G?"Turn keep-warm off":"Turn keep-warm on",knobs:[{kind:"toggle",id:"enabled",label:"Keep-warm",value:!G}],run:async({values:H})=>{let V=H.enabled===!0;if(await J("cache_keep_enabled",V,(F)=>{F.enabled=V}),Y.setCacheKeepEnabled?.(V),V)X.start();else{for(let F of X.status().targets)if(!j4(F.sessionKey,!1))X.remove(F.sessionKey);if(X.status().tracked===0)X.stop()}return K6.info(V?"cachekeep enabled":"cachekeep disabled"),V?`Keep-warm is on. TTL ${Math.round(W.ttlMs/1000)}s, idle cap ${Math.round(W.maxIdleWarmMs/60000)}min.`:"Keep-warm is off."}},{id:"subagents",label:z?"Stop warming subagent sessions":"Warm subagent sessions too",knobs:[{kind:"toggle",id:"subagents",label:"Subagent warming",value:!z}],run:async({values:H})=>{let V=H.subagents===!0;return await J("cache_keep_subagents",V,(F)=>{F.subagents=V}),Y.setCacheKeepSubagents?.(V),`Subagent warming is ${V?"on":"off"}.`}},{id:"sustain",label:W.sustain?"Stop sustaining main sessions":"Sustain main sessions past the idle cap",knobs:[{kind:"toggle",id:"sustain",label:"Sustain",value:!W.sustain}],run:async({values:H})=>{let V=H.sustain===!0;return await J("cache_keep_sustain",V,(F)=>{F.sustain=V}),Y.setCacheKeepSustain?.(V),V?cH:"Main-agent sessions again stop warming at the configured idle cap."}},{id:"window",label:"Set the warm window",description:"Warm only between these local hours, e.g. 9-18 or 22-6. Leave it empty to warm at any hour.",knobs:[{kind:"text",id:"window",label:"Window (HH-HH)",placeholder:"9-18",...W.window?{value:YJ(W.window)}:{}}],run:async({values:H})=>{let V=H.window;if(typeof V!=="string"||V.trim()==="")return await J("cache_keep_window",[],(L)=>{delete L.startHour,delete L.endHour}),Y.setCacheKeepWindow?.(void 0),"Warm window cleared: keep-warm warms at any hour (within idle caps).";let F=mH(V);if(!F.ok)return{ok:!1,text:`Invalid window: ${F.reason}`};let{startHour:j,endHour:K}=F;return await J("cache_keep_window",[{start_hour:j,end_hour:K}],(L)=>{L.startHour=j,L.endHour=K}),Y.setCacheKeepWindow?.({startHour:j,endHour:K}),`Warming limited to ${YJ(F)} local hours.`}}]}}}}var F2=["error","warn","info","debug","trace"];function pH(Y){return{title:"Diagnostics",build:async()=>{let J=D2(Y),X=p8(J)?await oX({configPath:J,snapshot:Y.settingsSnapshot,log:K6}):{lines:[]},$=await G9(Y),Q=D1(J),G=s8(J),W=($?$.snapshot.view():await Y.loadAccounts(m6(Y)).catch(()=>null))?.logging?.level,U=!W||W==="default"?"info":W,H=G?await V2(Q.dumpDir):void 0,V=H===void 0?"size unavailable":aY(H),F=Q.dumpMaxBytes===0?"no cap":`${aY(Q.dumpMaxBytes)} cap`,j=Y.layoutNotice?.();return{lines:[G?`Dumps on (${V} / ${F})`:"Dumps off",`Dump directory: ${Q.dumpDir}`,`Log level: ${U}`,...j?[j]:[],...X.lines],actions:[{id:"dump",label:G?"Turn request dumps off":"Turn request dumps on",knobs:[{kind:"toggle",id:"enabled",label:"Request dumps",value:!G}],run:async({values:K})=>{let L=K.enabled===!0;await JJ(Y,{setting:"request_dumps",value:L},()=>R6(Y.store(),r1(m6(Y)),(q)=>{q.dump={...q.dump??{},enabled:L}}));let O=W7(J);return K6.info(L?"request dump enabled":"request dump disabled"),L?`Request dumps are on, written to ${O.dumpDir}.
|
|
5
|
-
|
|
6
|
-
Body dumps may contain prompt and session content. Turn this off after debugging.`:"Request dumps are off."}},{id:"logging",label:"Set the log level",knobs:[{kind:"choice",id:"level",label:"Level",choices:F2.map((K)=>({value:K,label:K})),value:F2.includes(U)?U:"info"}],run:async({values:K})=>{let L=String(K.level);return await JJ(Y,{setting:"log_level",value:L},()=>R6(Y.store(),r1(m6(Y)),(O)=>{O.logging={...O.logging??{},level:L}})),B4(L),K6.info("log level changed",{level:L}),`Log level set to ${L}.`}}]}}}}async function lH(Y){let J=await Y.store().read(),X=J.status==="ready"?J.rows:[];return[...new Set(["main",...X.filter(($)=>$.enabled&&$.type==="oauth").map(($)=>$.id)])]}function O2(Y){let J=m6(Y),X=Y.configPath??J.configPath,$=r1(J),Q=Y.settings??(Y.settingsSnapshot&&y1(X)==="shared"?{read:async()=>{let W=await G9(Y);if(!W)throw Error("Shared settings are unavailable");return i8({...W,host:"opencode",log:K6}).read()},update:async(W)=>{let U=await G9(Y);if(!U)throw Error("Shared settings are unavailable");await i8({...U,host:"opencode",log:K6}).update(W)}}:void 0),G=Y.quotaManager&&Y.resolveResetTarget&&Y.refreshResetTargetQuota&&Y.fetchImpl&&Y.now&&Y.randomUUID?TY({configPath:J.configPath,statePath:J.statePath,quotaManager:Y.quotaManager,loadAccounts:Y.loadAccounts,mutateAccounts:MY(Y.store(),$,X),resolveResetTarget:Y.resolveResetTarget,refreshResetTargetQuota:Y.refreshResetTargetQuota,fetchImpl:Y.fetchImpl,now:Y.now,randomUUID:Y.randomUUID,accountKeys:()=>lH(Y)}):void 0,z=Y.beginAccountLogin;return RY({store:Y.store(),configPath:X,...Q?{settings:Q}:{},...Y.readOnly?{readOnly:!0}:{},...Y.allowAction?{allowAction:Y.allowAction}:{},...Y.unavailableSections?{unavailableSections:Y.unavailableSections}:{},...Y.vault?{vault:Y.vault}:{},...Y.now?{now:Y.now}:{},extraLocks:$,rowLocks:(W)=>Z8(J,W),migration:Y.migration,...z?{login:{begin:(W)=>z({...W,version:Y.packageVersion}),mainIdentity:async()=>{let W=await Y.store().read();if(W.status!=="ready")return;return W.rows.find((U)=>U.id==="main")?.identity}}}:{},protect:(W,U)=>J4(W,U),...Y.refreshAllQuota?{quotaCheck:async(W)=>{if(W.length===1){let V=Y.store();for(let F of W)await V.requestReading(F);await V.pullsSettled();return}let H=(await Y.refreshAllQuota?.()??[]).filter((V)=>!V.ok);if(H.length>0)throw new d8("quota-check-failed",H.map((V)=>V.permanent?`${V.account}: sign-in no longer accepted — remove and add this account again`:`${V.account}: fetch failed — check again to retry`).join(`
|
|
7
|
-
`))}}:{},cache:uH(Y),diagnostics:pH(Y),extras:[...G?[G]:[],EY({...Y.getStickyRouting?{getPin:Y.getStickyRouting}:{},...Y.clearStickyRouting?{clearPin:Y.clearStickyRouting}:{}}),...Y.vault?[AY({vault:Y.vault,changed:Y.afterWrite})]:[]],afterApply:async()=>{await Y.afterWrite?.(),await Y.refreshSidebar?.().catch(()=>{})}})}function _2(Y){return(J,X="info")=>{K6.info("menu notification",{sessionId:Y,kind:X}),V4({command:W6,notify:{message:J,kind:X}},Y)}}function q2(Y,J){return O2(Y).open({...J!==void 0?{sessionId:J}:{},notify:_2(J)})}function P2(Y,J){return O2(Y).apply(J,{...J.sessionId!==void 0?{sessionId:J.sessionId}:{},notify:_2(J.sessionId)})}function M2(Y){let J=[`## ${Y.title}`];for(let X of Y.sections){J.push("",`### ${X.title}`);for(let $ of X.lines)J.push($);for(let $ of X.items){let Q=$.detail??$.status;J.push(`- ${$.label}${Q?`: ${Q}`:""}`)}}return J.push("","Open the OpenCode TUI to change these settings."),J.join(`
|
|
8
|
-
`)}var dH=300000,iH=30000,E2=240000,nH="bg-quota-refresh",oH=120000;function XJ(Y,J){return N4({name:nH,ttlMs:oH,path:Y,renew:!0,...J})}function A2(Y,J=L8,X=()=>XJ(Y.paths.configPath)){return rH(Y,J,X)}function rH(Y,J,X){return T2(async()=>J({...Y,respectBackoff:!0,skipFresherThanMs:E2}),X,[])}async function T2(Y,J,X){let $;try{$=await J()}catch{$=void 0}if($===null)return X;try{return await Y()}finally{await $?.release().catch(()=>{})}}function R2(Y,J,X){return T2(async()=>{return await Y.refreshDueTokens(J),Y.pollRows(J,{skipReadWithinMs:E2})},X,[])}class $J{setIntervalFn;clearIntervalFn;random;onError;run;timer;tickPromise;stopped=!1;constructor(Y={}){this.setIntervalFn=Y.setIntervalFn??setInterval,this.clearIntervalFn=Y.clearIntervalFn??clearInterval,this.random=Y.random??Math.random,this.onError=Y.onError}start(Y,J=this.onError){if(this.run=Y,this.onError=J,this.stopped=!1,this.timer)return;let X=Math.round((this.random()*2-1)*iH);if(this.timer=this.setIntervalFn(()=>{let $=this.run;if(this.stopped||!$||this.tickPromise)return;let Q=$().catch((G)=>{try{this.onError?.(G)}catch{}}).finally(()=>{if(this.tickPromise===Q)this.tickPromise=void 0});this.tickPromise=Q},dH+X),"unref"in this.timer)this.timer.unref()}stop(){if(this.stopped=!0,this.run=void 0,!this.timer)return;this.clearIntervalFn(this.timer),this.timer=void 0}isStopped(){return this.stopped}}function C2(Y,J){let X=new Intl.DateTimeFormat("en-GB",{timeZone:Y.tz,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(J),$=X.find((z)=>z.type==="hour")?.value,Q=X.find((z)=>z.type==="minute")?.value,G=`${$}:${Q}`;return Y.from<Y.to?G>=Y.from&&G<Y.to:G>=Y.from||G<Y.to}function QJ(Y){let{mode:J,now:X,ttlMs:$,leadMs:Q=30000,lastRealRequestAt:G,lastWarmAt:z,warmsSinceLastRealRequest:W,warmCostSoFar:U,nextWarmCost:H,rewriteCost:V}=Y;if(J==="off")return{action:"stop",reason:"unsupported"};if(!Number.isFinite($)||$<=0)return{action:"stop",reason:"unsupported"};if((J==="hours"||J==="always")&&W>=24)return{action:"stop",reason:"count-cap"};if(J==="auto"&&U!==void 0&&H!==void 0&&V!==void 0&&U+H>=V)return{action:"stop",reason:"cost-cap"};let j=Math.max(G,z??G)+$,K=Math.min(Number.isFinite(Q)&&Q>0?Q:30000,$/2),L=j-K,O=Math.max(X,L);if(O>=j-Math.min(5000,$/10))return{action:"stop",reason:"deadline-missed"};if(J==="hours"&&(!C2(Y.hours,L)||!C2(Y.hours,O)))return{action:"stop",reason:"outside-hours"};return X<L?{action:"wait",until:L}:{action:"warm",at:O}}var sH=["AbortError","TimeoutError","TypeError"],w2=["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","ENOTFOUND","EAI_AGAIN","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_HEADERS_OVERFLOW","UND_ERR_BODY_TIMEOUT","UND_ERR_RESPONSE_STATUS_CODE","UND_ERR_INVALID_ARG","UND_ERR_INVALID_RETURN_VALUE","UND_ERR_ABORTED","UND_ERR_CLIENT_DESTROYED","UND_ERR_CLIENT_CLOSED","UND_ERR_SOCKET","UND_ERR_NOT_SUPPORTED","UND_ERR_REQ_CONTENT_LENGTH_MISMATCH","UND_ERR_RES_CONTENT_LENGTH_MISMATCH","UND_ERR_INFO","UND_ERR_RES_EXCEEDED_MAX_SIZE","UND_ERR_PRX_TLS"];function GJ(Y,J){return typeof J==="string"&&Y.includes(J)}function j6(Y,J,X){try{if(X!==void 0&&Number.isInteger(X)&&X>=100&&X<=599&&(X<200||X>=300))return{stage:"response",class:X};if(typeof Y==="object"&&Y!==null){let $=Y,Q=$.name;if(Q==="AbortError"||Q==="TimeoutError")return{stage:J,class:Q};let G=$.code;if(GJ(w2,G))return{stage:J,class:G};let z=$.cause?.code;if(GJ(w2,z))return{stage:J,class:z};if(GJ(sH,Q))return{stage:J,class:Q}}}catch{}return{stage:J,class:"unknown"}}function zJ(Y){if(!Y||typeof Y!=="object")return;let J=Y,X=Number(J.startHour),$=Number(J.endHour);if(!Number.isInteger(X)||!Number.isInteger($)||X<0||X>23||$<0||$>23||X===$)return;return{startHour:X,endHour:$}}function z9(Y,J=new Date){if(!Y)return!1;let X=J.getHours();if(Y.startHour<Y.endHour)return X>=Y.startHour&&X<Y.endHour;return X>=Y.startHour||X<Y.endHour}var aH=300000,tH=3600000,eH=1800000,YV=60000,JV=32,XV=8388608,$V=30000,QV=600000,GV=20000,zV=60000,WV=5000;function c1(Y,J){return typeof Y==="number"&&Number.isFinite(Y)&&Y>0?Y:J}class W9{targets=new Map;lastDropReasons=new Map;adapter;now;log;ttlMs;leadMs;planLeadMs;maxIdleWarmMs;maxSubagentIdleMs;tickIntervalMs;maxTargets;maxBytes;warmTimeoutMs;backoff;getWindow;getSustain;setIntervalImpl;clearIntervalImpl;timer=null;startedAt=null;totalBytes=0;tickPromise=null;disposed=!1;planWarningLogged=!1;abortController=new AbortController;constructor(Y){this.adapter=Y.adapter,this.now=Y.now,this.log=Y.logger,this.ttlMs=c1(Y.ttlMs,aH),this.tickIntervalMs=c1(Y.tickIntervalMs,YV),this.leadMs=c1(Y.leadMs,this.tickIntervalMs+15000),this.planLeadMs=Y.planLeadMs,this.maxIdleWarmMs=c1(Y.maxIdleWarmMs,tH),this.maxSubagentIdleMs=c1(Y.maxSubagentIdleMs,eH),this.maxTargets=c1(Y.maxTargets,JV),this.maxBytes=c1(Y.maxBytes,XV),this.warmTimeoutMs=c1(Y.warmTimeoutMs,$V),this.backoff=Y.backoffMs,this.getWindow=Y.getWindow,this.getSustain=Y.getSustain,this.setIntervalImpl=Y.setIntervalImpl??globalThis.setInterval,this.clearIntervalImpl=Y.clearIntervalImpl??globalThis.clearInterval}track(Y){let{sessionKey:J,bodyText:X}=Y,$=this.targets.get(J),Q=this.readPlan(J);if(!Q&&$?.plan)return this.drop(J,"session-ended"),{tracked:!1,reason:"session-ended"};if(Q?.mode==="off")return this.drop(J,"unsupported"),{tracked:!1,reason:"unsupported"};this.pruneStale(Q?J:void 0);let G=Buffer.byteLength(X,"utf8");if(G>this.maxBytes)return this.log?.debug("cachekeep track skipped (body exceeds maxBytes)",{sessionKey:J,bodyBytes:G,maxBytes:this.maxBytes}),{tracked:!1,reason:"body-exceeds-max-bytes"};let z=this.getWindow?.();if(!Q&&z&&!z9(z,new Date(this.now())))return this.log?.debug("cachekeep track skipped (outside window)",{sessionKey:J,startHour:z.startHour,endHour:z.endHour}),{tracked:!1,reason:"outside-window"};let W=this.targets.get(J)?.hasWarmed??!1;this.drop(J,null);while(this.targets.size>=this.maxTargets||this.totalBytes+G>this.maxBytes&&this.targets.size>0){let L=this.leastRecentlyTouched();if(L===void 0)break;this.log?.debug("cachekeep evicted least recently used target",{sessionKey:L}),this.drop(L,"evicted")}let U=Y.isSubagent===!0,H=Y.accountId||void 0,V=this.adapter.profile?.({bodyText:X,isSubagent:U,accountId:H,meta:Y.meta}),F=c1(V?.ttlMs,this.ttlMs),j=this.now(),K={plan:Q,warmCostSoFar:0,hasWarmed:W,bodyText:X,bodyBytes:G,accountId:H,isSubagent:U,meta:Y.meta,ttlMs:F,maxWarms:V?.maxWarms!==void 0&&V.maxWarms>0?Math.floor(V.maxWarms):void 0,maxIdleMs:V?.maxIdleMs!==void 0?c1(V.maxIdleMs,this.idleDefault(U)):void 0,cacheExpiresAt:j+F,lastRealRequestAt:j,failures:0,warmCount:0};if(this.targets.set(J,K),this.lastDropReasons.delete(J),this.totalBytes+=G,this.log?.debug("cachekeep captured target",{sessionKey:J,accountId:H}),this.start(),Q)this.planDecision(J,K);return{tracked:!0}}remove(Y){if(this.drop(Y))this.log?.debug("cachekeep removed target",{sessionKey:Y})}start(){if(this.disposed=!1,this.timer)return;if(this.startedAt=this.now(),this.timer=this.setIntervalImpl(()=>{this.tick().catch((Y)=>{this.log?.warn("cachekeep tick failed",j6(Y,"send"))})},this.tickIntervalMs),typeof this.timer==="object"&&"unref"in this.timer)this.timer.unref();this.log?.debug("cachekeep started",{ttlMs:this.ttlMs,leadMs:this.leadMs,maxIdleWarmMs:this.maxIdleWarmMs})}stop(){if(this.disposed=!0,this.abortController.abort(),this.abortController=new AbortController,this.timer)this.clearIntervalImpl(this.timer),this.timer=null;this.startedAt=null;for(let Y of this.targets.keys())this.drop(Y,"stopped");this.totalBytes=0,this.log?.debug("cachekeep stopped")}warming(Y){try{if(this.targets.has(Y))return{on:!0};let J=this.lastDropReasons.get(Y);return{on:!1,...J!==void 0?{stopReason:J}:{}}}catch{return{on:!1}}}status(){let Y=this.getWindow?.();return{running:this.timer!==null,tracked:this.targets.size,totalBytes:this.totalBytes,generatedAt:this.now(),startedAt:this.startedAt,ttlMs:this.ttlMs,leadMs:this.leadMs,maxIdleWarmMs:this.maxIdleWarmMs,maxSubagentIdleMs:this.maxSubagentIdleMs,sustain:this.getSustain?.()===!0,...Y?{window:Y}:{},targets:[...this.targets].map(([J,X])=>({sessionKey:J,...X.plan?{mode:X.plan.mode}:{},accountId:X.accountId,isSubagent:X.isSubagent,cacheExpiresAt:X.cacheExpiresAt,lastRealRequestAt:X.lastRealRequestAt,...X.lastWarmedAt!==void 0?{lastWarmedAt:X.lastWarmedAt}:{},...X.backoffUntil!==void 0?{backoffUntil:X.backoffUntil}:{},failures:X.failures,warmCount:X.warmCount,ttlMs:X.ttlMs,bodyBytes:X.bodyBytes}))}}tick(){if(this.tickPromise)return this.tickPromise;let Y=this.runTick().finally(()=>{if(this.tickPromise===Y)this.tickPromise=null});return this.tickPromise=Y,Y}async runTick(){this.pruneStale();let Y=this.getWindow?.(),J=Y&&!z9(Y,new Date(this.now()));for(let[X,$]of[...this.targets]){if(this.disposed)return;if(this.targets.get(X)!==$)continue;if(!this.refreshPlan(X,$))continue;let Q=this.now();if($.plan){if(this.planDecision(X,$).action!=="warm")continue;if($.backoffUntil!==void 0&&Q<$.backoffUntil){this.schedulePlan(X,$,$.backoffUntil);continue}}else{if(J)continue;if($.cacheExpiresAt>Q+this.leadMs)continue}if($.backoffUntil!==void 0&&Q<$.backoffUntil)continue;if(!this.canRetry($))continue;await this.warm(X,$)}}retireIfExpired(Y,J){if(this.now()<J.cacheExpiresAt)return!1;return this.log?.debug("cachekeep retired target (cache lifetime ended)",{sessionKey:Y,accountId:J.accountId,cacheExpiresAt:J.cacheExpiresAt,failures:J.failures}),this.drop(Y,J.plan?"deadline-missed":"expired"),!0}isCurrent(Y,J){return!this.disposed&&this.targets.get(Y)===J}view(Y,J){return{sessionKey:Y,accountId:J.accountId,bodyText:J.bodyText,isSubagent:J.isSubagent,meta:J.meta,warmCount:J.warmCount,ttlMs:J.ttlMs}}readPlan(Y){try{return this.adapter.plan?.(Y)}catch{if(!this.planWarningLogged)this.planWarningLogged=!0,this.log?.warn("cachekeep plan unavailable");return}}refreshPlan(Y,J){let X=this.readPlan(Y);if(!X&&J.plan)return this.drop(Y,"session-ended"),!1;if(J.plan=X,X?.mode==="off")return this.drop(Y,"unsupported"),!1;return!0}usesLegacyBounds(Y){return!Y.plan||Y.plan.mode==="auto"&&!Y.plan.costs}planDecision(Y,J){let X=J.plan;if(!X)return{action:"stop",reason:"session-ended"};if(this.usesLegacyBounds(J)){if(this.retireIfIdle(Y,J,this.getSustain?.()===!0))return{action:"stop",reason:"idle"};if(J.maxWarms!==void 0&&J.warmCount>=J.maxWarms)return this.drop(Y,"count-cap"),{action:"stop",reason:"count-cap"}}let $=X.mode==="hours"&&!X.hours?{action:"stop",reason:"unsupported"}:QJ({...X.mode==="hours"?{mode:X.mode,hours:X.hours}:{mode:X.mode},now:this.now(),ttlMs:J.ttlMs,...this.planLeadMs!==void 0?{leadMs:this.planLeadMs}:{},lastRealRequestAt:J.lastRealRequestAt,lastWarmAt:J.lastWarmedAt,warmsSinceLastRealRequest:J.warmCount,...X.costs?{warmCostSoFar:J.warmCostSoFar,nextWarmCost:X.costs.nextWarm,rewriteCost:X.costs.rewrite}:{}});if($.action==="stop")this.drop(Y,$.reason);else if($.action==="wait")this.schedulePlan(Y,J,Math.max($.until,J.backoffUntil??0));else this.clearPlanTimer(J);return $}clearPlanTimer(Y){if(Y.planTimer===void 0)return;this.clearIntervalImpl(Y.planTimer),Y.planTimer=void 0,Y.planDueAt=void 0}schedulePlan(Y,J,X){if(J.planTimer!==void 0&&J.planDueAt===X)return;if(this.clearPlanTimer(J),J.planDueAt=X,J.planTimer=this.setIntervalImpl(()=>{return this.clearPlanTimer(J),(async()=>{if(await this.tickPromise,this.isCurrent(Y,J))await this.tick()})().catch(($)=>{this.log?.warn("cachekeep tick failed",j6($,"send"))})},Math.max(0,X-this.now())),typeof J.planTimer==="object"&&"unref"in J.planTimer)J.planTimer.unref()}report(Y){try{Promise.resolve(Y()).catch(()=>{this.log?.debug("cachekeep report failed")})}catch{this.log?.debug("cachekeep report failed")}}fail(Y,J,X,$,Q=!1,G){if(!this.isCurrent(Y,J))return;J.failures+=1;let z=this.now(),W=typeof this.backoff==="function"?this.backoff({sessionKey:Y,failures:J.failures}):this.backoff??QV,U=this.lastRetryStart(J),H=this.backoff===void 0&&Q&&z<U;if(H)W=Math.min(GV*J.failures,zV,U-z);if(J.backoffUntil=z+(Number.isFinite(W)&&W>0?W:0),this.clearRetry(J),H)this.scheduleRetry(Y,J,W);else if(J.plan)this.schedulePlan(Y,J,J.backoffUntil);this.log?.warn(X,{sessionKey:Y,accountId:J.accountId,failures:J.failures,backoffUntil:J.backoffUntil,...$,...G!==void 0&&{status:G}})}lastRetryStart(Y){return Y.cacheExpiresAt-this.warmTimeoutMs-WV}canRetry(Y){return this.backoff!==void 0||Y.failures===0||this.now()<=this.lastRetryStart(Y)}clearRetry(Y){if(Y.retryTimer===void 0)return;this.clearIntervalImpl(Y.retryTimer),Y.retryTimer=void 0}scheduleRetry(Y,J,X){if(J.retryTimer=this.setIntervalImpl(()=>{return this.clearRetry(J),(async()=>{if(await this.tickPromise,this.isCurrent(Y,J))await this.tick()})().catch(($)=>{this.log?.warn("cachekeep tick failed",j6($,"send"))})},X),typeof J.retryTimer==="object"&&"unref"in J.retryTimer)J.retryTimer.unref()}async warm(Y,J){if(this.retireIfExpired(Y,J))return;if(!this.canRetry(J))return;this.clearRetry(J);let X=this.view(Y,J);if(this.adapter.activeAccount){let K;try{K=await this.adapter.activeAccount(Y,X)}catch(L){this.fail(Y,J,"cachekeep skip (active account unknown)",j6(L,"authorization"),!0);return}if(!this.isCurrent(Y,J))return;if(K!==void 0&&K!==J.accountId){this.log?.debug("cachekeep dropped target (session changed account)",{sessionKey:Y,accountId:J.accountId,activeAccountId:K}),this.drop(Y,"account-changed");return}}let $;try{$=await this.adapter.buildBody(X)}catch(K){this.fail(Y,J,"cachekeep skip (replay body unbuildable)",j6(K,"authorization"));return}if(!this.isCurrent(Y,J))return;if(this.retireIfExpired(Y,J))return;if(!this.canRetry(J))return;if(!this.refreshPlan(Y,J))return;if(J.plan&&this.planDecision(Y,J).action!=="warm")return;let Q=J.plan?.costs?.nextWarm??0,G=I2([AbortSignal.timeout(this.warmTimeoutMs),this.abortController.signal]),z=G.signal,W,U="",H="send",V;try{W=await this.adapter.send({target:X,body:$,signal:z}),H="response",V=W.status,U=await W.text()}catch(K){this.fail(Y,J,"cachekeep failed",j6(K,H,V),V===void 0||V>=200&&V<300||V===408||V===429||V>=500,V);return}finally{G.dispose()}if(!this.isCurrent(Y,J))return;if(!W.ok){this.fail(Y,J,"cachekeep failed",j6(void 0,"response",W.status),W.status===408||W.status===429||W.status>=500,W.status);return}let F;try{F=this.adapter.readUsage?.({target:X,response:W,text:U})}catch{}let j=this.now();if(J.cacheExpiresAt=j+J.ttlMs,J.lastWarmedAt=j,J.backoffUntil=void 0,this.clearRetry(J),J.failures=0,J.warmCount+=1,J.hasWarmed=!0,J.warmCostSoFar+=Q,this.adapter.onWarmed)this.report(()=>this.adapter.onWarmed?.(Y,{at:j}));if(this.log?.debug("cachekeep fired",{sessionKey:Y,accountId:J.accountId,warmCount:J.warmCount,...F}),this.usesLegacyBounds(J)&&J.maxWarms!==void 0&&J.warmCount>=J.maxWarms)this.log?.debug("cachekeep retired target (warm cap reached)",{sessionKey:Y,warmCount:J.warmCount}),this.drop(Y,"count-cap");if(J.plan&&this.isCurrent(Y,J)){if(this.refreshPlan(Y,J))this.planDecision(Y,J)}}idleDefault(Y){return Y?this.maxSubagentIdleMs:this.maxIdleWarmMs}pruneStale(Y){let J=this.now(),X=this.getSustain?.()===!0;for(let[$,Q]of[...this.targets]){if($===Y)continue;if(this.retireIfExpired($,Q))continue;if(!this.refreshPlan($,Q))continue;if(!this.usesLegacyBounds(Q))continue;this.retireIfIdle($,Q,X,J)}}retireIfIdle(Y,J,X,$=this.now()){if(X&&!J.isSubagent)return!1;let Q=J.maxIdleMs??this.idleDefault(J.isSubagent);if(J.lastRealRequestAt>=$-Q)return!1;return this.log?.debug("cachekeep pruned idle target",{sessionKey:Y,accountId:J.accountId,lastRealRequestAt:J.lastRealRequestAt,maxIdleMs:Q}),this.drop(Y,"idle"),!0}leastRecentlyTouched(){let Y,J=Number.POSITIVE_INFINITY;for(let[X,$]of this.targets){let Q=Math.max($.lastRealRequestAt,$.lastWarmedAt??0);if(Q<J)Y=X,J=Q}return Y}drop(Y,J="session-ended"){let X=this.targets.get(Y);if(!X)return!1;if(this.clearRetry(X),this.clearPlanTimer(X),this.totalBytes-=X.bodyBytes,this.targets.delete(Y),J!==null){this.lastDropReasons.delete(Y),this.lastDropReasons.set(Y,J);while(this.lastDropReasons.size>this.maxTargets*4){let $=this.lastDropReasons.keys().next();if($.done)break;this.lastDropReasons.delete($.value)}}if(J!==null&&X.hasWarmed&&this.adapter.onWarmStopped)this.report(()=>this.adapter.onWarmStopped?.(Y,{at:this.now(),reason:J}));return!0}}function WJ(Y){if(typeof Y!=="string")return!1;try{let J=JSON.parse(Y);return n(J)&&n(J.client_metadata)&&J.client_metadata.ws_request_header_x_openai_internal_codex_responses_lite==="true"}catch{return!1}}function ZJ(Y){if(typeof Y!=="string")return Y;try{let J=JSON.parse(Y);if(!n(J)||!n(J.client_metadata))return Y;if(!(("x-codex-turn-metadata"in J.client_metadata)||("x-codex-ws-stream-request-start-ms"in J.client_metadata)||("ws_request_header_x_openai_internal_codex_responses_lite"in J.client_metadata)))return Y;let X={...J.client_metadata};return delete X["x-codex-turn-metadata"],delete X["x-codex-ws-stream-request-start-ms"],delete X.ws_request_header_x_openai_internal_codex_responses_lite,JSON.stringify({...J,client_metadata:X})}catch{return Y}}function L4(Y){if(Y?.method?.toUpperCase()!=="POST")return Y;let J=new Headers(Y.headers);if(J.set("accept","text/event-stream"),J.set("content-type","application/json"),WJ(Y.body))J.set("x-openai-internal-codex-responses-lite","true");return{...Y,headers:J,body:ZJ(Y.body)}}var v_=Object.freeze({maxTargets:32,maxBytes:8388608});function h2(Y){if(!Y.enabled||typeof Y.body!=="string")return;let J=Y.headers.has("x-parent-session-id");if(J&&!Y.includeSubagents)return;let X=Y.sessionID??Y.headers.get("session-id")??Y.headers.get("x-opencode-session")??Y.headers.get("x-session-affinity")??void 0;if(!X)return;let $={};for(let Q of["session-id","x-session-affinity","x-parent-session-id","user-agent","version","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-client-request-id","thread-id","x-openai-internal-codex-responses-lite"]){let G=Y.headers.get(Q);if(G)$[Q]=G}return{sessionKey:X,bodyText:Y.body,replayHeaders:$,isSubagent:J}}function y2(Y){return zJ(Y?.cachekeep)}var UJ=1800000,ZV=2,UV=2*UJ+900000;function HV(Y,J){return F4(Y,J)}function VV(Y){if(!S2(Y.bodyText))return;if(!Y.isSubagent)return{ttlMs:UJ};return{ttlMs:UJ,maxWarms:ZV,maxIdleMs:UV}}function BV(Y){let X=JSON.parse(Y);return X.store=!1,delete X.max_output_tokens,delete X.max_tokens,delete X.max_completion_tokens,JSON.stringify(X)}function HJ(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function f2(Y){if(!Y||typeof Y!=="object")return HJ();let J=Y,X=Number(J.input_tokens)||Number(J.prompt_tokens)||0,$=Number(J.output_tokens)||Number(J.completion_tokens)||0,Q=J.input_tokens_details??J.prompt_tokens_details,G=Number(Q?.cached_tokens)||Number(J.cached_tokens)||0,z=X>0?G/X:null;return{input_tokens:X,output_tokens:$,cached_tokens:G,hit_rate:z}}function KV(Y){try{let J=JSON.parse(Y);return f2(J.usage)}catch{return HJ()}}function jV(Y){let J,X=[],$,Q=()=>{if(!X.length)return;let G=X.join(`
|
|
9
|
-
`).trim();X=[];let z=J;if(J=void 0,!G||G==="[DONE]")return;try{let W=JSON.parse(G),U=W.type??z;if(U!=="response.completed"&&U!=="response.done")return;let H=W.response;$=f2(H?.usage??W.usage)}catch{}};for(let G of Y.split(/\r?\n/)){if(G===""){Q();continue}if(G.startsWith("event:")){J=G.slice(6).trim();continue}if(G.startsWith("data:"))X.push(G.slice(5).trim())}return Q(),$??HJ()}function g2(Y,J,X=Date.now()){if(!J)return;if(Y.route==="sticky-balanced"){let Q=Y.stickyAssignments?.[u1(J)];if(!Q)return;if(Q.lastSeenAt<X-v2)return;return Q.accountId}let $=Y.activeRouting?.[J];if(!$||$.route!==Y.route)return;return $.activeId}function NV(Y){let J=W1(Y);return J?Z1(J):void 0}function LV(Y){let{logger:J,activeAccount:X}=Y;return{plan:b2,onWarmed:k2,onWarmStopped:x2,buildBody:($)=>BV($.bodyText),async send({target:$,body:Q,signal:G}){let z=0,W=async(K,L,O)=>{G.throwIfAborted();let q={target:$,mode:L?"vault":"local",identity:(L?L.accountIdentity:O)??NV(K)};await Y.verifyCredential?.(q);let x=await Y.activity?.accountKey(q);G.throwIfAborted();let P=x?{sessionId:$.meta.routingSessionId??$.sessionKey,accountKey:x,dispatchedAt:(Y.now??Date.now)(),ttlMs:HV($.bodyText,$.ttlMs)}:void 0,b={...$.meta.replayHeaders,authorization:`Bearer ${K}`,"content-type":"application/json"};if($.meta.chatgptAccountId)b["ChatGPT-Account-Id"]=$.meta.chatgptAccountId;else delete b["ChatGPT-Account-Id"];let M,w=L&&Y.observeBillingSend?Y.observeBillingSend($,Q,L,++z):void 0;try{let S=JSON.parse(Q);M={warmBodyKeys:Object.keys(S),stream:S.stream,max_output_tokens:S.max_output_tokens,store:S.store,has_stream_options:"stream_options"in S,has_max_tokens:"max_tokens"in S,model:S.model}}catch{}J?.debug("cachekeep warm request",{...M,headerKeys:Object.keys(b),hasChatGptAccountId:"ChatGPT-Account-Id"in b});try{let S=await Y.fetchImpl($.meta.url??Y.codexResponsesUrl,L4({method:"POST",headers:b,body:Q,signal:G})),E=w?w.response(S):S;if(L&&$.accountId)Y.vault?.reportUsage($.accountId,{headers:E.headers},L);let v=await F8(E,K,"event-stream");if(!v.ok||!P||!Y.activity)return v;let u=Y.activity,c=async()=>{let J0=await X?.($.meta.routingSessionId);if(X&&J0!==$.accountId)return;let l=await u.accountKey(q);D4(u.store,P,l,{kind:"keep-warm",status:v.status,aborted:G.aborted})};if(!v.body)return await c(),v;let r=v.body.getReader();return new Response(new ReadableStream({async pull(J0){try{let l=await r.read();if(l.done)await c(),J0.close();else J0.enqueue(l.value)}catch(l){J0.error(l)}},cancel(J0){return r.cancel(J0)}}),{status:v.status,statusText:v.statusText,headers:v.headers})}catch(S){throw w?.failed(),c6(S,K)}};if($.accountId&&Y.vault?.owns($.accountId)){let K=await Y.vault.send($.accountId,W,{site:"cachekeep",signal:G});if(!K)throw Error(`vault refused warm for ${$.accountId}`);return K}if(Y.vault&&await Y.vault.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");let U,H,V,F=Y.resolveLocal?await Y.resolveLocal($):$.accountId&&$.accountId!=="main"?await Y.refreshFallback($.accountId):await Y.getMainToken();if(typeof F==="string")U=F;else U=F.token,H=F.identity,V=F.onAuthFailure;if(Y.vault&&await Y.vault.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");let j=await W(U,void 0,H);if(j.status===401)await V?.(j.status);return j},readUsage({response:$,text:Q}){let G=$.headers.get("content-type")??"",z=G.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(Q.slice(0,200));J?.debug("cachekeep warm response",{status:$.status,contentType:G,bodyLen:Q.length,isSse:z});let W=z?jV(Q):KV(Q),U=a1($.headers);return{...W,quota_primary_pct:U.primary?.usedPercent??null,quota_secondary_pct:U.secondary?.usedPercent??null}},profile:VV,...X?{activeAccount:($,Q)=>X(Q.meta.routingSessionId)}:{}}}function m2(Y){let{fetchImpl:J,observeBillingSend:X,getMainToken:$,refreshFallback:Q,resolveLocal:G,vault:z,codexResponsesUrl:W,activeAccount:U,verifyCredential:H,activity:V,logger:F,...j}=Y,K=Y.resolveLocal!==void 0?{resolveLocal:Y.resolveLocal}:{getMainToken:Y.getMainToken,refreshFallback:Y.refreshFallback};return new W9({...j,logger:F,adapter:LV({fetchImpl:J,observeBillingSend:X,...K,vault:z,codexResponsesUrl:W,activeAccount:U,verifyCredential:H,activity:V,now:Y.now,logger:F})})}function c2(Y){let J,X=0,$=0,Q=!1,G;return{read(){let z=Y.path(),W=Y.stat(z);if(W&&J?.path===z&&J.mtimeMs===W.mtimeMs&&J.size===W.size)return J.value;if(!W)J=void 0;let U=++X;return Y.read(z).catch(Y.fallback).then((H)=>{if(U>$){if($=U,G=H,Q=!0,W)J={...W,path:z,value:H};return Y.onRead(H),H}return Q?G:H})},invalidate(){J=void 0}}}import{readFileSync as FV}from"node:fs";var DV=60000,OV=15000,H9=2000,KJ=1e4;async function O8(Y,J){let X,$=await Promise.race([Y.then(()=>!0,()=>!0),new Promise((Q)=>{X=setTimeout(()=>Q(!1),J),X.unref?.()})]);return clearTimeout(X),$}function _V(Y){if(!t1(Y.quota))return;let J=_8(Y.quota);return J.limits.some((X)=>X.kind==="reading")?J.checkedAt:void 0}function qV(Y){if(!Y)return;let J=W1(Y);return J?Z1(J):void 0}function u2(Y){try{let J=JSON.parse(FV(Y,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return;return a8(J).migratedAt}catch{return}}function PV(Y){if(Y.type!=="oauth")return!1;return Y.candidate||Y.torn===!0&&Y.enabled}class jJ{listeners=new Set;deps;now;log;snapshot={active:!1,rows:[],key:void 0,readAt:0};inflightRead;store;stores=new Set;disposal;refreshing=new Map;backoff=new Map;rotated=new Map;pending=new Map;writes=new Map;limits;retiredLimits=[];lastPull=new Map;quotaPulls=new Map;polled=new Set;pollOutcomes=new Map;disposed=!1;vaultRosterSettled;pollsAwaitVault=!1;constructor(Y){this.deps=Y,this.now=Y.now??Date.now,this.log=Y.log??W0("pool"),this.vaultRosterSettled=Y.vaultFirstRoster===void 0;let J=()=>{this.vaultRosterSettled=!0};Y.vaultFirstRoster?.then(J,J)}async awaitVaultRoster(Y){let J=this.deps.vaultFirstRoster;if(this.vaultRosterSettled||!J)return;await O8(J,Y)}peek(){return{active:this.snapshot.active,rows:this.snapshot.rows}}subscribe(Y){return this.listeners.add(Y),()=>{this.listeners.delete(Y)}}async sidebarView(){let Y=this.deps.paths();if(u2(Y.configPath)===void 0)return{active:!1,rows:[]};let J=await this.storeFor(Y).read();return J.status==="ready"?{active:!0,rows:this.withLocalState(J.rows)}:{active:!1,rows:[]}}changed(){for(let Y of this.listeners)Y()}async current(){if(this.disposed)return this.peek();let Y=this.filesKey();if(this.snapshot.key===Y)return this.peek();let J=this.startRead(Y),X=await U9(J,this.deps.readBudgetMs??_4,()=>this.snapshot);return{active:X.active,rows:X.rows}}async load(){if(this.disposed)return this.peek();if(await this.deps.vaultAuthority?.(),this.disposed)return this.peek();let Y=await this.startRead(this.filesKey());return{active:Y.active,rows:Y.rows}}filesKey(){let Y=this.deps.paths();return`${Y.configPath}|${BJ(Y.configPath)}|${BJ(Y.statePath)}`}storeFor(Y){if(this.store?.configPath===Y.configPath&&this.store.statePath===Y.statePath)return this.store.store;let J=W8({provider:"openai",configPath:Y.configPath,statePath:Y.statePath,quota:z8,coalesceQuota:!0,now:this.now,pull:(X)=>this.coalescedPull(X),onPullFailure:(X,$)=>{this.pollOutcomes.set(X,{id:X,ok:!1,error:$.message}),this.log.warn("pool quota poll failed",{rowId:X,kind:$.kind,error:$.message})},logger:this.log,...this.deps.store,onStep:async(X,$)=>{if(await this.deps.store?.onStep?.(X,$),$.operation!=="updateSettings"&&X.startsWith("before-")&&this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")throw Error("Local account writes are disabled while connected to the vault.")}});return this.store={configPath:Y.configPath,statePath:Y.statePath,store:J},this.stores.add(J),J}startRead(Y){if(this.disposed)return Promise.resolve(this.snapshot);if(this.inflightRead?.key===Y)return this.inflightRead.promise;let J=this.now(),X=this.read(Y,J),$={key:Y,promise:X};this.inflightRead=$;let Q=()=>{if(this.inflightRead===$)this.inflightRead=void 0};return X.then(Q,Q),X}async read(Y,J){let X=this.deps.paths(),$={active:!1,rows:[],key:Y,readAt:J};try{if(u2(X.configPath)!==void 0){let z=await this.storeFor(X).read();if(z.status==="ready")$={active:!0,rows:z.rows,key:Y,readAt:J};else this.log.warn("migrated install has no readable account pool",{status:z.status,...z.status==="error"?{reason:z.reason}:{}})}}catch(G){return this.log.warn("account pool read failed",{error:G instanceof Error?G.message:String(G)}),this.snapshot}if(this.disposed)return this.snapshot;let Q=this.snapshot.active;if(J>=this.snapshot.readAt)this.snapshot={...$,rows:this.withLocalState($.rows)},this.changed();if(this.snapshot.active){if(!Q)this.log.info("account pool serves requests");this.pollUnseenRows()}return this.snapshot}withLocalState(Y){let J=this.now();return Y.map((X)=>{let $=X,Q=this.rotated.get(X.id),G=Q?.credential;if(Q&&Q.credentialEpoch!==X.credentialEpoch)this.rotated.delete(X.id);else if(G?.type==="oauth"&&X.credential?.type==="oauth"){let z=X.credential.lastRefreshedAt??0,W=G.lastRefreshedAt??0;if(z>=W)this.rotated.delete(X.id);else $={...$,credential:G}}return i2($,this.pending,J)})}replaceRow(Y,J){this.snapshot={...this.snapshot,rows:this.snapshot.rows.map((X)=>X.id===Y?J(X):X)},this.changed()}vaultOwned(Y){if(this.deps.vaultMode?.())return!0;return Y.identity!==void 0&&(this.deps.vaultIdentities?.().has(Y.identity)??!1)}pollUnseenRows(){if(this.disposed)return;let Y=this.deps.vaultFirstRoster;if(!this.vaultRosterSettled&&Y&&!this.deps.vaultMode?.()){if(this.pollsAwaitVault)return;this.pollsAwaitVault=!0,O8(Y,this.deps.vaultFirstRosterBackgroundWaitMs??KJ).then((J)=>{if(this.pollsAwaitVault=!1,J)this.pollUnseenRows();else this.log.info("first quota polls skipped: the vault has not read its accounts yet")});return}for(let J of this.snapshot.rows){if(!PV(J)||this.vaultOwned(J))continue;let X=`${J.id}\x00${J.credentialEpoch??0}\x00${J.identity??""}`;if(this.polled.has(X))continue;this.polled.add(X),this.requestReading(J.id,!0)}}requestReading(Y,J=!1){if(this.disposed||this.deps.vaultMode?.())return;let X=this.now(),$=this.lastPull.get(Y);if(!J&&$!==void 0&&X-$<(this.deps.pullRetryMs??OV))return this.storeFor(this.deps.paths()).pullsSettled();this.lastPull.set(Y,X);let Q=this.storeFor(this.deps.paths());return Q.requestReading(Y),Q.pullsSettled()}coalescedPull(Y){let J=JSON.stringify([this.deps.paths().configPath,Y.id,Y.credentialEpoch,Y.identity]),X=this.quotaPulls.get(J);if(X)return X;let $=this.pull(Y).finally(()=>this.quotaPulls.delete(J));return this.quotaPulls.set(J,$),$}async pull(Y){if(this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")throw Error("local accounts are not polled while this host is connected to the vault");let J;try{if(J=await this.deps.pullQuota(Y),!J)throw Error("the quota poll returned no reading")}catch($){throw this.pollOutcomes.set(Y.id,{id:Y.id,ok:!1,error:$ instanceof Error?$.message:String($)}),$}this.pollOutcomes.set(Y.id,{id:Y.id,ok:!0});let X=this.snapshot.rows.find(($)=>$.id===Y.id);if(X&&X.credentialEpoch===Y.credentialEpoch&&X.identity===Y.identity)this.applyObservation(X,J);return J}applyObservation(Y,J){d2(this.pending,Y,J),this.replaceRow(Y.id,(X)=>({...X,quota:l2(X.quota,J),needsFirstReading:!1}))}recordSnapshot(Y,J,X,$){if(!this.snapshot.active||this.disposed||this.deps.vaultMode?.())return;let Q=this.snapshot.rows.find((j)=>j.id===Y);if(Q?.type!=="oauth")return;let G=qV(X);if(!(G&&Q.identity?G===Q.identity:D8(Q)?.access===X))return;let W=B8(J,this.now(),$);if(!W)return;if(this.applyObservation(Q,W),Q.credentialEpoch===void 0)return;let U={credentialEpoch:Q.credentialEpoch,...Q.identity!==void 0?{identity:Q.identity}:{}},H=this.storeFor(this.deps.paths()),F=(this.writes.get(Q.id)??Promise.resolve()).then(async()=>{if(this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")return;return H.recordQuota(Q.id,U,W)}).catch((j)=>{this.log.warn("pool quota not recorded",{rowId:Q.id,error:j instanceof Error?j.message:String(j)})});this.writes.set(Q.id,F),F.finally(()=>{if(this.writes.get(Q.id)===F)this.writes.delete(Q.id)})}limitsBindings(){let Y=this.limits?.owner.namespace;if(!Y||!this.snapshot.active||this.deps.vaultMode?.())return[];return this.snapshot.rows.flatMap((J)=>{let X=VJ(Y,J);return X?[X]:[]})}limitsBinding(Y){let J=this.limits?.owner.namespace;return J?VJ(J,Y):void 0}async limitsForRequest(){if(this.disposed)return;let Y=await this.deps.vaultAuthority?.();if(Y!==void 0&&Y!=="local")return;if(this.disposed||this.deps.vaultMode?.())return;let J=await this.load();if(this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")return;if(!J.active||this.disposed||this.deps.vaultMode?.())return;let X=this.deps.paths(),$=JSON.stringify([X.configPath,X.statePath]);if(this.limits?.key!==$){if(this.limits)this.retiredLimits.push(this.limits.owner.dispose());this.limits={key:$,owner:O4({source:{kind:"pool",...X,store:this.poolStore()},log:(G)=>this.log.warn(G)})}}let Q=await this.limits.owner.forRequest(!0);return await Q.reloadForBindings(()=>this.limitsBindings()),Q}limitsOwner(){return this.limits?.owner}async prepareTokens(Y,J,X={}){if(this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")return;if(!this.deps.vaultMode?.())await this.awaitVaultRoster(this.deps.vaultFirstRosterWaitMs??H9);let $=this.now(),Q=p2(M1(J,this.deps.paths().configPath)),G=[];for(let z of Y){if(!z.candidate||this.vaultOwned(z))continue;let W=D8(z);if(!W)continue;let U=(W.expires??0)-$;if(!(!W.access||!W.expires||U<=Q)||this.refreshBackedOff(z,J,$))continue;let V=this.refresh(z.id);if(X.waitForAll||!W.access||!W.expires||U<=DV)G.push(V)}await Promise.all(G)}refreshBackedOff(Y,J,X=this.now()){let $=D8(Y);if(!$)return!1;let Q=Z9($.refresh),G=this.backoff.get(Y.id);if(G&&G.tokenHash===Q&&G.nextRetryAt>X)return!0;let z=J?.accounts.find((W)=>W.id===Y.id);return Boolean(z?.type==="oauth"&&z.corrupt!==!0&&s1(z.lastRefreshError,$.refresh,X))}usableToken(Y,J=this.now()){let X=this.snapshot.rows.find((Q)=>Q.id===Y.id);if(!X?.enabled||!X.candidate||X.type!=="oauth"||X.identity!==Y.identity||X.credentialEpoch!==Y.credentialEpoch||this.vaultOwned(X))return;let $=D8(X);if(!$?.access.trim())return;if(typeof $.expires!=="number"||$.expires<=J)return;return $.access}refresh(Y){let J=this.refreshing.get(Y);if(J)return J;let X=this.runRefresh(Y).finally(()=>{if(this.refreshing.get(Y)===X)this.refreshing.delete(Y)});return this.refreshing.set(Y,X),X}async runRefresh(Y){if(this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")return;let J=this.deps.paths(),X=this.snapshot.rows.find((z)=>z.id===Y),$=X?D8(X)?.refresh:void 0,Q,G=(z,W)=>{return Q=W.credentialEpoch,this.deps.refreshProvider(z,W)};try{let z=await r2({paths:J,store:this.storeFor(J),now:this.now,...this.deps.legacyLocks?{legacyLocks:this.deps.legacyLocks}:{}},Y,G);if(z.status==="rotated"){this.backoff.delete(Y),this.rotated.set(Y,{credential:z.credential,credentialEpoch:Q}),this.replaceRow(Y,(W)=>W.credentialEpoch!==Q?W:{...W,credential:z.credential,...z.identity!==void 0&&W.identity===void 0?{identity:z.identity}:{}});return}if(z.status==="identity-contradicted"){this.backoff.delete(Y),this.replaceRow(Y,(W)=>({...W,enabled:!1,candidate:!1})),this.log.warn("pool row disabled: its refresh returned a different account",{rowId:Y});return}this.recordRefreshFailure(Y,$,Error(z.reason))}catch(z){this.recordRefreshFailure(Y,$,z)}}recordRefreshFailure(Y,J,X){if(this.log.warn("pool row refresh failed",{rowId:Y,error:X instanceof Error?X.message:String(X)}),!J)return;this.backoff.set(Y,n2(J,X,this.now(),this.backoff.get(Y)))}refreshBackoffFor(Y){return o2(Y,this.backoff,this.now(),(J,X)=>this.usableToken(J,X))}async active(){return(await this.current()).active}poolStore(){return this.storeFor(this.deps.paths())}async refreshDueTokens(Y){let J=await this.current();if(!J.active||this.disposed)return;await this.prepareTokens(J.rows,Y,{waitForAll:!0})}async pollRows(Y,J={}){let X=await this.load();if(!X.active||this.disposed)return[];let $=this.now(),Q=X.rows.filter((G)=>{if(!G.candidate||G.type!=="oauth"||this.vaultOwned(G))return!1;if(J.ids&&!J.ids.includes(G.id))return!1;if(J.skipReadWithinMs===void 0)return!0;let z=_V(G);return z===void 0||$-z>=J.skipReadWithinMs});if(Q.length===0)return[];await this.prepareTokens(Q,Y,{waitForAll:!0});for(let G of Q)this.pollOutcomes.delete(G.id),this.requestReading(G.id,!0);return await this.poolStore().pullsSettled(),Q.map((G)=>this.pollOutcomes.get(G.id)??{id:G.id,ok:!1,error:"the quota poll did not run"})}async accessFor(Y,J){let X=await this.current();if(!X.active)return;let $=X.rows.find((z)=>z.id===Y);if(!$?.candidate)return;await this.prepareTokens([$],J);let Q=this.snapshot.rows.find((z)=>z.id===Y)??$;if(!Q.candidate)return;let G=this.usableToken(Q);return G?{row:Q,token:G}:void 0}async rowAccess(Y,J){let X=await this.current();if(!X.active)return;let $=X.rows.find((G)=>G.id===Y);if(!$)return{};let Q=await this.accessFor(Y,J);return{row:{id:$.id,type:$.type,enabled:$.enabled,...$.label!==void 0?{label:$.label}:{},...$.identity!==void 0?{identity:$.identity}:{}},...Q?{token:Q.token}:{}}}dispose(){return this.disposed=!0,this.disposal??=(async()=>{await Promise.allSettled([...this.writes.values()]),await Promise.all([...this.retiredLimits,this.limits?.owner.dispose()]),await Promise.all([...this.stores].map((Y)=>Y.close()))})(),this.disposal}async settled(){for(;;){let Y=[...this.writes.values(),...this.refreshing.values(),...this.inflightRead?[this.inflightRead.promise]:[]];if(await Promise.allSettled(Y),await this.store?.store.pullsSettled(),this.writes.size===0&&this.refreshing.size===0&&!this.inflightRead){await this.disposal;return}}}}async function V9(Y,J){let X=Y-performance.now();if(X<=0)return;let $;return await O8(J().then((Q)=>{$=Q}),X),$}class LJ{options;activity=s2();vaultOwner;disposed=!1;disposal;constructor(Y){this.options=Y}async forRequest(Y=performance.now()+H9){if(this.disposed)return;let J=this.options.vault.enrolled()?await V9(Y,()=>this.options.vault.authority()):await this.options.vault.authority();if(this.disposed||!J||J==="unreadable")return;if(J==="local")return this.options.pool.limitsForRequest();return V9(Y,()=>this.vaultRequest(Y))}async vaultRequest(Y){if(await this.options.vault.awaitRequestRoster(),this.disposed||performance.now()>=Y)return;let J=await this.options.vault.authority();if(J!=="vault"&&J!=="host")return;if(this.disposed||performance.now()>=Y)return;if(!this.options.vault.snapshot()||!this.options.vault.routes().some(($)=>$.kind==="oauth"))return;this.vaultOwner??=O4({source:{kind:"vault",rosterPath:this.options.vault.paths.rosterPath},log:this.options.log});let X=await this.vaultOwner.forRequest(!0);if(this.disposed||performance.now()>=Y)return;return await X.reloadForBindings(()=>this.ownershipBindings()),X}owner(){return this.options.vault.enrolled()?this.vaultOwner:this.options.pool.limitsOwner()}bindings(){if(this.disposed)return[];let Y=this.options.vault,J=this.vaultOwner;if(Y.enrolled()){if(!J)return[];let X=new Set(Y.routes().filter(($)=>$.kind==="oauth").map(($)=>$.id));return(Y.snapshot()?.rows??[]).flatMap(($)=>X.has($.routeId)?[NJ(J.namespace,$)]:[])}return this.options.pool.limitsBindings()}ownershipBindings(){if(this.disposed)return[];if(!this.options.vault.enrolled())return this.options.pool.limitsBindings();let Y=this.vaultOwner;return Y?(this.options.vault.snapshot()?.rows??[]).filter((J)=>J.credentialType==="oauth").map((J)=>NJ(Y.namespace,J)):[]}accountKey(Y){return this.bindings().find((J)=>J.account.accountId===Y)?.account}marks(){let Y=this.bindings();return Y.length?MV(this.owner()?.snapshot(),Y):new Map}forget(Y){this.activity.forgetSession(Y)}dispose(){return this.disposed=!0,this.disposal??=(async()=>{await this.vaultOwner?.dispose(),await this.options.pool.dispose()})(),this.disposal}}function MV(Y,J,X=Date.now()){let $=new Map;for(let Q of J)for(let G of Y?.marks??[]){if(G.key.scope.kind!=="pool"||G.key.window!=="account")continue;if(!O1(Q.account,G.key.account))continue;for(let z of G.entries)if(z.until>X&&z.until>($.get(Q.account.accountId)??0))$.set(Q.account.accountId,z.until)}return $}var a2=60000,FJ=900000,EV={set(Y,J){let X=setTimeout(Y,J);return X.unref?.(),X},clear(Y){clearTimeout(Y)}};function AV(Y){return Y.status==="completed"||Y.status==="already-migrated"||Y.status==="nothing-to-import"||Y.status==="ambiguous"}function t2(Y){return Y.status==="deferred"||Y.status==="retry"||Y.status==="error"}function e2(Y){let J=Y.log??W0("pool-migration"),X=Y.timers??EV,$=Y.random??Math.random,Q=Y.migrate??q4,G=Y.adopt??P4,z=Y.fence??(()=>K8({currentVersion:Y.version})),W=!1,U=new AbortController,H=!1,V=!1,F=0,j,K=Promise.resolve(),L,O,q,x=!1;function P(){if(x)return;x=!0,J.warn(H8,{reason:"placeholder-without-main"})}let b=()=>({paths:Y.paths(),slot:Y.slot,log:J,...Y.runDeps,signal:U.signal});function M(l){let T=K.then(l).catch((B0)=>{J.warn("account pool background run failed",{error:B0 instanceof Error?B0.message:String(B0)})});return K=T,T}function w(l){if(H)return;if(j!==void 0)X.clear(j);j=X.set(()=>{j=void 0,M(r)},l)}function S(){let l=Math.min(a2*2**Math.min(F,10),FJ);return F++,E(l)}let E=(l)=>Math.round(l*(1-0.2*$()));async function v(){if(!await Y.paused?.())return!1;return w(E(a2)),!0}async function u(){if(H||await v()||H)return;let l;try{l=await Q({...b(),fence:z})}catch(T){J.warn("account pool migration failed; it will be tried again",{error:T instanceof Error?T.message:String(T)}),w(S());return}if(l.status==="refused"){if(l.reason==="placeholder-without-main")P();w(E(FJ));return}if(AV(l)){if(V=!0,F=0,l.status==="completed")J.info("account pool migration completed",{rowId:l.rowId});await c();return}if(t2(l)){if(l.status!=="deferred")J.warn("account pool migration will be tried again",{outcome:l});w(S())}}async function c(){if(H||await v()||H)return;let l;try{let T=await z();if(H)return;if(!T.open){let B0=JSON.stringify(T.blockers);if(B0!==q)q=B0,J.info("host login adoption waits for older plugin versions",{blockers:T.blockers});w(S());return}l=await G(b())}catch(T){J.warn("adopting the host login into the account pool failed",{error:T instanceof Error?T.message:String(T)}),w(S());return}if(l.status==="not-migrated")return;if(l.status==="slot-read-only")return;if(V=!0,l.status==="completed")J.info("host login adopted into the account pool",{rowId:l.rowId,operation:l.operation});if(t2(l)){J.warn("host login adoption will be tried again",{outcome:l}),w(S());return}if(F=0,V)w(E(FJ))}async function r(){if(H)return;if(V)await c();else await u()}function J0(){if(L)return L;let l=M(async()=>{if(L=void 0,!H)if(V)await c();else await u()});return L=l,l}return{start(){if(W||H)return;W=!0,M(u)},requestAdoption:J0,noticePlaceholderWithoutMain:P,noticeRealSlot(l){if(!V||H||l===O)return;O=l,J0()},dispose(){if(H=!0,U.abort(),j!==void 0)X.clear(j);j=void 0},idle:async()=>{for(;;){let l=K;if(await l,l===K)return}},migrated:()=>V}}var p0={};OJ(p0,{toWebSocketUrl:()=>iN,streamResponsesWebSocket:()=>aN,parseRateLimitSignal:()=>n6,observeHttpCompletion:()=>n4,normalizeHeaders:()=>nN,markOversizedFrame:()=>xz,isUpgradeFailure:()=>oN,isOversizedFrame:()=>rN,isNonEmittingFrame:()=>yz,isAbortError:()=>V3,connectResponsesWebSocket:()=>sN,TERMINAL_AFTER_OUTPUT_MESSAGE:()=>H3,RATE_LIMIT_WINDOW:()=>hz,PROTOCOL_HEADER:()=>Sz,OpenAIWebSocket:()=>p0,OVERSIZED_FRAME_MESSAGE:()=>fz});var TV=Symbol.for("vercel.ai.error"),e1=class Y extends Error{constructor({name:J,message:X,cause:$}){super(X);this[TV]=!0,this.name=J,this.cause=$}static isInstance(J){return Y.hasMarker(J,"vercel.ai.error")}static hasMarker(J,X){let $=Symbol.for(X);return J!=null&&typeof J==="object"&&$ in J&&typeof J[$]==="boolean"&&J[$]===!0}},RV="AI_DecisionUnsupportedQuestionTypeError",Qq=`vercel.ai.error.${RV}`;var Y5="AI_APICallError",J5=`vercel.ai.error.${Y5}`,CV=Symbol.for(J5),u6=class extends e1{constructor({message:Y,url:J,requestBodyValues:X,statusCode:$,responseHeaders:Q,responseBody:G,cause:z,isRetryable:W=$!=null&&($===408||$===409||$===429||$>=500),data:U}){super({name:Y5,message:Y,cause:z});this[CV]=!0,this.url=J,this.requestBodyValues=X,this.statusCode=$,this.responseHeaders=Q,this.responseBody=G,this.isRetryable=W,this.data=U}static isInstance(Y){return e1.hasMarker(Y,J5)}},wV="AI_EmptyResponseBodyError",Gq=`vercel.ai.error.${wV}`;var IV="AI_DecisionRefusalError",zq=`vercel.ai.error.${IV}`;var X5="AI_InvalidArgumentError",$5=`vercel.ai.error.${X5}`,SV=Symbol.for($5),Q5=class extends e1{constructor({message:Y,cause:J,argument:X}){super({name:X5,message:Y,cause:J});this[SV]=!0,this.argument=X}static isInstance(Y){return e1.hasMarker(Y,$5)}},bV="AI_InvalidPromptError",Wq=`vercel.ai.error.${bV}`;var kV="AI_InvalidResponseDataError",Zq=`vercel.ai.error.${kV}`;var xV="AI_JSONParseError",Uq=`vercel.ai.error.${xV}`;var vV="AI_LoadAPIKeyError",Hq=`vercel.ai.error.${vV}`;var hV="AI_LoadSettingError",Vq=`vercel.ai.error.${hV}`;var yV="AI_NoContentGeneratedError",Bq=`vercel.ai.error.${yV}`;var fV="AI_NoSuchModelError",Kq=`vercel.ai.error.${fV}`;var gV="AI_NoSuchProviderReferenceError",jq=`vercel.ai.error.${gV}`;var mV="AI_TooManyEmbeddingValuesForCallError",Nq=`vercel.ai.error.${mV}`;var cV="AI_TypeValidationError",Lq=`vercel.ai.error.${cV}`;var uV="AI_UnsupportedFunctionalityError",Fq=`vercel.ai.error.${uV}`;var qq=Object.freeze({status:"aborted"});function _(Y,J,X){function $(W,U){var H;Object.defineProperty(W,"_zod",{value:W._zod??{},enumerable:!1}),(H=W._zod).traits??(H.traits=new Set),W._zod.traits.add(Y),J(W,U);for(let V in z.prototype)if(!(V in W))Object.defineProperty(W,V,{value:z.prototype[V].bind(W)});W._zod.constr=z,W._zod.def=U}let Q=X?.Parent??Object;class G extends Q{}Object.defineProperty(G,"name",{value:Y});function z(W){var U;let H=X?.Parent?new G:this;$(H,W),(U=H._zod).deferred??(U.deferred=[]);for(let V of H._zod.deferred)V();return H}return Object.defineProperty(z,"init",{value:$}),Object.defineProperty(z,Symbol.hasInstance,{value:(W)=>{if(X?.Parent&&W instanceof X.Parent)return!0;return W?._zod?.traits?.has(Y)}}),Object.defineProperty(z,"name",{value:Y}),z}var Pq=Symbol("zod_brand");class Y6 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class B9 extends Error{constructor(Y){super(`Encountered unidirectional transform during encode: ${Y}`);this.name="ZodEncodeError"}}var M4={};function p1(Y){if(Y)Object.assign(M4,Y);return M4}var $0={};OJ($0,{unwrapMessage:()=>K9,uint8ArrayToHex:()=>jB,uint8ArrayToBase64url:()=>BB,uint8ArrayToBase64:()=>B5,stringifyPrimitive:()=>Z5,shallowClone:()=>z5,safeExtend:()=>zB,required:()=>UB,randomString:()=>eV,propertyKeyTypes:()=>PJ,promiseAllObject:()=>tV,primitiveTypes:()=>W5,prefixIssues:()=>X6,pick:()=>$B,partial:()=>ZB,optionalKeys:()=>MJ,omit:()=>QB,objectClone:()=>rV,numKeys:()=>YB,nullish:()=>N9,normalizeParams:()=>o,mergeDefs:()=>L6,merge:()=>WB,jsonStringifyReplacer:()=>q8,joinValues:()=>oV,issue:()=>M8,isPlainObject:()=>F6,isObject:()=>p6,hexToUint8Array:()=>KB,getSizableOrigin:()=>H5,getParsedType:()=>JB,getLengthableOrigin:()=>F9,getEnumValues:()=>j9,getElementAtPath:()=>aV,floatSafeRemainder:()=>_J,finalizeIssue:()=>A1,extend:()=>GB,escapeRegex:()=>J6,esc:()=>E4,defineLazy:()=>U0,createTransparentProxy:()=>XB,cloneDef:()=>sV,clone:()=>E1,cleanRegex:()=>L9,cleanEnum:()=>HB,captureStackTrace:()=>A4,cached:()=>P8,base64urlToUint8Array:()=>VB,base64ToUint8Array:()=>V5,assignProp:()=>N6,assertNotEqual:()=>lV,assertNever:()=>iV,assertIs:()=>dV,assertEqual:()=>pV,assert:()=>nV,allowsEval:()=>qJ,aborted:()=>D6,NUMBER_FORMAT_RANGES:()=>EJ,Class:()=>K5,BIGINT_FORMAT_RANGES:()=>U5});function pV(Y){return Y}function lV(Y){return Y}function dV(Y){}function iV(Y){throw Error()}function nV(Y){}function j9(Y){let J=Object.values(Y).filter(($)=>typeof $==="number");return Object.entries(Y).filter(([$,Q])=>J.indexOf(+$)===-1).map(([$,Q])=>Q)}function oV(Y,J="|"){return Y.map((X)=>Z5(X)).join(J)}function q8(Y,J){if(typeof J==="bigint")return J.toString();return J}function P8(Y){return{get value(){{let X=Y();return Object.defineProperty(this,"value",{value:X}),X}throw Error("cached value already set")}}}function N9(Y){return Y===null||Y===void 0}function L9(Y){let J=Y.startsWith("^")?1:0,X=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(J,X)}function _J(Y,J){let X=(Y.toString().split(".")[1]||"").length,$=J.toString(),Q=($.split(".")[1]||"").length;if(Q===0&&/\d?e-\d?/.test($)){let U=$.match(/\d?e-(\d?)/);if(U?.[1])Q=Number.parseInt(U[1])}let G=X>Q?X:Q,z=Number.parseInt(Y.toFixed(G).replace(".","")),W=Number.parseInt(J.toFixed(G).replace(".",""));return z%W/10**G}var G5=Symbol("evaluating");function U0(Y,J,X){let $=void 0;Object.defineProperty(Y,J,{get(){if($===G5)return;if($===void 0)$=G5,$=X();return $},set(Q){Object.defineProperty(Y,J,{value:Q})},configurable:!0})}function rV(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function N6(Y,J,X){Object.defineProperty(Y,J,{value:X,writable:!0,enumerable:!0,configurable:!0})}function L6(...Y){let J={};for(let X of Y){let $=Object.getOwnPropertyDescriptors(X);Object.assign(J,$)}return Object.defineProperties({},J)}function sV(Y){return L6(Y._zod.def)}function aV(Y,J){if(!J)return Y;return J.reduce((X,$)=>X?.[$],Y)}function tV(Y){let J=Object.keys(Y),X=J.map(($)=>Y[$]);return Promise.all(X).then(($)=>{let Q={};for(let G=0;G<J.length;G++)Q[J[G]]=$[G];return Q})}function eV(Y=10){let X="";for(let $=0;$<Y;$++)X+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return X}function E4(Y){return JSON.stringify(Y)}var A4="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function p6(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var qJ=P8(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function F6(Y){if(p6(Y)===!1)return!1;let J=Y.constructor;if(J===void 0)return!0;let X=J.prototype;if(p6(X)===!1)return!1;if(Object.prototype.hasOwnProperty.call(X,"isPrototypeOf")===!1)return!1;return!0}function z5(Y){if(F6(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function YB(Y){let J=0;for(let X in Y)if(Object.prototype.hasOwnProperty.call(Y,X))J++;return J}var JB=(Y)=>{let J=typeof Y;switch(J){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(Y)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(Y))return"array";if(Y===null)return"null";if(Y.then&&typeof Y.then==="function"&&Y.catch&&typeof Y.catch==="function")return"promise";if(typeof Map<"u"&&Y instanceof Map)return"map";if(typeof Set<"u"&&Y instanceof Set)return"set";if(typeof Date<"u"&&Y instanceof Date)return"date";if(typeof File<"u"&&Y instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${J}`)}},PJ=new Set(["string","number","symbol"]),W5=new Set(["string","number","bigint","boolean","symbol","undefined"]);function J6(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function E1(Y,J,X){let $=new Y._zod.constr(J??Y._zod.def);if(!J||X?.parent)$._zod.parent=Y;return $}function o(Y){let J=Y;if(!J)return{};if(typeof J==="string")return{error:()=>J};if(J?.message!==void 0){if(J?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");J.error=J.message}if(delete J.message,typeof J.error==="string")return{...J,error:()=>J.error};return J}function XB(Y){let J;return new Proxy({},{get(X,$,Q){return J??(J=Y()),Reflect.get(J,$,Q)},set(X,$,Q,G){return J??(J=Y()),Reflect.set(J,$,Q,G)},has(X,$){return J??(J=Y()),Reflect.has(J,$)},deleteProperty(X,$){return J??(J=Y()),Reflect.deleteProperty(J,$)},ownKeys(X){return J??(J=Y()),Reflect.ownKeys(J)},getOwnPropertyDescriptor(X,$){return J??(J=Y()),Reflect.getOwnPropertyDescriptor(J,$)},defineProperty(X,$,Q){return J??(J=Y()),Reflect.defineProperty(J,$,Q)}})}function Z5(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function MJ(Y){return Object.keys(Y).filter((J)=>{return Y[J]._zod.optin==="optional"&&Y[J]._zod.optout==="optional"})}var EJ={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},U5={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function $B(Y,J){let X=Y._zod.def,$=L6(Y._zod.def,{get shape(){let Q={};for(let G in J){if(!(G in X.shape))throw Error(`Unrecognized key: "${G}"`);if(!J[G])continue;Q[G]=X.shape[G]}return N6(this,"shape",Q),Q},checks:[]});return E1(Y,$)}function QB(Y,J){let X=Y._zod.def,$=L6(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape};for(let G in J){if(!(G in X.shape))throw Error(`Unrecognized key: "${G}"`);if(!J[G])continue;delete Q[G]}return N6(this,"shape",Q),Q},checks:[]});return E1(Y,$)}function GB(Y,J){if(!F6(J))throw Error("Invalid input to extend: expected a plain object");let X=Y._zod.def.checks;if(X&&X.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let Q=L6(Y._zod.def,{get shape(){let G={...Y._zod.def.shape,...J};return N6(this,"shape",G),G},checks:[]});return E1(Y,Q)}function zB(Y,J){if(!F6(J))throw Error("Invalid input to safeExtend: expected a plain object");let X={...Y._zod.def,get shape(){let $={...Y._zod.def.shape,...J};return N6(this,"shape",$),$},checks:Y._zod.def.checks};return E1(Y,X)}function WB(Y,J){let X=L6(Y._zod.def,{get shape(){let $={...Y._zod.def.shape,...J._zod.def.shape};return N6(this,"shape",$),$},get catchall(){return J._zod.def.catchall},checks:[]});return E1(Y,X)}function ZB(Y,J,X){let $=L6(J._zod.def,{get shape(){let Q=J._zod.def.shape,G={...Q};if(X)for(let z in X){if(!(z in Q))throw Error(`Unrecognized key: "${z}"`);if(!X[z])continue;G[z]=Y?new Y({type:"optional",innerType:Q[z]}):Q[z]}else for(let z in Q)G[z]=Y?new Y({type:"optional",innerType:Q[z]}):Q[z];return N6(this,"shape",G),G},checks:[]});return E1(J,$)}function UB(Y,J,X){let $=L6(J._zod.def,{get shape(){let Q=J._zod.def.shape,G={...Q};if(X)for(let z in X){if(!(z in G))throw Error(`Unrecognized key: "${z}"`);if(!X[z])continue;G[z]=new Y({type:"nonoptional",innerType:Q[z]})}else for(let z in Q)G[z]=new Y({type:"nonoptional",innerType:Q[z]});return N6(this,"shape",G),G},checks:[]});return E1(J,$)}function D6(Y,J=0){if(Y.aborted===!0)return!0;for(let X=J;X<Y.issues.length;X++)if(Y.issues[X]?.continue!==!0)return!0;return!1}function X6(Y,J){return J.map((X)=>{var $;return($=X).path??($.path=[]),X.path.unshift(Y),X})}function K9(Y){return typeof Y==="string"?Y:Y?.message}function A1(Y,J,X){let $={...Y,path:Y.path??[]};if(!Y.message){let Q=K9(Y.inst?._zod.def?.error?.(Y))??K9(J?.error?.(Y))??K9(X.customError?.(Y))??K9(X.localeError?.(Y))??"Invalid input";$.message=Q}if(delete $.inst,delete $.continue,!J?.reportInput)delete $.input;return $}function H5(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function F9(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function M8(...Y){let[J,X,$]=Y;if(typeof J==="string")return{message:J,code:"custom",input:X,inst:$};return{...J}}function HB(Y){return Object.entries(Y).filter(([J,X])=>{return Number.isNaN(Number.parseInt(J,10))}).map((J)=>J[1])}function V5(Y){let J=atob(Y),X=new Uint8Array(J.length);for(let $=0;$<J.length;$++)X[$]=J.charCodeAt($);return X}function B5(Y){let J="";for(let X=0;X<Y.length;X++)J+=String.fromCharCode(Y[X]);return btoa(J)}function VB(Y){let J=Y.replace(/-/g,"+").replace(/_/g,"/"),X="=".repeat((4-J.length%4)%4);return V5(J+X)}function BB(Y){return B5(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function KB(Y){let J=Y.replace(/^0x/,"");if(J.length%2!==0)throw Error("Invalid hex string length");let X=new Uint8Array(J.length/2);for(let $=0;$<J.length;$+=2)X[$/2]=Number.parseInt(J.slice($,$+2),16);return X}function jB(Y){return Array.from(Y).map((J)=>J.toString(16).padStart(2,"0")).join("")}class K5{constructor(...Y){}}var j5=(Y,J)=>{Y.name="$ZodError",Object.defineProperty(Y,"_zod",{value:Y._zod,enumerable:!1}),Object.defineProperty(Y,"issues",{value:J,enumerable:!1}),Y.message=JSON.stringify(J,q8,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},T4=_("$ZodError",j5),AJ=_("$ZodError",j5,{Parent:Error});function N5(Y,J=(X)=>X.message){let X={},$=[];for(let Q of Y.issues)if(Q.path.length>0)X[Q.path[0]]=X[Q.path[0]]||[],X[Q.path[0]].push(J(Q));else $.push(J(Q));return{formErrors:$,fieldErrors:X}}function L5(Y,J){let X=J||function(G){return G.message},$={_errors:[]},Q=(G)=>{for(let z of G.issues)if(z.code==="invalid_union"&&z.errors.length)z.errors.map((W)=>Q({issues:W}));else if(z.code==="invalid_key")Q({issues:z.issues});else if(z.code==="invalid_element")Q({issues:z.issues});else if(z.path.length===0)$._errors.push(X(z));else{let W=$,U=0;while(U<z.path.length){let H=z.path[U];if(U!==z.path.length-1)W[H]=W[H]||{_errors:[]};else W[H]=W[H]||{_errors:[]},W[H]._errors.push(X(z));W=W[H],U++}}};return Q(Y),$}var R4=(Y)=>(J,X,$,Q)=>{let G=$?Object.assign($,{async:!1}):{async:!1},z=J._zod.run({value:X,issues:[]},G);if(z instanceof Promise)throw new Y6;if(z.issues.length){let W=new(Q?.Err??Y)(z.issues.map((U)=>A1(U,G,p1())));throw A4(W,Q?.callee),W}return z.value};var C4=(Y)=>async(J,X,$,Q)=>{let G=$?Object.assign($,{async:!0}):{async:!0},z=J._zod.run({value:X,issues:[]},G);if(z instanceof Promise)z=await z;if(z.issues.length){let W=new(Q?.Err??Y)(z.issues.map((U)=>A1(U,G,p1())));throw A4(W,Q?.callee),W}return z.value};var D9=(Y)=>(J,X,$)=>{let Q=$?{...$,async:!1}:{async:!1},G=J._zod.run({value:X,issues:[]},Q);if(G instanceof Promise)throw new Y6;return G.issues.length?{success:!1,error:new(Y??T4)(G.issues.map((z)=>A1(z,Q,p1())))}:{success:!0,data:G.value}},F5=D9(AJ),O9=(Y)=>async(J,X,$)=>{let Q=$?Object.assign($,{async:!0}):{async:!0},G=J._zod.run({value:X,issues:[]},Q);if(G instanceof Promise)G=await G;return G.issues.length?{success:!1,error:new Y(G.issues.map((z)=>A1(z,Q,p1())))}:{success:!0,data:G.value}},D5=O9(AJ),O5=(Y)=>(J,X,$)=>{let Q=$?Object.assign($,{direction:"backward"}):{direction:"backward"};return R4(Y)(J,X,Q)};var _5=(Y)=>(J,X,$)=>{return R4(Y)(J,X,$)};var q5=(Y)=>async(J,X,$)=>{let Q=$?Object.assign($,{direction:"backward"}):{direction:"backward"};return C4(Y)(J,X,Q)};var P5=(Y)=>async(J,X,$)=>{return C4(Y)(J,X,$)};var M5=(Y)=>(J,X,$)=>{let Q=$?Object.assign($,{direction:"backward"}):{direction:"backward"};return D9(Y)(J,X,Q)};var E5=(Y)=>(J,X,$)=>{return D9(Y)(J,X,$)};var A5=(Y)=>async(J,X,$)=>{let Q=$?Object.assign($,{direction:"backward"}):{direction:"backward"};return O9(Y)(J,X,Q)};var T5=(Y)=>async(J,X,$)=>{return O9(Y)(J,X,$)};var R5=/^[cC][^\s-]{8,}$/,C5=/^[0-9a-z]+$/,w5=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,I5=/^[0-9a-vA-V]{20}$/,S5=/^[A-Za-z0-9]{27}$/,b5=/^[a-zA-Z0-9_-]{21}$/,k5=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var x5=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,TJ=(Y)=>{if(!Y)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${Y}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var v5=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function h5(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var y5=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,f5=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,g5=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,m5=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,c5=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,RJ=/^[A-Za-z0-9_-]*$/,u5=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;var p5=/^\+(?:[0-9]){6,14}[0-9]$/,l5="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",d5=new RegExp(`^${l5}$`);function i5(Y){return typeof Y.precision==="number"?Y.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":Y.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${Y.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function n5(Y){return new RegExp(`^${i5(Y)}$`)}function o5(Y){let J=i5({precision:Y.precision}),X=["Z"];if(Y.local)X.push("");if(Y.offset)X.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let $=`${J}(?:${X.join("|")})`;return new RegExp(`^${l5}T(?:${$})$`)}var r5=(Y)=>{let J=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${J}$`)};var s5=/^-?\d+$/,a5=/^-?\d+(?:\.\d+)?/,t5=/^(?:true|false)$/i,e5=/^null$/i;var Y$=/^[^A-Z]*$/,J$=/^[^a-z]*$/;var v0=_("$ZodCheck",(Y,J)=>{var X;Y._zod??(Y._zod={}),Y._zod.def=J,(X=Y._zod).onattach??(X.onattach=[])}),X$={number:"number",bigint:"bigint",object:"date"},CJ=_("$ZodCheckLessThan",(Y,J)=>{v0.init(Y,J);let X=X$[typeof J.value];Y._zod.onattach.push(($)=>{let Q=$._zod.bag,G=(J.inclusive?Q.maximum:Q.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(J.value<G)if(J.inclusive)Q.maximum=J.value;else Q.exclusiveMaximum=J.value}),Y._zod.check=($)=>{if(J.inclusive?$.value<=J.value:$.value<J.value)return;$.issues.push({origin:X,code:"too_big",maximum:J.value,input:$.value,inclusive:J.inclusive,inst:Y,continue:!J.abort})}}),wJ=_("$ZodCheckGreaterThan",(Y,J)=>{v0.init(Y,J);let X=X$[typeof J.value];Y._zod.onattach.push(($)=>{let Q=$._zod.bag,G=(J.inclusive?Q.minimum:Q.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(J.value>G)if(J.inclusive)Q.minimum=J.value;else Q.exclusiveMinimum=J.value}),Y._zod.check=($)=>{if(J.inclusive?$.value>=J.value:$.value>J.value)return;$.issues.push({origin:X,code:"too_small",minimum:J.value,input:$.value,inclusive:J.inclusive,inst:Y,continue:!J.abort})}}),$$=_("$ZodCheckMultipleOf",(Y,J)=>{v0.init(Y,J),Y._zod.onattach.push((X)=>{var $;($=X._zod.bag).multipleOf??($.multipleOf=J.value)}),Y._zod.check=(X)=>{if(typeof X.value!==typeof J.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof X.value==="bigint"?X.value%J.value===BigInt(0):_J(X.value,J.value)===0)return;X.issues.push({origin:typeof X.value,code:"not_multiple_of",divisor:J.value,input:X.value,inst:Y,continue:!J.abort})}}),Q$=_("$ZodCheckNumberFormat",(Y,J)=>{v0.init(Y,J),J.format=J.format||"float64";let X=J.format?.includes("int"),$=X?"int":"number",[Q,G]=EJ[J.format];Y._zod.onattach.push((z)=>{let W=z._zod.bag;if(W.format=J.format,W.minimum=Q,W.maximum=G,X)W.pattern=s5}),Y._zod.check=(z)=>{let W=z.value;if(X){if(!Number.isInteger(W)){z.issues.push({expected:$,format:J.format,code:"invalid_type",continue:!1,input:W,inst:Y});return}if(!Number.isSafeInteger(W)){if(W>0)z.issues.push({input:W,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:$,continue:!J.abort});else z.issues.push({input:W,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:$,continue:!J.abort});return}}if(W<Q)z.issues.push({origin:"number",input:W,code:"too_small",minimum:Q,inclusive:!0,inst:Y,continue:!J.abort});if(W>G)z.issues.push({origin:"number",input:W,code:"too_big",maximum:G,inst:Y})}});var G$=_("$ZodCheckMaxLength",(Y,J)=>{var X;v0.init(Y,J),(X=Y._zod.def).when??(X.when=($)=>{let Q=$.value;return!N9(Q)&&Q.length!==void 0}),Y._zod.onattach.push(($)=>{let Q=$._zod.bag.maximum??Number.POSITIVE_INFINITY;if(J.maximum<Q)$._zod.bag.maximum=J.maximum}),Y._zod.check=($)=>{let Q=$.value;if(Q.length<=J.maximum)return;let z=F9(Q);$.issues.push({origin:z,code:"too_big",maximum:J.maximum,inclusive:!0,input:Q,inst:Y,continue:!J.abort})}}),z$=_("$ZodCheckMinLength",(Y,J)=>{var X;v0.init(Y,J),(X=Y._zod.def).when??(X.when=($)=>{let Q=$.value;return!N9(Q)&&Q.length!==void 0}),Y._zod.onattach.push(($)=>{let Q=$._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(J.minimum>Q)$._zod.bag.minimum=J.minimum}),Y._zod.check=($)=>{let Q=$.value;if(Q.length>=J.minimum)return;let z=F9(Q);$.issues.push({origin:z,code:"too_small",minimum:J.minimum,inclusive:!0,input:Q,inst:Y,continue:!J.abort})}}),W$=_("$ZodCheckLengthEquals",(Y,J)=>{var X;v0.init(Y,J),(X=Y._zod.def).when??(X.when=($)=>{let Q=$.value;return!N9(Q)&&Q.length!==void 0}),Y._zod.onattach.push(($)=>{let Q=$._zod.bag;Q.minimum=J.length,Q.maximum=J.length,Q.length=J.length}),Y._zod.check=($)=>{let Q=$.value,G=Q.length;if(G===J.length)return;let z=F9(Q),W=G>J.length;$.issues.push({origin:z,...W?{code:"too_big",maximum:J.length}:{code:"too_small",minimum:J.length},inclusive:!0,exact:!0,input:$.value,inst:Y,continue:!J.abort})}}),_9=_("$ZodCheckStringFormat",(Y,J)=>{var X,$;if(v0.init(Y,J),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;if(G.format=J.format,J.pattern)G.patterns??(G.patterns=new Set),G.patterns.add(J.pattern)}),J.pattern)(X=Y._zod).check??(X.check=(Q)=>{if(J.pattern.lastIndex=0,J.pattern.test(Q.value))return;Q.issues.push({origin:"string",code:"invalid_format",format:J.format,input:Q.value,...J.pattern?{pattern:J.pattern.toString()}:{},inst:Y,continue:!J.abort})});else($=Y._zod).check??($.check=()=>{})}),Z$=_("$ZodCheckRegex",(Y,J)=>{_9.init(Y,J),Y._zod.check=(X)=>{if(J.pattern.lastIndex=0,J.pattern.test(X.value))return;X.issues.push({origin:"string",code:"invalid_format",format:"regex",input:X.value,pattern:J.pattern.toString(),inst:Y,continue:!J.abort})}}),U$=_("$ZodCheckLowerCase",(Y,J)=>{J.pattern??(J.pattern=Y$),_9.init(Y,J)}),H$=_("$ZodCheckUpperCase",(Y,J)=>{J.pattern??(J.pattern=J$),_9.init(Y,J)}),V$=_("$ZodCheckIncludes",(Y,J)=>{v0.init(Y,J);let X=J6(J.includes),$=new RegExp(typeof J.position==="number"?`^.{${J.position}}${X}`:X);J.pattern=$,Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add($)}),Y._zod.check=(Q)=>{if(Q.value.includes(J.includes,J.position))return;Q.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:J.includes,input:Q.value,inst:Y,continue:!J.abort})}}),B$=_("$ZodCheckStartsWith",(Y,J)=>{v0.init(Y,J);let X=new RegExp(`^${J6(J.prefix)}.*`);J.pattern??(J.pattern=X),Y._zod.onattach.push(($)=>{let Q=$._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add(X)}),Y._zod.check=($)=>{if($.value.startsWith(J.prefix))return;$.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:J.prefix,input:$.value,inst:Y,continue:!J.abort})}}),K$=_("$ZodCheckEndsWith",(Y,J)=>{v0.init(Y,J);let X=new RegExp(`.*${J6(J.suffix)}$`);J.pattern??(J.pattern=X),Y._zod.onattach.push(($)=>{let Q=$._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add(X)}),Y._zod.check=($)=>{if($.value.endsWith(J.suffix))return;$.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:J.suffix,input:$.value,inst:Y,continue:!J.abort})}});var j$=_("$ZodCheckOverwrite",(Y,J)=>{v0.init(Y,J),Y._zod.check=(X)=>{X.value=J.tx(X.value)}});class IJ{constructor(Y=[]){if(this.content=[],this.indent=0,this)this.args=Y}indented(Y){this.indent+=1,Y(this),this.indent-=1}write(Y){if(typeof Y==="function"){Y(this,{execution:"sync"}),Y(this,{execution:"async"});return}let X=Y.split(`
|
|
10
|
-
`).filter((G)=>G),$=Math.min(...X.map((G)=>G.length-G.trimStart().length)),Q=X.map((G)=>G.slice($)).map((G)=>" ".repeat(this.indent*2)+G);for(let G of Q)this.content.push(G)}compile(){let Y=Function,J=this?.args,$=[...(this?.content??[""]).map((Q)=>` ${Q}`)];return new Y(...J,$.join(`
|
|
11
|
-
`))}}var L$={major:4,minor:1,patch:8};var j0=_("$ZodType",(Y,J)=>{var X;Y??(Y={}),Y._zod.def=J,Y._zod.bag=Y._zod.bag||{},Y._zod.version=L$;let $=[...Y._zod.def.checks??[]];if(Y._zod.traits.has("$ZodCheck"))$.unshift(Y);for(let Q of $)for(let G of Q._zod.onattach)G(Y);if($.length===0)(X=Y._zod).deferred??(X.deferred=[]),Y._zod.deferred?.push(()=>{Y._zod.run=Y._zod.parse});else{let Q=(z,W,U)=>{let H=D6(z),V;for(let F of W){if(F._zod.def.when){if(!F._zod.def.when(z))continue}else if(H)continue;let j=z.issues.length,K=F._zod.check(z);if(K instanceof Promise&&U?.async===!1)throw new Y6;if(V||K instanceof Promise)V=(V??Promise.resolve()).then(async()=>{if(await K,z.issues.length===j)return;if(!H)H=D6(z,j)});else{if(z.issues.length===j)continue;if(!H)H=D6(z,j)}}if(V)return V.then(()=>{return z});return z},G=(z,W,U)=>{if(D6(z))return z.aborted=!0,z;let H=Q(W,$,U);if(H instanceof Promise){if(U.async===!1)throw new Y6;return H.then((V)=>Y._zod.parse(V,U))}return Y._zod.parse(H,U)};Y._zod.run=(z,W)=>{if(W.skipChecks)return Y._zod.parse(z,W);if(W.direction==="backward"){let H=Y._zod.parse({value:z.value,issues:[]},{...W,skipChecks:!0});if(H instanceof Promise)return H.then((V)=>{return G(V,z,W)});return G(H,z,W)}let U=Y._zod.parse(z,W);if(U instanceof Promise){if(W.async===!1)throw new Y6;return U.then((H)=>Q(H,$,W))}return Q(U,$,W)}}Y["~standard"]={validate:(Q)=>{try{let G=F5(Y,Q);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return D5(Y,Q).then((z)=>z.success?{value:z.data}:{issues:z.error?.issues})}},vendor:"zod",version:1}}),b4=_("$ZodString",(Y,J)=>{j0.init(Y,J),Y._zod.pattern=[...Y?._zod.bag?.patterns??[]].pop()??r5(Y._zod.bag),Y._zod.parse=(X,$)=>{if(J.coerce)try{X.value=String(X.value)}catch(Q){}if(typeof X.value==="string")return X;return X.issues.push({expected:"string",code:"invalid_type",input:X.value,inst:Y}),X}}),L0=_("$ZodStringFormat",(Y,J)=>{_9.init(Y,J),b4.init(Y,J)}),A$=_("$ZodGUID",(Y,J)=>{J.pattern??(J.pattern=x5),L0.init(Y,J)}),T$=_("$ZodUUID",(Y,J)=>{if(J.version){let $={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[J.version];if($===void 0)throw Error(`Invalid UUID version: "${J.version}"`);J.pattern??(J.pattern=TJ($))}else J.pattern??(J.pattern=TJ());L0.init(Y,J)}),R$=_("$ZodEmail",(Y,J)=>{J.pattern??(J.pattern=v5),L0.init(Y,J)}),C$=_("$ZodURL",(Y,J)=>{L0.init(Y,J),Y._zod.check=(X)=>{try{let $=X.value.trim(),Q=new URL($);if(J.hostname){if(J.hostname.lastIndex=0,!J.hostname.test(Q.hostname))X.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:u5.source,input:X.value,inst:Y,continue:!J.abort})}if(J.protocol){if(J.protocol.lastIndex=0,!J.protocol.test(Q.protocol.endsWith(":")?Q.protocol.slice(0,-1):Q.protocol))X.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:J.protocol.source,input:X.value,inst:Y,continue:!J.abort})}if(J.normalize)X.value=Q.href;else X.value=$;return}catch($){X.issues.push({code:"invalid_format",format:"url",input:X.value,inst:Y,continue:!J.abort})}}}),w$=_("$ZodEmoji",(Y,J)=>{J.pattern??(J.pattern=h5()),L0.init(Y,J)}),I$=_("$ZodNanoID",(Y,J)=>{J.pattern??(J.pattern=b5),L0.init(Y,J)}),S$=_("$ZodCUID",(Y,J)=>{J.pattern??(J.pattern=R5),L0.init(Y,J)}),b$=_("$ZodCUID2",(Y,J)=>{J.pattern??(J.pattern=C5),L0.init(Y,J)}),k$=_("$ZodULID",(Y,J)=>{J.pattern??(J.pattern=w5),L0.init(Y,J)}),x$=_("$ZodXID",(Y,J)=>{J.pattern??(J.pattern=I5),L0.init(Y,J)}),v$=_("$ZodKSUID",(Y,J)=>{J.pattern??(J.pattern=S5),L0.init(Y,J)}),h$=_("$ZodISODateTime",(Y,J)=>{J.pattern??(J.pattern=o5(J)),L0.init(Y,J)}),y$=_("$ZodISODate",(Y,J)=>{J.pattern??(J.pattern=d5),L0.init(Y,J)}),f$=_("$ZodISOTime",(Y,J)=>{J.pattern??(J.pattern=n5(J)),L0.init(Y,J)}),g$=_("$ZodISODuration",(Y,J)=>{J.pattern??(J.pattern=k5),L0.init(Y,J)}),m$=_("$ZodIPv4",(Y,J)=>{J.pattern??(J.pattern=y5),L0.init(Y,J),Y._zod.onattach.push((X)=>{let $=X._zod.bag;$.format="ipv4"})}),c$=_("$ZodIPv6",(Y,J)=>{J.pattern??(J.pattern=f5),L0.init(Y,J),Y._zod.onattach.push((X)=>{let $=X._zod.bag;$.format="ipv6"}),Y._zod.check=(X)=>{try{new URL(`http://[${X.value}]`)}catch{X.issues.push({code:"invalid_format",format:"ipv6",input:X.value,inst:Y,continue:!J.abort})}}}),u$=_("$ZodCIDRv4",(Y,J)=>{J.pattern??(J.pattern=g5),L0.init(Y,J)}),p$=_("$ZodCIDRv6",(Y,J)=>{J.pattern??(J.pattern=m5),L0.init(Y,J),Y._zod.check=(X)=>{let $=X.value.split("/");try{if($.length!==2)throw Error();let[Q,G]=$;if(!G)throw Error();let z=Number(G);if(`${z}`!==G)throw Error();if(z<0||z>128)throw Error();new URL(`http://[${Q}]`)}catch{X.issues.push({code:"invalid_format",format:"cidrv6",input:X.value,inst:Y,continue:!J.abort})}}});function l$(Y){if(Y==="")return!0;if(Y.length%4!==0)return!1;try{return atob(Y),!0}catch{return!1}}var d$=_("$ZodBase64",(Y,J)=>{J.pattern??(J.pattern=c5),L0.init(Y,J),Y._zod.onattach.push((X)=>{X._zod.bag.contentEncoding="base64"}),Y._zod.check=(X)=>{if(l$(X.value))return;X.issues.push({code:"invalid_format",format:"base64",input:X.value,inst:Y,continue:!J.abort})}});function LB(Y){if(!RJ.test(Y))return!1;let J=Y.replace(/[-_]/g,($)=>$==="-"?"+":"/"),X=J.padEnd(Math.ceil(J.length/4)*4,"=");return l$(X)}var i$=_("$ZodBase64URL",(Y,J)=>{J.pattern??(J.pattern=RJ),L0.init(Y,J),Y._zod.onattach.push((X)=>{X._zod.bag.contentEncoding="base64url"}),Y._zod.check=(X)=>{if(LB(X.value))return;X.issues.push({code:"invalid_format",format:"base64url",input:X.value,inst:Y,continue:!J.abort})}}),n$=_("$ZodE164",(Y,J)=>{J.pattern??(J.pattern=p5),L0.init(Y,J)});function FB(Y,J=null){try{let X=Y.split(".");if(X.length!==3)return!1;let[$]=X;if(!$)return!1;let Q=JSON.parse(atob($));if("typ"in Q&&Q?.typ!=="JWT")return!1;if(!Q.alg)return!1;if(J&&(!("alg"in Q)||Q.alg!==J))return!1;return!0}catch{return!1}}var o$=_("$ZodJWT",(Y,J)=>{L0.init(Y,J),Y._zod.check=(X)=>{if(FB(X.value,J.alg))return;X.issues.push({code:"invalid_format",format:"jwt",input:X.value,inst:Y,continue:!J.abort})}});var bJ=_("$ZodNumber",(Y,J)=>{j0.init(Y,J),Y._zod.pattern=Y._zod.bag.pattern??a5,Y._zod.parse=(X,$)=>{if(J.coerce)try{X.value=Number(X.value)}catch(z){}let Q=X.value;if(typeof Q==="number"&&!Number.isNaN(Q)&&Number.isFinite(Q))return X;let G=typeof Q==="number"?Number.isNaN(Q)?"NaN":!Number.isFinite(Q)?"Infinity":void 0:void 0;return X.issues.push({expected:"number",code:"invalid_type",input:Q,inst:Y,...G?{received:G}:{}}),X}}),r$=_("$ZodNumber",(Y,J)=>{Q$.init(Y,J),bJ.init(Y,J)}),s$=_("$ZodBoolean",(Y,J)=>{j0.init(Y,J),Y._zod.pattern=t5,Y._zod.parse=(X,$)=>{if(J.coerce)try{X.value=Boolean(X.value)}catch(G){}let Q=X.value;if(typeof Q==="boolean")return X;return X.issues.push({expected:"boolean",code:"invalid_type",input:Q,inst:Y}),X}});var a$=_("$ZodNull",(Y,J)=>{j0.init(Y,J),Y._zod.pattern=e5,Y._zod.values=new Set([null]),Y._zod.parse=(X,$)=>{let Q=X.value;if(Q===null)return X;return X.issues.push({expected:"null",code:"invalid_type",input:Q,inst:Y}),X}});var t$=_("$ZodUnknown",(Y,J)=>{j0.init(Y,J),Y._zod.parse=(X)=>X}),e$=_("$ZodNever",(Y,J)=>{j0.init(Y,J),Y._zod.parse=(X,$)=>{return X.issues.push({expected:"never",code:"invalid_type",input:X.value,inst:Y}),X}});function F$(Y,J,X){if(Y.issues.length)J.issues.push(...X6(X,Y.issues));J.value[X]=Y.value}var YQ=_("$ZodArray",(Y,J)=>{j0.init(Y,J),Y._zod.parse=(X,$)=>{let Q=X.value;if(!Array.isArray(Q))return X.issues.push({expected:"array",code:"invalid_type",input:Q,inst:Y}),X;X.value=Array(Q.length);let G=[];for(let z=0;z<Q.length;z++){let W=Q[z],U=J.element._zod.run({value:W,issues:[]},$);if(U instanceof Promise)G.push(U.then((H)=>F$(H,X,z)));else F$(U,X,z)}if(G.length)return Promise.all(G).then(()=>X);return X}});function S4(Y,J,X,$){if(Y.issues.length)J.issues.push(...X6(X,Y.issues));if(Y.value===void 0){if(X in $)J.value[X]=void 0}else J.value[X]=Y.value}function JQ(Y){let J=Object.keys(Y.shape);for(let $ of J)if(!Y.shape?.[$]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${$}": expected a Zod schema`);let X=MJ(Y.shape);return{...Y,keys:J,keySet:new Set(J),numKeys:J.length,optionalKeys:new Set(X)}}function XQ(Y,J,X,$,Q,G){let z=[],W=Q.keySet,U=Q.catchall._zod,H=U.def.type;for(let V of Object.keys(J)){if(W.has(V))continue;if(H==="never"){z.push(V);continue}let F=U.run({value:J[V],issues:[]},$);if(F instanceof Promise)Y.push(F.then((j)=>S4(j,X,V,J)));else S4(F,X,V,J)}if(z.length)X.issues.push({code:"unrecognized_keys",keys:z,input:J,inst:G});if(!Y.length)return X;return Promise.all(Y).then(()=>{return X})}var DB=_("$ZodObject",(Y,J)=>{j0.init(Y,J);let X=P8(()=>JQ(J));U0(Y._zod,"propValues",()=>{let z=J.shape,W={};for(let U in z){let H=z[U]._zod;if(H.values){W[U]??(W[U]=new Set);for(let V of H.values)W[U].add(V)}}return W});let $=p6,Q=J.catchall,G;Y._zod.parse=(z,W)=>{G??(G=X.value);let U=z.value;if(!$(U))return z.issues.push({expected:"object",code:"invalid_type",input:U,inst:Y}),z;z.value={};let H=[],V=G.shape;for(let F of G.keys){let K=V[F]._zod.run({value:U[F],issues:[]},W);if(K instanceof Promise)H.push(K.then((L)=>S4(L,z,F,U)));else S4(K,z,F,U)}if(!Q)return H.length?Promise.all(H).then(()=>z):z;return XQ(H,U,z,W,X.value,Y)}}),$Q=_("$ZodObjectJIT",(Y,J)=>{DB.init(Y,J);let X=Y._zod.parse,$=P8(()=>JQ(J)),Q=(j)=>{let K=new IJ(["shape","payload","ctx"]),L=$.value,O=(b)=>{let M=E4(b);return`shape[${M}]._zod.run({ value: input[${M}], issues: [] }, ctx)`};K.write("const input = payload.value;");let q=Object.create(null),x=0;for(let b of L.keys)q[b]=`key_${x++}`;K.write("const newResult = {};");for(let b of L.keys){let M=q[b],w=E4(b);K.write(`const ${M} = ${O(b)};`),K.write(`
|
|
12
|
-
if (${M}.issues.length) {
|
|
13
|
-
payload.issues = payload.issues.concat(${M}.issues.map(iss => ({
|
|
14
|
-
...iss,
|
|
15
|
-
path: iss.path ? [${w}, ...iss.path] : [${w}]
|
|
16
|
-
})));
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
if (${M}.value === undefined) {
|
|
21
|
-
if (${w} in input) {
|
|
22
|
-
newResult[${w}] = undefined;
|
|
23
|
-
}
|
|
24
|
-
} else {
|
|
25
|
-
newResult[${w}] = ${M}.value;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
`)}K.write("payload.value = newResult;"),K.write("return payload;");let P=K.compile();return(b,M)=>P(j,b,M)},G,z=p6,W=!M4.jitless,H=W&&qJ.value,V=J.catchall,F;Y._zod.parse=(j,K)=>{F??(F=$.value);let L=j.value;if(!z(L))return j.issues.push({expected:"object",code:"invalid_type",input:L,inst:Y}),j;if(W&&H&&K?.async===!1&&K.jitless!==!0){if(!G)G=Q(J.shape);if(j=G(j,K),!V)return j;return XQ([],L,j,K,F,Y)}return X(j,K)}});function D$(Y,J,X,$){for(let G of Y)if(G.issues.length===0)return J.value=G.value,J;let Q=Y.filter((G)=>!D6(G));if(Q.length===1)return J.value=Q[0].value,Q[0];return J.issues.push({code:"invalid_union",input:J.value,inst:X,errors:Y.map((G)=>G.issues.map((z)=>A1(z,$,p1())))}),J}var kJ=_("$ZodUnion",(Y,J)=>{j0.init(Y,J),U0(Y._zod,"optin",()=>J.options.some((Q)=>Q._zod.optin==="optional")?"optional":void 0),U0(Y._zod,"optout",()=>J.options.some((Q)=>Q._zod.optout==="optional")?"optional":void 0),U0(Y._zod,"values",()=>{if(J.options.every((Q)=>Q._zod.values))return new Set(J.options.flatMap((Q)=>Array.from(Q._zod.values)));return}),U0(Y._zod,"pattern",()=>{if(J.options.every((Q)=>Q._zod.pattern)){let Q=J.options.map((G)=>G._zod.pattern);return new RegExp(`^(${Q.map((G)=>L9(G.source)).join("|")})$`)}return});let X=J.options.length===1,$=J.options[0]._zod.run;Y._zod.parse=(Q,G)=>{if(X)return $(Q,G);let z=!1,W=[];for(let U of J.options){let H=U._zod.run({value:Q.value,issues:[]},G);if(H instanceof Promise)W.push(H),z=!0;else{if(H.issues.length===0)return H;W.push(H)}}if(!z)return D$(W,Q,Y,G);return Promise.all(W).then((U)=>{return D$(U,Q,Y,G)})}}),QQ=_("$ZodDiscriminatedUnion",(Y,J)=>{kJ.init(Y,J);let X=Y._zod.parse;U0(Y._zod,"propValues",()=>{let Q={};for(let G of J.options){let z=G._zod.propValues;if(!z||Object.keys(z).length===0)throw Error(`Invalid discriminated union option at index "${J.options.indexOf(G)}"`);for(let[W,U]of Object.entries(z)){if(!Q[W])Q[W]=new Set;for(let H of U)Q[W].add(H)}}return Q});let $=P8(()=>{let Q=J.options,G=new Map;for(let z of Q){let W=z._zod.propValues?.[J.discriminator];if(!W||W.size===0)throw Error(`Invalid discriminated union option at index "${J.options.indexOf(z)}"`);for(let U of W){if(G.has(U))throw Error(`Duplicate discriminator value "${String(U)}"`);G.set(U,z)}}return G});Y._zod.parse=(Q,G)=>{let z=Q.value;if(!p6(z))return Q.issues.push({code:"invalid_type",expected:"object",input:z,inst:Y}),Q;let W=$.value.get(z?.[J.discriminator]);if(W)return W._zod.run(Q,G);if(J.unionFallback)return X(Q,G);return Q.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:J.discriminator,input:z,path:[J.discriminator],inst:Y}),Q}}),GQ=_("$ZodIntersection",(Y,J)=>{j0.init(Y,J),Y._zod.parse=(X,$)=>{let Q=X.value,G=J.left._zod.run({value:Q,issues:[]},$),z=J.right._zod.run({value:Q,issues:[]},$);if(G instanceof Promise||z instanceof Promise)return Promise.all([G,z]).then(([U,H])=>{return O$(X,U,H)});return O$(X,G,z)}});function SJ(Y,J){if(Y===J)return{valid:!0,data:Y};if(Y instanceof Date&&J instanceof Date&&+Y===+J)return{valid:!0,data:Y};if(F6(Y)&&F6(J)){let X=Object.keys(J),$=Object.keys(Y).filter((G)=>X.indexOf(G)!==-1),Q={...Y,...J};for(let G of $){let z=SJ(Y[G],J[G]);if(!z.valid)return{valid:!1,mergeErrorPath:[G,...z.mergeErrorPath]};Q[G]=z.data}return{valid:!0,data:Q}}if(Array.isArray(Y)&&Array.isArray(J)){if(Y.length!==J.length)return{valid:!1,mergeErrorPath:[]};let X=[];for(let $=0;$<Y.length;$++){let Q=Y[$],G=J[$],z=SJ(Q,G);if(!z.valid)return{valid:!1,mergeErrorPath:[$,...z.mergeErrorPath]};X.push(z.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function O$(Y,J,X){if(J.issues.length)Y.issues.push(...J.issues);if(X.issues.length)Y.issues.push(...X.issues);if(D6(Y))return Y;let $=SJ(J.value,X.value);if(!$.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify($.mergeErrorPath)}`);return Y.value=$.data,Y}var zQ=_("$ZodRecord",(Y,J)=>{j0.init(Y,J),Y._zod.parse=(X,$)=>{let Q=X.value;if(!F6(Q))return X.issues.push({expected:"record",code:"invalid_type",input:Q,inst:Y}),X;let G=[];if(J.keyType._zod.values){let z=J.keyType._zod.values;X.value={};for(let U of z)if(typeof U==="string"||typeof U==="number"||typeof U==="symbol"){let H=J.valueType._zod.run({value:Q[U],issues:[]},$);if(H instanceof Promise)G.push(H.then((V)=>{if(V.issues.length)X.issues.push(...X6(U,V.issues));X.value[U]=V.value}));else{if(H.issues.length)X.issues.push(...X6(U,H.issues));X.value[U]=H.value}}let W;for(let U in Q)if(!z.has(U))W=W??[],W.push(U);if(W&&W.length>0)X.issues.push({code:"unrecognized_keys",input:Q,inst:Y,keys:W})}else{X.value={};for(let z of Reflect.ownKeys(Q)){if(z==="__proto__")continue;let W=J.keyType._zod.run({value:z,issues:[]},$);if(W instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(W.issues.length){X.issues.push({code:"invalid_key",origin:"record",issues:W.issues.map((H)=>A1(H,$,p1())),input:z,path:[z],inst:Y}),X.value[W.value]=W.value;continue}let U=J.valueType._zod.run({value:Q[z],issues:[]},$);if(U instanceof Promise)G.push(U.then((H)=>{if(H.issues.length)X.issues.push(...X6(z,H.issues));X.value[W.value]=H.value}));else{if(U.issues.length)X.issues.push(...X6(z,U.issues));X.value[W.value]=U.value}}}if(G.length)return Promise.all(G).then(()=>X);return X}});var WQ=_("$ZodEnum",(Y,J)=>{j0.init(Y,J);let X=j9(J.entries),$=new Set(X);Y._zod.values=$,Y._zod.pattern=new RegExp(`^(${X.filter((Q)=>PJ.has(typeof Q)).map((Q)=>typeof Q==="string"?J6(Q):Q.toString()).join("|")})$`),Y._zod.parse=(Q,G)=>{let z=Q.value;if($.has(z))return Q;return Q.issues.push({code:"invalid_value",values:X,input:z,inst:Y}),Q}}),ZQ=_("$ZodLiteral",(Y,J)=>{if(j0.init(Y,J),J.values.length===0)throw Error("Cannot create literal schema with no valid values");Y._zod.values=new Set(J.values),Y._zod.pattern=new RegExp(`^(${J.values.map((X)=>typeof X==="string"?J6(X):X?J6(X.toString()):String(X)).join("|")})$`),Y._zod.parse=(X,$)=>{let Q=X.value;if(Y._zod.values.has(Q))return X;return X.issues.push({code:"invalid_value",values:J.values,input:Q,inst:Y}),X}});var UQ=_("$ZodTransform",(Y,J)=>{j0.init(Y,J),Y._zod.parse=(X,$)=>{if($.direction==="backward")throw new B9(Y.constructor.name);let Q=J.transform(X.value,X);if($.async)return(Q instanceof Promise?Q:Promise.resolve(Q)).then((z)=>{return X.value=z,X});if(Q instanceof Promise)throw new Y6;return X.value=Q,X}});function _$(Y,J){if(Y.issues.length&&J===void 0)return{issues:[],value:void 0};return Y}var HQ=_("$ZodOptional",(Y,J)=>{j0.init(Y,J),Y._zod.optin="optional",Y._zod.optout="optional",U0(Y._zod,"values",()=>{return J.innerType._zod.values?new Set([...J.innerType._zod.values,void 0]):void 0}),U0(Y._zod,"pattern",()=>{let X=J.innerType._zod.pattern;return X?new RegExp(`^(${L9(X.source)})?$`):void 0}),Y._zod.parse=(X,$)=>{if(J.innerType._zod.optin==="optional"){let Q=J.innerType._zod.run(X,$);if(Q instanceof Promise)return Q.then((G)=>_$(G,X.value));return _$(Q,X.value)}if(X.value===void 0)return X;return J.innerType._zod.run(X,$)}}),VQ=_("$ZodNullable",(Y,J)=>{j0.init(Y,J),U0(Y._zod,"optin",()=>J.innerType._zod.optin),U0(Y._zod,"optout",()=>J.innerType._zod.optout),U0(Y._zod,"pattern",()=>{let X=J.innerType._zod.pattern;return X?new RegExp(`^(${L9(X.source)}|null)$`):void 0}),U0(Y._zod,"values",()=>{return J.innerType._zod.values?new Set([...J.innerType._zod.values,null]):void 0}),Y._zod.parse=(X,$)=>{if(X.value===null)return X;return J.innerType._zod.run(X,$)}}),BQ=_("$ZodDefault",(Y,J)=>{j0.init(Y,J),Y._zod.optin="optional",U0(Y._zod,"values",()=>J.innerType._zod.values),Y._zod.parse=(X,$)=>{if($.direction==="backward")return J.innerType._zod.run(X,$);if(X.value===void 0)return X.value=J.defaultValue,X;let Q=J.innerType._zod.run(X,$);if(Q instanceof Promise)return Q.then((G)=>q$(G,J));return q$(Q,J)}});function q$(Y,J){if(Y.value===void 0)Y.value=J.defaultValue;return Y}var KQ=_("$ZodPrefault",(Y,J)=>{j0.init(Y,J),Y._zod.optin="optional",U0(Y._zod,"values",()=>J.innerType._zod.values),Y._zod.parse=(X,$)=>{if($.direction==="backward")return J.innerType._zod.run(X,$);if(X.value===void 0)X.value=J.defaultValue;return J.innerType._zod.run(X,$)}}),jQ=_("$ZodNonOptional",(Y,J)=>{j0.init(Y,J),U0(Y._zod,"values",()=>{let X=J.innerType._zod.values;return X?new Set([...X].filter(($)=>$!==void 0)):void 0}),Y._zod.parse=(X,$)=>{let Q=J.innerType._zod.run(X,$);if(Q instanceof Promise)return Q.then((G)=>P$(G,Y));return P$(Q,Y)}});function P$(Y,J){if(!Y.issues.length&&Y.value===void 0)Y.issues.push({code:"invalid_type",expected:"nonoptional",input:Y.value,inst:J});return Y}var NQ=_("$ZodCatch",(Y,J)=>{j0.init(Y,J),U0(Y._zod,"optin",()=>J.innerType._zod.optin),U0(Y._zod,"optout",()=>J.innerType._zod.optout),U0(Y._zod,"values",()=>J.innerType._zod.values),Y._zod.parse=(X,$)=>{if($.direction==="backward")return J.innerType._zod.run(X,$);let Q=J.innerType._zod.run(X,$);if(Q instanceof Promise)return Q.then((G)=>{if(X.value=G.value,G.issues.length)X.value=J.catchValue({...X,error:{issues:G.issues.map((z)=>A1(z,$,p1()))},input:X.value}),X.issues=[];return X});if(X.value=Q.value,Q.issues.length)X.value=J.catchValue({...X,error:{issues:Q.issues.map((G)=>A1(G,$,p1()))},input:X.value}),X.issues=[];return X}});var LQ=_("$ZodPipe",(Y,J)=>{j0.init(Y,J),U0(Y._zod,"values",()=>J.in._zod.values),U0(Y._zod,"optin",()=>J.in._zod.optin),U0(Y._zod,"optout",()=>J.out._zod.optout),U0(Y._zod,"propValues",()=>J.in._zod.propValues),Y._zod.parse=(X,$)=>{if($.direction==="backward"){let G=J.out._zod.run(X,$);if(G instanceof Promise)return G.then((z)=>I4(z,J.in,$));return I4(G,J.in,$)}let Q=J.in._zod.run(X,$);if(Q instanceof Promise)return Q.then((G)=>I4(G,J.out,$));return I4(Q,J.out,$)}});function I4(Y,J,X){if(Y.issues.length)return Y.aborted=!0,Y;return J._zod.run({value:Y.value,issues:Y.issues},X)}var FQ=_("$ZodReadonly",(Y,J)=>{j0.init(Y,J),U0(Y._zod,"propValues",()=>J.innerType._zod.propValues),U0(Y._zod,"values",()=>J.innerType._zod.values),U0(Y._zod,"optin",()=>J.innerType._zod.optin),U0(Y._zod,"optout",()=>J.innerType._zod.optout),Y._zod.parse=(X,$)=>{if($.direction==="backward")return J.innerType._zod.run(X,$);let Q=J.innerType._zod.run(X,$);if(Q instanceof Promise)return Q.then(M$);return M$(Q)}});function M$(Y){return Y.value=Object.freeze(Y.value),Y}var DQ=_("$ZodLazy",(Y,J)=>{j0.init(Y,J),U0(Y._zod,"innerType",()=>J.getter()),U0(Y._zod,"pattern",()=>Y._zod.innerType._zod.pattern),U0(Y._zod,"propValues",()=>Y._zod.innerType._zod.propValues),U0(Y._zod,"optin",()=>Y._zod.innerType._zod.optin??void 0),U0(Y._zod,"optout",()=>Y._zod.innerType._zod.optout??void 0),Y._zod.parse=(X,$)=>{return Y._zod.innerType._zod.run(X,$)}}),OQ=_("$ZodCustom",(Y,J)=>{v0.init(Y,J),j0.init(Y,J),Y._zod.parse=(X,$)=>{return X},Y._zod.check=(X)=>{let $=X.value,Q=J.fn($);if(Q instanceof Promise)return Q.then((G)=>E$(G,X,$,Y));E$(Q,X,$,Y);return}});function E$(Y,J,X,$){if(!Y){let Q={code:"custom",input:X,inst:$,path:[...$._zod.def.path??[]],continue:!$._zod.def.abort};if($._zod.def.params)Q.params=$._zod.def.params;J.issues.push(M8(Q))}}var yq=Symbol("ZodOutput"),fq=Symbol("ZodInput");class k4{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Y,...J){let X=J[0];if(this._map.set(Y,X),X&&typeof X==="object"&&"id"in X){if(this._idmap.has(X.id))throw Error(`ID ${X.id} already exists in the registry`);this._idmap.set(X.id,Y)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Y){let J=this._map.get(Y);if(J&&typeof J==="object"&&"id"in J)this._idmap.delete(J.id);return this._map.delete(Y),this}get(Y){let J=Y._zod.parent;if(J){let X={...this.get(J)??{}};delete X.id;let $={...X,...this._map.get(Y)};return Object.keys($).length?$:void 0}return this._map.get(Y)}has(Y){return this._map.has(Y)}}function OB(){return new k4}var l6=OB();function _Q(Y,J){return new Y({type:"string",...o(J)})}function qQ(Y,J){return new Y({type:"string",format:"email",check:"string_format",abort:!1,...o(J)})}function xJ(Y,J){return new Y({type:"string",format:"guid",check:"string_format",abort:!1,...o(J)})}function PQ(Y,J){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...o(J)})}function MQ(Y,J){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...o(J)})}function EQ(Y,J){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...o(J)})}function AQ(Y,J){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...o(J)})}function TQ(Y,J){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...o(J)})}function RQ(Y,J){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...o(J)})}function CQ(Y,J){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...o(J)})}function wQ(Y,J){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...o(J)})}function IQ(Y,J){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...o(J)})}function SQ(Y,J){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...o(J)})}function bQ(Y,J){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...o(J)})}function kQ(Y,J){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...o(J)})}function xQ(Y,J){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...o(J)})}function vQ(Y,J){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...o(J)})}function hQ(Y,J){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...o(J)})}function yQ(Y,J){return new Y({type:"string",format:"cidrv6",check:"string_format",abort:!1,...o(J)})}function fQ(Y,J){return new Y({type:"string",format:"base64",check:"string_format",abort:!1,...o(J)})}function gQ(Y,J){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...o(J)})}function mQ(Y,J){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...o(J)})}function cQ(Y,J){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...o(J)})}function uQ(Y,J){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...o(J)})}function pQ(Y,J){return new Y({type:"string",format:"date",check:"string_format",...o(J)})}function lQ(Y,J){return new Y({type:"string",format:"time",check:"string_format",precision:null,...o(J)})}function dQ(Y,J){return new Y({type:"string",format:"duration",check:"string_format",...o(J)})}function iQ(Y,J){return new Y({type:"number",checks:[],...o(J)})}function nQ(Y,J){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...o(J)})}function oQ(Y,J){return new Y({type:"boolean",...o(J)})}function rQ(Y,J){return new Y({type:"null",...o(J)})}function sQ(Y){return new Y({type:"unknown"})}function aQ(Y,J){return new Y({type:"never",...o(J)})}function x4(Y,J){return new CJ({check:"less_than",...o(J),value:Y,inclusive:!1})}function q9(Y,J){return new CJ({check:"less_than",...o(J),value:Y,inclusive:!0})}function v4(Y,J){return new wJ({check:"greater_than",...o(J),value:Y,inclusive:!1})}function P9(Y,J){return new wJ({check:"greater_than",...o(J),value:Y,inclusive:!0})}function h4(Y,J){return new $$({check:"multiple_of",...o(J),value:Y})}function y4(Y,J){return new G$({check:"max_length",...o(J),maximum:Y})}function E8(Y,J){return new z$({check:"min_length",...o(J),minimum:Y})}function f4(Y,J){return new W$({check:"length_equals",...o(J),length:Y})}function vJ(Y,J){return new Z$({check:"string_format",format:"regex",...o(J),pattern:Y})}function hJ(Y){return new U$({check:"string_format",format:"lowercase",...o(Y)})}function yJ(Y){return new H$({check:"string_format",format:"uppercase",...o(Y)})}function fJ(Y,J){return new V$({check:"string_format",format:"includes",...o(J),includes:Y})}function gJ(Y,J){return new B$({check:"string_format",format:"starts_with",...o(J),prefix:Y})}function mJ(Y,J){return new K$({check:"string_format",format:"ends_with",...o(J),suffix:Y})}function d6(Y){return new j$({check:"overwrite",tx:Y})}function cJ(Y){return d6((J)=>J.normalize(Y))}function uJ(){return d6((Y)=>Y.trim())}function pJ(){return d6((Y)=>Y.toLowerCase())}function lJ(){return d6((Y)=>Y.toUpperCase())}function tQ(Y,J,X){return new Y({type:"array",element:J,...o(X)})}function eQ(Y,J,X){let $=o(X);return $.abort??($.abort=!0),new Y({type:"custom",check:"custom",fn:J,...$})}function YG(Y,J,X){return new Y({type:"custom",check:"custom",fn:J,...o(X)})}function JG(Y){let J=_B((X)=>{return X.addIssue=($)=>{if(typeof $==="string")X.issues.push(M8($,X.value,J._zod.def));else{let Q=$;if(Q.fatal)Q.continue=!1;Q.code??(Q.code="custom"),Q.input??(Q.input=X.value),Q.inst??(Q.inst=J),Q.continue??(Q.continue=!J._zod.def.abort),X.issues.push(M8(Q))}},Y(X.value,X)});return J}function _B(Y,J){let X=new v0({check:"custom",...o(J)});return X._zod.check=Y,X}class dJ{constructor(Y){this.counter=0,this.metadataRegistry=Y?.metadata??l6,this.target=Y?.target??"draft-2020-12",this.unrepresentable=Y?.unrepresentable??"throw",this.override=Y?.override??(()=>{}),this.io=Y?.io??"output",this.seen=new Map}process(Y,J={path:[],schemaPath:[]}){var X;let $=Y._zod.def,Q={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},G=this.seen.get(Y);if(G){if(G.count++,J.schemaPath.includes(Y))G.cycle=J.path;return G.schema}let z={schema:{},count:1,cycle:void 0,path:J.path};this.seen.set(Y,z);let W=Y._zod.toJSONSchema?.();if(W)z.schema=W;else{let V={...J,schemaPath:[...J.schemaPath,Y],path:J.path},F=Y._zod.parent;if(F)z.ref=F,this.process(F,V),this.seen.get(F).isParent=!0;else{let j=z.schema;switch($.type){case"string":{let K=j;K.type="string";let{minimum:L,maximum:O,format:q,patterns:x,contentEncoding:P}=Y._zod.bag;if(typeof L==="number")K.minLength=L;if(typeof O==="number")K.maxLength=O;if(q){if(K.format=Q[q]??q,K.format==="")delete K.format}if(P)K.contentEncoding=P;if(x&&x.size>0){let b=[...x];if(b.length===1)K.pattern=b[0].source;else if(b.length>1)z.schema.allOf=[...b.map((M)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:M.source}))]}break}case"number":{let K=j,{minimum:L,maximum:O,format:q,multipleOf:x,exclusiveMaximum:P,exclusiveMinimum:b}=Y._zod.bag;if(typeof q==="string"&&q.includes("int"))K.type="integer";else K.type="number";if(typeof b==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")K.minimum=b,K.exclusiveMinimum=!0;else K.exclusiveMinimum=b;if(typeof L==="number"){if(K.minimum=L,typeof b==="number"&&this.target!=="draft-4")if(b>=L)delete K.minimum;else delete K.exclusiveMinimum}if(typeof P==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")K.maximum=P,K.exclusiveMaximum=!0;else K.exclusiveMaximum=P;if(typeof O==="number"){if(K.maximum=O,typeof P==="number"&&this.target!=="draft-4")if(P<=O)delete K.maximum;else delete K.exclusiveMaximum}if(typeof x==="number")K.multipleOf=x;break}case"boolean":{let K=j;K.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema");break}case"null":{if(this.target==="openapi-3.0")j.type="string",j.nullable=!0,j.enum=[null];else j.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema");break}case"never":{j.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let K=j,{minimum:L,maximum:O}=Y._zod.bag;if(typeof L==="number")K.minItems=L;if(typeof O==="number")K.maxItems=O;K.type="array",K.items=this.process($.element,{...V,path:[...V.path,"items"]});break}case"object":{let K=j;K.type="object",K.properties={};let L=$.shape;for(let x in L)K.properties[x]=this.process(L[x],{...V,path:[...V.path,"properties",x]});let O=new Set(Object.keys(L)),q=new Set([...O].filter((x)=>{let P=$.shape[x]._zod;if(this.io==="input")return P.optin===void 0;else return P.optout===void 0}));if(q.size>0)K.required=Array.from(q);if($.catchall?._zod.def.type==="never")K.additionalProperties=!1;else if(!$.catchall){if(this.io==="output")K.additionalProperties=!1}else if($.catchall)K.additionalProperties=this.process($.catchall,{...V,path:[...V.path,"additionalProperties"]});break}case"union":{let K=j,L=$.options.map((O,q)=>this.process(O,{...V,path:[...V.path,"anyOf",q]}));K.anyOf=L;break}case"intersection":{let K=j,L=this.process($.left,{...V,path:[...V.path,"allOf",0]}),O=this.process($.right,{...V,path:[...V.path,"allOf",1]}),q=(P)=>("allOf"in P)&&Object.keys(P).length===1,x=[...q(L)?L.allOf:[L],...q(O)?O.allOf:[O]];K.allOf=x;break}case"tuple":{let K=j;K.type="array";let L=this.target==="draft-2020-12"?"prefixItems":"items",O=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",q=$.items.map((M,w)=>this.process(M,{...V,path:[...V.path,L,w]})),x=$.rest?this.process($.rest,{...V,path:[...V.path,O,...this.target==="openapi-3.0"?[$.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(K.prefixItems=q,x)K.items=x}else if(this.target==="openapi-3.0"){if(K.items={anyOf:q},x)K.items.anyOf.push(x);if(K.minItems=q.length,!x)K.maxItems=q.length}else if(K.items=q,x)K.additionalItems=x;let{minimum:P,maximum:b}=Y._zod.bag;if(typeof P==="number")K.minItems=P;if(typeof b==="number")K.maxItems=b;break}case"record":{let K=j;if(K.type="object",this.target==="draft-7"||this.target==="draft-2020-12")K.propertyNames=this.process($.keyType,{...V,path:[...V.path,"propertyNames"]});K.additionalProperties=this.process($.valueType,{...V,path:[...V.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let K=j,L=j9($.entries);if(L.every((O)=>typeof O==="number"))K.type="number";if(L.every((O)=>typeof O==="string"))K.type="string";K.enum=L;break}case"literal":{let K=j,L=[];for(let O of $.values)if(O===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof O==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else L.push(Number(O));else L.push(O);if(L.length===0);else if(L.length===1){let O=L[0];if(K.type=O===null?"null":typeof O,this.target==="draft-4"||this.target==="openapi-3.0")K.enum=[O];else K.const=O}else{if(L.every((O)=>typeof O==="number"))K.type="number";if(L.every((O)=>typeof O==="string"))K.type="string";if(L.every((O)=>typeof O==="boolean"))K.type="string";if(L.every((O)=>O===null))K.type="null";K.enum=L}break}case"file":{let K=j,L={type:"string",format:"binary",contentEncoding:"binary"},{minimum:O,maximum:q,mime:x}=Y._zod.bag;if(O!==void 0)L.minLength=O;if(q!==void 0)L.maxLength=q;if(x)if(x.length===1)L.contentMediaType=x[0],Object.assign(K,L);else K.anyOf=x.map((P)=>{return{...L,contentMediaType:P}});else Object.assign(K,L);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let K=this.process($.innerType,V);if(this.target==="openapi-3.0")z.ref=$.innerType,j.nullable=!0;else j.anyOf=[K,{type:"null"}];break}case"nonoptional":{this.process($.innerType,V),z.ref=$.innerType;break}case"success":{let K=j;K.type="boolean";break}case"default":{this.process($.innerType,V),z.ref=$.innerType,j.default=JSON.parse(JSON.stringify($.defaultValue));break}case"prefault":{if(this.process($.innerType,V),z.ref=$.innerType,this.io==="input")j._prefault=JSON.parse(JSON.stringify($.defaultValue));break}case"catch":{this.process($.innerType,V),z.ref=$.innerType;let K;try{K=$.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}j.default=K;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let K=j,L=Y._zod.pattern;if(!L)throw Error("Pattern not found in template literal");K.type="string",K.pattern=L.source;break}case"pipe":{let K=this.io==="input"?$.in._zod.def.type==="transform"?$.out:$.in:$.out;this.process(K,V),z.ref=K;break}case"readonly":{this.process($.innerType,V),z.ref=$.innerType,j.readOnly=!0;break}case"promise":{this.process($.innerType,V),z.ref=$.innerType;break}case"optional":{this.process($.innerType,V),z.ref=$.innerType;break}case"lazy":{let K=Y._zod.innerType;this.process(K,V),z.ref=K;break}case"custom":{if(this.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema");break}case"function":{if(this.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema");break}default:}}}let U=this.metadataRegistry.get(Y);if(U)Object.assign(z.schema,U);if(this.io==="input"&&I0(Y))delete z.schema.examples,delete z.schema.default;if(this.io==="input"&&z.schema._prefault)(X=z.schema).default??(X.default=z.schema._prefault);return delete z.schema._prefault,this.seen.get(Y).schema}emit(Y,J){let X={cycles:J?.cycles??"ref",reused:J?.reused??"inline",external:J?.external??void 0},$=this.seen.get(Y);if(!$)throw Error("Unprocessed schema. This is a bug in Zod.");let Q=(H)=>{let V=this.target==="draft-2020-12"?"$defs":"definitions";if(X.external){let L=X.external.registry.get(H[0])?.id,O=X.external.uri??((x)=>x);if(L)return{ref:O(L)};let q=H[1].defId??H[1].schema.id??`schema${this.counter++}`;return H[1].defId=q,{defId:q,ref:`${O("__shared")}#/${V}/${q}`}}if(H[1]===$)return{ref:"#"};let j=`${"#"}/${V}/`,K=H[1].schema.id??`__schema${this.counter++}`;return{defId:K,ref:j+K}},G=(H)=>{if(H[1].schema.$ref)return;let V=H[1],{ref:F,defId:j}=Q(H);if(V.def={...V.schema},j)V.defId=j;let K=V.schema;for(let L in K)delete K[L];K.$ref=F};if(X.cycles==="throw")for(let H of this.seen.entries()){let V=H[1];if(V.cycle)throw Error(`Cycle detected: #/${V.cycle?.join("/")}/<root>
|
|
29
|
-
|
|
30
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let H of this.seen.entries()){let V=H[1];if(Y===H[0]){G(H);continue}if(X.external){let j=X.external.registry.get(H[0])?.id;if(Y!==H[0]&&j){G(H);continue}}if(this.metadataRegistry.get(H[0])?.id){G(H);continue}if(V.cycle){G(H);continue}if(V.count>1){if(X.reused==="ref"){G(H);continue}}}let z=(H,V)=>{let F=this.seen.get(H),j=F.def??F.schema,K={...j};if(F.ref===null)return;let L=F.ref;if(F.ref=null,L){z(L,V);let O=this.seen.get(L).schema;if(O.$ref&&(V.target==="draft-7"||V.target==="draft-4"||V.target==="openapi-3.0"))j.allOf=j.allOf??[],j.allOf.push(O);else Object.assign(j,O),Object.assign(j,K)}if(!F.isParent)this.override({zodSchema:H,jsonSchema:j,path:F.path??[]})};for(let H of[...this.seen.entries()].reverse())z(H[0],{target:this.target});let W={};if(this.target==="draft-2020-12")W.$schema="https://json-schema.org/draft/2020-12/schema";else if(this.target==="draft-7")W.$schema="http://json-schema.org/draft-07/schema#";else if(this.target==="draft-4")W.$schema="http://json-schema.org/draft-04/schema#";else if(this.target==="openapi-3.0");else console.warn(`Invalid target: ${this.target}`);if(X.external?.uri){let H=X.external.registry.get(Y)?.id;if(!H)throw Error("Schema is missing an `id` property");W.$id=X.external.uri(H)}Object.assign(W,$.def);let U=X.external?.defs??{};for(let H of this.seen.entries()){let V=H[1];if(V.def&&V.defId)U[V.defId]=V.def}if(X.external);else if(Object.keys(U).length>0)if(this.target==="draft-2020-12")W.$defs=U;else W.definitions=U;try{return JSON.parse(JSON.stringify(W))}catch(H){throw Error("Error converting schema to JSON.")}}}function XG(Y,J){if(Y instanceof k4){let $=new dJ(J),Q={};for(let W of Y._idmap.entries()){let[U,H]=W;$.process(H)}let G={},z={registry:Y,uri:J?.uri,defs:Q};for(let W of Y._idmap.entries()){let[U,H]=W;G[U]=$.emit(H,{...J,external:z})}if(Object.keys(Q).length>0){let W=$.target==="draft-2020-12"?"$defs":"definitions";G.__shared={[W]:Q}}return{schemas:G}}let X=new dJ(J);return X.process(Y),X.emit(Y,J)}function I0(Y,J){let X=J??{seen:new Set};if(X.seen.has(Y))return!1;X.seen.add(Y);let Q=Y._zod.def;switch(Q.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return I0(Q.element,X);case"object":{for(let G in Q.shape)if(I0(Q.shape[G],X))return!0;return!1}case"union":{for(let G of Q.options)if(I0(G,X))return!0;return!1}case"intersection":return I0(Q.left,X)||I0(Q.right,X);case"tuple":{for(let G of Q.items)if(I0(G,X))return!0;if(Q.rest&&I0(Q.rest,X))return!0;return!1}case"record":return I0(Q.keyType,X)||I0(Q.valueType,X);case"map":return I0(Q.keyType,X)||I0(Q.valueType,X);case"set":return I0(Q.valueType,X);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return I0(Q.innerType,X);case"lazy":return I0(Q.getter(),X);case"default":return I0(Q.innerType,X);case"prefault":return I0(Q.innerType,X);case"custom":return!1;case"transform":return!0;case"pipe":return I0(Q.in,X)||I0(Q.out,X);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${Q.type}`)}var TB=_("ZodISODateTime",(Y,J)=>{h$.init(Y,J),F0.init(Y,J)});function $G(Y){return uQ(TB,Y)}var RB=_("ZodISODate",(Y,J)=>{y$.init(Y,J),F0.init(Y,J)});function QG(Y){return pQ(RB,Y)}var CB=_("ZodISOTime",(Y,J)=>{f$.init(Y,J),F0.init(Y,J)});function GG(Y){return lQ(CB,Y)}var wB=_("ZodISODuration",(Y,J)=>{g$.init(Y,J),F0.init(Y,J)});function zG(Y){return dQ(wB,Y)}var WG=(Y,J)=>{T4.init(Y,J),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(X)=>L5(Y,X)},flatten:{value:(X)=>N5(Y,X)},addIssue:{value:(X)=>{Y.issues.push(X),Y.message=JSON.stringify(Y.issues,q8,2)}},addIssues:{value:(X)=>{Y.issues.push(...X),Y.message=JSON.stringify(Y.issues,q8,2)}},isEmpty:{get(){return Y.issues.length===0}}})},jP=_("ZodError",WG),U1=_("ZodError",WG,{Parent:Error});var ZG=R4(U1),UG=C4(U1),HG=D9(U1),m4=O9(U1),VG=O5(U1),BG=_5(U1),KG=q5(U1),jG=P5(U1),NG=M5(U1),LG=E5(U1),FG=A5(U1),DG=T5(U1);var D0=_("ZodType",(Y,J)=>{return j0.init(Y,J),Y.def=J,Y.type=J.type,Object.defineProperty(Y,"_def",{value:J}),Y.check=(...X)=>{return Y.clone({...J,checks:[...J.checks??[],...X.map(($)=>typeof $==="function"?{_zod:{check:$,def:{check:"custom"},onattach:[]}}:$)]})},Y.clone=(X,$)=>E1(Y,X,$),Y.brand=()=>Y,Y.register=(X,$)=>{return X.add(Y,$),Y},Y.parse=(X,$)=>ZG(Y,X,$,{callee:Y.parse}),Y.safeParse=(X,$)=>HG(Y,X,$),Y.parseAsync=async(X,$)=>UG(Y,X,$,{callee:Y.parseAsync}),Y.safeParseAsync=async(X,$)=>m4(Y,X,$),Y.spa=Y.safeParseAsync,Y.encode=(X,$)=>VG(Y,X,$),Y.decode=(X,$)=>BG(Y,X,$),Y.encodeAsync=async(X,$)=>KG(Y,X,$),Y.decodeAsync=async(X,$)=>jG(Y,X,$),Y.safeEncode=(X,$)=>NG(Y,X,$),Y.safeDecode=(X,$)=>LG(Y,X,$),Y.safeEncodeAsync=async(X,$)=>FG(Y,X,$),Y.safeDecodeAsync=async(X,$)=>DG(Y,X,$),Y.refine=(X,$)=>Y.check(PK(X,$)),Y.superRefine=(X)=>Y.check(MK(X)),Y.overwrite=(X)=>Y.check(d6(X)),Y.optional=()=>qG(Y),Y.nullable=()=>PG(Y),Y.nullish=()=>qG(PG(Y)),Y.nonoptional=(X)=>NK(Y,X),Y.array=()=>oJ(Y),Y.or=(X)=>rJ([Y,X]),Y.and=(X)=>GK(Y,X),Y.transform=(X)=>MG(Y,UK(X)),Y.default=(X)=>BK(Y,X),Y.prefault=(X)=>jK(Y,X),Y.catch=(X)=>FK(Y,X),Y.pipe=(X)=>MG(Y,X),Y.readonly=()=>_K(Y),Y.describe=(X)=>{let $=Y.clone();return l6.add($,{description:X}),$},Object.defineProperty(Y,"description",{get(){return l6.get(Y)?.description},configurable:!0}),Y.meta=(...X)=>{if(X.length===0)return l6.get(Y);let $=Y.clone();return l6.add($,X[0]),$},Y.isOptional=()=>Y.safeParse(void 0).success,Y.isNullable=()=>Y.safeParse(null).success,Y}),EG=_("_ZodString",(Y,J)=>{b4.init(Y,J),D0.init(Y,J);let X=Y._zod.bag;Y.format=X.format??null,Y.minLength=X.minimum??null,Y.maxLength=X.maximum??null,Y.regex=(...$)=>Y.check(vJ(...$)),Y.includes=(...$)=>Y.check(fJ(...$)),Y.startsWith=(...$)=>Y.check(gJ(...$)),Y.endsWith=(...$)=>Y.check(mJ(...$)),Y.min=(...$)=>Y.check(E8(...$)),Y.max=(...$)=>Y.check(y4(...$)),Y.length=(...$)=>Y.check(f4(...$)),Y.nonempty=(...$)=>Y.check(E8(1,...$)),Y.lowercase=($)=>Y.check(hJ($)),Y.uppercase=($)=>Y.check(yJ($)),Y.trim=()=>Y.check(uJ()),Y.normalize=(...$)=>Y.check(cJ(...$)),Y.toLowerCase=()=>Y.check(pJ()),Y.toUpperCase=()=>Y.check(lJ())}),kB=_("ZodString",(Y,J)=>{b4.init(Y,J),EG.init(Y,J),Y.email=(X)=>Y.check(qQ(xB,X)),Y.url=(X)=>Y.check(TQ(vB,X)),Y.jwt=(X)=>Y.check(cQ(sB,X)),Y.emoji=(X)=>Y.check(RQ(hB,X)),Y.guid=(X)=>Y.check(xJ(OG,X)),Y.uuid=(X)=>Y.check(PQ(c4,X)),Y.uuidv4=(X)=>Y.check(MQ(c4,X)),Y.uuidv6=(X)=>Y.check(EQ(c4,X)),Y.uuidv7=(X)=>Y.check(AQ(c4,X)),Y.nanoid=(X)=>Y.check(CQ(yB,X)),Y.guid=(X)=>Y.check(xJ(OG,X)),Y.cuid=(X)=>Y.check(wQ(fB,X)),Y.cuid2=(X)=>Y.check(IQ(gB,X)),Y.ulid=(X)=>Y.check(SQ(mB,X)),Y.base64=(X)=>Y.check(fQ(nB,X)),Y.base64url=(X)=>Y.check(gQ(oB,X)),Y.xid=(X)=>Y.check(bQ(cB,X)),Y.ksuid=(X)=>Y.check(kQ(uB,X)),Y.ipv4=(X)=>Y.check(xQ(pB,X)),Y.ipv6=(X)=>Y.check(vQ(lB,X)),Y.cidrv4=(X)=>Y.check(hQ(dB,X)),Y.cidrv6=(X)=>Y.check(yQ(iB,X)),Y.e164=(X)=>Y.check(mQ(rB,X)),Y.datetime=(X)=>Y.check($G(X)),Y.date=(X)=>Y.check(QG(X)),Y.time=(X)=>Y.check(GG(X)),Y.duration=(X)=>Y.check(zG(X))});function AG(Y){return _Q(kB,Y)}var F0=_("ZodStringFormat",(Y,J)=>{L0.init(Y,J),EG.init(Y,J)}),xB=_("ZodEmail",(Y,J)=>{R$.init(Y,J),F0.init(Y,J)});var OG=_("ZodGUID",(Y,J)=>{A$.init(Y,J),F0.init(Y,J)});var c4=_("ZodUUID",(Y,J)=>{T$.init(Y,J),F0.init(Y,J)});var vB=_("ZodURL",(Y,J)=>{C$.init(Y,J),F0.init(Y,J)});var hB=_("ZodEmoji",(Y,J)=>{w$.init(Y,J),F0.init(Y,J)});var yB=_("ZodNanoID",(Y,J)=>{I$.init(Y,J),F0.init(Y,J)});var fB=_("ZodCUID",(Y,J)=>{S$.init(Y,J),F0.init(Y,J)});var gB=_("ZodCUID2",(Y,J)=>{b$.init(Y,J),F0.init(Y,J)});var mB=_("ZodULID",(Y,J)=>{k$.init(Y,J),F0.init(Y,J)});var cB=_("ZodXID",(Y,J)=>{x$.init(Y,J),F0.init(Y,J)});var uB=_("ZodKSUID",(Y,J)=>{v$.init(Y,J),F0.init(Y,J)});var pB=_("ZodIPv4",(Y,J)=>{m$.init(Y,J),F0.init(Y,J)});var lB=_("ZodIPv6",(Y,J)=>{c$.init(Y,J),F0.init(Y,J)});var dB=_("ZodCIDRv4",(Y,J)=>{u$.init(Y,J),F0.init(Y,J)});var iB=_("ZodCIDRv6",(Y,J)=>{p$.init(Y,J),F0.init(Y,J)});var nB=_("ZodBase64",(Y,J)=>{d$.init(Y,J),F0.init(Y,J)});var oB=_("ZodBase64URL",(Y,J)=>{i$.init(Y,J),F0.init(Y,J)});var rB=_("ZodE164",(Y,J)=>{n$.init(Y,J),F0.init(Y,J)});var sB=_("ZodJWT",(Y,J)=>{o$.init(Y,J),F0.init(Y,J)});var TG=_("ZodNumber",(Y,J)=>{bJ.init(Y,J),D0.init(Y,J),Y.gt=($,Q)=>Y.check(v4($,Q)),Y.gte=($,Q)=>Y.check(P9($,Q)),Y.min=($,Q)=>Y.check(P9($,Q)),Y.lt=($,Q)=>Y.check(x4($,Q)),Y.lte=($,Q)=>Y.check(q9($,Q)),Y.max=($,Q)=>Y.check(q9($,Q)),Y.int=($)=>Y.check(_G($)),Y.safe=($)=>Y.check(_G($)),Y.positive=($)=>Y.check(v4(0,$)),Y.nonnegative=($)=>Y.check(P9(0,$)),Y.negative=($)=>Y.check(x4(0,$)),Y.nonpositive=($)=>Y.check(q9(0,$)),Y.multipleOf=($,Q)=>Y.check(h4($,Q)),Y.step=($,Q)=>Y.check(h4($,Q)),Y.finite=()=>Y;let X=Y._zod.bag;Y.minValue=Math.max(X.minimum??Number.NEGATIVE_INFINITY,X.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Y.maxValue=Math.min(X.maximum??Number.POSITIVE_INFINITY,X.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Y.isInt=(X.format??"").includes("int")||Number.isSafeInteger(X.multipleOf??0.5),Y.isFinite=!0,Y.format=X.format??null});function RG(Y){return iQ(TG,Y)}var aB=_("ZodNumberFormat",(Y,J)=>{r$.init(Y,J),TG.init(Y,J)});function _G(Y){return nQ(aB,Y)}var tB=_("ZodBoolean",(Y,J)=>{s$.init(Y,J),D0.init(Y,J)});function CG(Y){return oQ(tB,Y)}var eB=_("ZodNull",(Y,J)=>{a$.init(Y,J),D0.init(Y,J)});function wG(Y){return rQ(eB,Y)}var YK=_("ZodUnknown",(Y,J)=>{t$.init(Y,J),D0.init(Y,J)});function M9(){return sQ(YK)}var JK=_("ZodNever",(Y,J)=>{e$.init(Y,J),D0.init(Y,J)});function nJ(Y){return aQ(JK,Y)}var XK=_("ZodArray",(Y,J)=>{YQ.init(Y,J),D0.init(Y,J),Y.element=J.element,Y.min=(X,$)=>Y.check(E8(X,$)),Y.nonempty=(X)=>Y.check(E8(1,X)),Y.max=(X,$)=>Y.check(y4(X,$)),Y.length=(X,$)=>Y.check(f4(X,$)),Y.unwrap=()=>Y.element});function oJ(Y,J){return tQ(XK,Y,J)}var IG=_("ZodObject",(Y,J)=>{$Q.init(Y,J),D0.init(Y,J),$0.defineLazy(Y,"shape",()=>J.shape),Y.keyof=()=>sJ(Object.keys(Y._zod.def.shape)),Y.catchall=(X)=>Y.clone({...Y._zod.def,catchall:X}),Y.passthrough=()=>Y.clone({...Y._zod.def,catchall:M9()}),Y.loose=()=>Y.clone({...Y._zod.def,catchall:M9()}),Y.strict=()=>Y.clone({...Y._zod.def,catchall:nJ()}),Y.strip=()=>Y.clone({...Y._zod.def,catchall:void 0}),Y.extend=(X)=>{return $0.extend(Y,X)},Y.safeExtend=(X)=>{return $0.safeExtend(Y,X)},Y.merge=(X)=>$0.merge(Y,X),Y.pick=(X)=>$0.pick(Y,X),Y.omit=(X)=>$0.omit(Y,X),Y.partial=(...X)=>$0.partial(yG,Y,X[0]),Y.required=(...X)=>$0.required(fG,Y,X[0])});function SG(Y,J){let X={type:"object",get shape(){return $0.assignProp(this,"shape",Y?$0.objectClone(Y):{}),this.shape},...$0.normalizeParams(J)};return new IG(X)}function bG(Y,J){return new IG({type:"object",get shape(){return $0.assignProp(this,"shape",$0.objectClone(Y)),this.shape},catchall:M9(),...$0.normalizeParams(J)})}var kG=_("ZodUnion",(Y,J)=>{kJ.init(Y,J),D0.init(Y,J),Y.options=J.options});function rJ(Y,J){return new kG({type:"union",options:Y,...$0.normalizeParams(J)})}var $K=_("ZodDiscriminatedUnion",(Y,J)=>{kG.init(Y,J),QQ.init(Y,J)});function xG(Y,J,X){return new $K({type:"union",options:J,discriminator:Y,...$0.normalizeParams(X)})}var QK=_("ZodIntersection",(Y,J)=>{GQ.init(Y,J),D0.init(Y,J)});function GK(Y,J){return new QK({type:"intersection",left:Y,right:J})}var zK=_("ZodRecord",(Y,J)=>{zQ.init(Y,J),D0.init(Y,J),Y.keyType=J.keyType,Y.valueType=J.valueType});function vG(Y,J,X){return new zK({type:"record",keyType:Y,valueType:J,...$0.normalizeParams(X)})}var iJ=_("ZodEnum",(Y,J)=>{WQ.init(Y,J),D0.init(Y,J),Y.enum=J.entries,Y.options=Object.values(J.entries);let X=new Set(Object.keys(J.entries));Y.extract=($,Q)=>{let G={};for(let z of $)if(X.has(z))G[z]=J.entries[z];else throw Error(`Key ${z} not found in enum`);return new iJ({...J,checks:[],...$0.normalizeParams(Q),entries:G})},Y.exclude=($,Q)=>{let G={...J.entries};for(let z of $)if(X.has(z))delete G[z];else throw Error(`Key ${z} not found in enum`);return new iJ({...J,checks:[],...$0.normalizeParams(Q),entries:G})}});function sJ(Y,J){let X=Array.isArray(Y)?Object.fromEntries(Y.map(($)=>[$,$])):Y;return new iJ({type:"enum",entries:X,...$0.normalizeParams(J)})}var WK=_("ZodLiteral",(Y,J)=>{ZQ.init(Y,J),D0.init(Y,J),Y.values=new Set(J.values),Object.defineProperty(Y,"value",{get(){if(J.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return J.values[0]}})});function hG(Y,J){return new WK({type:"literal",values:Array.isArray(Y)?Y:[Y],...$0.normalizeParams(J)})}var ZK=_("ZodTransform",(Y,J)=>{UQ.init(Y,J),D0.init(Y,J),Y._zod.parse=(X,$)=>{if($.direction==="backward")throw new B9(Y.constructor.name);X.addIssue=(G)=>{if(typeof G==="string")X.issues.push($0.issue(G,X.value,J));else{let z=G;if(z.fatal)z.continue=!1;z.code??(z.code="custom"),z.input??(z.input=X.value),z.inst??(z.inst=Y),X.issues.push($0.issue(z))}};let Q=J.transform(X.value,X);if(Q instanceof Promise)return Q.then((G)=>{return X.value=G,X});return X.value=Q,X}});function UK(Y){return new ZK({type:"transform",transform:Y})}var yG=_("ZodOptional",(Y,J)=>{HQ.init(Y,J),D0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType});function qG(Y){return new yG({type:"optional",innerType:Y})}var HK=_("ZodNullable",(Y,J)=>{VQ.init(Y,J),D0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType});function PG(Y){return new HK({type:"nullable",innerType:Y})}var VK=_("ZodDefault",(Y,J)=>{BQ.init(Y,J),D0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function BK(Y,J){return new VK({type:"default",innerType:Y,get defaultValue(){return typeof J==="function"?J():$0.shallowClone(J)}})}var KK=_("ZodPrefault",(Y,J)=>{KQ.init(Y,J),D0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType});function jK(Y,J){return new KK({type:"prefault",innerType:Y,get defaultValue(){return typeof J==="function"?J():$0.shallowClone(J)}})}var fG=_("ZodNonOptional",(Y,J)=>{jQ.init(Y,J),D0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType});function NK(Y,J){return new fG({type:"nonoptional",innerType:Y,...$0.normalizeParams(J)})}var LK=_("ZodCatch",(Y,J)=>{NQ.init(Y,J),D0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function FK(Y,J){return new LK({type:"catch",innerType:Y,catchValue:typeof J==="function"?J:()=>J})}var DK=_("ZodPipe",(Y,J)=>{LQ.init(Y,J),D0.init(Y,J),Y.in=J.in,Y.out=J.out});function MG(Y,J){return new DK({type:"pipe",in:Y,out:J})}var OK=_("ZodReadonly",(Y,J)=>{FQ.init(Y,J),D0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType});function _K(Y){return new OK({type:"readonly",innerType:Y})}var qK=_("ZodLazy",(Y,J)=>{DQ.init(Y,J),D0.init(Y,J),Y.unwrap=()=>Y._zod.def.getter()});function gG(Y){return new qK({type:"lazy",getter:Y})}var aJ=_("ZodCustom",(Y,J)=>{OQ.init(Y,J),D0.init(Y,J)});function mG(Y,J){return eQ(aJ,Y??(()=>!0),J)}function PK(Y,J={}){return YG(aJ,Y,J)}function MK(Y){return JG(Y)}function cG(Y,J={error:`Input not instance of ${Y.name}`}){let X=new aJ({type:"custom",check:"custom",fn:($)=>$ instanceof Y,abort:!0,...$0.normalizeParams(J)});return X._zod.bag.Class=Y,X}var RK=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag).get,CK=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get;function aG(Y){return ArrayBuffer.isView(Y)&&RK.call(Y)==="Uint8Array"}function tG(Y){if(typeof Y!=="object"||Y===null||!("byteLength"in Y))return!1;try{return CK.call(Y),!0}catch{return!1}}function eG(Y=globalThis){if(Y.navigator?.userAgent)return Y.navigator.userAgent.toLowerCase();if(Y.process?.versions?.node)return`node.js/${Y.process.version}`;if(Y.EdgeRuntime)return"vercel-edge";return""}function Yz(Y){if(Y==null)return{};let J={};if(Y instanceof Headers)Y.forEach((X,$)=>{J[$.toLowerCase()]=X});else{if(!Array.isArray(Y))Y=Object.entries(Y);for(let[X,$]of Y)if($!=null)J[X.toLowerCase()]=$}return J}function Jz(Y,...J){let X=new Headers(Yz(Y)),$=X.get("user-agent")||"";return X.set("user-agent",[$,...J].filter(Boolean).join(" ")),Object.fromEntries(X.entries())}var wK=[{mediaType:"audio/aac",bytesPrefix:[255,240]},{mediaType:"audio/aac",bytesPrefix:[255,241]},{mediaType:"audio/aac",bytesPrefix:[255,248]},{mediaType:"audio/aac",bytesPrefix:[255,249]},{mediaType:"audio/mpeg",bytesPrefix:[255,251]},{mediaType:"audio/mpeg",bytesPrefix:[255,250]},{mediaType:"audio/mpeg",bytesPrefix:[255,243]},{mediaType:"audio/mpeg",bytesPrefix:[255,242]},{mediaType:"audio/mpeg",bytesPrefix:[255,227]},{mediaType:"audio/mpeg",bytesPrefix:[255,226]},{mediaType:"audio/wav",bytesPrefix:[82,73,70,70,null,null,null,null,87,65,86,69]},{mediaType:"audio/ogg",bytesPrefix:[79,103,103,83]},{mediaType:"audio/flac",bytesPrefix:[102,76,97,67]},{mediaType:"audio/aac",bytesPrefix:[64,21,0,0]},{mediaType:"audio/webm",bytesPrefix:[26,69,223,163]}],GM=[...wK,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];async function u4(Y){try{await Y.body?.cancel()}catch{}}var Xz="AI_DownloadError",$z=`vercel.ai.error.${Xz}`,IK=Symbol.for($z),h0=class extends e1{constructor({url:Y,statusCode:J,statusText:X,cause:$,message:Q=$==null?`Failed to download ${Y}: ${J} ${X}`:`Failed to download ${Y}: ${$}`}){super({name:Xz,message:Q,cause:$});this[IK]=!0,this.url=Y,this.statusCode=J,this.statusText=X}static isInstance(Y){return e1.hasMarker(Y,$z)}};function SK(Y=globalThis){return Y.window!=null}function Y3(Y,J){try{return new URL(Y).origin===new URL(J).origin}catch{return!1}}function bK(Y){let J;try{J=new URL(Y)}catch{throw new h0({url:Y,message:`Invalid URL: ${Y}`})}if(J.protocol==="data:")return;if(J.protocol!=="http:"&&J.protocol!=="https:")throw new h0({url:Y,message:`URL scheme must be http, https, or data, got ${J.protocol}`});let X=J.hostname.toLowerCase().replace(/\.+$/,"");if(!X)throw new h0({url:Y,message:"URL must have a hostname"});if(X==="localhost"||X.endsWith(".local")||X.endsWith(".localhost")||X.endsWith(".internal"))throw new h0({url:Y,message:`URL with hostname ${X} is not allowed`});if(X.startsWith("[")&&X.endsWith("]")){if(Qz(X.slice(1,-1)))throw new h0({url:Y,message:`URL with IPv6 address ${X} is not allowed`});return}if(X3(X)){if($3(X))throw new h0({url:Y,message:`URL with IP address ${X} is not allowed`})}}function kK({address:Y,family:J,hostname:X}){if(J===4?!X3(Y)||$3(Y):J===6?Qz(Y):!0)throw new h0({url:X,message:`Hostname ${X} resolved to disallowed IP address ${Y}`})}function X3(Y){let J=Y.split(".");if(J.length!==4)return!1;return J.every((X)=>{let $=Number(X);return Number.isInteger($)&&$>=0&&$<=255&&String($)===X})}function $3(Y){let[J,X,$]=Y.split(".").map(Number);if(J===0)return!0;if(J===10)return!0;if(J===100&&X>=64&&X<=127)return!0;if(J===127)return!0;if(J===169&&X===254)return!0;if(J===172&&X>=16&&X<=31)return!0;if(J===192&&X===0&&$===0)return!0;if(J===192&&X===0&&$===2)return!0;if(J===192&&X===168)return!0;if(J===198&&(X===18||X===19))return!0;if(J===198&&X===51&&$===100)return!0;if(J===203&&X===0&&$===113)return!0;if(J>=224)return!0;return!1}function xK(Y){let J=Y.toLowerCase(),X=J.indexOf("%");if(X!==-1)J=J.slice(0,X);let $=J.split("::");if($.length>2)return null;let Q=(z)=>{if(z==="")return[];let W=[],U=z.split(":");for(let H=0;H<U.length;H++){let V=U[H];if(V.includes(".")){if(H!==U.length-1||!X3(V))return null;let[F,j,K,L]=V.split(".").map(Number);W.push(F<<8|j,K<<8|L);continue}if(!/^[0-9a-f]{1,4}$/.test(V))return null;W.push(parseInt(V,16))}return W},G=Q($[0]);if(G===null)return null;if($.length===2){let z=Q($[1]);if(z===null)return null;let W=8-G.length-z.length;if(W<0)return null;return[...G,...Array(W).fill(0),...z]}return G.length===8?G:null}function Qz(Y){let J=xK(Y);if(J===null)return!0;let X=($)=>J.slice(0,$).every((Q)=>Q===0);if(X(7)&&(J[7]===0||J[7]===1))return!0;if((J[0]&65024)===64512)return!0;if((J[0]&65472)===65152)return!0;if((J[0]&65472)===65216)return!0;if((J[0]&65280)===65280)return!0;if(J[0]===8193&&J[1]===3512)return!0;if(J[0]===16383&&(J[1]&61440)===0)return!0;if(X(6)||X(5)&&J[5]===65535||X(4)&&J[4]===65535&&J[5]===0||J[0]===100&&J[1]===65435&&J[2]===0&&J[3]===0&&J[4]===0&&J[5]===0||J[0]===100&&J[1]===65435&&J[2]===1)return $3(`${J[6]>>8&255}.${J[6]&255}.${J[7]>>8&255}.${J[7]&255}`);return!1}function vK(Y){return(J,X,$)=>{Y(J,{...X,all:!0},(Q,G)=>{if(Q){$(Q);return}try{let[z]=G;if(z==null)throw Error(`Hostname ${J} did not resolve to an address`);for(let{address:W,family:U}of G)kK({address:W,family:U,hostname:J});if(X.all===!0)$(null,G);else $(null,z.address,z.family)}catch(z){$(z instanceof Error?z:Error(String(z)))}})}}var hK;function yK(){let Y=globalThis.process;return Y?.release?.name==="node"&&Y.versions?.bun==null&&Y.versions?.deno==null&&Y.title!=="workerd"&&globalThis.EdgeRuntime==null}async function fK(){if(!yK())return globalThis.fetch;return hK??=Promise.resolve().then(gK)}function gK(){let Y=uG("node:module"),{lookup:J}=uG("node:dns"),{Agent:X,fetch:$}=Y.createRequire(Gz())("undici"),Q=new X({connect:{lookup:vK(J)}});return(G,z)=>$(G,{...z,dispatcher:Q})}function uG(Y){let J=globalThis.process?.getBuiltinModule?.(Y);if(J==null)throw Error(`Node.js built-in module ${Y} is unavailable`);return J}function Gz(){let Y=Error.prepareStackTrace;try{Error.prepareStackTrace=(Q,G)=>G;let J=Error("Capture current module path");Error.captureStackTrace(J,Gz);let[X]=J.stack,$=X?.getFileName();if($==null)throw Error("Unable to determine the current module path");return $}finally{Error.prepareStackTrace=Y}}var mK=["connection","keep-alive","te","trailer","transfer-encoding","upgrade","host","forwarded","proxy-authorization","via","x-forwarded-for","x-forwarded-host","x-forwarded-proto","x-real-ip","metadata","metadata-flavor","x-aws-ec2-metadata-token","x-metadata-token","cookie","set-cookie"];function zz(Y){let J=new Headers(Y);for(let X of mK)J.delete(X);return J}var cK=10,uK=new Set([301,302,303,307,308]);async function pK(Y){return Y==null||Y===globalThis.fetch?await fK():Y}async function lK({url:Y,headers:J,abortSignal:X,maxRedirects:$=cK,fetch:Q,trustedOrigin:G}){let z=J===void 0?void 0:zz(J),W=(H)=>{let V={signal:X,redirect:H};if(z!==void 0)V.headers=new Headers(z);return V},U=Y;for(let H=0;H<=$;H++){let V=G!==void 0&&Y3(U,G);if(!V)bK(U);let F=V&&Q!=null?Q:V?globalThis.fetch:await pK(Q),j=await F(U,W("manual"));if(j.type==="opaqueredirect"){if(!SK())throw new h0({url:Y,message:`Redirect from ${U} could not be validated and was blocked`});return await F(U,W("follow"))}let K=j.headers?.get("location");if(uK.has(j.status)&&K){u4(j);let L=new URL(K,U).toString();if(new URL(U).protocol==="https:"&&new URL(L).protocol==="http:")throw new h0({url:Y,message:"Redirect from HTTPS to HTTP was blocked"});if(z!==void 0&&!Y3(L,U)){let O=z.get("user-agent");z=new Headers(O==null?void 0:{"user-agent":O})}U=L;continue}return j}throw new h0({url:Y,message:`Too many redirects (max ${$})`})}var dK=new Set(["accept","accept-language","baggage","cache-control","idempotency-key","if-match","if-modified-since","if-none-match","if-range","if-unmodified-since","pragma","range","traceparent","tracestate","user-agent","x-correlation-id","x-request-id"]);async function Wz({headers:Y,credentialedOrigin:J,untrustedFirstHopHeaders:X,...$}){let Q;if(Y!==void 0){Q=zz(Y);let G=J??$.trustedOrigin;if(G===void 0||!Y3($.url,G)){let z=new Set([...dK,...(X??[]).map((W)=>W.toLowerCase())]);Q=new Headers([...Q].filter(([W])=>z.has(W)))}}return lK({...$,headers:Q})}var Q3=2147483648;async function Zz({response:Y,url:J,maxBytes:X=Q3,onChunk:$}){let Q=Y.headers.get("content-length");if(Q!=null){let F=parseInt(Q,10);if(!isNaN(F)&&F>X)throw await u4(Y),new h0({url:J,message:`Download of ${J} exceeded maximum size of ${X} bytes (Content-Length: ${F}).`})}let G=Y.body;if(G==null)return new Uint8Array(0);let z=G.getReader(),W=[],U=0;try{while(!0){let{done:F,value:j}=await z.read();if(F)break;if(U+=j.length,U>X)throw new h0({url:J,message:`Download of ${J} exceeded maximum size of ${X} bytes.`});if($!=null){$(j);continue}W.push(j.byteLength<j.buffer.byteLength?new Uint8Array(j):j)}}finally{try{await z.cancel()}catch{}finally{z.releaseLock()}}let H=new Uint8Array($!=null?0:U),V=0;for(let F of W)H.set(F,V),V+=F.length;return H}var S0=({prefix:Y,size:J=16,alphabet:X="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:$="-"}={})=>{let Q=()=>{let G=X.length,z=Array(J);for(let W=0;W<J;W++)z[W]=X[Math.random()*G|0];return z.join("")};if(Y==null)return Q;if(X.includes($))throw new Q5({argument:"separator",message:`The separator "${$}" must not be part of the alphabet "${X}".`});return()=>`${Y}${$}${Q()}`},Uz=S0();function Hz(Y){return globalThis.Buffer?.isBuffer(Y)??!1}function Vz(Y){if(Y.type==="object"||Array.isArray(Y.type)&&Y.type.includes("object")){let{additionalProperties:X}=Y;Y.additionalProperties=X!=null&&typeof X!=="boolean"?O6(X):!1;let{properties:$}=Y;if($!=null)for(let Q of Object.keys($))$[Q]=O6($[Q])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(O6):O6(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(O6);if(Y.allOf!=null)Y.allOf=Y.allOf.map(O6);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(O6);let{definitions:J}=Y;if(J!=null)for(let X of Object.keys(J))J[X]=O6(J[X]);return Y}function O6(Y){if(typeof Y==="boolean")return Y;return Vz(Y)}var iK=Symbol("Let zodToJsonSchema decide on which parser to use"),pG={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},nK=(Y)=>typeof Y==="string"?{...pG,name:Y}:{...pG,...Y};function H1(){return{}}function oK(Y,J){let X={type:"array"};if(Y.type?._def&&Y.type?._def?.typeName!=="ZodAny")X.items=V0(Y.type._def,{...J,currentPath:[...J.currentPath,"items"]});if(Y.minLength)X.minItems=Y.minLength.value;if(Y.maxLength)X.maxItems=Y.maxLength.value;if(Y.exactLength)X.minItems=Y.exactLength.value,X.maxItems=Y.exactLength.value;return X}function rK(Y){let J={type:"integer",format:"int64"};if(!Y.checks)return J;for(let X of Y.checks)switch(X.kind){case"min":if(X.inclusive)J.minimum=X.value;else J.exclusiveMinimum=X.value;break;case"max":if(X.inclusive)J.maximum=X.value;else J.exclusiveMaximum=X.value;break;case"multipleOf":J.multipleOf=X.value}return J}function sK(){return{type:"boolean"}}function Bz(Y,J){return V0(Y.type._def,J)}var aK=(Y,J)=>{return V0(Y.innerType._def,J)};function Kz(Y,J,X){let $=X??J.dateStrategy;if(Array.isArray($))return{anyOf:$.map((Q)=>Kz(Y,J,Q))};switch($){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return tK(Y)}}var tK=(Y)=>{let J={type:"integer",format:"unix-time"};for(let X of Y.checks)switch(X.kind){case"min":J.minimum=X.value;break;case"max":J.maximum=X.value}return J};function eK(Y,J){return{...V0(Y.innerType._def,J),default:Y.defaultValue()}}function Yj(Y,J){return J.effectStrategy==="input"?V0(Y.schema._def,J):H1()}function Jj(Y){return{type:"string",enum:Array.from(Y.values)}}var Xj=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function $j(Y,J){let X=[V0(Y.left._def,{...J,currentPath:[...J.currentPath,"allOf","0"]}),V0(Y.right._def,{...J,currentPath:[...J.currentPath,"allOf","1"]})].filter((Q)=>!!Q),$=[];return X.forEach((Q)=>{if(Xj(Q))$.push(...Q.allOf);else{let G=Q;if("additionalProperties"in Q&&Q.additionalProperties===!1){let{additionalProperties:z,...W}=Q;G=W}$.push(G)}}),$.length?{allOf:$}:void 0}function Qj(Y){let J=typeof Y.value;if(J!=="bigint"&&J!=="number"&&J!=="boolean"&&J!=="string")return{type:Array.isArray(Y.value)?"array":"object"};return{type:J==="bigint"?"integer":J,const:Y.value}}var tJ=void 0,T1={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(tJ===void 0)tJ=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return tJ},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function jz(Y,J){let X={type:"string"};if(Y.checks)for(let $ of Y.checks)switch($.kind){case"min":X.minLength=typeof X.minLength==="number"?Math.max(X.minLength,$.value):$.value;break;case"max":X.maxLength=typeof X.maxLength==="number"?Math.min(X.maxLength,$.value):$.value;break;case"email":switch(J.emailStrategy){case"format:email":R1(X,"email",$.message,J);break;case"format:idn-email":R1(X,"idn-email",$.message,J);break;case"pattern:zod":r0(X,T1.email,$.message,J)}break;case"url":R1(X,"uri",$.message,J);break;case"uuid":R1(X,"uuid",$.message,J);break;case"regex":r0(X,$.regex,$.message,J);break;case"cuid":r0(X,T1.cuid,$.message,J);break;case"cuid2":r0(X,T1.cuid2,$.message,J);break;case"startsWith":r0(X,RegExp(`^${eJ($.value,J)}`),$.message,J);break;case"endsWith":r0(X,RegExp(`${eJ($.value,J)}$`),$.message,J);break;case"datetime":R1(X,"date-time",$.message,J);break;case"date":R1(X,"date",$.message,J);break;case"time":R1(X,"time",$.message,J);break;case"duration":R1(X,"duration",$.message,J);break;case"length":X.minLength=typeof X.minLength==="number"?Math.max(X.minLength,$.value):$.value,X.maxLength=typeof X.maxLength==="number"?Math.min(X.maxLength,$.value):$.value;break;case"includes":r0(X,RegExp(eJ($.value,J)),$.message,J);break;case"ip":if($.version!=="v6")R1(X,"ipv4",$.message,J);if($.version!=="v4")R1(X,"ipv6",$.message,J);break;case"base64url":r0(X,T1.base64url,$.message,J);break;case"jwt":r0(X,T1.jwt,$.message,J);break;case"cidr":if($.version!=="v6")r0(X,T1.ipv4Cidr,$.message,J);if($.version!=="v4")r0(X,T1.ipv6Cidr,$.message,J);break;case"emoji":r0(X,T1.emoji(),$.message,J);break;case"ulid":r0(X,T1.ulid,$.message,J);break;case"base64":switch(J.base64Strategy){case"format:binary":R1(X,"binary",$.message,J);break;case"contentEncoding:base64":X.contentEncoding="base64";break;case"pattern:zod":r0(X,T1.base64,$.message,J)}break;case"nanoid":r0(X,T1.nanoid,$.message,J)}return X}function eJ(Y,J){return J.patternStrategy==="escape"?zj(Y):Y}var Gj=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function zj(Y){let J="";for(let X=0;X<Y.length;X++){if(!Gj.has(Y[X]))J+="\\";J+=Y[X]}return J}function R1(Y,J,X,$){if(Y.format||Y.anyOf?.some((Q)=>Q.format)){if(!Y.anyOf)Y.anyOf=[];if(Y.format)Y.anyOf.push({format:Y.format}),delete Y.format;Y.anyOf.push({format:J,...X&&$.errorMessages&&{errorMessage:{format:X}}})}else Y.format=J}function r0(Y,J,X,$){if(Y.pattern||Y.allOf?.some((Q)=>Q.pattern)){if(!Y.allOf)Y.allOf=[];if(Y.pattern)Y.allOf.push({pattern:Y.pattern}),delete Y.pattern;Y.allOf.push({pattern:lG(J,$),...X&&$.errorMessages&&{errorMessage:{pattern:X}}})}else Y.pattern=lG(J,$)}function lG(Y,J){if(!J.applyRegexFlags||!Y.flags)return Y.source;let X={i:Y.flags.includes("i"),m:Y.flags.includes("m"),s:Y.flags.includes("s")},$=X.i?Y.source.toLowerCase():Y.source,Q="",G=!1,z=!1,W=!1;for(let U=0;U<$.length;U++){if(G){Q+=$[U],G=!1;continue}if(X.i){if(z){if($[U].match(/[a-z]/)){if(W)Q+=$[U],Q+=`${$[U-2]}-${$[U]}`.toUpperCase(),W=!1;else if($[U+1]==="-"&&$[U+2]?.match(/[a-z]/))Q+=$[U],W=!0;else Q+=`${$[U]}${$[U].toUpperCase()}`;continue}}else if($[U].match(/[a-z]/)){Q+=`[${$[U]}${$[U].toUpperCase()}]`;continue}}if(X.m){if($[U]==="^"){Q+=`(^|(?<=[\r
|
|
31
|
-
]))`;continue}else if($[U]==="$"){Q+=`($|(?=[\r
|
|
32
|
-
]))`;continue}}if(X.s&&$[U]==="."){Q+=z?`${$[U]}\r
|
|
33
|
-
`:`[${$[U]}\r
|
|
34
|
-
]`;continue}if(Q+=$[U],$[U]==="\\")G=!0;else if(z&&$[U]==="]")z=!1;else if(!z&&$[U]==="[")z=!0}try{new RegExp(Q)}catch{return console.warn(`Could not convert regex pattern at ${J.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Y.source}return Q}function Nz(Y,J){let X={type:"object",additionalProperties:V0(Y.valueType._def,{...J,currentPath:[...J.currentPath,"additionalProperties"]})??J.allowedAdditionalProperties};if(Y.keyType?._def.typeName==="ZodString"&&Y.keyType._def.checks?.length){let{type:$,...Q}=jz(Y.keyType._def,J);return{...X,propertyNames:Q}}else if(Y.keyType?._def.typeName==="ZodEnum")return{...X,propertyNames:{enum:Y.keyType._def.values}};else if(Y.keyType?._def.typeName==="ZodBranded"&&Y.keyType._def.type._def.typeName==="ZodString"&&Y.keyType._def.type._def.checks?.length){let{type:$,...Q}=Bz(Y.keyType._def,J);return{...X,propertyNames:Q}}return X}function Wj(Y,J){if(J.mapStrategy==="record")return Nz(Y,J);return{type:"array",maxItems:125,items:{type:"array",items:[V0(Y.keyType._def,{...J,currentPath:[...J.currentPath,"items","items","0"]})||H1(),V0(Y.valueType._def,{...J,currentPath:[...J.currentPath,"items","items","1"]})||H1()],minItems:2,maxItems:2}}}function Zj(Y){let J=Y.values,X=Object.keys(Y.values).filter((Q)=>{return typeof J[J[Q]]!=="number"}).map((Q)=>J[Q]),$=Array.from(new Set(X.map((Q)=>typeof Q)));return{type:$.length===1?$[0]==="string"?"string":"number":["string","number"],enum:X}}function Uj(){return{not:H1()}}function Hj(){return{type:"null"}}var J3={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Vj(Y,J){let X=Y.options instanceof Map?Array.from(Y.options.values()):Y.options;if(X.every(($)=>($._def.typeName in J3)&&(!$._def.checks||!$._def.checks.length))){let $=X.reduce((Q,G)=>{let z=J3[G._def.typeName];return z&&!Q.includes(z)?[...Q,z]:Q},[]);return{type:$.length>1?$:$[0]}}else if(X.every(($)=>$._def.typeName==="ZodLiteral"&&!$.description)){let $=X.reduce((Q,G)=>{let z=typeof G._def.value;switch(z){case"string":case"number":case"boolean":return[...Q,z];case"bigint":return[...Q,"integer"];case"object":if(G._def.value===null)return[...Q,"null"];default:return Q}},[]);if($.length===X.length){let Q=$.filter((G,z,W)=>W.indexOf(G)===z);return{type:Q.length>1?Q:Q[0],enum:X.reduce((G,z)=>{return G.includes(z._def.value)?G:[...G,z._def.value]},[])}}}else if(X.every(($)=>$._def.typeName==="ZodEnum"))return{type:"string",enum:X.reduce(($,Q)=>[...$,...Q._def.values.filter((G)=>!$.includes(G))],[])};return Bj(Y,J)}var Bj=(Y,J)=>{let X=(Y.options instanceof Map?Array.from(Y.options.values()):Y.options).map(($,Q)=>V0($._def,{...J,currentPath:[...J.currentPath,"anyOf",`${Q}`]})).filter(($)=>!!$&&(!J.strictUnions||typeof $==="object"&&Object.keys($).length>0));return X.length?{anyOf:X}:void 0};function Kj(Y,J){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Y.innerType._def.typeName)&&(!Y.innerType._def.checks||!Y.innerType._def.checks.length))return{type:[J3[Y.innerType._def.typeName],"null"]};let X=V0(Y.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","0"]});return X&&{anyOf:[X,{type:"null"}]}}function jj(Y){let J={type:"number"};if(!Y.checks)return J;for(let X of Y.checks)switch(X.kind){case"int":J.type="integer";break;case"min":if(X.inclusive)J.minimum=X.value;else J.exclusiveMinimum=X.value;break;case"max":if(X.inclusive)J.maximum=X.value;else J.exclusiveMaximum=X.value;break;case"multipleOf":J.multipleOf=X.value}return J}function Nj(Y,J){let X={type:"object",properties:{}},$=[],Q=Y.shape();for(let z in Q){let W=Q[z];if(W===void 0||W._def===void 0)continue;let U=Fj(W),H=V0(W._def,{...J,currentPath:[...J.currentPath,"properties",z],propertyPath:[...J.currentPath,"properties",z]});if(H===void 0)continue;if(X.properties[z]=H,!U)$.push(z)}if($.length)X.required=$;let G=Lj(Y,J);if(G!==void 0)X.additionalProperties=G;return X}function Lj(Y,J){if(Y.catchall._def.typeName!=="ZodNever")return V0(Y.catchall._def,{...J,currentPath:[...J.currentPath,"additionalProperties"]});switch(Y.unknownKeys){case"passthrough":return J.allowedAdditionalProperties;case"strict":return J.rejectedAdditionalProperties;case"strip":return J.removeAdditionalStrategy==="strict"?J.allowedAdditionalProperties:J.rejectedAdditionalProperties}}function Fj(Y){try{return Y.isOptional()}catch{return!0}}var Dj=(Y,J)=>{if(J.currentPath.toString()===J.propertyPath?.toString())return V0(Y.innerType._def,J);let X=V0(Y.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","1"]});return X?{anyOf:[{not:H1()},X]}:H1()},Oj=(Y,J)=>{if(J.pipeStrategy==="input")return V0(Y.in._def,J);else if(J.pipeStrategy==="output")return V0(Y.out._def,J);let X=V0(Y.in._def,{...J,currentPath:[...J.currentPath,"allOf","0"]});return{allOf:[X,V0(Y.out._def,{...J,currentPath:[...J.currentPath,"allOf",X?"1":"0"]})].filter(($)=>$!==void 0)}};function _j(Y,J){return V0(Y.type._def,J)}function qj(Y,J){let X={type:"array",uniqueItems:!0,items:V0(Y.valueType._def,{...J,currentPath:[...J.currentPath,"items"]})};if(Y.minSize)X.minItems=Y.minSize.value;if(Y.maxSize)X.maxItems=Y.maxSize.value;return X}function Pj(Y,J){if(Y.rest)return{type:"array",minItems:Y.items.length,items:Y.items.map((X,$)=>V0(X._def,{...J,currentPath:[...J.currentPath,"items",`${$}`]})).reduce((X,$)=>$===void 0?X:[...X,$],[]),additionalItems:V0(Y.rest._def,{...J,currentPath:[...J.currentPath,"additionalItems"]})};else return{type:"array",minItems:Y.items.length,maxItems:Y.items.length,items:Y.items.map((X,$)=>V0(X._def,{...J,currentPath:[...J.currentPath,"items",`${$}`]})).reduce((X,$)=>$===void 0?X:[...X,$],[])}}function Mj(){return{not:H1()}}function Ej(){return H1()}var Aj=(Y,J)=>{return V0(Y.innerType._def,J)},Tj=(Y,J,X)=>{switch(J){case"ZodString":return jz(Y,X);case"ZodNumber":return jj(Y);case"ZodObject":return Nj(Y,X);case"ZodBigInt":return rK(Y);case"ZodBoolean":return sK();case"ZodDate":return Kz(Y,X);case"ZodUndefined":return Mj();case"ZodNull":return Hj();case"ZodArray":return oK(Y,X);case"ZodUnion":case"ZodDiscriminatedUnion":return Vj(Y,X);case"ZodIntersection":return $j(Y,X);case"ZodTuple":return Pj(Y,X);case"ZodRecord":return Nz(Y,X);case"ZodLiteral":return Qj(Y);case"ZodEnum":return Jj(Y);case"ZodNativeEnum":return Zj(Y);case"ZodNullable":return Kj(Y,X);case"ZodOptional":return Dj(Y,X);case"ZodMap":return Wj(Y,X);case"ZodSet":return qj(Y,X);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return _j(Y,X);case"ZodNaN":case"ZodNever":return Uj();case"ZodEffects":return Yj(Y,X);case"ZodAny":return H1();case"ZodUnknown":return Ej();case"ZodDefault":return eK(Y,X);case"ZodBranded":return Bz(Y,X);case"ZodReadonly":return Aj(Y,X);case"ZodCatch":return aK(Y,X);case"ZodPipeline":return Oj(Y,X);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return(($)=>{return})(J)}},Rj=(Y,J)=>{let X=0;for(;X<Y.length&&X<J.length;X++)if(Y[X]!==J[X])break;return[(Y.length-X).toString(),...J.slice(X)].join("/")};function V0(Y,J,X=!1){let $=J.seen.get(Y);if(J.override){let W=J.override?.(Y,J,$,X);if(W!==iK)return W}if($&&!X){let W=Cj($,J);if(W!==void 0)return W}let Q={def:Y,path:J.currentPath,jsonSchema:void 0};J.seen.set(Y,Q);let G=Tj(Y,Y.typeName,J),z=typeof G==="function"?V0(G(),J):G;if(z)wj(Y,J,z);if(J.postProcess){let W=J.postProcess(z,Y,J);return Q.jsonSchema=z,W}return Q.jsonSchema=z,z}var Cj=(Y,J)=>{switch(J.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:Rj(J.currentPath,Y.path)};case"none":case"seen":if(Y.path.length<J.currentPath.length&&Y.path.every((X,$)=>J.currentPath[$]===X))return console.warn(`Recursive reference detected at ${J.currentPath.join("/")}! Defaulting to any`),H1();return J.$refStrategy==="seen"?H1():void 0}},wj=(Y,J,X)=>{if(Y.description)X.description=Y.description;return X},Ij=(Y)=>{let J=nK(Y),X=J.name!==void 0?[...J.basePath,J.definitionPath,J.name]:J.basePath;return{...J,currentPath:X,propertyPath:void 0,seen:new Map(Object.entries(J.definitions).map(([$,Q])=>[Q._def,{def:Q._def,path:[...J.basePath,J.definitionPath,$],jsonSchema:void 0}]))}},Sj=(Y,J)=>{let X=Ij(J),$=typeof J==="object"&&J.definitions?Object.entries(J.definitions).reduce((U,[H,V])=>({...U,[H]:V0(V._def,{...X,currentPath:[...X.basePath,X.definitionPath,H]},!0)??H1()}),{}):void 0,Q=typeof J==="string"?J:J?.nameStrategy==="title"?void 0:J?.name,G=V0(Y._def,Q===void 0?X:{...X,currentPath:[...X.basePath,X.definitionPath,Q]},!1)??H1(),z=typeof J==="object"&&J.name!==void 0&&J.nameStrategy==="title"?J.name:void 0;if(z!==void 0)G.title=z;let W=Q===void 0?$?{...G,[X.definitionPath]:$}:G:{$ref:[...X.$refStrategy==="relative"?[]:X.basePath,X.definitionPath,Q].join("/"),[X.definitionPath]:{...$,[Q]:G}};return W.$schema="http://json-schema.org/draft-07/schema#",W},bj=Symbol.for("vercel.ai.schema");function G3(Y){let J;return()=>{if(J==null)J=Y();return J}}function p4(Y,{validate:J}={}){return{[bj]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:J}}function kj(Y,J){let X=J?.useReferences??!1;return p4(()=>Sj(Y,{$refStrategy:X?"root":"none"}),{validate:async($)=>{let Q=await Y.safeParseAsync($);return Q.success?{success:!0,value:Q.data}:{success:!1,error:Q.error}}})}function xj(Y,J){let X=J?.useReferences??!1;return p4(()=>Vz(XG(Y,{target:"draft-7",io:"input",reused:X?"ref":"inline"})),{validate:async($)=>{let Q=await m4(Y,$);return Q.success?{success:!0,value:Q.data}:{success:!1,error:Q.error}}})}function vj(Y){return"_zod"in Y}function l4(Y,J){if(vj(Y))return xj(Y,J);else return kj(Y,J)}var hj="AI_SerializationError",zM=`vercel.ai.error.${hj}`;var lj="AI_InvalidArgumentError",nM=`vercel.ai.error.${lj}`;var dj="AI_InvalidStreamPartError",oM=`vercel.ai.error.${dj}`;var ij="AI_InvalidToolApprovalError",rM=`vercel.ai.error.${ij}`;var nj="AI_InvalidToolApprovalSignatureError",sM=`vercel.ai.error.${nj}`;var oj="AI_InvalidToolInputError",aM=`vercel.ai.error.${oj}`;var rj="AI_ToolCallNotFoundForApprovalError",tM=`vercel.ai.error.${rj}`;var sj="AI_MissingToolResultsError",eM=`vercel.ai.error.${sj}`;var aj="AI_NoImageGeneratedError",YE=`vercel.ai.error.${aj}`;var tj="AI_NoObjectGeneratedError",JE=`vercel.ai.error.${tj}`;var ej="AI_NoOutputGeneratedError",XE=`vercel.ai.error.${ej}`;var YN="AI_NoSpeechGeneratedError",$E=`vercel.ai.error.${YN}`;var JN="AI_NoTranscriptGeneratedError",QE=`vercel.ai.error.${JN}`;var XN="AI_NoTranslationGeneratedError",GE=`vercel.ai.error.${XN}`;var $N="AI_NoVideoGeneratedError",zE=`vercel.ai.error.${$N}`;var QN="AI_NoSuchToolError",WE=`vercel.ai.error.${QN}`;var GN="AI_StreamProviderError",ZE=`vercel.ai.error.${GN}`;var zN="AI_ToolCallRepairError",UE=`vercel.ai.error.${zN}`;var WN="AI_ToolChoiceViolationError",HE=`vercel.ai.error.${WN}`;var ZN="AI_UIMessageStreamError",VE=`vercel.ai.error.${ZN}`;var UN="AI_InvalidDataContentError",BE=`vercel.ai.error.${UN}`;var HN="AI_InvalidMessageRoleError",KE=`vercel.ai.error.${HN}`;var VN="AI_MessageConversionError",jE=`vercel.ai.error.${VN}`;var BN="AI_RetryError",NE=`vercel.ai.error.${BN}`;var KN="7.0.165",jN=async({url:Y,maxBytes:J,abortSignal:X})=>{let $=Y.toString();try{let Q=Jz({},`ai-sdk/${KN}`,eG()),G=await Wz({url:$,headers:Q,abortSignal:X});if(!G.ok)throw await u4(G),new h0({url:$,statusCode:G.status,statusText:G.statusText});return{data:await Zz({response:G,url:$,maxBytes:J??Q3}),mediaType:G.headers.get("content-type")??void 0}}catch(Q){if(h0.isInstance(Q))throw Q;throw new h0({url:$,cause:Q})}};var LE=Symbol("ai-sdk-tool-call-input-schema-input");var FE=S0({prefix:"steer",size:24});var DE=S0({prefix:"aitxt",size:24}),OE=S0({prefix:"call",size:24});var _E=class extends TransformStream{constructor(){super({transform(Y,J){J.enqueue(`data: ${JSON.stringify(Y)}
|
|
35
|
-
|
|
36
|
-
`)},flush(Y){Y.enqueue(`data: [DONE]
|
|
37
|
-
|
|
38
|
-
`)}})}};var Z={array:oJ,boolean:CG,custom:mG,discriminatedUnion:xG,enum:sJ,instanceof:cG,lazy:gG,literal:hG,looseObject:bG,never:nJ,null:wG,number:RG,object:SG,record:vG,string:AG,union:rJ,unknown:M9},i6=Z.lazy(()=>Z.union([Z.null(),Z.string(),Z.number(),Z.boolean(),Z.record(Z.string(),i6.optional()),Z.array(i6)])),y=Z.record(Z.string(),Z.record(Z.string(),i6.optional())),Fz=Z.object({source:Z.discriminatedUnion("sourceType",[Z.object({type:Z.literal("source"),sourceType:Z.literal("url"),id:Z.string(),url:Z.string(),title:Z.string().optional(),providerMetadata:y.optional()}),Z.object({type:Z.literal("source"),sourceType:Z.literal("document"),id:Z.string(),mediaType:Z.string(),title:Z.string(),filename:Z.string().optional(),providerMetadata:y.optional()})]),startIndex:Z.number().int().nonnegative().optional(),endIndex:Z.number().int().nonnegative().optional(),citedText:Z.string().optional()}),E9=Z.record(Z.string(),i6.optional()),qE=G3(()=>l4(Z.union([Z.looseObject({type:Z.literal("text-start"),id:Z.string(),providerMetadata:y.optional()}),Z.looseObject({type:Z.literal("text-delta"),id:Z.string(),delta:Z.string(),providerMetadata:y.optional()}),Z.looseObject({type:Z.literal("text-end"),id:Z.string(),citations:Z.array(Fz).optional(),providerMetadata:y.optional()}),Z.looseObject({type:Z.literal("error"),errorText:Z.string()}),Z.looseObject({type:Z.literal("tool-input-start"),toolCallId:Z.string(),toolName:Z.string(),inputEncoding:Z.enum(["json","text"]).optional(),providerExecuted:Z.boolean().optional(),providerMetadata:y.optional(),toolMetadata:E9.optional(),dynamic:Z.boolean().optional(),title:Z.string().optional()}),Z.looseObject({type:Z.literal("tool-input-delta"),toolCallId:Z.string(),inputTextDelta:Z.string()}),Z.looseObject({type:Z.literal("tool-input-available"),toolCallId:Z.string(),toolName:Z.string(),input:Z.unknown(),providerExecuted:Z.boolean().optional(),providerMetadata:y.optional(),toolMetadata:E9.optional(),dynamic:Z.boolean().optional(),title:Z.string().optional()}),Z.looseObject({type:Z.literal("tool-input-error"),toolCallId:Z.string(),toolName:Z.string(),input:Z.unknown(),providerExecuted:Z.boolean().optional(),providerMetadata:y.optional(),toolMetadata:E9.optional(),dynamic:Z.boolean().optional(),errorText:Z.string(),title:Z.string().optional()}),Z.looseObject({type:Z.literal("tool-approval-request"),approvalId:Z.string(),toolCallId:Z.string(),approvalDescriptor:Z.unknown().optional(),inputSchemaInput:Z.unknown().optional(),reason:Z.string().optional(),isAutomatic:Z.boolean().optional(),signature:Z.string().optional()}),Z.looseObject({type:Z.literal("tool-approval-response"),approvalId:Z.string(),approved:Z.boolean(),reason:Z.string().optional(),providerExecuted:Z.boolean().optional(),providerMetadata:y.optional()}),Z.looseObject({type:Z.literal("tool-output-available"),toolCallId:Z.string(),output:Z.unknown(),providerExecuted:Z.boolean().optional(),providerMetadata:y.optional(),toolMetadata:E9.optional(),dynamic:Z.boolean().optional(),preliminary:Z.boolean().optional()}),Z.looseObject({type:Z.literal("tool-output-error"),toolCallId:Z.string(),errorText:Z.string(),providerExecuted:Z.boolean().optional(),providerMetadata:y.optional(),toolMetadata:E9.optional(),dynamic:Z.boolean().optional()}),Z.looseObject({type:Z.literal("tool-output-denied"),toolCallId:Z.string()}),Z.looseObject({type:Z.literal("reasoning-start"),id:Z.string(),providerMetadata:y.optional()}),Z.looseObject({type:Z.literal("reasoning-delta"),id:Z.string(),delta:Z.string(),providerMetadata:y.optional()}),Z.looseObject({type:Z.literal("reasoning-end"),id:Z.string(),providerMetadata:y.optional()}),Z.looseObject({type:Z.literal("custom"),kind:Z.string().transform((Y)=>Y),providerMetadata:y.optional()}),Z.looseObject({type:Z.literal("source-url"),sourceId:Z.string(),url:Z.string(),title:Z.string().optional(),providerMetadata:y.optional()}),Z.looseObject({type:Z.literal("source-document"),sourceId:Z.string(),mediaType:Z.string(),title:Z.string(),filename:Z.string().optional(),providerMetadata:y.optional()}),Z.looseObject({type:Z.literal("file"),url:Z.string(),mediaType:Z.string(),providerMetadata:y.optional()}),Z.looseObject({type:Z.literal("reasoning-file"),url:Z.string(),mediaType:Z.string(),providerMetadata:y.optional()}),Z.looseObject({type:Z.literal("steering-message"),id:Z.string(),parts:Z.array(Z.union([Z.looseObject({type:Z.literal("text"),text:Z.string(),providerMetadata:y.optional()}),Z.looseObject({type:Z.literal("file"),mediaType:Z.string(),url:Z.string(),filename:Z.string().optional(),providerReference:Z.record(Z.string(),Z.string()).optional(),providerMetadata:y.optional()})]))}),Z.looseObject({type:Z.custom((Y)=>typeof Y==="string"&&Y.startsWith("data-"),{message:'Type must start with "data-"'}),id:Z.string().optional(),data:Z.unknown(),transient:Z.boolean().optional()}),Z.looseObject({type:Z.literal("start-step")}),Z.looseObject({type:Z.literal("finish-step")}),Z.looseObject({type:Z.literal("reset-step")}),Z.looseObject({type:Z.literal("start"),messageId:Z.string().optional(),messageMetadata:Z.unknown().optional()}),Z.looseObject({type:Z.literal("finish"),finishReason:Z.enum(["stop","length","content-filter","tool-calls","error","interrupted","other"]).optional(),messageMetadata:Z.unknown().optional()}),Z.looseObject({type:Z.literal("abort"),reason:Z.string().optional()}),Z.looseObject({type:Z.literal("message-metadata"),messageMetadata:Z.unknown()})])));var PE=Symbol("streamRetryAttemptBoundary");var ME=S0({prefix:"aitxt",size:24}),EE=S0({prefix:"call",size:24});var AE=S0({prefix:"aitxt",size:24}),TE=S0({prefix:"call",size:24});var RE=Symbol("streamRetryBoundary");var e0=Z.record(Z.string(),i6.optional()),Lz=Z.record(Z.string(),Z.string());var CE=G3(()=>{let Y=Z.object({id:Z.string(),approved:Z.never().optional(),descriptor:Z.unknown().optional(),requestReason:Z.string().optional(),reason:Z.never().optional(),isAutomatic:Z.boolean().optional(),signature:Z.string().optional(),inputSchemaInput:Z.unknown().optional()}),J=Y.extend({approved:Z.boolean(),reason:Z.string().optional()}),X=J.extend({approved:Z.literal(!0)}),$=J.extend({approved:Z.literal(!1)});return l4(Z.array(Z.object({id:Z.string(),role:Z.enum(["system","user","assistant"]),metadata:Z.unknown().optional(),parts:Z.array(Z.union([Z.object({type:Z.literal("text"),text:Z.string(),citations:Z.array(Fz).optional(),state:Z.enum(["streaming","done"]).optional(),providerMetadata:y.optional()}),Z.object({type:Z.literal("reasoning"),id:Z.string().optional(),text:Z.string(),state:Z.enum(["streaming","done"]).optional(),providerMetadata:y.optional()}),Z.object({type:Z.literal("custom"),kind:Z.string(),providerMetadata:y.optional()}),Z.object({type:Z.literal("source-url"),sourceId:Z.string(),url:Z.string(),title:Z.string().optional(),providerMetadata:y.optional()}),Z.object({type:Z.literal("source-document"),sourceId:Z.string(),mediaType:Z.string(),title:Z.string(),filename:Z.string().optional(),providerMetadata:y.optional()}),Z.object({type:Z.literal("file"),mediaType:Z.string(),filename:Z.string().optional(),url:Z.string(),providerReference:Lz.optional(),providerMetadata:y.optional()}),Z.object({type:Z.literal("reasoning-file"),mediaType:Z.string(),url:Z.string(),providerMetadata:y.optional()}),Z.object({type:Z.literal("steering-message"),id:Z.string(),parts:Z.array(Z.union([Z.object({type:Z.literal("text"),text:Z.string(),providerMetadata:y.optional()}),Z.object({type:Z.literal("file"),mediaType:Z.string(),filename:Z.string().optional(),url:Z.string(),providerReference:Lz.optional(),providerMetadata:y.optional()})]))}),Z.object({type:Z.literal("step-start")}),Z.object({type:Z.string().startsWith("data-"),id:Z.string().optional(),data:Z.unknown()}),Z.object({type:Z.literal("dynamic-tool"),dynamic:Z.literal(!1).optional(),toolName:Z.string(),toolCallId:Z.string(),title:Z.string().optional(),toolMetadata:e0.optional(),state:Z.literal("input-streaming"),input:Z.unknown().optional(),rawInput:Z.string().optional(),inputEncoding:Z.enum(["json","text"]).optional(),providerExecuted:Z.boolean().optional(),callProviderMetadata:y.optional(),output:Z.never().optional(),errorText:Z.never().optional(),approval:Z.never().optional()}),Z.object({type:Z.literal("dynamic-tool"),dynamic:Z.literal(!1).optional(),toolName:Z.string(),toolCallId:Z.string(),title:Z.string().optional(),toolMetadata:e0.optional(),state:Z.literal("input-available"),input:Z.unknown(),providerExecuted:Z.boolean().optional(),output:Z.never().optional(),errorText:Z.never().optional(),callProviderMetadata:y.optional(),approval:Z.never().optional()}),Z.object({type:Z.literal("dynamic-tool"),dynamic:Z.literal(!1).optional(),toolName:Z.string(),toolCallId:Z.string(),title:Z.string().optional(),toolMetadata:e0.optional(),state:Z.literal("approval-requested"),input:Z.unknown(),providerExecuted:Z.boolean().optional(),output:Z.never().optional(),errorText:Z.never().optional(),callProviderMetadata:y.optional(),approval:Y}),Z.object({type:Z.literal("dynamic-tool"),dynamic:Z.literal(!1).optional(),toolName:Z.string(),toolCallId:Z.string(),title:Z.string().optional(),toolMetadata:e0.optional(),state:Z.literal("approval-responded"),input:Z.unknown(),providerExecuted:Z.boolean().optional(),output:Z.never().optional(),errorText:Z.never().optional(),callProviderMetadata:y.optional(),approval:J}),Z.object({type:Z.literal("dynamic-tool"),dynamic:Z.literal(!1).optional(),toolName:Z.string(),toolCallId:Z.string(),title:Z.string().optional(),toolMetadata:e0.optional(),state:Z.literal("output-available"),input:Z.unknown(),providerExecuted:Z.boolean().optional(),output:Z.unknown(),errorText:Z.never().optional(),callProviderMetadata:y.optional(),resultProviderMetadata:y.optional(),preliminary:Z.boolean().optional(),approval:X.optional()}),Z.object({type:Z.literal("dynamic-tool"),dynamic:Z.literal(!1).optional(),toolName:Z.string(),toolCallId:Z.string(),title:Z.string().optional(),toolMetadata:e0.optional(),state:Z.literal("output-error"),input:Z.unknown().optional(),rawInput:Z.unknown().optional(),providerExecuted:Z.boolean().optional(),output:Z.never().optional(),errorText:Z.string(),callProviderMetadata:y.optional(),resultProviderMetadata:y.optional(),approval:X.optional()}),Z.object({type:Z.literal("dynamic-tool"),dynamic:Z.literal(!1).optional(),toolName:Z.string(),toolCallId:Z.string(),title:Z.string().optional(),toolMetadata:e0.optional(),state:Z.literal("output-denied"),input:Z.unknown(),providerExecuted:Z.boolean().optional(),output:Z.never().optional(),errorText:Z.never().optional(),callProviderMetadata:y.optional(),approval:$}),Z.object({type:Z.string().startsWith("tool-"),toolCallId:Z.string(),title:Z.string().optional(),toolMetadata:e0.optional(),state:Z.literal("input-streaming"),providerExecuted:Z.boolean().optional(),callProviderMetadata:y.optional(),input:Z.unknown().optional(),rawInput:Z.string().optional(),inputEncoding:Z.enum(["json","text"]).optional(),output:Z.never().optional(),errorText:Z.never().optional(),approval:Z.never().optional()}),Z.object({type:Z.string().startsWith("tool-"),toolCallId:Z.string(),title:Z.string().optional(),toolMetadata:e0.optional(),state:Z.literal("input-available"),providerExecuted:Z.boolean().optional(),input:Z.unknown(),output:Z.never().optional(),errorText:Z.never().optional(),callProviderMetadata:y.optional(),approval:Z.never().optional()}),Z.object({type:Z.string().startsWith("tool-"),toolCallId:Z.string(),title:Z.string().optional(),toolMetadata:e0.optional(),state:Z.literal("approval-requested"),input:Z.unknown(),providerExecuted:Z.boolean().optional(),output:Z.never().optional(),errorText:Z.never().optional(),callProviderMetadata:y.optional(),approval:Y}),Z.object({type:Z.string().startsWith("tool-"),toolCallId:Z.string(),title:Z.string().optional(),toolMetadata:e0.optional(),state:Z.literal("approval-responded"),input:Z.unknown(),providerExecuted:Z.boolean().optional(),output:Z.never().optional(),errorText:Z.never().optional(),callProviderMetadata:y.optional(),approval:J}),Z.object({type:Z.string().startsWith("tool-"),toolCallId:Z.string(),title:Z.string().optional(),toolMetadata:e0.optional(),state:Z.literal("output-available"),providerExecuted:Z.boolean().optional(),input:Z.unknown(),output:Z.unknown(),errorText:Z.never().optional(),callProviderMetadata:y.optional(),resultProviderMetadata:y.optional(),preliminary:Z.boolean().optional(),approval:X.optional()}),Z.object({type:Z.string().startsWith("tool-"),toolCallId:Z.string(),title:Z.string().optional(),toolMetadata:e0.optional(),state:Z.literal("output-error"),providerExecuted:Z.boolean().optional(),input:Z.unknown().optional(),rawInput:Z.unknown().optional(),output:Z.never().optional(),errorText:Z.string(),callProviderMetadata:y.optional(),resultProviderMetadata:y.optional(),approval:X.optional()}),Z.object({type:Z.string().startsWith("tool-"),toolCallId:Z.string(),title:Z.string().optional(),toolMetadata:e0.optional(),state:Z.literal("output-denied"),providerExecuted:Z.boolean().optional(),input:Z.unknown(),output:Z.never().optional(),errorText:Z.never().optional(),callProviderMetadata:y.optional(),approval:$})]))}).superRefine((Q,G)=>{if(Q.role!=="assistant"&&Q.parts.length===0)G.addIssue({origin:"array",code:"too_small",minimum:1,inclusive:!0,input:Q.parts,path:["parts"],message:"Message must contain at least one part"})})).nonempty("Messages array must not be empty"))});var wE=S0({prefix:"call",size:24});var IE=S0({prefix:"call",size:24});var SE=S0({prefix:"call",size:24});var bE=S0({prefix:"aiobj",size:24});function Dz(Y){return({url:J,abortSignal:X})=>jN({url:J,maxBytes:Y?.maxBytes,abortSignal:X})}var kE=S0({prefix:"aiobj",size:24});var xE=S0({prefix:"call",size:24});var vE=Dz();var A9=Z.union([Z.string(),Z.custom(aG,{message:"Must be a Uint8Array"}),Z.custom(tG,{message:"Must be an ArrayBuffer"}),Z.custom(Hz,{message:"Must be a Buffer"})]),z3=Z.record(Z.string(),Z.string()),Oz=Z.object({type:Z.literal("text"),text:Z.string(),providerOptions:y.optional()}),NN=Z.object({type:Z.literal("image"),image:Z.union([A9,Z.instanceof(URL),z3]),mediaType:Z.string().optional(),providerOptions:y.optional()}),_z=Z.discriminatedUnion("type",[Z.object({type:Z.literal("data"),data:A9}),Z.object({type:Z.literal("url"),url:Z.instanceof(URL)}),Z.object({type:Z.literal("reference"),reference:z3}),Z.object({type:Z.literal("text"),text:Z.string()})]),LN=Z.discriminatedUnion("type",[Z.object({type:Z.literal("data"),data:A9}),Z.object({type:Z.literal("url"),url:Z.instanceof(URL)})]),qz=Z.object({type:Z.literal("file"),data:Z.union([_z,A9,Z.instanceof(URL),z3]),filename:Z.string().optional(),mediaType:Z.string(),providerOptions:y.optional()}),FN=Z.object({type:Z.literal("reasoning"),text:Z.string(),providerOptions:y.optional()}),DN=Z.object({type:Z.literal("custom"),kind:Z.string().transform((Y)=>Y),providerOptions:y.optional()}),ON=Z.object({type:Z.literal("reasoning-file"),data:Z.union([LN,A9,Z.instanceof(URL)]),mediaType:Z.string(),providerOptions:y.optional()}),_N=Z.object({type:Z.literal("tool-call"),toolCallId:Z.string(),toolName:Z.string(),input:Z.unknown(),providerOptions:y.optional(),providerExecuted:Z.boolean().optional()}),qN=Z.discriminatedUnion("type",[Z.object({type:Z.literal("text"),value:Z.string(),providerOptions:y.optional()}),Z.object({type:Z.literal("json"),value:i6,providerOptions:y.optional()}),Z.object({type:Z.literal("execution-denied"),reason:Z.string().optional(),providerOptions:y.optional()}),Z.object({type:Z.literal("error-text"),value:Z.string(),providerOptions:y.optional()}),Z.object({type:Z.literal("error-json"),value:i6,providerOptions:y.optional()}),Z.object({type:Z.literal("content"),value:Z.array(Z.union([Z.object({type:Z.literal("text"),text:Z.string(),providerOptions:y.optional()}),Z.object({type:Z.literal("file"),data:_z,mediaType:Z.string(),filename:Z.string().optional(),providerOptions:y.optional()}),Z.object({type:Z.literal("file-data"),data:Z.string(),mediaType:Z.string(),filename:Z.string().optional(),providerOptions:y.optional()}),Z.object({type:Z.literal("file-url"),url:Z.string(),mediaType:Z.string().optional(),providerOptions:y.optional()}),Z.object({type:Z.literal("file-id"),fileId:Z.union([Z.string(),Z.record(Z.string(),Z.string())]),providerOptions:y.optional()}),Z.object({type:Z.literal("file-reference"),providerReference:Z.record(Z.string(),Z.string()),providerOptions:y.optional()}),Z.object({type:Z.literal("image-data"),data:Z.string(),mediaType:Z.string(),providerOptions:y.optional()}),Z.object({type:Z.literal("image-url"),url:Z.string(),providerOptions:y.optional()}),Z.object({type:Z.literal("image-file-id"),fileId:Z.union([Z.string(),Z.record(Z.string(),Z.string())]),providerOptions:y.optional()}),Z.object({type:Z.literal("image-file-reference"),providerReference:Z.record(Z.string(),Z.string()),providerOptions:y.optional()}),Z.object({type:Z.literal("custom"),providerOptions:y.optional()})]))})]),Pz=Z.object({type:Z.literal("tool-result"),toolCallId:Z.string(),toolName:Z.string(),output:qN,providerOptions:y.optional()}),PN=Z.object({type:Z.literal("tool-approval-request"),approvalId:Z.string(),toolCallId:Z.string(),reason:Z.string().optional(),isAutomatic:Z.boolean().optional(),signature:Z.string().optional(),inputSchemaInput:Z.unknown().optional()}),MN=Z.object({type:Z.literal("tool-approval-response"),approvalId:Z.string(),approved:Z.boolean(),reason:Z.string().optional()}),EN=Z.object({role:Z.literal("system"),content:Z.string(),providerOptions:y.optional()}),AN=Z.object({role:Z.literal("user"),content:Z.union([Z.string(),Z.array(Z.union([Oz,NN,qz]))]),providerOptions:y.optional()}),TN=Z.object({role:Z.literal("assistant"),content:Z.union([Z.string(),Z.array(Z.union([Oz,DN,qz,FN,ON,_N,Pz,PN]))]),providerOptions:y.optional()}),RN=Z.object({role:Z.literal("tool"),content:Z.array(Z.union([Pz,MN])),providerOptions:y.optional()}),hE=Z.union([EN,AN,TN,RN]);var yE=Z.object({token:Z.string().refine((Y)=>Y.trim().length>0),url:Z.string().refine((Y)=>{try{let J=new URL(Y);return(J.protocol==="ws:"||J.protocol==="wss:")&&J.hostname!==""}catch{return!1}}),expiresAt:Z.number().positive().max(Number.MAX_SAFE_INTEGER).optional(),tools:Z.array(Z.object({type:Z.literal("function"),name:Z.string().min(1),description:Z.string().optional(),parameters:Z.record(Z.string(),Z.unknown())})).optional()});var CN="AI_NoSuchProviderError",fE=`vercel.ai.error.${CN}`;var gE=S0({prefix:"call",size:24});var mE=S0({prefix:"call",size:24}),cE=Dz();var uE=S0({prefix:"call",size:24});function T9(Y){let J=Number(Y.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(J)?J:void 0}function d4(Y,J,X=!1){let Q=Buffer.from(Y.slice(0,J)).toString("latin1").split(`\r
|
|
39
|
-
`),G=Q[0]??"",z=T9(G);if(z===void 0||z===101)return;let W=Object.fromEntries(Q.slice(1).flatMap((K)=>{let L=K.indexOf(":");return L===-1?[]:[[K.slice(0,L).trim().toLowerCase(),K.slice(L+1).trim()]]})),U=Y.slice(J+4),H=W["content-length"],V=Number(H);if(!X&&(H===void 0||Number.isFinite(V)&&U.length<V))return;let F=Buffer.from(U).toString("utf8"),j=(()=>{try{let K=JSON.parse(F);return n(K)?K:void 0}catch{return}})();return{message:`WS upgrade failed: ${G}`,status:z,status_code:z,headers:W,body:F,...n(j?.error)?{error:j.error}:{}}}var wN="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",Mz=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class W3{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];writeQueue=[];constructor(Y,J,X){this.url=Y,this.sessionID=X?.sessionID,this.connect(Y,J)}addEventListener(Y,J,X){this.listeners[Y]?.add(J)}removeEventListener(Y,J){this.listeners[Y]?.delete(J)}peerClose;closeEmitted=!1;emitClose(Y,J){if(this.closeEmitted)return;this.closeEmitted=!0,this.emit("close",{code:Y,reason:J})}emit(Y,J){for(let X of[...this.listeners[Y]??[]])try{X(J)}catch{}}async connect(Y,J){let X=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),$=X.hostname,Q=X.port?Number(X.port):X.protocol==="https:"?443:80,G=`${X.pathname}${X.search}`,z=crypto.getRandomValues(new Uint8Array(16)),W=Buffer.from(z).toString("base64"),U=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(W+wN));this.expectedAccept=Buffer.from(new Uint8Array(U)).toString("base64");let H={};for(let[j,K]of Object.entries(J))H[j.toLowerCase()]=K;let V=[`GET ${G} HTTP/1.1`,`Host: ${$}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${W}`];for(let j of Mz)if(H[j]!==void 0)V.push(`${IN(j)}: ${H[j]}`);for(let[j,K]of Object.entries(J))if(!Mz.includes(j.toLowerCase())&&j.toLowerCase()!=="content-length")V.push(`${j}: ${K}`);let F=`${V.join(`\r
|
|
40
|
-
`)}\r
|
|
41
|
-
\r
|
|
42
|
-
`;try{this.log("connect_start",{host:$,port:Q,tls:X.protocol==="https:"});let j=globalThis.Bun?.connect;if(!j)throw Error("Bun.connect is not available");this.socket=await j({hostname:$,port:Q,tls:X.protocol==="https:"?{serverName:$}:void 0,socket:{open:(K)=>{this.socket=K,this.enqueueWrite(new TextEncoder().encode(F))},data:(K,L)=>this.onData(L),drain:()=>this.flushWrites(),error:(K,L)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let O=L instanceof Error?L.message:String(L);this.log("socket_error",{message:O}),this.emit("error",{message:O})},close:()=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close"),this.emitClose(this.peerClose?.code??1006,this.peerClose?.reason??"socket closed")}}})}catch(j){this.readyState=3;let K=j instanceof Error?j.message:String(j);this.log("connect_exception",{message:K}),this.emit("error",{message:K})}}onData(Y){if(this.rxBuffer=SN(this.rxBuffer,Y),!this.handshakeDone){let J=Buffer.from(this.rxBuffer).toString("latin1"),X=J.indexOf(`\r
|
|
43
|
-
\r
|
|
44
|
-
`);if(X===-1)return;let $=J.slice(0,X),Q=$.split(`\r
|
|
45
|
-
`)[0]??"",G=$.match(/sec-websocket-accept:\s*(\S+)/i),z=T9(Q);if(z!==101){if(z===void 0){this.readyState=3;try{this.socket?.end()}catch{}this.log("upgrade_failed",{statusLine:Q}),this.emit("error",{message:`WS upgrade failed: ${Q}`});return}if(!this.emitRejectedUpgrade())return;try{this.socket?.end()}catch{}return}if(!G||G[1]!==this.expectedAccept){this.readyState=3;try{this.socket?.end()}catch{}this.log("accept_mismatch",{statusLine:Q}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(X+4),this.log("open",{statusLine:Q}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let J=Buffer.from(this.rxBuffer).indexOf(`\r
|
|
46
|
-
\r
|
|
47
|
-
`);if(J===-1)return!1;let X=d4(this.rxBuffer,J,Y);if(!X)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:X.status,partial:Y}),this.emit("error",X),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let J=Y[0],X=Y[1],$=(J&128)!==0,Q=J&15,G=(X&128)!==0,z=X&127,W=2;if(z===126){if(Y.length<4)return;z=Y[2]<<8|Y[3],W=4}else if(z===127){if(Y.length<10)return;z=0;for(let H=0;H<8;H++)z=z*256+Y[2+H];W=10}if(G)W+=4;if(Y.length<W+z)return;let U=Y.slice(W,W+z);this.rxBuffer=Y.slice(W+z),this.handleFrame($,Q,U)}}handleFrame(Y,J,X){if(J===9){this.writeFrame(10,X);return}if(J===10)return;if(J===8){let Q=1005,G="";if(X.length>=2)Q=X[0]<<8|X[1],G=Buffer.from(X.slice(2)).toString("utf-8");this.readyState=3,this.peerClose={code:Q,reason:G};try{this.socket?.end()}catch{}this.log("close_frame",{code:Q,reason:G}),this.emitClose(Q,G);return}if(J===1||J===2)this.fragOpcode=J,this.fragChunks=[X];else if(J===0)this.fragChunks.push(X);if(!Y)return;let $=bN(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let Q=Buffer.from($).toString("utf-8");this.emit("message",{data:Q})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,J){let X=J.length,$=crypto.getRandomValues(new Uint8Array(4)),Q;if(X<126)Q=[128|Y,128|X];else if(X<65536)Q=[128|Y,254,X>>8&255,X&255];else{Q=[128|Y,255];for(let W=7;W>=0;W--)Q.push(X/2**(8*W)&255)}let G=new Uint8Array(X);for(let W=0;W<X;W++)G[W]=J[W]^$[W%4];let z=new Uint8Array(Q.length+4+X);z.set(Q,0),z.set($,Q.length),z.set(G,Q.length+4);try{this.enqueueWrite(z)}catch{}}enqueueWrite(Y){this.writeQueue.push(Y),this.flushWrites()}flushWrites(){let Y=this.socket;if(!Y)return;while(this.writeQueue.length>0){let J=this.writeQueue[0],X=Y.write(J);if(X<J.length){this.writeQueue[0]=J.slice(X),this.log("write_backpressure",{written:X,remaining:J.length-X});return}this.writeQueue.shift()}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,J){return h6({component:"raw-ws-bun",event:Y,sessionID:this.sessionID,url:this.url,...J})}}function IN(Y){return Y}function SN(Y,J){let X=new Uint8Array(Y.length+J.length);return X.set(Y,0),X.set(J,Y.length),X}function bN(Y){let J=0;for(let Q of Y)J+=Q.length;let X=new Uint8Array(J),$=0;for(let Q of Y)X.set(Q,$),$+=Q.length;return X}import{connect as kN}from"node:net";import{connect as xN}from"node:tls";var vN="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",Ez=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class Z3{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];constructor(Y,J,X){this.url=Y,this.sessionID=X?.sessionID,this.connect(Y,J)}addEventListener(Y,J,X){this.listeners[Y]?.add(J)}removeEventListener(Y,J){this.listeners[Y]?.delete(J)}peerClose;closeEmitted=!1;emitClose(Y,J){if(this.closeEmitted)return;this.closeEmitted=!0,this.emit("close",{code:Y,reason:J})}emit(Y,J){for(let X of[...this.listeners[Y]??[]])try{X(J)}catch{}}async connect(Y,J){let X=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),$=X.hostname,Q=X.port?Number(X.port):X.protocol==="https:"?443:80,G=`${X.pathname}${X.search}`,z=crypto.getRandomValues(new Uint8Array(16)),W=Buffer.from(z).toString("base64"),U=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(W+vN));this.expectedAccept=Buffer.from(new Uint8Array(U)).toString("base64");let H={};for(let[j,K]of Object.entries(J))H[j.toLowerCase()]=K;let V=[`GET ${G} HTTP/1.1`,`Host: ${$}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${W}`];for(let j of Ez)if(H[j]!==void 0)V.push(`${hN(j)}: ${H[j]}`);for(let[j,K]of Object.entries(J))if(!Ez.includes(j.toLowerCase())&&j.toLowerCase()!=="content-length")V.push(`${j}: ${K}`);let F=`${V.join(`\r
|
|
48
|
-
`)}\r
|
|
49
|
-
\r
|
|
50
|
-
`;try{this.log("connect_start",{host:$,port:Q,tls:X.protocol==="https:"});let j=()=>{this.socket?.write(F)},K=X.protocol==="https:"?xN({host:$,port:Q,servername:$},j):kN({host:$,port:Q},j);this.socket=K,K.on("data",(L)=>{this.onData(typeof L==="string"?Buffer.from(L,"binary"):L)}),K.on("error",(L)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let O=L instanceof Error?L.message:String(L);this.log("socket_error",{message:O}),this.emit("error",{message:O})}),K.on("close",(L)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close",{hadError:L}),this.emitClose(this.peerClose?.code??1006,this.peerClose?.reason??"socket closed")})}catch(j){this.readyState=3,this.log("connect_exception",{message:j instanceof Error?j.message:String(j)}),this.emit("error",{message:j instanceof Error?j.message:String(j)})}}onData(Y){if(this.rxBuffer=yN(this.rxBuffer,Y),!this.handshakeDone){let J=Buffer.from(this.rxBuffer).toString("latin1"),X=J.indexOf(`\r
|
|
51
|
-
\r
|
|
52
|
-
`);if(X===-1)return;let $=J.slice(0,X),Q=$.split(`\r
|
|
53
|
-
`)[0]??"",G=$.match(/sec-websocket-accept:\s*(\S+)/i),z=T9(Q);if(z!==101){if(z===void 0){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:Q}),this.emit("error",{message:`WS upgrade failed: ${Q}`});return}if(!this.emitRejectedUpgrade())return;this.socket?.destroy?.();return}if(!G||G[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:Q}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(X+4),this.log("open",{statusLine:Q}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let J=Buffer.from(this.rxBuffer).indexOf(`\r
|
|
54
|
-
\r
|
|
55
|
-
`);if(J===-1)return!1;let X=d4(this.rxBuffer,J,Y);if(!X)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:X.status,partial:Y}),this.emit("error",X),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let J=Y[0],X=Y[1],$=(J&128)!==0,Q=J&15,G=(X&128)!==0,z=X&127,W=2;if(z===126){if(Y.length<4)return;z=Y[2]<<8|Y[3],W=4}else if(z===127){if(Y.length<10)return;z=0;for(let H=0;H<8;H++)z=z*256+Y[2+H];W=10}if(G)W+=4;if(Y.length<W+z)return;let U=Y.slice(W,W+z);this.rxBuffer=Y.slice(W+z),this.handleFrame($,Q,U)}}handleFrame(Y,J,X){if(J===9){this.writeFrame(10,X);return}if(J===10)return;if(J===8){let Q=1005,G="";if(X.length>=2)Q=X[0]<<8|X[1],G=Buffer.from(X.slice(2)).toString("utf-8");this.readyState=3,this.peerClose={code:Q,reason:G};try{this.socket?.end()}catch{}this.log("close_frame",{code:Q,reason:G}),this.emitClose(Q,G);return}if(J===1||J===2)this.fragOpcode=J,this.fragChunks=[X];else if(J===0)this.fragChunks.push(X);if(!Y)return;let $=fN(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let Q=Buffer.from($).toString("utf-8");this.emit("message",{data:Q})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,J){let X=J.length,$=crypto.getRandomValues(new Uint8Array(4)),Q;if(X<126)Q=[128|Y,128|X];else if(X<65536)Q=[128|Y,254,X>>8&255,X&255];else{Q=[128|Y,255];for(let W=7;W>=0;W--)Q.push(X/2**(8*W)&255)}let G=new Uint8Array(X);for(let W=0;W<X;W++)G[W]=J[W]^$[W%4];let z=new Uint8Array(Q.length+4+X);z.set(Q,0),z.set($,Q.length),z.set(G,Q.length+4);try{this.socket?.write(z)}catch{}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,J){return h6({component:"raw-ws-node",event:Y,sessionID:this.sessionID,url:this.url,...J})}}function hN(Y){return Y}function yN(Y,J){let X=new Uint8Array(Y.length+J.length);return X.set(Y,0),X.set(J,Y.length),X}function fN(Y){let J=0;for(let Q of Y)J+=Q.length;let X=new Uint8Array(J),$=0;for(let Q of Y)X.set(Q,$),$+=Q.length;return X}function gN(){return typeof globalThis.Bun?.connect==="function"}var Az=gN()?W3:Z3;class Y1 extends u6{name="ProviderResponseStreamError";constructor(Y,J){super({message:Y,url:"",requestBodyValues:void 0,cause:J?.cause,isRetryable:J?.retryable??!0})}}function i4(Y){return process.env[Y]??process.env[Y.toLowerCase()]}function mN(Y){let J=i4("NO_PROXY");if(!J)return!1;let X=Y.hostname.toLowerCase(),$=J.split(",").map((Q)=>Q.trim().toLowerCase()).filter(Boolean);for(let Q of $){if(Q==="*")return!0;if(Q.startsWith(".")){if(X===Q.slice(1)||X.endsWith(Q))return!0}else if(X===Q||X.endsWith(`.${Q}`))return!0}return!1}function cN(Y){let J=new URL(Y);if(mN(J))return;if(J.protocol==="http:")return i4("HTTP_PROXY");if(J.protocol==="https:")return i4("HTTPS_PROXY")??i4("HTTP_PROXY");return}var Tz={getProxyForUrl:cN};var uN=W0("quota"),_6=W0("transport"),Sz="responses_websockets=2026-02-06",Rz=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"],pN=new Set([B6,"x-opencode-title"]);function lN(Y){let J=new Map;for(let $ of Object.keys(Y))J.set($.toLowerCase(),$);let X={};for(let $ of Rz){let Q=J.get($),G=Q===void 0?void 0:Y[Q];if(Q!==void 0&&G!==void 0)X[Q]=G}for(let[$,Q]of Object.entries(Y))if(!Rz.includes($.toLowerCase()))X[$]=Q;return X}function dN(Y){let J={};for(let[X,$]of Object.entries(Y)){if(pN.has(X.toLowerCase()))continue;J[X]=$}return J}function iN(Y){return Y.replace(/^http/,"ws")}function nN(Y){let J={};if(!Y)return J;if(Y instanceof Headers)return Y.forEach((X,$)=>{J[$.toLowerCase()]=X}),J;if(Array.isArray(Y)){for(let[X,$]of Y)J[X.toLowerCase()]=$;return J}for(let[X,$]of Object.entries(Y))if($!=null)J[X.toLowerCase()]=String($);return J}function V3(Y){return Y instanceof DOMException&&Y.name==="AbortError"}var bz=new WeakSet;function oN(Y){return typeof Y==="object"&&Y!==null&&bz.has(Y)}var kz=new WeakSet;function rN(Y){return typeof Y==="object"&&Y!==null&&kz.has(Y)}function xz(Y){return kz.add(Y),Y}function Cz(Y,J){let X=Error(Y,J===void 0?void 0:{cause:J});return bz.add(X),X}function sN(Y){return new Promise((J,X)=>{if(Y.signal?.aborted){X(U3(Y.signal));return}let $={...Y.headers,"openai-beta":Y.headers["openai-beta"]??Sz},Q=$[B6]??$["session-id"];delete $["content-length"],$=lN(dN($));let G=typeof Bun>"u"?void 0:Tz.getProxyForUrl(Y.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),z=!0,W=Y.rawWebSocket?new Az(Y.url,$,{sessionID:Q}):new globalThis.WebSocket(Y.url,{headers:$,...G?{proxy:G}:{},perMessageDeflate:z}),U=Y.timeout?setTimeout(()=>{H(),W.close(),X(Error("WebSocket connect timed out"))},Y.timeout):void 0;function H(){if(U)clearTimeout(U);W.removeEventListener("open",V),W.removeEventListener("error",F),W.removeEventListener("close",j),Y.signal?.removeEventListener("abort",K)}function V(){H(),J(W)}function F(L){H(),X(Cz(A8(L),L))}function j(L){H(),X(Cz(gz("WebSocket closed before open",L.code,L.reason)))}function K(){H(),W.close(),X(U3(Y.signal))}W.addEventListener("open",V,{once:!0}),W.addEventListener("error",F,{once:!0}),W.addEventListener("close",j,{once:!0}),Y.signal?.addEventListener("abort",K,{once:!0})})}function aN(Y){let J=new TextEncoder,X=Y.socket,$,Q=()=>{},G=!1,z=0,W=!1,U=!1,H,V=[],F=12,j=[],K=typeof Y.body.previous_response_id==="string"?Y.body.previous_response_id:void 0,L=typeof Y.body.prompt_cache_key==="string"?Y.body.prompt_cache_key:void 0,O={sessionID:Y.sessionID,codexSessionID:L},q,x=0,P,b=new Set,M={addedItemIds:new Set,reasoningItemIds:new Set,finished:!1,other:!1};function w(){if(H)clearTimeout(H);Q(),Y.signal?.removeEventListener("abort",d)}function S(m=X){m.close()}function E(){w(),$?.enqueue(J.encode(`data: [DONE]
|
|
56
|
-
|
|
57
|
-
`)),$?.close()}function v(m){J0(m,m)}function u(){if(!U)return"none";if(M.other)return"other";if(M.finished)return M.reasoningItemIds.size>0?"other":"finished-calls";return M.addedItemIds.size>0?"unfinished-calls":"none"}function c(){$?.enqueue(J.encode(`data: ${JSON.stringify(GL)}
|
|
58
|
-
|
|
59
|
-
`)),E()}function r(m){let Z0={...O,openingFrameTypes:V,openingItemTypes:j,responseID:q,previousResponseID:K,hasContinuation:K!==void 0,framesSinceCreated:x,msSinceLastFrame:P===void 0?void 0:Date.now()-P},p=u();if(p==="finished-calls"){if(G)return;_6.warn("stream failed after finished function calls only; ended as completed",{reason:m.message,emittedOutput:!0,outputShape:p,...Z0}),G=!0,w(),Y.onConnectionInvalid?.(m),c();return}if(p==="other"){let l0=H3;_6.warn("stream failed after output; not retried",{reason:m.message,emittedOutput:!0,outputShape:p,...Z0}),J0(Error(l0,{cause:m}),new Y1(l0,{cause:m}));return}let M0=M.reasoningItemIds.size;_6.warn(p==="unfinished-calls"?"stream failed after unfinished function calls only; retryable":M0>0?"stream failed after reasoning without text only; retryable":"stream failed before output; retryable",{reason:m.message,emittedOutput:U,outputShape:p,emptyReasoningItems:M0,...Z0}),v(m)}function J0(m,Z0){if(G)return;G=!0,w(),Y.onConnectionInvalid?.(Z0),$?.error(m)}function l(m){if(G)return;if(!Y.idleTimeout)return;if(H)clearTimeout(H);H=setTimeout(()=>r(new Y1(m)),Y.idleTimeout)}async function T(m){if(G)return;if(typeof m.data!=="string"){r(new Y1("Unexpected binary WebSocket frame"));return}let Z0=m.data,p=(()=>{try{let e=JSON.parse(Z0);return typeof e==="object"&&e!==null?e:void 0}catch{return}})();if(p?.type==="codex.rate_limits"){uN.debug("codex.rate_limits frame received",{pid:process.pid}),l("idle timeout waiting for websocket");let e=Iz(p);Y.onQuota?.(e,p);return}let M0=u(),l0=M0==="none"||M0==="unfinished-calls"?n6(p):void 0;if(l0&&p){G=!0,w(),Y.onRateLimitReached?.(l0.window,l0.resetAt),Y.onTerminal?.(p),Y.onFirstEvent?.(),$?.error(new Y1(`OpenAI account rate limit reached at admission (${l0.window})`));return}if(p?.type==="error"&&Y.onRetryableTerminal){if(Q(),H)clearTimeout(H);H=void 0;try{let e=await Y.onRetryableTerminal(p);if(G){if(e)S(e);return}if(e){T0(e);return}}catch(e){r(new Y1(e instanceof Error?e.message:String(e),{cause:e}));return}}let O0=YL(p,Z0);if(O0&&p){if(!W)Y.onFirstEvent?.(O0);G=!0,w(),Y.onTerminal?.(p);let e=new u6({message:O0.message,url:X.url,requestBodyValues:Y.body,statusCode:O0.status,responseHeaders:O0.headers,responseBody:O0.body}),f0=u();if(f0==="none"||f0==="unfinished-calls"){if(f0==="unfinished-calls")_6.warn("protocol error after unfinished function calls only; surfaced as before output",{...O,status:O0.status,reason:O0.message,outputShape:f0,responseID:q,previousResponseID:K});$?.error(e);return}if(_6.warn(f0==="finished-calls"?"protocol error after finished function calls only; ended as completed":"protocol error after output; not retried",{...O,status:O0.status,reason:O0.message,outputShape:f0,responseID:q,previousResponseID:K}),f0==="finished-calls"){c();return}$?.error(Error(H3,{cause:e}));return}if(n(p)&&p.type==="response.failed"){let e=n(p.response)?p.response.failed:void 0,f0=n(e)?e.rate_limit_reached_type:void 0;if(typeof f0==="string"){G=!0,w(),Y.onRateLimitReached?.(f0),Y.onTerminal?.(p);let R0=u();if(R0!=="none")_6.warn(R0==="other"?"rate limit reached after output; ended without retry":R0==="finished-calls"?"rate limit reached after finished function calls only; ended as completed":"rate limit reached after unfinished function calls only; retryable",{...O,outputShape:R0,responseID:q,previousResponseID:K});if(R0==="none"||R0==="unfinished-calls")Y.onFirstEvent?.(),$?.error(new Y1(`OpenAI account rate limit reached mid-stream (${f0})`));else if(R0==="finished-calls")c();else E();return}}if(!p){if(!W)Y.onFirstEvent?.();l("idle timeout waiting for websocket");return}if(tN(p,b),!W)Y.onFirstEvent?.();if($?.enqueue(J.encode(`${Z0.split(/\r?\n/).map((e)=>`data: ${e}`).join(`
|
|
60
|
-
`)}
|
|
61
|
-
|
|
62
|
-
`)),W=!0,P=Date.now(),q!==void 0)x++;if(V.length<F)V.push(String(p.type));if(p.type==="response.output_item.added"&&j.length<F)j.push(n(p.item)?String(p.item.type):"unknown");if(p.type==="response.created")q=$L(p),_6.debug("response created",{...O,responseID:q,previousResponseID:K,hasContinuation:K!==void 0});if(!yz(p.type))U=!0,QL(p,M);if(l("idle timeout waiting for websocket"),p.type==="response.completed"||p.type==="response.done"){G=!0,eN(p,b),Y.onComplete?.(p,b),Y.onTerminal?.(p),E();return}if(p.type==="response.failed"||p.type==="response.incomplete"||p.type==="error")G=!0,Y.onTerminal?.(p),E()}function B0(m){r(new Y1(A8(m),{cause:m}))}function P0(m){if(G)return;let Z0=m.code===1009,p=new Y1(Z0?fz:gz("WebSocket closed before response.completed",m.code,m.reason),{retryable:!Z0});if(Z0)_6.warn("websocket peer refused the request size",{...O,requestBytes:z,reason:m.reason.toString()});r(Z0?xz(p):p)}function d(){let m=U3(Y.signal);if(G)return;G=!0,w(),S(),Y.onAbort?.(m),$?.error(m)}function k0(m){if(G)return;G=!0,w(),S(),Y.onAbort?.(JL(m))}function T0(m){Q(),X=m,X.addEventListener("message",T),X.addEventListener("error",B0,{once:!0}),X.addEventListener("close",P0,{once:!0}),Q=()=>{X.removeEventListener("message",T),X.removeEventListener("error",B0),X.removeEventListener("close",P0)};let{background:Z0,...p}=Y.body;l("idle timeout sending websocket request");try{let M0=JSON.stringify({type:"response.create",...p});z=M0.length,X.send(M0),l("idle timeout waiting for websocket")}catch(M0){if(G)return;v(new Y1(M0 instanceof Error?M0.message:String(M0),{cause:M0}))}}return new Response(new ReadableStream({start(m){if($=m,Y.signal?.addEventListener("abort",d,{once:!0}),Y.signal?.aborted){d();return}T0(X)},cancel(m){k0(m)}}),{status:200,headers:{"content-type":"text/event-stream"}})}function tN(Y,J){if(Y.type!=="response.output_item.done")return;if(!n(Y.item))return;vz(Y.item,J)}function eN(Y,J){let X=Y.response;if(!n(X)||!Array.isArray(X.output))return;for(let $ of X.output)if(n($))vz($,J)}function vz(Y,J){if(Y.type!=="function_call"&&Y.type!=="custom_tool_call")return;let X=typeof Y.call_id==="string"?Y.call_id:typeof Y.id==="string"?Y.id:void 0;if(X)J.add(X)}function YL(Y,J){if(Y?.type!=="error")return;let X=Y.status??Y.status_code;if(typeof X!=="number"||X>=200&&X<300)return;return{status:X,headers:n(Y.headers)?Object.fromEntries(Object.entries(Y.headers).flatMap(([$,Q])=>typeof Q==="string"||typeof Q==="number"||typeof Q==="boolean"?[[$,String(Q)]]:[])):void 0,body:J,message:n(Y.error)&&typeof Y.error.message==="string"?Y.error.message:`${X}`}}function n6(Y,J=Date.now()){if(typeof Y==="string")try{return n6(JSON.parse(Y),J)}catch{return}if(!n(Y))return;let X=n6(Y.cause,J);if(X)return X;let $=n6(Y.body,J);if($)return $;let Q=n(Y.error)?Y.error:Y,G=typeof Q.type==="string"?Q.type:void 0,z=Y.status??Y.status_code;if(G!=="usage_limit_reached"&&z!==429)return;let{resets_at:W,resets_in_seconds:U}=Q,H=typeof W==="number"&&Number.isFinite(W)&&W>0?W*1000:typeof U==="number"&&Number.isFinite(U)&&U>0?J+U*1000:void 0,V=typeof Q.code==="string"?Q.code:void 0;return{window:G??V??hz,resetAt:H}}var hz="rate_limit";function JL(Y){if(V3(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function U3(Y){let J=Y?.reason;if(V3(J))return J;if(XL(J))return J;return new DOMException(J instanceof Error?J.message:"Aborted","AbortError")}function XL(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function $L(Y){let J=Y.response;if(!n(J))return;return typeof J.id==="string"?J.id:void 0}function QL(Y,J){let X=n(Y.item)?Y.item:void 0;switch(Y.type){case"response.output_item.added":if(X?.type==="function_call"&&typeof X.id==="string"){J.addedItemIds.add(X.id);return}if(wz(X)&&typeof X?.id==="string"){J.reasoningItemIds.add(X.id);return}break;case"response.function_call_arguments.delta":case"response.function_call_arguments.done":if(typeof Y.item_id==="string"&&J.addedItemIds.has(Y.item_id))return;break;case"response.output_item.done":if(X?.type==="function_call"&&X.status==="completed"&&typeof X.id==="string"&&typeof X.call_id==="string"&&typeof X.name==="string"&&typeof X.arguments==="string"){J.finished=!0;return}if(wz(X)&&typeof X?.id==="string"&&J.reasoningItemIds.has(X.id))return;break}J.other=!0}function wz(Y){if(Y?.type!=="reasoning")return!1;let J=(X)=>X===void 0||X===null||Array.isArray(X)&&X.length===0;return J(Y.summary)&&J(Y.content)}var GL={type:"response.completed",response:{status:"completed",incomplete_details:null,usage:{input_tokens:0,output_tokens:0,total_tokens:0}}};function yz(Y){return Y==="response.created"||Y==="response.in_progress"||Y.startsWith("codex.")}var H3="The response ended early after part of it had already been shown. It was not sent again, because repeating it would duplicate that output and re-run any tools it had started. The transport log records what ended it.",fz="The request was larger than the websocket would carry, so it was sent over HTTP instead. Resending it unchanged over the same socket cannot succeed. The transport log records the size.";function gz(Y,J,X){let $=[`code ${J}`];if(X.length>0)$.push(X.toString());return`${Y} (${$.join(": ")})`}function n4(Y,J){if(!Y.ok||!Y.body||!Y.headers.get("content-type")?.includes("text/event-stream"))return Y;let X=Y.body.getReader(),$=new TextDecoder,Q="",G=!1,z=!1,W=!1,U=(H)=>{Q+=H;for(;;){let V=/\r?\n\r?\n/.exec(Q);if(!V||V.index===void 0)break;let F=Q.slice(0,V.index);if(Q=Q.slice(V.index+V[0].length),W){W=!1;continue}let j=F.split(/\r?\n/).filter((K)=>K.startsWith("data:")).map((K)=>K.slice(5).trimStart()).join(`
|
|
63
|
-
`);if(!j||j==="[DONE]")continue;try{let K=JSON.parse(j);if(K.type==="response.completed")G=!0;if(K.type==="response.failed"||K.type==="response.incomplete"||K.type==="error")z=!0}catch{z=!0}}if(Q.length>1048576)Q=Q.slice(-1),W=!0,z=!0};return new Response(new ReadableStream({async pull(H){try{let V=await X.read();if(V.done)U($.decode()),J(G&&!z),H.close();else U($.decode(V.value,{stream:!0})),H.enqueue(V.value)}catch(V){H.error(V)}},cancel(H){return X.cancel(H)}}),{status:Y.status,statusText:Y.statusText,headers:Y.headers})}var r6={"missing-main":"Request refused locally: this setup has no main login in its account store. Sign in with opencode auth login.","no-accounts":"Request refused locally: no eligible account is configured. Sign in with opencode auth login.",unusable:"Request refused locally: no usable account credential. Sign in with opencode auth login.",...iz};function _3(Y){return Y!==void 0&&dz.includes(Y)}function q3(Y){try{let J=JSON.parse(Y.body??"{}");return typeof J.model==="string"?J.model:""}catch{return""}}function P3(Y){return Y.sessionId&&(Y.requestKind===void 0?Y.sessionId:JSON.stringify([Y.sessionId,Y.requestKind]))}function M3(Y,J,X,$){let Q=R9(Y,J);return J.flatMap((G)=>{let z=Y.limitPolicy?.accountKey(G.id);if(!z)return[];let W=$?.id===G.id?$.reading:V1(G.quota),U=JW(X&&O1(X.account,z)?X:void 0,W,Q.now),H=Q.rateLimitMarks.get(G.id),V=Q.refreshBackoff.get(G.id),F=[...H&&H>Q.now?[{kind:"hard",until:H}]:[],...V&&V>Q.now?[{kind:"cooldown",until:V}]:[]],j=l1(W,Y.storage,G.id===C1?void 0:G.id,Q.now)&&!!(W?.primary||W?.secondary)&&!uz(_8(t1(G.quota)?G.quota:void 0),Q.now)&&(!G.row||!!Y.source.usableToken(G.row));return[{account:z,admitted:j,placementEligible:j,ready:j&&!F.length&&!U.length,blockers:F,confirmedBlockers:U}]})}function E3(Y,J){let X=Y.now();return{phase:"after-limit",host:"opencode1",hostPhase:"request",now:X,clockNow:X,sessionId:Y.sessionId??"",requestScope:{kind:"pool"},history:pz({requestId:Y.sessionId??"request",originalUrl:"https://api.openai.com/v1/responses",clockNow:X}),delivery:{owned:!0,attributable:!0,replayable:Y.replayable},candidates:J}}function A3(Y,J){let X=QW({decision:J,now:Y.now(),host:"opencode1",maxSameAccountWait:Y.storage?.routing?.maxSameAccountWait});if(X.kind!=="http")throw Error("Expected an OC1 HTTP quota refusal");return new Response(X.body,{status:X.status,headers:X.headers})}async function zW(Y,J,X,$,Q,G){let z=Y.limitPolicy;if(!z||!Y.replayable||$==="ordered"&&!j3(Y.storage).includes(X.status)||$==="sticky"&&![401,403,429].includes(X.status))return{confirmed:!1};let W=G;if(!W)return{confirmed:!1};let U=o4(Y),H=U.find((P)=>P.id===J.id),V={...V1(H?.quota),...a1(X.headers)},F=X.status===429?YW({account:W,status:X.status,headers:X.headers,body:await X.clone().text(),now:Y.now(),reading:V}):void 0,j=M3(Y,U,F,{id:J.id,reading:V}),K=j.find((P)=>O1(P.account,W)),L=Q&&j.find((P)=>P.account.accountId===Q),O=z.currentAccountKey(),q=(z.decide??F3)({...E3(Y,j),attempted:W,status:X.status,signal:F,affinity:$==="sticky"?"sticky":"none",...L?{selection:{account:L.account,pin:"preserve"}}:{},hold:K&&Y.sessionId&&!Y.suppressHold&&O&&O1(O,K.account)?L3({candidate:K,status:X.status,activity:z.activity(),now:Y.now(),maxSameAccountWait:Y.storage?.routing?.maxSameAccountWait}):void 0},{mode:$,fallbackOn:Y.storage?.fallbackOn}),x=P3(Y);if(q?.action==="hold"&&Y.sessionId&&x){if(z.pending.set(x,{sessionId:Y.sessionId,accountKey:W,model:q3(Y),target:q.target,checkpoint:q.checkpoint,decidedAt:Y.now(),decision:q}),z.pending.size>256){let P=z.pending.keys().next().value;if(P)z.pending.delete(P)}return X.body?.cancel().catch(()=>{}),{hold:A3(Y,q),confirmed:!0}}return{confirmed:!!K?.confirmedBlockers?.length&&X.status===429}}async function zL(Y,J){let{limitPolicy:X,sessionId:$}=Y,Q=P3(Y),G=Q&&X?.pending.get(Q);if(!G||!X||!$||!Q)return;let z=M3(Y,J),W=z.find((L)=>O1(L.account,G.accountKey)),U=new Map(G.checkpoint.blockers.map((L)=>[L.window,{...L,confirmed:!0,confirmedByReading:!1,observedAt:G.decidedAt,provenance:"provider"}]));for(let L of W?.confirmedBlockers??[])U.set(L.window,L);let H=W&&L3({candidate:{...W,confirmedBlockers:[...U.values()]},activity:X.activity(),now:Y.now(),maxSameAccountWait:Y.storage?.routing?.maxSameAccountWait});X.pending.delete(Q);let V=X.currentAccountKey();if(!Y.replayable||q3(Y)!==G.model||!V||!O1(V,G.accountKey)||!W?.admitted||!H||H.maxWaitMs<=0||Y.now()>H.cacheExpiresAt||G.target>Math.min(H.cacheExpiresAt,Y.now()+H.maxWaitMs))return;if(Y.now()<G.target)return X.pending.set(Q,G),{response:A3(Y,{...G.decision,delayMs:G.target-Y.now(),retryAfterMs:G.target-Y.now()}),servedId:W.account.accountId};let F=(X.decide??F3)({...E3(Y,z.map((L)=>L===W?{...L,confirmedBlockers:[...U.values()]}:L)),phase:"pre-send",attempted:W.account,hold:H,wake:{target:G.target,checkpoint:G.checkpoint,kind:"hold"}},{mode:"sticky"});if(F?.action!=="retain"||F.reason!=="wait-elapsed")return;let j=J.find((L)=>L.id===W.account.accountId),K=j&&await r4(Y,j);return K&&j?{response:K,servedId:j.id}:void 0}function WL(Y,J,X){if(!Y.limitPolicy||!["quota-exhausted","killswitch","mid-stream-rate-limit"].includes(X.reason))return;let $=Y.limitPolicy,Q=Y.now(),G=$.owner(),z=J.flatMap((U)=>{let H=$.accountKey(U.id);if(!H)return[];return[{account:H,reading:V1(U.quota),floors:o6(Y.storage)?U6(Y.storage,U.id===C1?void 0:U.id):void 0,marks:G?.snapshot()?.marks.filter((V)=>V.key.window==="account"&&V.key.scope.kind==="pool"&&O1(V.key.account,H)).flatMap((V)=>V.entries.map((F)=>({until:F.until,evidenceAt:F.evidenceAt})))}]}),W=XW({accounts:z,now:Q,effectiveModel:q3(Y),maxSameAccountWait:Y.storage?.routing?.maxSameAccountWait,activity:$.activity(),currentAccountKey:$.currentAccountKey(),provenance:G?.provenance});return A3(Y,$W({...E3(Y,M3(Y,J)),phase:"pre-send"},z.length?W:{...W,messageKey:X.reason==="killswitch"?"killswitch":X.reason==="quota-exhausted"?"quota":"timed-mark"}))}function ZL(Y,J,X,$=new Set,Q=F1()){let G=M1(J,Q);return Y.filter((z)=>{if(!z.enabled||!z.candidate||z.type!=="oauth")return!1;if(z.credential?.type!=="oauth")return!1;if(u0(z.credential))return!1;if(z.identity!==void 0&&$.has(z.identity))return!1;if(z.id===C1)return!0;if(lz(J,{accountId:z.identity}))return!1;return N3(V1(z.quota),G,X)})}function o4(Y){let J=Y.vault;return[...(J?[]:ZL(Y.source.peek().rows,Y.storage,Y.now(),void 0,Y.configPath)).map(($)=>({id:$.id,kind:"oauth",...$.identity!==void 0?{identity:$.identity}:{},...$.quota!==void 0?{quota:$.quota}:{},row:$})),...(J?.routes()??[]).filter(($)=>N3(V1($.quota),Y.storage,Y.now())).map(($)=>({id:$.id,kind:$.kind,...$.identity!==void 0?{identity:$.identity}:{},...$.quota!==void 0?{quota:$.quota}:{}}))]}function UL(Y){return Y.flatMap((J)=>J.row?[J.row]:[])}function R9(Y,J){let X=Y.now(),$=C9(J,Y.storage,X),Q=J.map((U)=>({id:U.id,kind:U.kind,...t1(U.quota)?{quota:U.quota}:{}})),G=UL(J),z=new Set(J.filter((U)=>!U.row).map((U)=>U.id)),W=Y.rateLimitMarks();for(let[U,H]of Y.vault?.rateLimitMarks?.()??[])if(z.has(U)&&H>X)W.set(U,H);return{rows:Q,now:X,rateLimitMarks:W,refreshBackoff:Y.source.refreshBackoffFor(G),killswitch:$,requestPull:(U)=>z.has(U)?Y.vault?.requestReading(U):Y.source.requestReading(U)}}function mz(Y){let J=Y.find((X)=>X.id===C1);return{main:J?V1(J.quota):void 0,fallbacks:Y.filter((X)=>X.id!==C1).map((X)=>{let $=V1(X.quota);return{accountId:X.id,...$?{quota:$}:{}}})}}async function r4(Y,J){if(J.row){let X=Y.source.usableToken(J.row);if(!X)return;let $=await Y.send(J,X);return Y.recordQuota($,J,X),$}return Y.vault?.send(J.id,async(X,$)=>{let Q=await Y.send(J,X,$);return Y.recordQuota(Q,J,X,$),GW(Y.sessionId,$,Q,{parseLimit:(G)=>n6({...n(G)?G:{},status:Q.status}),quota:J.quota,now:Y.now})})}async function WW(Y){let J=Y.configPath??F1(),X=M1(Y.storage,J);if(Y={...Y,storage:X,mode:y1(J)==="shared"?X.routing?.mode??"main-first":Y.mode},Y.vault)await Y.vault.awaitRoster();else await Y.source.current(),await Y.source.prepareTokens(Y.source.peek().rows,Y.storage);let $=o4(Y),Q=Y.replayable===!1&&$.some((H)=>H.id===C1)?$.filter((H)=>H.id===C1):$,G=rz(R9(Y,Q));if(G)await G,$=o4(Y);let z=P3(Y),W=z&&Y.limitPolicy?.pending.has(z),U=await zL(Y,$);if(U)return U;if(W)Y={...Y,suppressHold:!0};if(Y.mode==="sticky-balanced"&&Y.sessionId&&Y.replayable&&Y.body!==void 0){let H=await HL(Y,$,Y.sessionId,Y.body);if(H)return H;return cz({...Y,routingRequest:void 0},$)}return cz(Y,$)}async function cz(Y,J){let X=oz(Y.mode),$=R9(Y,J),Q=sz({...$,placement:X,mainId:Y.vault?Y.mode==="sticky-balanced"?null:nz(Y.vault.routes()):void 0,replayable:Y.replayable});if(Q.kind==="block")return Y.log.debug("pool admission blocked the request",{pid:process.pid,reason:Q.block.reason}),{response:WL(Y,J,Q.block)??Y.blocked(Q.block,mz(J),Y.vault?J.length===0?Y.vault.noRouteCause():void 0:J.length===0?"no-accounts":"unusable"),servedId:C1};if(Q.lastPath)Y.log.debug("pool admission: every account is exhausted; probing anyway",{pid:process.pid,order:Q.order});let G=new Map(J.map((K)=>[K.id,K])),z=await O3({vaultMode:Y.vault!==void 0,fresh:!0,sessionId:Y.sessionId,request:Y.routingRequest,routes:Y.vault?.routes()??[],routing:$,eligibleIds:Q.order,warmAccountId:Y.mode==="sticky-balanced"?Y.warmAccountId:Y.limitPolicy?.currentAccountKey()?.accountId});if(z&&typeof z!=="string")throw Error(D3);let W=z?[z,...Q.order.filter((K)=>K!==z)]:Q.order,U=j3(Y.storage),H=[],V=new Set,F,j=!1;for(;;){let K=B3(W.filter((b)=>!V.has(b)),H,U),L=K===void 0?void 0:G.get(K);if(!L)break;let O=Y.limitPolicy?.accountKey(L.id),q;try{q=await r4(Y,L)}catch(b){if(Y.isAbort(b)||!F||Y.mode==="fallback-first")throw b;return Y.log.debug("pool fallback attempt threw; stopping",{pid:process.pid,accountId:L.id}),F}if(!q){if(!L.row)j=!0;V.add(L.id);continue}F?.response.body?.cancel().catch(()=>{}),F={response:q,servedId:L.id},H.push({id:L.id,status:q.status});let x=B3(W.filter((b)=>!V.has(b)),H,U),P=await zW(Y,L,q,"ordered",x,O);if(P.hold)return{response:P.hold,servedId:L.id}}if(F)return ZW(Y,$,F.servedId),F;return{response:Y.blocked({reason:"no-credential"},mz(J),j?"vault-refused":Y.vault?"vault-empty":"unusable"),servedId:C1}}async function HL(Y,J,X,$){let Q=Buffer.byteLength($,"utf8"),G=new Map(J.map((S)=>[S.id,S])),z=R9(Y,J),W=K3(z),U={requestBytes:Q,reservePercent:(S)=>U6(Y.storage,S===C1?void 0:S),resetCredits:Y.resetCredits,onEmptyWeightedSet:()=>{Y.log.debug("sticky routing: no fresh weighted candidates; using configured order")}},H,V=!1,F=(S,E)=>(v,u)=>{let c=new Set(v);return Y.placePin({sessionId:X,requestBytes:Q,now:S.now,validPinnedAccountIds:S.rows.map((r)=>r.id).filter((r)=>!E.excluded.has(r)),excludeAccountIds:v,quotaCheckedAtByAccount:Object.fromEntries(S.rows.map((r)=>[r.id,E.projections.get(r.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(J.map((r)=>[r.id,r.identity])),select:(r)=>{if(!u&&v.length===0)V=!0;return H??az(S,U,c,r)},persist:u})},j=F(z,W);if((Y.vault&&Y.routingRequest?j([],!1):void 0)&&V){let S=await O3({vaultMode:Y.vault!==void 0,fresh:!0,sessionId:X,request:Y.routingRequest,routes:Y.vault?.routes()??[],warmAccountId:Y.warmAccountId,routing:z});if(S&&typeof S!=="string")throw Error(D3);H=S?{accountId:S,source:"mode-fallback",quotaCheckedAt:W.projections.get(S)?.checkedAt}:void 0}let L=j([],!0);if(H=void 0,!L)return;let O=L.accountId,q=(S)=>{let E=j([O],!0);if(!E)return!1;return Y.log.debug("sticky routing: migrated session pin",{pid:process.pid,fromAccountId:O,toAccountId:E.accountId,reason:S}),O=E.accountId,!0},x=tz(z,U,O);if(x.kind==="none")return;if(x.kind==="move"){if(!q(x.reason)&&x.reason==="killswitch")return}else if(x.kind==="detour"){let S=j([O],!1);if(!S)return;Y.log.debug("sticky routing: pinned account awaits a quota reading",{pid:process.pid,pinnedAccountId:O,servedAccountId:S.accountId}),O=S.accountId}let P=G.get(O);if(!P)return;let b=Y.limitPolicy?.accountKey(P.id),M=await r4(Y,P);if(!M)return;let w=await zW(Y,P,M,"sticky",void 0,b);if(w.hold)return{response:w.hold,servedId:P.id};if(M.status===401||M.status===403||M.status===429){let S=o4(Y);z=R9(Y,S),W=K3(z),j=F(z,W);let E=ez(z,W,O,M.status);if(E.action==="migrate"||w.confirmed){let v=O;if(q(w.confirmed?"exhausted":E.reason)&&O!==v){let u=S.find((r)=>r.id===O),c=u?await r4(Y,u):void 0;if(u&&c){let r=M;M=c,r.body?.cancel().catch(()=>{}),P=u}else O=v}}}return ZW(Y,z,P.id),{response:M,servedId:P.id}}function ZW(Y,J,X){let $=Y.log.info;Y.creditsServing?.served(J,X,$?{info:(Q,G)=>$.call(Y.log,Q,G)}:void 0)}var VL=new Map([["needs_reauth","needs sign-in"],["retired","turned off in vault"],["corrupt","unavailable"]]);function w9(Y){return typeof Y==="number"&&Number.isFinite(Y)}function BL(Y){if(!t1(Y))return;let J=Y.budget;if(J?.kind!=="reading")return;let{limit:X,used:$,remaining:Q,usedPercent:G,remainingPercent:z}=J;if(!w9(X)||!w9($)||!w9(Q)||!w9(G)||!w9(z))return;return{limit:X,used:$,remaining:Q,usedPercent:G,remainingPercent:z,reached:J.reached,...J.resetsAt!==void 0?{resetsAt:J.resetsAt}:{},...J.unit!==void 0?{unit:J.unit}:{}}}function T3(Y,J){let X=V1(Y),$=BL(Y),Q=t1(Y)?Y.credits:void 0;if(!X&&!$&&!Q)return null;let G=t1(Y)?_8(Y).checkedAt:void 0;return{...G!==void 0?{checkedAt:G}:{},...X?.primary?{primary:X.primary}:{},...X?.secondary?{secondary:X.secondary}:{},...$?{spendControl:$}:{},...J!==void 0?{resetCreditsAvailable:J}:{},...Q?{credits:{...Q}}:{}}}function HW(Y,J,X,$){let Q=Y??[],G=C9(Q.map((z)=>({id:z.routeId,quota:z.quota})),{version:1,accounts:[],...X},$);return{main:{quota:null,killed:!1},fallbacks:[],vaultDiscovered:Y!==void 0,vaultAccounts:Q.map((z)=>{let W=z.quota?.counters?.resetCredits?.value;return{id:z.routeId,credentialId:z.credentialId,label:UW(z),...z.accountIdentity!==void 0?{accountId:z.accountIdentity}:{},quota:T3(z.quota,W),killed:G.get(z.routeId)===!1,enabled:z.enabled,routable:J.has(z.routeId),...z.state!=="active"||z.stale||z.enabled&&!J.has(z.routeId)?{vaultState:VL.get(z.state)??"unavailable"}:{},...W!==void 0?{resetCredits:W}:{}}}),route:X?.routing?.mode??"main-first",lastUpdated:$}}function VW(Y,J,X,$=()=>{return}){let Q=C9(Y,{version:1,accounts:[],...J},X),G=Y.find((W)=>W.id===f1),z=G?$(G.id):void 0;return{main:{quota:G?T3(G.quota,z):null,...G?.identity!==void 0?{mainAccountId:G.identity}:{},killed:Q.get(f1)===!1,...z!==void 0?{resetCredits:z}:{}},fallbacks:Y.filter((W)=>W.id!==f1&&W.enabled).map((W)=>{let U=$(W.id);return{id:W.id,label:W.label,...W.identity!==void 0?{accountId:W.identity}:{},quota:T3(W.quota,U),killed:Q.get(W.id)===!1,enabled:!0,...U!==void 0?{resetCredits:U}:{}}}),route:J?.routing?.mode??"main-first",lastUpdated:X,accountPool:!0}}var KL=["killswitch_enabled","killswitch_default_primary","killswitch_default_secondary","killswitch_account_floors","quota_minimum_remaining","cache_keep_window"];function jL(Y,J){let X=[],$=(U,H)=>{X.push({file:{kind:"user",path:J},keyPath:[U],reason:"invalid-value",detail:H})},Q=Y.killswitch_account_floors,G=Q.map(({account:U,host:H})=>JSON.stringify([U,H]));if(new Set(G).size!==G.length)$("killswitch_account_floors","Duplicate account and host pair");if(Q.some(({account:U,host:H})=>H==="both"&&!U.startsWith("vault:")))$("killswitch_account_floors","Only vault accounts may use host both");let z=Y.quota_minimum_remaining.map(({window:U})=>U);if(new Set(z).size!==z.length)$("quota_minimum_remaining","Duplicate quota window");let W=Y.cache_keep_window;if(W.length>1||W.some(({start_hour:U,end_hour:H})=>U===H))$("cache_keep_window","Use at most one window with unequal hours");return X}function NL(Y,J){let X=Y.killswitch_account_floors,$=Object.fromEntries([...X.filter((G)=>G.host==="both"),...X.filter((G)=>G.host===J)].map(({account:G,primary:z,secondary:W})=>[G,{primary:z,secondary:W}])),Q=Y.cache_keep_window[0];return{version:1,accounts:[],routing:{mode:Y.routing_mode,maxSameAccountWait:{off:0,"15m":15,cache:"max"}[Y.max_same_account_wait]},fallbackOn:Y.fallback_on,refresh:{enabled:Y.refresh_enabled,refreshBeforeExpiryMinutes:Y.refresh_before_expiry_minutes},quota:{enabled:Y.quota_enabled,checkIntervalMinutes:Y.quota_check_interval_minutes,minimumRemaining:Object.fromEntries(Y.quota_minimum_remaining.map(({window:G,floor:z})=>[G,z])),failClosedOnUnknownQuota:Y.quota_fail_closed_on_unknown},costZeroing:{enabled:Y.cost_zeroing},killswitch:{schema:X8,enabled:Y.killswitch_enabled,defaults:{primary:Y.killswitch_default_primary,secondary:Y.killswitch_default_secondary},accounts:$},logging:{level:Y.log_level==="default"?void 0:Y.log_level},cachekeep:void 0,cacheKeep:{enabled:Y.cache_keep_enabled,subagents:Y.cache_keep_subagents,sustain:Y.cache_keep_sustain,startHour:Q?.start_hour,endHour:Q?.end_hour},dump:{enabled:Y.request_dumps},dumpDir:Y.dump_dir,dumpMaxBytes:Y.dump_max_bytes,webSockets:Y.web_sockets,rawWebSocket:Y.raw_web_socket,responsesLite:Y.responses_lite,codexApiEndpoint:Y.codex_api_endpoint}}async function BW(Y){let{handle:J,host:X,file:$}=Y,Q,G,z=[],W=!1,U=Promise.resolve(),H=new Set,V=async()=>{await J.read();let K=Object.fromEntries(await Promise.all(Object.keys(q0.settings).map(async(P)=>[P,await J.get(P,{host:X})]))),L=J.report();z=[...L,...jL(K,$)];let O=L.some((P)=>P.file.path===$&&(P.reason==="unreadable"||P.reason==="unparseable")),q=(P)=>z.some((b)=>b.reason==="invalid-value"&&b.keyPath[0]===P),x=(P)=>{K[P]=structuredClone(Q?.[P]??q0.settings[P].default)};for(let P of KL)if(O||q(P))x(P);if(O&&!Q)K.killswitch_enabled=!0;if(q("killswitch_account_floors"))K.killswitch_default_primary=Q?.killswitch_default_primary??K.killswitch_default_primary,K.killswitch_default_secondary=Q?.killswitch_default_secondary??K.killswitch_default_secondary;if(Q=K,G=NL(K,X),!W)for(let P of H)P()},F=()=>{return U=U.then(V,V),U},j=J.watch(()=>{F()});try{await F()}catch(K){throw j(),K}return{view(K){let L=structuredClone(G);return{...K,...L,accounts:K?.accounts??[],main:K?.main,refresh:{...L.refresh,mainLastRefreshError:K?.refresh?.mainLastRefreshError,mainRefreshLeaseId:K?.refresh?.mainRefreshLeaseId,mainRefreshLeaseUntil:K?.refresh?.mainRefreshLeaseUntil,mainRefreshLeaseTokenHash:K?.refresh?.mainRefreshLeaseTokenHash},quota:{...L.quota,mainQuota:K?.quota?.mainQuota,mainQuotaCheckedAt:K?.quota?.mainQuotaCheckedAt,mainQuotaToken:K?.quota?.mainQuotaToken,mainLastQuotaApiError:K?.quota?.mainLastQuotaApiError}}},get(K){return structuredClone(Q[K])},report(){return structuredClone(z)},refresh:F,onChange(K){return H.add(K),()=>{H.delete(K)}},dispose(){W=!0,j(),H.clear()}}}async function NW(Y){let J=Y.log??W0("settings"),X=KW({host:"opencode",paths:Y.paths??x6(),logger:J}),$=await dX({install:X,log:J,record:(z)=>jW({configPath:X.configIdentity,settings:z,version:Y.version})});if($.decision!=="shared")return{authority:$};let Q=Q8(q0,{file:$.install.target,log:J,separateInstall:!1,createMissing:!0}),G=await BW({handle:Q,file:$.install.target,host:"opencode"});return R3(G.get("log_level"),"startup"),G.onChange(()=>{R3(G.get("log_level"),"refresh")}),{authority:$,handle:Q,snapshot:G}}import{resolve as s4}from"node:path";import{resolveClaustrumConnectionPath as LW}from"@cortexkit/claustrum-client";var FW=W0("vault"),LL=60000,FL=240000,qW=Symbol.for("@cortexkit/openai-auth/opencode-vaults"),PW=globalThis,a4=PW[qW]??new Map;PW[qW]=a4;function DL(Y){if(!Y||typeof Y!=="object")return!1;let J=Y;return J.protocol===1&&J.holders instanceof Set&&typeof J.firstRoster?.resolve==="function"&&J.firstRoster.promise instanceof Promise&&typeof J.started==="boolean"&&typeof J.vault?.awaitRequestRoster==="function"&&typeof J.vault?.grantReach==="function"&&typeof J.vault?.reorder==="function"}function MW(Y,J){let X=Boolean(Y.connectScoped||Y.connectEnrollment),$=s4(Y.stateDir),Q=Q4()?"host":s4((Y.connectionFile??LW)()),G=JSON.stringify([DW,Y.host,$,Q,s4(J.configPath),s4(J.statePath)]),z={reservedRouteIds:Y.reservedRouteIds??(()=>[])},W=a4,U=a4.get(G);if(!X&&U!==void 0&&!DL(U)){let K=a4;K.compatibleV1??=new Map,W=K.compatibleV1}let H=X?void 0:W.get(G);if(!H){let K=new Set;if(H={protocol:1,vault:new OW({...Y,stateDir:$,connectionFile:()=>Q==="host"?(Y.connectionFile??LW)():Q,...!X?{projectRoot:$}:{},reservedRouteIds:()=>new Set([...K].flatMap((O)=>[...O.reservedRouteIds()])),afterDisconnect:async()=>{await Y.afterDisconnect?.();try{await _W($)}catch(O){FW.warn("could not remove the old vault enrollment state",{error:O instanceof Error?O.message:String(O)})}}}),holders:K,firstRoster:Promise.withResolvers(),started:!1},!X)W.set(G,H)}H.holders.add(z);let V=H,F=!1,j;return{vault:V.vault,firstRoster:V.firstRoster.promise,start(){if(F||V.started)return;V.started=!0;let K=async()=>{try{if(V.holders.size&&await V.vault.authority()!=="local")await V.vault.pollStale(FL)}catch(O){FW.warn("vault background quota poll failed",{error:O instanceof Error?O.message:String(O)})}};V.vault.start(),V.vault.firstRoster().finally(()=>{V.firstRoster.resolve(),K()}),V.quotaPoll=setInterval(K,LL),V.quotaPoll.unref?.()},release(){if(F)return j;if(F=!0,V.holders.delete(z),V.holders.size!==0)return;if(V.quotaPoll)clearInterval(V.quotaPoll);if(j=typeof V.vault.dispose==="function"?V.vault.dispose():Promise.resolve(V.vault.close()),V.firstRoster.resolve(),!X&&W.get(G)===V)W.delete(G);return j}}}var CW=900000,OL=0.016666666666666666,EW=0.000001;function w3(Y,J){for(let X of[Y?.primary?.checkedAt,Y?.checkedAt,J])if(typeof X==="number"&&Number.isFinite(X))return X;return}function I3(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let J=w3(Y.quota,Y.quotaCheckedAt);if(J===void 0||!Number.isFinite(J)||Y.now-J>CW)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let X=C3(Y.quota).sort((Q,G)=>{let z=Q.windowMs,W=G.windowMs,U=typeof z==="number"&&Number.isFinite(z),H=typeof W==="number"&&Number.isFinite(W);if(U!==H)return U?-1:1;if(U&&H)return W-z;return 0});for(let{key:Q,window:G}of X)if(Number.isFinite(G.remainingPercent)&&G.remainingPercent<=0)return{action:"migrate",reason:"exhausted",windowKey:Q,...typeof G.resetsAt==="string"?{resetsAt:G.resetsAt}:{}};let $=RW(Y.quota,Y.now);if($)return{action:"migrate",reason:"exhausted",resetsAt:$.resetsAt};if(Y.status===void 0||Y.status===0||!Number.isFinite(Y.status)||Y.status>=500&&Y.status<=599||Y.status===429)return{action:"retain",reason:"transient"};return{action:"retain",reason:"healthy"}}function AW(Y,J,X){let $=Math.max(0,Y.remainingPercent-J);if($<=0)return 0;if(!Y.resetsAt)return $;let Q=Date.parse(Y.resetsAt);if(!Number.isFinite(Q)||Q<=X)return $;let G=Math.max((Q-X)/3600000,OL);return $/G}function TW(Y,J){if(Y<J)return-1;if(Y>J)return 1;return 0}function _L(Y,J){if(!Y.quota)return;let X=w3(Y.quota,Y.quotaCheckedAt);if(X===void 0||J-X>CW)return;let $=C3(Y.quota).map(({key:z,window:W})=>{return AW(W,Y.reservePercent[z]??0,J)}),Q=Y.quota.spendControl;if(Q&&Number.isFinite(Q.remainingPercent))$.push(AW(Q,0,J));let G=$.length>0?Math.min(...$):0;return G>0?{candidate:Y,quotaCheckedAt:X,weight:G}:void 0}function wW(Y){let J=Y.candidates.filter((Q)=>Q.killswitchPasses!==!1);if(Y.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if(J.length===0)return;let X=J.map((Q)=>_L(Q,Y.now)).filter((Q)=>Q!==void 0);if(X.length>0){X.sort((G,z)=>{let W=((Y.pendingBytes.get(G.candidate.accountId)??0)+Y.requestBytes)/Math.max(G.weight,EW),U=((Y.pendingBytes.get(z.candidate.accountId)??0)+Y.requestBytes)/Math.max(z.weight,EW);return W-U||G.candidate.configuredOrder-z.candidate.configuredOrder||TW(G.candidate.accountId,z.candidate.accountId)});let Q=X[0];if(Q)return{accountId:Q.candidate.accountId,quotaCheckedAt:Q.quotaCheckedAt,source:"weighted"}}Y.onEmptyWeightedSet?.();let $=[...J].sort((Q,G)=>{let z=(Q.resetCreditsApplicable??0)>0?1:0;return((G.resetCreditsApplicable??0)>0?1:0)-z||Q.configuredOrder-G.configuredOrder||TW(Q.accountId,G.accountId)})[0];if(!$)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:$.accountId,quotaCheckedAt:w3($.quota,$.quotaCheckedAt),source:"mode-fallback"}}import{readFile as qL}from"node:fs/promises";import{homedir as PL}from"node:os";import{join as IW}from"node:path";var ML="https://models.dev/api.json",EL="OPENCODE_OPENAI_AUTH_MODELS_CACHE",AL="OPENCODE_MODELS_PATH",TL="OPENCODE_DISABLE_MODELS_FETCH",RL=1e4,CL=300000;function q6(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function SW(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function S3(Y){let{input:J,output:X}=Y;if(typeof J!=="number"||!Number.isFinite(J)||J<0)return null;if(typeof X!=="number"||!Number.isFinite(X)||X<0)return null;let $=SW(Y.cache_read),Q=SW(Y.cache_write);if($===null||Q===null)return null;return{input:J,output:X,cache:{read:$,write:Q}}}function wL(Y){let J=q6(Y);if(!J)return null;let X=S3(J);if(!X)return null;let $=X;if(Array.isArray(J.tiers)){let z=[];for(let W of J.tiers){let U=q6(W);if(!U)continue;let H=q6(U.tier),V=H?.size;if(H?.type!=="context")continue;if(typeof V!=="number"||!Number.isFinite(V)||V<=0)continue;let F=S3(U);if(!F)continue;z.push({...F,tier:{type:"context",size:V}})}if(z.length>0)$.tiers=z}let Q=q6(J.context_over_200k),G=Q?S3(Q):null;if(G)$.experimentalOver200K=G;return $}function bW(Y){let J=q6(Y),X=q6(J?.openai),$=q6(X?.models);if(!$)return null;let Q={};for(let[G,z]of Object.entries($)){let W=q6(z),U=wL(W?.cost);if(U)Q[G]=U}return Object.keys(Q).length>0?Q:null}function IL(){let Y=process.env[EL]?.trim();if(Y)return Y;let J=process.env[AL]?.trim();if(J)return J;let X=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||IW(PL(),".cache");return IW(X,"opencode","models.json")}function SL(){let Y=process.env[TL]?.toLowerCase();return Y==="true"||Y==="1"}async function bL(){try{let Y=bW(JSON.parse(await qL(IL(),"utf8")));if(Y)return Y}catch{}if(SL())return null;try{let Y=await fetch(ML,{signal:AbortSignal.timeout(RL)});if(!Y.ok)return null;return bW(await Y.json())}catch{return null}}var T8;function kW(){let Y=Date.now();if(T8&&T8.expiresAt>Y)return T8.promise;let J={expiresAt:Y+CL,promise:bL()};return T8=J,J.promise.then((X)=>{if(X===null&&T8===J)T8=void 0}),J.promise}function R8(Y){return typeof Y==="object"&&Y!==null}function kL(Y){if(Array.isArray(Y))return Y;if(R8(Y)&&Array.isArray(Y.data))return Y.data;return[]}function xL(Y){if(!R8(Y)||!R8(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function xW(Y){if(!R8(Y)||!R8(Y.info))return null;let J=Y.info,X=R8(J.model)?J.model:void 0,$=typeof J.agent==="string"?J.agent:void 0,Q=typeof X?.providerID==="string"?X.providerID:typeof J.providerID==="string"?J.providerID:void 0,G=typeof X?.modelID==="string"?X.modelID:typeof J.modelID==="string"?J.modelID:void 0,z=typeof X?.variant==="string"?X.variant:typeof J.variant==="string"?J.variant:void 0;if(!$&&(!Q||!G)&&!z)return null;let W={};if($)W.agent=$;if(Q&&G)W.model={providerID:Q,modelID:G};if(z)W.variant=z;return W}function vW(Y,J){return{agent:Y.agent??J.agent,model:Y.model??J.model,variant:Y.variant??J.variant}}function hW(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function yW(Y,J){if(!Y||!J)return null;let X=Y;if(typeof X.session?.messages!=="function")return null;let $=[];try{$=kL(await Promise.resolve(X.session.messages({path:{id:J},query:{limit:100}})))}catch{return null}if($.length===0)return null;let Q={};for(let G=$.length-1;G>=0;G--){if(xL($[G])!=="assistant")continue;let z=xW($[G]);if(!z)continue;if(Q=vW(Q,z),hW(Q))return Q}for(let G=$.length-1;G>=0;G--){let z=xW($[G]);if(!z)continue;if(Q=vW(Q,z),hW(Q))return Q}if(!Q.agent&&!Q.model&&!Q.variant)return null;return Q}class I9 extends Error{code="OPENAI_AUTH_PERSIST_FAILED";constructor(Y){super("OpenAI OAuth token refreshed but could not be persisted; re-login required",{cause:Y});this.name="AuthPersistError"}}class y0 extends Error{code;constructor(Y,J){super(J);this.name="ResetTargetResolutionError",this.code=Y}}function b3(Y,J,X,$,Q){let G=(M1(X,Q).refresh?.refreshBeforeExpiryMinutes??240)*60000;return!Y||!J||J-$<=G}function fW(Y,J){let X=Y==="main",$=J.row,Q=()=>new y0("token_unavailable",X?"Main OpenAI account has no usable access token.":`Fallback account ${Y} has no usable access token.`);if(!$){if(X)throw Q();throw new y0("unknown_account",`Fallback account ${Y} was not found.`)}if(!$.enabled)throw new y0("disabled_account",`${X?"Main":"Fallback"} account ${Y} is disabled.`);if($.type!=="oauth")throw new y0("non_oauth_account",`${X?"Main":"Fallback"} account ${Y} is not an OAuth account.`);if(!J.token)throw Q();let G=W1(J.token);return{accountKey:Y,label:X?"Main account":$.label??Y,accessToken:J.token,chatgptAccountId:$.identity??(G?Z1(G):void 0)}}function k3(Y){async function J(){let X=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),$=S6(X);if(!X||!$||u0($))throw new y0("token_unavailable","Main OpenAI account has no usable access token.");let Q=$;if(b3(Q.access,Q.expires,X,Y.now(),Y.accountStoragePath))Q=await(Y.refreshPoolMainRow??Y.refreshFallbackAccount)(Q,X);if(!Q.access)throw new y0("token_unavailable","Main OpenAI account has no usable access token.");let G=W1(Q.access);return{accountKey:"main",label:"Main account",accessToken:Q.access,chatgptAccountId:Q.accountId??(G?Z1(G):void 0)}}return async(X)=>{let $=await Y.poolAccess?.(X);if($)return fW(X,$);if(X==="main"){let V=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),F=await Y.getAuth();if(t0(F))return J();if(F.type!=="oauth")throw new y0("non_oauth_account","Main OpenAI account is not authenticated with OAuth.");if(b3(F.access,F.expires,V,Y.now(),Y.accountStoragePath))try{F={type:"oauth",...await Y.refreshMainWithLease()}}catch(O){if(O instanceof V6)return J();throw O}if(!F.access)throw new y0("token_unavailable","Main OpenAI account has no usable access token.");let j=W1(F.access),K=j?Z1(j):void 0,L=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath});return{accountKey:X,label:"Main account",accessToken:F.access,chatgptAccountId:K??L?.mainAccountId}}let Q=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),G=Q?.accounts.find((V)=>V.id===X);if(!Q||!G)throw new y0("unknown_account",`Fallback account ${X} was not found.`);if(G.enabled===!1)throw new y0("disabled_account",`Fallback account ${X} is disabled.`);if(!o0(G))throw new y0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);let z=()=>new y0("token_unavailable",`Fallback account ${X} has no usable access token.`);if(u0(G))throw z();let W=G;if(b3(W.access,W.expires,Q,Y.now(),Y.accountStoragePath))W=await Y.refreshFallbackAccount(W,Q);if(!W.access)throw z();let U=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),H=U?.accounts.find((V)=>V.id===X);if(!U||!H)throw new y0("unknown_account",`Fallback account ${X} was not found.`);if(H.enabled===!1)throw new y0("disabled_account",`Fallback account ${X} is disabled.`);if(!o0(H))throw new y0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);return{accountKey:X,label:W.label??X,accessToken:W.access,chatgptAccountId:H.accountId}}}function x3(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function t4(Y){return Y instanceof I9}var vL=W0("rpc"),uW="__openaiAuthRpcServers";async function pW(Y){let J=await gW({...Y,isManagedDir:cW,log:vL,drain:(X,$)=>Y.drain(X,$),apply:async(X)=>await Y.apply(X)});try{return await mW(Y.dir,{port:J.port,token:J.token,pid:process.pid},{secureDir:Y.secureDir}),J}catch(X){throw await J.stop(),X}}function v3(Y,J){return Y.find((X)=>X.enabled!==!1&&o0(X)&&(X.id===J||X.accountId===J))}function YY(Y,J){if(!J)return Y;let X={...Y};for(let $ of["resetCreditsAvailable","resetCreditsApplicable"]){let Q=J[$];if(X[$]===void 0&&Q!==void 0)X[$]=Q}if(X.spendControl===void 0&&X.spendControlCleared!==!0&&J.spendControl!==void 0)X.spendControl=J.spendControl;if(X.credits===void 0&&J.credits!==void 0)X.credits=J.credits;return X}function e4(Y,J){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:J}}function JY(Y,J,X=Date.now(),$=J.mainAccountId){let Q=Y.getMain(),G=Q?.quota;return{main:{quota:G?{...G,checkedAt:Q.checkedAt,primary:e4(G.primary,Q.checkedAt),secondary:e4(G.secondary,Q.checkedAt)}:null,...typeof $==="string"?{mainAccountId:$}:{},killed:!l1(G,J,void 0,X),...G?.resetCreditsAvailable!==void 0?{resetCredits:G.resetCreditsAvailable}:{}},fallbacks:J.accounts.filter((z)=>z.enabled).map((z)=>{let W=Y.getFallback(z.id),U=W?.quota;return{id:z.id,label:z.label,accountId:W?.accountId??z.accountId,quota:U?{...U,checkedAt:W.checkedAt,primary:e4(U.primary,W.checkedAt),secondary:e4(U.secondary,W.checkedAt)}:null,killed:!l1(U,J,z.id,X),enabled:!0,...U?.resetCreditsAvailable!==void 0?{resetCredits:U.resetCreditsAvailable}:{}}}),route:J.routing?.mode??"main-first",lastUpdated:X}}function hL(Y,J,X,$=Date.now()){return{...JY(Y,J,$),activeId:X}}function XY(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}var Q6={};OJ(Q6,{withoutInternalHeaders:()=>$Z,sanitizeHttpFallbackBody:()=>ZJ,orderCodexBody:()=>v6,hasWebSocketResponsesLiteMetadata:()=>WJ,createWebSocketFetch:()=>uL,applyTurnId:()=>aW,advanceTurn:()=>f3,TITLE_HEADER:()=>y3,QUOTA_ACCOUNT_HEADER:()=>$Y,OpenAIWebSocketPool:()=>Q6,CODEX_BODY_KEY_ORDER:()=>hY});import{createHash as yL}from"node:crypto";var y3="x-opencode-title",$Y="x-openai-auth-quota-account",h3=new Set([y3,B6,$Y,"x-opencode-session"]),fL=15000,gL=300000,mL=3300000,lW="websocket_connection_limit_reached";function cL(Y){let J=typeof Y["chatgpt-account-id"]==="string"?Y["chatgpt-account-id"]:"",X=typeof Y.authorization==="string"&&Y.authorization.startsWith("Bearer ")?Y.authorization.slice(7):"",$=J?`acct:${J}`:`tok:${X}`;return yL("sha256").update($).digest("hex").slice(0,12)}function uL(Y){let J=Y?.httpFetch??globalThis.fetch,X=new Map,$=Y?.connectTimeout??fL,Q=Y?.idleTimeout??gL,G=Y?.maxConnectionAge??mL,z=Y?.streamRetries??5,W=Y?.firstEventGraceMs??250,U=Y?.rawWebSocket??!1,H=Y?.onQuota,V=Y?.onRateLimitReached,F=setInterval(()=>O(),Math.min(Q,60000));if(typeof F==="object"&&"unref"in F&&typeof F.unref==="function")F.unref();function j(P,b,M,w){if(!b||!M)return M;f3(P,dW(b),void 0,w);let S=new Headers(M.headers),E=S.get("x-codex-turn-metadata");if(!E)return M;let v=tW(E,P.turnID,P.turnStartedAt);if(!v)return M;return S.set("x-codex-turn-metadata",v),{...M,headers:S}}async function K(P,b){let M=P instanceof URL?P.toString():typeof P==="string"?P:P.url,w=p0.normalizeHeaders(b?.headers),S=typeof w[$Y]==="string"?w[$Y]:void 0,E=async(m,Z0)=>{let p=await J(m,Z0);return Y?.onHttpResponse?.(p,S)??p},v=$Z(b),u=L4(v);if(b?.method!=="POST"||!new URL(M).pathname.endsWith("/responses"))return E(P,u);let c=(()=>{try{if(typeof b?.body!=="string")return;let m=JSON.parse(b.body);return typeof m==="object"&&m!==null?m:void 0}catch{return}})();if(!c?.stream)return E(P,u);if(w[y3]==="true")return E(P,u);let r=w[B6]??w["x-session-affinity"]??w["session-id"],J0=r;if(!r)return E(P,u);let l=p0.normalizeHeaders(v?.headers),T=cL(l),B0=`${r}:${T}:conversation`,P0=V?(m,Z0)=>V(m,S,Z0):void 0,d=X.get(B0)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};X.set(B0,d);let k0=dW(c),T0;if(d.fallback)return E(P,j(d,c,u,T0));if(d.busy)return E(P,j(d,c,u,T0));d.busy=!0,d.lastUsedAt=Date.now();try{T0=C8(d,k0);let m=p0.normalizeHeaders(v?.headers),Z0=typeof m.authorization==="string"&&m.authorization.startsWith("Bearer ")?m.authorization.slice(7):"",p=typeof m["chatgpt-account-id"]==="string"?m["chatgpt-account-id"]:void 0,M0=H?(E0,w1)=>H(E0,Z0,S,p,w1):void 0,l0=!d.socket&&!d.continuation?aL(m):m;if(d.socket=await iL(d,Y?.url??M,l0,$,G,U,b?.signal),YF(d,k0,T0))await nL(d,k0,Q,{signal:b?.signal??void 0,sessionID:J0,url:Y?.url??M,headers:v?.headers,onRateLimitReached:P0});let O0=()=>{},e=()=>{},f0=new Promise((E0,w1)=>{O0=E0,e=w1}),R0=eL(d,k0,T0),s6=v6(aW(d,R0,k0,T0)),k9=typeof s6.previous_response_id==="string";await j8({sessionID:J0,transport:"websocket",phase:"main",bodyText:()=>JSON.stringify(s6),url:Y?.url??M,method:v?.method,headers:v?.headers});let I8=p0.streamResponsesWebSocket({socket:d.socket,body:s6,sessionID:J0??void 0,idleTimeout:Q,signal:b?.signal??void 0,onQuota:M0,onRateLimitReached:P0,onFirstEvent:(E0)=>O0(E0??!0),onComplete:(E0,w1)=>{Y?.onComplete?.(E0,S);let v9=oW(E0);h6({component:"ws-pool",event:"main_completed",sessionID:J0,responseID:nW(E0),usage:v9}),sW(d,k0,E0,w1,k9,T0)},onTerminal:(E0)=>{if(d.busy=!1,d.lastUsedAt=Date.now(),d.streamFailures=0,E0.type!=="response.completed"&&E0.type!=="response.done")d.continuation=void 0,$6(d)},onConnectionInvalid:(E0)=>{if(d.busy=!1,d.lastUsedAt=Date.now(),p0.isOversizedFrame(E0))d.fallback=!0;if(!d.fallback)L(d);d.continuation=void 0,$6(d),O0(!1)},onAbort:(E0)=>{d.busy=!1,d.lastUsedAt=Date.now(),d.streamFailures=0,d.continuation=void 0,$6(d),e(E0)},onRetryableTerminal:async(E0)=>{let w1=iW(E0);if(!w1)return;throw d.fallback=!0,w1}}),d1=await pL(f0,W);if(d1!==!1){if(d1===!0||d1.status<200||d1.status>599)return I8;return new Response(d1.body,{status:d1.status,headers:{"content-type":"application/json",...d1.headers}})}let x9=()=>E(P,j(d,c,u,T0));if(!d.fallback)return lL(I8,x9);return x9()}catch(m){if(d.busy=!1,d.lastUsedAt=Date.now(),p0.isAbortError(m))throw d.streamFailures=0,d.continuation=void 0,$6(d),m;let Z0=p0.parseRateLimitSignal(m);if(Z0)P0?.(Z0.window,Z0.resetAt);if(p0.isUpgradeFailure(m)&&!U)d.fallback=!0;if(L(d),d.continuation=void 0,$6(d),d.fallback)return E(P,j(d,c,u,T0));return dL(new Y1(m instanceof Error?m.message:String(m),{cause:m}))}}function L(P){if(P.streamFailures++,P.streamFailures>z)P.fallback=!0}function O(){let P=Date.now();for(let[b,M]of X){if(M.busy)continue;if(P-M.lastUsedAt<Q)continue;$6(M),X.delete(b)}}function q(){clearInterval(F);for(let P of X.values())$6(P);X.clear()}function x(P){let b=`${P}:`;for(let[M,w]of X){if(!M.startsWith(b))continue;$6(w),X.delete(M)}}return Object.assign(K,{close:q,remove:x})}function iW(Y){if(Y.type!=="error"||!n(Y.error)||Y.error.code!==lW)return;return Error(typeof Y.error.message==="string"?Y.error.message:lW)}async function pL(Y,J){if(J<=0)return!1;return new Promise((X,$)=>{let Q=setTimeout(()=>X(!1),J);Y.then((G)=>{clearTimeout(Q),X(G)},(G)=>{clearTimeout(Q),$(G)})})}function lL(Y,J){let X=Y.body;if(!X)return Y;let $=!1,Q=new ReadableStream({async start(G){let z=X.getReader(),W=async(U)=>{while(!0){let{done:H,value:V}=await U.read();if(H)return;if(V&&V.length>0)$=!0,G.enqueue(V)}};try{await W(z),G.close()}catch(U){if($||!p0.isOversizedFrame(U)){G.error(U);return}try{let H=await J();if(!H.ok){G.error(new Y1(`HTTP fallback after an oversized WebSocket frame failed with ${H.status}`));return}if(H.body)await W(H.body.getReader());G.close()}catch(H){G.error(H)}}},cancel(G){X.cancel(G)}});return new Response(Q,{status:Y.status,headers:Y.headers})}function dL(Y){return new Response(new ReadableStream({start(J){J.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function iL(Y,J,X,$,Q,G,z){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<Q)return Y.socket;$6(Y);let W=await p0.connectResponsesWebSocket({url:p0.toWebSocketUrl(J),headers:X,timeout:$,rawWebSocket:G,signal:z??void 0});return Y.connectedAt=Date.now(),W}function $6(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function nL(Y,J,X,$){if(!Y.socket||!Array.isArray(J.input)||J.input.length===0)return;let Q=rL(J);await j8({sessionID:$.sessionID,transport:"websocket",phase:"prewarm",bodyText:()=>JSON.stringify(Q),url:$.url,method:"POST",headers:$.headers});let G=p0.streamResponsesWebSocket({socket:Y.socket,body:Q,sessionID:$.sessionID,idleTimeout:X,signal:$.signal,onRateLimitReached:$.onRateLimitReached,onComplete:(z,W)=>{h6({component:"ws-pool",event:"prewarm_completed",sessionID:$.sessionID,responseID:nW(z),usage:oW(z)}),sW(Y,Q,z,W,!1,{input:y6([]),signature:JZ(Q),priorInputs:new Map})},onTerminal:(z)=>{if(z.type!=="response.completed"&&z.type!=="response.done")Y.continuation=void 0},onConnectionInvalid:()=>{Y.continuation=void 0},onAbort:()=>{Y.continuation=void 0},onRetryableTerminal:async(z)=>{let W=iW(z);if(!W)return;throw Y.fallback=!0,W}});await oL(G)}function nW(Y){let J=Y.response;if(!n(J))return;return typeof J.id==="string"?J.id:void 0}function oW(Y){let J=Y.response;if(!n(J))return;return n(J.usage)?J.usage:void 0}async function oL(Y){let J=Y.body?.getReader();if(!J)return;while(!0)if((await J.read()).done)return}function rL(Y){return v6({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:sL(Y.client_metadata)})}function rW(Y){return JSON.stringify({session_id:Y.session_id,thread_id:Y.thread_id,thread_source:Y.thread_source,turn_id:"",sandbox:Y.sandbox,request_kind:"prewarm",window_id:Y.window_id})}function sL(Y){if(!n(Y))return Y;if(typeof Y["x-codex-turn-metadata"]!=="string")return Y;try{let J=JSON.parse(Y["x-codex-turn-metadata"]);if(!n(J))return Y;return{...Y,"x-codex-turn-metadata":rW(J),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function aL(Y){let J=Y["x-codex-turn-metadata"];if(!J)return Y;try{let X=JSON.parse(J);if(!n(X))return Y;return{...Y,"x-codex-turn-metadata":rW(X)}}catch{return Y}}function dW(Y){let J={...Y};if(Array.isArray(Y.input))J.input=Y.input.map(tL);return J}function tL(Y){if(!n(Y))return Y;if(typeof Y.type==="string")return Y;if(typeof Y.role!=="string")return Y;if(!("content"in Y))return Y;return{...Y,type:"message"}}function sW(Y,J,X,$,Q,G=C8(Y,J)){let z=X.response,W=n(z)&&typeof z.id==="string"?z.id:void 0;if(!W||!Array.isArray(J.input)){Y.continuation=void 0;return}let U=Q?new Set(Y.continuation?.finalizedCallIds):new Set;for(let H of $)U.add(H);Y.continuation={responseID:W,input:J.input,signature:G.signature,canonical:X9(G.input),finalizedCallIds:U}}function f3(Y,J,X=J,$=C8(Y,{...X,input:Array.isArray(X.input)?X.input:J.input})){let Q=Array.isArray(J.input)?J.input:[],G=Array.isArray(X.input)?X.input:Q,z=$.signature,W=Y.turnInput&&Y.turnSignature===z?$9(eW($,Y.turnInput),$.input):void 0,U=W===void 0?Q:G.slice(W);if(U.length>0&&U.some(YZ)||!Y.turnID)Y.turnID=g6(),Y.turnStartedAt=Date.now();Y.turnInput=G.slice(),$.priorInputs.set(Y.turnInput,$.input),Y.turnSignature=z,Y.turnCanonical=X9($.input)}function aW(Y,J,X=J,$=C8(Y,{...X,input:Array.isArray(X.input)?X.input:J.input})){f3(Y,J,X,$);let Q=J.client_metadata;if(!n(Q)||typeof Q["x-codex-turn-metadata"]!=="string")return J;let G=tW(Q["x-codex-turn-metadata"],Y.turnID,Y.turnStartedAt);if(!G)return J;return{...J,client_metadata:{...Q,"x-codex-turn-metadata":G}}}function tW(Y,J,X){let $;try{$=JSON.parse(Y)}catch{return}if(!n($))return;return JSON.stringify({session_id:$.session_id,thread_id:$.thread_id,thread_source:$.thread_source,turn_id:J,sandbox:$.sandbox,turn_started_at_unix_ms:X,request_kind:"turn",window_id:$.window_id})}function C8(Y,J){let X=Array.isArray(J.input)?J.input:[],$=new Map;if(Y.turnInput&&Y.turnCanonical)$.set(Y.turnInput,Y.turnCanonical);if(Y.continuation?.canonical)$.set(Y.continuation.input,Y.continuation.canonical);let Q=y6(X,Y.turnCanonical??Y.continuation?.canonical);return $.set(X,Q),{input:Q,signature:JZ(J),priorInputs:$}}function eW(Y,J){let X=Y.priorInputs.get(J);if(!X){for(let[$,Q]of Y.priorInputs)if($.length===J.length&&$.every((G,z)=>G===J[z])){X=Q;break}X??=y6(J),Y.priorInputs.set(J,X)}return X}function eL(Y,J,X=C8(Y,J)){let $=Array.isArray(J.input)?J.input:void 0;if(!$||!Y.continuation)return J;if(Y.continuation.signature!==X.signature)return Y.continuation=void 0,J;if(!XZ(Y.continuation,X))return Y.continuation=void 0,J;if(Y.continuation.input.length===0)return{...J,previous_response_id:Y.continuation.responseID};let Q=$.slice(Y.continuation.input.length),G=JF(Q,Y.continuation.finalizedCallIds);if(G.length===0)return J;return{...J,previous_response_id:Y.continuation.responseID,input:G}}function YF(Y,J,X=C8(Y,J)){let $=Array.isArray(J.input)?J.input:void 0;if(!Y.continuation)return!0;if(!$)return!1;if(!XZ(Y.continuation,X))return!0;return $.slice(Y.continuation.input.length).some(YZ)}function YZ(Y){if(!n(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function JF(Y,J){return Y.filter((X)=>{if(!n(X))return!0;if(typeof X.type==="string"&&X.type.endsWith("_output"))return!0;if(X.type==="function_call_output"||X.type==="custom_tool_call_output")return!0;if(X.type==="function_call"||X.type==="custom_tool_call"){let $=typeof X.call_id==="string"?X.call_id:typeof X.id==="string"?X.id:void 0;return $?!J.has($):!0}if(X.type==="message")return X.role!=="assistant";if(typeof X.role==="string")return X.role!=="assistant";return!1})}function JZ(Y){return N8(XF(Object.fromEntries(Object.entries(Y).filter(([J])=>J!=="input"&&J!=="stream"&&J!=="background"&&J!=="previous_response_id"&&J!=="generate"))))}function XF(Y){if(!n(Y.client_metadata))return Y;let J=Object.fromEntries(Object.entries(Y.client_metadata).filter(([X])=>X!=="x-codex-turn-metadata"&&X!=="x-codex-ws-stream-request-start-ms"));return{...Y,client_metadata:J}}function XZ(Y,J){if(Y.input.length>=J.input.texts.length)return!1;return $9(eW(J,Y.input),J.input)!==void 0}function $Z(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let J=new Headers(Y.headers);for(let X of h3)J.delete(X);return{...Y,headers:J}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((J)=>!h3.has(J[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([J])=>!h3.has(J.toLowerCase())))}}var QF="Refusing to send a request with no access token. This is a defect in the plugin, not a problem with the provider or the account; the transport log names the account and the path that produced it.",GF="opencode-oauth-dummy-key",qR=()=>t8,zF=120000,WF=90000,ZF=4000,GZ=50,zZ=3,UF=25,HF=60000,VF=2000,BF="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",n3=!1,UY;function PR(){return UY}function MR(){n3=!1,UY=void 0}var WZ=W0("models"),ZZ=!1,UZ=!1;function HZ(){throw Error(BF)}async function KF(Y,J={}){let X=J.paths??x6(F1());if(kY(X.configPath)){await R6(U8(X),J.holdsMainRefreshLock?void 0:r1(X),($)=>{if(J.canWrite&&!J.canWrite())throw Error(r6["vault-refused"]);Y($)});return}await z4(($)=>{return Y($),$},X,{canWrite:J.canWrite})}var YU=null;function ER(){return YU}function jF(Y){return Math.floor(Math.random()*Y)}var NF=!0;function LF(Y,J,X){let $=Y.get(J);if($)return $;let Q=g6(),G={threadID:Q,turnID:g6(),windowID:`${Q}:0`};return Y.set(J,G),X?.(),G}function m3(){return bZ("opencode1")}function c3(Y,J){if(J?.headers!==void 0)return new Headers(J.headers);if(Y instanceof Request)return new Headers(Y.headers);return new Headers}async function u3(Y,J){if(!(Y instanceof Request))return J;let X=new Request(Y,J),$=X.method.toUpperCase(),Q=$==="GET"||$==="HEAD"||X.body===null?void 0:await X.text();return{method:X.method,headers:new Headers(X.headers),body:Q,signal:X.signal,cache:X.cache,credentials:X.credentials,integrity:X.integrity,keepalive:X.keepalive,mode:X.mode,redirect:X.redirect,referrer:X.referrer,referrerPolicy:X.referrerPolicy}}async function FF(Y,J={}){await eZ({version:g1,...J.runtimeLayout});let X=F1(),$=await NW({version:g1}),Q=x6(X),G=$.snapshot?X7(X,$.snapshot):void 0,z=(g)=>M1(g,X),W=(g)=>g===null?null:z(g),U=async(g)=>W(await k6(g)),H=async(g)=>W(await OZ(g));class V extends PZ{async load(){return W(await super.load())}}let F=D1(X);J={...J,experimentalWebSockets:J.experimentalWebSockets??F.webSockets,responsesLite:J.responsesLite??F.responsesLite};let j=J.codexApiEndpoint??F.codexApiEndpoint,K=crypto.randomUUID(),L=hZ(m3()),O=()=>fZ(m3(),L),q=!1,x=!1,P=[],b=null,M=vZ(Y.client),w=new Map,S=new Map,E,v=!1,u,c=new Map,r,J0,l=MW({host:"opencode",stateDir:J.vault?.stateDir??MZ(Q.statePath),...Y.directory?{projectRoot:Y.directory}:{},reservedRouteIds:()=>m?.peek().rows.map((g)=>g.id)??[],...J.vault?.connectionFile?{connectionFile:J.vault.connectionFile}:{},...J.vault?.connectScoped?{connectScoped:J.vault.connectScoped}:{},...J.vault?.connectEnrollment?{connectEnrollment:J.vault.connectEnrollment}:{},...J.vault?.pollIntervalMs!==void 0?{pollIntervalMs:J.vault.pollIntervalMs}:{},...J.vault?.now?{now:J.vault.now}:{},...J.vault?.setTimeoutImpl?{setTimeoutImpl:J.vault.setTimeoutImpl}:{},...J.vault?.clearTimeoutImpl?{clearTimeoutImpl:J.vault.clearTimeoutImpl}:{},fetchImpl:()=>fetch},Q),T=l.vault;await T.authority();let B0=l.firstRoster,P0=Promise.withResolvers(),d=Promise.race([B0,P0.promise]),k0=J.vault?.firstRosterWaitMs??KJ,T0,m,Z0,p=new Map,M0=new Map,l0=(g)=>{for(let[s,Q0]of M0)if(Q0.sessionId===g)M0.delete(s)},{enabled:O0,...e}=J.poolMigration??{},f0=O0??NF;if(f0&&"reason"in M)(e.log??W0("pool")).warn("account pool migration is off for this OpenCode client",{reason:M.reason});let R0=f0&&"slot"in M?e2({paths:()=>Q,slot:M.slot,version:g1,...e,runDeps:{vaultServes:()=>T.serves(),...e.runDeps},paused:async()=>await T.authority()!=="local",migrate:async(g)=>{let s=await(e.migrate??q4)(g);return m?.load(),s},adopt:async(g)=>{if(!await O8(d,k0))return{status:"retry",reason:"vault-roster-pending"};let s=await(e.adopt??P4)(g);return m?.load(),s}}):void 0,s6=(g,s="")=>g?async()=>{let Q0=await g();return{url:Q0.url,instructions:Q0.instructions??s,method:"auto",callback:async()=>{try{let G0=await Q0.tokens;return{type:"success",refresh:G0.refresh_token,access:G0.access_token,expires:Date.now()+(G0.expires_in??3600)*1000,accountId:b6(G0)}}finally{Q0.cleanup?.()}}}}:void 0,k9=new $J(J.backgroundQuota),I8,d1=c7({client:Y.client,getAuth:async()=>I8?.(),fetchImpl:fetch,dependencies:{...J.login?.authorize?{authorizeBrowser:s6(J.login.authorize.browser,"Complete authorization in your browser. This window will close automatically."),authorizeHeadless:s6(J.login.authorize.headless)}:{}},vault:T,onMainSlotWritten:async()=>{await R0?.requestAdoption()}}),x9=(g)=>async(s)=>{let Q0=await g(s);if(Q0.method!=="auto")return Q0;return{...Q0,callback:async()=>{let G0=await Q0.callback();if(G0.type==="success"&&"refresh"in G0)E0(G0.refresh);return G0}}};async function E0(g){if(!R0||!("slot"in M))return;let s=J.login?.sleep??((Q0)=>Bun.sleep(Q0));for(let Q0=0;Q0<5000;Q0+=100){try{let G0=await M.slot.get({path:{id:"openai"}});if(n(G0)&&G0.refresh===g){await R0.requestAdoption();return}}catch{}await s(100)}}let w1=d1.map((g)=>g.type==="oauth"?{...g,authorize:x9(g.authorize)}:g);async function v9(g,s){let Q0=Y.client.session;if(typeof Q0?.promptAsync==="function"){let G0=await yW(Y.client,g),d0={noReply:!0,parts:[{type:"text",text:s,ignored:!0}]};if(G0?.agent)d0.agent=G0.agent;if(G0?.model)d0.model=G0.model;if(G0?.variant)d0.variant=G0.variant;await Q0.promptAsync({path:{id:g},body:d0});return}}return{async dispose(){G?.(),$.snapshot?.dispose(),await U9(yZ(m3()),VF,()=>{return}),await Z0?.dispose(),await l.release(),R0?.dispose(),await m?.dispose(),k9.stop(),J0?.stop(),E?.stopBackgroundRefresh(),E=void 0;for(let Q0 of P)Q0.close();P.length=0;let g=globalThis;for(let[Q0,G0]of w)if(g.__openaiAuthCacheKeepManagers?.get(Q0)===G0)G0.stop(),g.__openaiAuthCacheKeepManagers.delete(Q0);w.clear();for(let Q0 of S.values())await Q0.release().catch(()=>{});S.clear();let s=T0;T0=void 0,await(await s)?.release()},async event(g){if(g.event.type!=="session.deleted")return;let s=g.event.properties.info;if(Z0?.forget(s.id),l0(s.id),p.delete(s.id),b?.cacheKeepManager?.remove(s.id),L.delete(s.id))O();let Q0=u1(s.id);if(c.delete(Q0),J0?.cancel(`pin:${Q0}`),u){let G0=await T.authority()!=="local"?T.routes().map((d0)=>({id:d0.id})):(await U(Q))?.accounts;await lZ(s.id,G0,u).catch(()=>{})}for(let G0 of P)G0.remove(s.id)},provider:{id:"openai",async models(g,s){if(s.auth?.type!=="oauth")return g.models;let Q0=await T.authority()!=="local"?await H(Q):await U(Q),G0=!Q0||DZ(z(Q0)),d0=G0?null:await kW();if(!G0&&d0&&!ZZ)ZZ=!0,WZ.debug("restoring OAuth model costs from models.dev catalog");if(!G0&&!d0&&!UZ)UZ=!0,WZ.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(g.models).filter(([,G6])=>G6.options.reasoningMode!=="pro"&&oY(G6.api.id)).map(([G6,s0])=>{let g0=sY(s0.id),a6=g0?g.models[g0]?.variants:void 0;return[G6,{...s0,...a6?{variants:{...a6,...s0.variants}}:{},cost:G0?{input:0,output:0,cache:{read:0,write:0}}:d0?.[s0.api.id]??d0?.[G6]??s0.cost,limit:rY(s0.id)??s0.limit}]}))}},auth:{provider:"openai",async loader(g){await T.authority(),I8=g,T0??=aZ({version:g1,logger:W0("heartbeat")}),await T0,R0?.start();let s=await g();if(s.type!=="oauth")return P0.resolve(),{};let Q0=d3(s).kind==="tombstone";l.start();let G0=Y.directory?await SZ(Y.directory):void 0,d0=G0?.dir??X;async function G6(B,N={}){if(await T.authority()!=="local")return;return KF(B,{...N,paths:Q,canWrite:()=>!T.enrolled()})}let s0=await T.authority()!=="local";if(!Q0&&!s0)await qZ({type:"oauth",access:s.access??"",refresh:s.refresh??"",expires:s.expires??0},Q);let g0=await(s0?H(Q):U(Q)).catch(async(B)=>{if(await T.authority()!=="local")return null;throw Error(`OpenAI auth store at ${X} is corrupt or unreadable: ${B instanceof Error?B.message:String(B)}. Fix or remove it to continue.`,{cause:B})});if(!s0&&await zY(Q,s)){if(R0)R0.noticePlaceholderWithoutMain();else if(!v)v=!0,W0("pool-migration").warn(H8,{reason:"placeholder-without-main"})}let a6=g0,o3=!s0,HY=c2({path:()=>X,stat:(B)=>{try{let N=$F(B);return{mtimeMs:N.mtimeMs,size:N.size}}catch{return}},read:()=>U(Q),fallback:async(B)=>{if(await T.authority()!=="local")return H(Q);throw B},onRead:(B)=>{a6=B,o3=!0}});function VY(){let B=HY.read();return B instanceof Promise?B.then(W):W(B)}async function r3(){if(!o3)return VY();return U9(Promise.resolve(VY()),_4,()=>W(a6))}function h9(){HY.invalidate()}if(g0&&s.access&&!Q0&&!s0){let B=b6({id_token:"",access_token:s.access,refresh_token:s.refresh??""});if(B&&B!==g0.mainAccountId)await G6((N)=>{N.mainAccountId=B}),g0.mainAccountId=B,h9()}let BY=z(g0).logging?.level;if(BY&&typeof BY==="string")B4(BY);let S8=W0("transport"),B1=W0("quota"),y9=W0("refresh"),I1=W0("accounts"),JU=new AZ;S8.info("codex auth loader ready",{codexApiEndpoint:j,transport:D1(X).rawWebSocket?"raw-websocket":D1(X).webSockets?"websocket":"http"});let Y0=new FZ({storage:z(g0),configPath:X,fetchQuotaFn:void 0}),b8,k8=0;await Z0?.dispose(),await m?.dispose();let A0=new jJ({paths:()=>Q,refreshProvider:async(B)=>{let N=await S9({refreshToken:B.refresh,fetchImpl:fetch,now:Date.now}),D=b6({id_token:"",access_token:N.access,refresh_token:N.refresh});return{...N,...D?{identity:D}:{}}},pullQuota:async(B)=>{let N=B.credential;if(N.type!=="oauth"||!N.access)throw Error("the row holds no access token to poll with");let D=await e8({accessToken:N.access,fetchImpl:fetch,now:Date.now,...B.identity?{accountId:B.identity}:{},accountKey:B.id,logger:B1}),R=Date.now(),A={quota:D,refreshAfter:R+300000,checkedAt:R};if(B.id==="main")Y0.setMain(N.access,A,B.identity,!0);else Y0.setFallback(B.id,A,N.access,!0,B.identity);return B8(D,R,!0)},vaultIdentities:()=>T.identities(),vaultMode:()=>T.enrolled(),vaultAuthority:()=>T.authority(),vaultFirstRoster:B0,vaultFirstRosterBackgroundWaitMs:k0,log:W0("pool")});if(m=A0,!s0)await A0.load();Z0=new LJ({pool:A0,vault:T,log:(B)=>B1.warn(B)});let J1=Z0,s3=new Map,KY=(B)=>{let N=p.get(B),D=N&&(J1.accountKey(N.accountId)??s3.get(N.accountId));return N&&D&&O1(N,D)?D:void 0},K1=new V({paths:Q,refreshFn:async(B)=>{if(await T.authority()!=="local")throw Error(r6["vault-refused"]);return S9({refreshToken:B.refreshToken,fetchImpl:B.fetchImpl,now:B.now})},quotaManager:Y0,canWrite:()=>!T.enrolled(),onFallbackStorageChanged:h9,backgroundRefreshPaused:async()=>T.enrolled()||await A0.active()});if(g0&&g0.accounts.length>0)K1.startBackgroundRefresh();function jY(B){if(u0(B))return;return B.access||void 0}function f9(B={}){let{readSidebarState:N,respectBackoff:D,skipFresherThanMs:R}=B;return{getAuth:g,codexRefreshFn:S9,refreshMainWithLease:WX,fallbackManager:K1,quotaManager:Y0,loadAccounts:U,writeSidebarState:(A)=>S1(A),client:Y.client,fetchImpl:fetch,now:Date.now,paths:Q,readSidebarState:N??(()=>mZ(a0)),storageMainAccountId:g0?.mainAccountId,isOAuthAccountFn:o0,whamFn:e8,...D===void 0?{}:{respectBackoff:D},...R===void 0?{}:{skipFresherThanMs:R}}}async function a3(B){return(await A0.pollRows(await U(Q),B?{ids:B}:{})).map((D)=>({account:D.id,ok:D.ok,...D.error!==void 0?{error:D.error}:{}}))}async function t3(B){return A0.accessFor(B,await U(Q))}let e3=W0("cachekeep"),g9=K4(z(g0)),YX=g9?.enabled===!0,JX=g9?.subagents===!0,XX=g9?.sustain===!0,$X=y2({...z(g0),cachekeep:g9}),m9;async function XU(B){await new Promise((N)=>setTimeout(N,B))}async function $U(B){let N;for(let D=1;D<=zZ;D++){if(await T.authority()!=="local")throw Error(r6["vault-refused"]);try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:B.refresh,access:B.access,expires:B.expires}});return}catch(R){if(N=R,D<zZ)await XU(UF*D)}}throw new I9(N)}async function c9(B){await G6((N)=>{N.refresh=N.refresh??{},B(N)},{holdsMainRefreshLock:!0}),h9()}async function NY(B){let N=Date.now()+ZF;while(Date.now()<N){await new Promise((A)=>setTimeout(A,GZ+jF(GZ)));let D=await g();if(t0(D))throw new V6;if(D.type!=="oauth"||!D.access)continue;if((D.access!==B.access||D.refresh!==B.refresh||(D.expires??0)>(B.expires??0)+60000)&&(!D.expires||D.expires>Date.now()))return y9.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:D.expires?D.expires-Date.now():void 0}),{access:D.access,refresh:D.refresh??B.refresh??"",expires:D.expires??0}}return null}function QX(B){if(t0(B))throw new V6;if(B.type!=="oauth")throw Error("not oauth");if(u0(B))throw new NZ;if(!B.refresh)throw Error("Token refresh failed: missing refresh token");return B.refresh}async function LY(){if(!m9)m9=(async()=>{let B=await g(),N=QX(B);if(B.type!=="oauth")throw Error("not oauth");let D=Z9(N),R=await k6(Q),A=R?.refresh?.mainLastRefreshError;if(A&&s1(A,N,Date.now()))throw Error(p3(A,Date.now()));if(R?.refresh?.mainRefreshLeaseUntil&&R.refresh.mainRefreshLeaseUntil>Date.now()&&R.refresh.mainRefreshLeaseTokenHash===D){let C=await NY(B);if(C)return C;throw Error("Codex OAuth refresh is already in progress")}let k=await N4({name:t8,ttlMs:zF,path:X,renew:!0});if(!k){let C=await NY(B);if(C)return C;throw Error("Codex OAuth refresh is already in progress")}let I;try{let C=await g(),t=QX(C);if(C.type!=="oauth")throw Error("not oauth");if(t!==N){if(C.access&&(C.expires??0)>Date.now())return y9.debug("main token rotated while awaiting the lock",{pid:process.pid}),await k.release().catch(()=>{}),{access:C.access,refresh:t,expires:C.expires??0};let _0=(await k6(Q))?.refresh?.mainLastRefreshError;if(_0&&s1(_0,t,Date.now()))throw Error(p3(_0,Date.now()))}I={...C,refresh:t}}catch(C){throw await k.release().catch(()=>{}),C}await xZ(Q,I.refresh,I.access!==void 0?{slotAccess:I.access}:{}).catch(()=>!1);let f=Z9(I.refresh),h=crypto.randomUUID(),i=f;try{await c9((z0)=>{if(kZ(X,I.refresh))throw new l3;z0.refresh=z0.refresh??{},z0.refresh.mainRefreshLeaseId=h,z0.refresh.mainRefreshLeaseUntil=Date.now()+WF,z0.refresh.mainRefreshLeaseTokenHash=f});let C=await k6(Q);if(C?.refresh?.mainRefreshLeaseId!==h||C.refresh.mainRefreshLeaseTokenHash!==f)throw Error("Codex OAuth refresh is already in progress");if(await T.authority()!=="local")throw Error(r6["vault-refused"]);let t=await S9({refreshToken:I.refresh,fetchImpl:fetch,now:Date.now});return await $U(t),await c9((z0)=>{if(z0.refresh=z0.refresh??{},z0.refresh.mainLastRefreshError=void 0,z0.refresh.mainRefreshLeaseId===h)z0.refresh.mainRefreshLeaseId=void 0,z0.refresh.mainRefreshLeaseUntil=void 0,z0.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),i=void 0,t}catch(C){if(!(C instanceof l3)){if(!t4(C))await c9((t)=>{t.refresh=t.refresh??{},t.refresh.mainLastRefreshError=KZ({error:C,now:Date.now(),refreshToken:I.refresh,previous:t.refresh.mainLastRefreshError})}).catch(()=>{});throw C}}finally{if(i)await c9((C)=>{if(C.refresh?.mainRefreshLeaseId===h&&C.refresh.mainRefreshLeaseTokenHash===i)C.refresh.mainRefreshLeaseId=void 0,C.refresh.mainRefreshLeaseUntil=void 0,C.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await k.release().catch(()=>{})}let X0=await NY(I);if(X0)return X0;throw Error("Codex OAuth refresh is already in progress")})().finally(()=>{m9=void 0});return m9}function GX(B){return Z7({storage:B,now:Date.now,refreshAccount:(N,D)=>K1.refreshAccount(N,D,{asPoolMain:!0}),warn:(N,D)=>y9.warn(N,{pid:process.pid,...D})})}async function zX(){let B=await GX(await U(Q));if(!B)throw Error("The main OpenAI account has no usable token in the account pool");return{access:B.token,refresh:B.account.refresh,expires:B.account.expires??0}}async function WX(){try{return await LY()}catch(B){if(B instanceof V6)return zX();throw B}}let ZX=globalThis,FY=ZX.__openaiAuthCacheKeepManagers??new Map;ZX.__openaiAuthCacheKeepManagers=FY,FY.get(d0)?.stop();let x8=m2({fetchImpl:fetch,vault:T,activity:{store:J1.activity,accountKey:({target:B})=>{let N=KY(B.meta.routingSessionId??B.sessionKey);return N?.accountId===B.accountId?N:void 0}},getMainToken:async()=>{if(await T.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(await A0.active()){let N=await t3("main");if(!N)throw Error("main pool row has no usable token");return N.token}let B=await g();if(await T.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(t0(B))return(await zX()).access;if(B.type!=="oauth")throw Error("not oauth");if(!B.access||(B.expires??0)<Date.now())try{return(await WX()).access}catch(N){if(t4(N))throw N;if(B.access)return B.access;throw Error("main token refresh failed")}return B.access},refreshFallback:async(B)=>{if(await T.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(await A0.active()){let I=await t3(B);if(!I)throw Error(`no access token for ${B}`);return{token:I.token}}let N=await r3(),D=N?v3(N.accounts,B):void 0;if(!D)throw Error(`fallback account ${B} not found`);let R=N??{version:1,accounts:[D]},A=u0(D)?D:await K1.refreshAccount(D,R),k=jY(A);if(!k)throw Error(`no access token for ${B}`);return{token:k}},codexResponsesUrl:j,activeAccount:async(B)=>g2(P6(await M6.read(),c),B),logger:e3,now:Date.now,getWindow:()=>$X,getSustain:()=>XX});FY.set(d0,x8),w.set(d0,x8);function t6(B,N,D,R,A=!1){try{QU(B,N,D,R,A)}catch(k){B1.warn("quota push failed",{pid:process.pid,accountId:D??"main",error:A8(k)})}}function QU(B,N,D,R,A){if(Object.keys(B).length===0&&!A)return;let k=Date.now(),I=B,f={quota:I,refreshAfter:k+300000,checkedAt:k},h;if(D&&D!=="main"){let X0=N?W1(N):null,C=X0?Z1(X0):void 0,t=Y0.peekFallbackForPolicy(D)?.quota,z0=YY(I,t);f={...f,quota:z0},Y0.setFallback(D,f,N,A,C)}else{if(h=R,!h&&N){let t=W1(N);h=t?Z1(t):void 0}if(h&&b8&&h!==b8){B1.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:h,currentMainIdentity:b8});return}let X0=Y0.peekMainForPolicy(h)?.quota,C=YY(I,X0);f={...f,quota:C},Y0.setMain(N,f,h,A)}B1.debug("quota pushed",{pid:process.pid,accountId:D??"main",snapshot:f.quota}),A0.recordSnapshot(D&&D!=="main"?D:"main",B,N,A);let i=Boolean(D&&D!=="main");i1.enqueue("machine-state","quota",()=>S1(Y0,i?void 0:h))}function UX(B,N=!1){if(N)return T.enrolled()?V1(T.routes().find((D)=>D.id===B)?.quota):V1(A0.peek().rows.find((D)=>D.id===B)?.quota);return B==="main"?Y0.peekMainForPolicy()?.quota:Y0.peekFallbackForPolicy(B)?.quota}function GU(B,N,D){let R=UX(B);return LZ(R,N,Date.now(),HF,D)}let e6=new Map;function HX(){if(!T.enrolled())return;i1.enqueue("machine-state","quota",()=>S1(Y0))}let v8=J.experimentalWebSockets?Q6.createWebSocketFetch({httpFetch:fetch,rawWebSocket:D1(X).rawWebSocket,onQuota:(B,N,D,R,A)=>{let k=D?e6.get(D):void 0;if(k?.receipt){T.reportUsage(k.id,{frame:A},k.receipt),T.recordSnapshot(k.id,B,!0,k.receipt).then(HX);return}let I=k?.id??D;t6(B,N,I,!I||I==="main"?R:void 0,!0)},onRateLimitReached:(B,N,D)=>{if(!N)B1.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:B});let R=N?e6.get(N):void 0;if(!R&&N?.startsWith("stream:"))return;let A=R?.id??N??"main";if(R)R.limited=!0;if(R?.migrated){let{owner:I,probe:f}=R;if(!I)return;if(!f||I.registry!==f.registry){I.dropSignal();return}let h=Date.now(),{command:i,provenance:X0}=CZ({binding:f.binding,baseRevision:f.baseRevision,producerId:K,operationId:QZ(),parsed:{window:B,resetAt:D},reading:UX(A,!0),now:h,observedAt:h,evidenceAt:h});I.enqueue(i,X0);return}let k=GU(A,B,D);Y0.markRateLimited(A,k),B1.debug("mid-stream rate limit mark",{pid:process.pid,accountId:A,window:B})},onComplete:(B,N)=>{if(B.type==="response.completed"&&N)e6.get(N)?.complete("ws")},onHttpResponse:(B,N)=>{let D=N?e6.get(N):void 0;return n4(B,(R)=>{if(R)D?.complete("http")})}}):void 0;if(v8)P.push(v8),q=!0;let a0=gZ();u=a0;async function S1(B,N){if(T.enrolled()){HY.invalidate();let I=await H(Q);await WY(HW(T.snapshot()?.rows,new Set(T.routes().map((f)=>f.id)),z(I),Date.now()),a0,{canWrite:()=>T.enrolled()});return}let D=VY(),R=D instanceof Promise?await D.catch(()=>a6):D,A=N??R?.mainAccountId,k=await A0.current();if(k.active){await WY(VW(k.rows,z(R),Date.now(),(I)=>(I==="main"?B.getMain():B.getFallback(I))?.quota?.resetCreditsAvailable),a0,{canWrite:()=>!T.enrolled()});return}if(!R)return;await WY(JY(B,R,Date.now(),A),a0,{canWrite:()=>!T.enrolled()})}let M6=oZ(a0);M6.read(),J0?.stop();let i1=sZ({logger:S8,onWritten:()=>M6.refreshInBackground()});if(J0=i1,r!==a0)c.clear(),r=a0;function DY(B,N,D,R,A,k,I=!1){let f={vaultMode:I,canWrite:()=>T.enrolled()===I},h={activeId:D,route:R,updatedAt:Date.now()};if(!B){i1.enqueue("routing:legacy","routing",()=>pZ(h,a0,f));return}if(i1.enqueue(`routing:${B}`,"routing",()=>ZY({sessionId:B,...h},A,a0,f)),!N||N===B)return;if(R==="sticky-balanced"){let i=k.stickyAssignments?.[u1(N)]?.accountId,X0=A===void 0||i==="main"||A.some((C)=>C.enabled!==!1&&C.id===i);if(!i||!X0)return;i1.enqueue(`routing:${N}`,"routing",()=>ZY({sessionId:N,activeId:i,route:R,updatedAt:Date.now()},A,a0,f));return}i1.enqueue(`routing:${N}`,"routing",()=>ZY({sessionId:N,...h},A,a0,f))}E?.stopBackgroundRefresh(),E=K1;let h8=Q,VX=$.authority.install.target,zU=$.snapshot&&VX?{settingsSnapshot:$.snapshot,settings:i8({file:VX,host:"opencode",snapshot:$.snapshot,log:W0("settings")})}:{};if(b=YU={configPath:X,...zU,accountStoragePath:h8.configPath,accountStatePath:h8.statePath,packageVersion:g1,layoutNotice:tZ,quotaManager:Y0,loadAccounts:U,beginAccountLogin:G4,store:()=>U8(h8),migration:async()=>{if(await Y4(h8,U8(h8))!==void 0)return{migrated:!0};let B=await(e.fence??(()=>K8({currentVersion:g1})))();return{migrated:!1,blockers:B.open?[]:B.blockers.map((N)=>({pid:N.pid,version:N.version}))}},afterWrite:()=>A0.load(),vault:T,resolveResetTarget:k3({getAuth:g,refreshMainWithLease:LY,refreshFallbackAccount:(B,N)=>K1.refreshAccount(B,N),refreshPoolMainRow:(B,N)=>K1.refreshAccount(B,N,{asPoolMain:!0}),poolAccess:async(B)=>A0.rowAccess(B,await U(Q)),loadAccounts:U,accountStoragePath:X,accountStatePath:Q.statePath,now:Date.now}),...x3(),cacheKeepManager:x8,setCacheKeepEnabled:(B)=>{YX=B},setCacheKeepSubagents:(B)=>{JX=B},setCacheKeepSustain:(B)=>{XX=B},setCacheKeepWindow:(B)=>{$X=B},clearStickyRouting:async(B)=>{J1.forget(B),l0(B),p.delete(B);let N=u1(B),D=c.delete(N);return i1.cancel(`pin:${N}`),await nZ(B,a0)||D},getStickyRouting:async(B)=>i3(P6(await M6.read(),c),B),refreshSidebar:async()=>{h9(),await S1(Y0)},refreshAllQuota:async()=>{if(await T.authority(),T.enrolled()){let B=await T.pollStale(0);return await S1(Y0),B.map((N)=>({account:N.id,ok:N.ok,...N.error!==void 0?{error:N.error}:{}}))}if(await A0.active()){let[B,N]=await Promise.all([a3(),T.pollStale(0)]);return await S1(Y0),[...B,...N.map((D)=>({account:D.id,ok:D.ok,...D.error!==void 0?{error:D.error}:{}}))]}return L8(f9())},refreshResetTargetQuota:async(B)=>{if(await T.authority(),T.enrolled())return{account:B,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};if(await A0.active()){let[D]=await a3([B]);return D??{account:B,ok:!1,error:"targeted quota refresh returned no result"}}return(await L8(f9({respectBackoff:!1}),{accountKey:B})).find((D)=>D.account===B)??{account:B,ok:!1,error:"targeted quota refresh returned no result"}}},G0){let B=G0;try{let N=await BZ(uW,B.dir,()=>pW({dir:B.dir,secureDir:B.secureDir,sweepRoot:B.sweepRoot,drain:L2,apply:async(D)=>{let R=VZ(D);if(!R)throw Error("not an /openai apply request");return P2(b,R)}}));S.set(B.dir,N)}catch{}}async function Y8(B,N,D,R,A="main",k,I,f,h=!1,i){if(!D.trim())throw S8.warn("refusing to send a request with no access token",{account:A,accountId:R}),Error(QF);if(!k&&await T.authority()!=="local")return Response.json({error:{message:r6["vault-refused"]}},{status:400});let X0=c3(B,N);if(X0.delete("x-api-key"),X0.delete("api-key"),X0.set("authorization",`Bearer ${D}`),R)X0.set("ChatGPT-Account-Id",R);X0.set(Q6.QUOTA_ACCOUNT_HEADER,A);let C=XY(X0),t=X0.get(f6)??void 0,z0=C?LF(L,C,O):void 0,_0=B instanceof URL?B:new URL(typeof B==="string"?B:B.url),j1=_0.pathname.includes("/v1/responses")||_0.pathname.includes("/chat/completions")?new URL(j):_0,N1=G2({rewriteLite:nY,applyEffort:W2,init:{...N,headers:X0},headers:X0,metadata:z0,installationID:K,websocket:Boolean(v8&&_0.pathname.endsWith("/responses")),responsesLite:J.responsesLite??!1,dumpSessionID:C}).init;if(I){let H0=()=>{if(!f)return!0;let _1=J1.accountKey(A);return Boolean(_1&&O1(f.account,_1))};if(!H0())return k?new Response(QY(GY(T),T.name),{status:401}):u9(null,"quota-unknown");let k1=()=>I.beforeDispatch(f,()=>J1.ownershipBindings(),A),L1=i===void 0?await k1():await V9(i,k1),i0=H0()?L1?.status:"absent";if(i0!=="ready")return i0==="absent"&&k?new Response(QY(GY(T),T.name),{status:401}):u9(null,"quota-unknown")}let X1=h?J1.owner():void 0,n1=I?X1?.observe(f):void 0,$1=f?.account??(!h?RZ(TZ(X,Q.statePath),{kind:"legacy",id:A,verifiedIdentity:R}):void 0);if(!h&&$1)s3.set(A,$1);let a=C&&$1&&typeof N1?.body==="string"?{sessionId:C,accountKey:$1,dispatchedAt:Date.now(),ttlMs:F4(N1.body)}:void 0;if(C)p.delete(C);if(a){if(p.set(a.sessionId,a.accountKey),p.size>256){let H0=p.keys().next().value;if(H0)p.delete(H0)}}let N0={id:A,receipt:k,migrated:h,owner:X1,probe:n1,limited:!1,complete:(H0)=>{if(N?.signal?.aborted||N0.limited)return;if(a)D4(J1.activity,a,KY(a.sessionId),H0==="ws"?{kind:H0,event:"response.completed",aborted:!1}:{kind:H0,completed:!0,failed:!1,aborted:!1});X1?.afterProbe(n1,!0,N0.limited)}},m0=j4(C??"",YX),c0=new Headers(N1?.headers),C0=h2({enabled:!["title","compaction","summary"].includes(t??""),includeSubagents:JX,headers:c0,body:N1?.body,sessionID:C}),b1=(H0)=>IZ(H0,C0&&t?C:void 0);if(m0)e3.trace("cachekeep headers",{pid:process.pid,hasParent:c0.has("x-parent-session-id"),sessionKey:C0?.sessionKey,captured:Boolean(C0),affinity:c0.get("x-session-affinity"),opencodeSession:c0.get("x-opencode-session"),sessionId:c0.get("session-id")});if(v8&&_0.pathname.endsWith("/responses")){if(S8.debug("WS transport",{pid:process.pid,pathname:_0.pathname,accountId:A}),m0&&C0)x8.track({sessionKey:C0.sessionKey,bodyText:C0.bodyText,accountId:A,isSubagent:C0.isSubagent,meta:{replayHeaders:C0.replayHeaders,chatgptAccountId:R,routingSessionId:C}});let H0=`stream:${QZ()}`;e6.set(H0,N0);let k1=new Headers(N1?.headers);k1.set(Q6.QUOTA_ACCOUNT_HEADER,H0);let L1=()=>e6.delete(H0);try{let i0=await v8(j1,{...N1,headers:k1});if(!i0.body)return L1(),b1(i0);let _1=i0.body.getReader();return b1(await F8(new Response(new ReadableStream({async pull(z6){try{let A6=await _1.read();if(A6.done)L1(),z6.close();else z6.enqueue(A6.value)}catch(A6){L1(),z6.error(c6(A6,D))}},cancel(z6){return L1(),_1.cancel(z6)}}),{status:i0.status,statusText:i0.statusText,headers:i0.headers}),D,"event-stream"))}catch(i0){throw L1(),c6(i0,D)}}let w0=Q6.withoutInternalHeaders(N1);if(typeof w0?.body!=="string")try{return await F8(await fetch(j1,w0),D,"event-stream")}catch(H0){throw c6(H0,D)}if(m0&&C0)x8.track({sessionKey:C0.sessionKey,bodyText:C0.bodyText,accountId:A,isSubagent:C0.isSubagent,meta:{replayHeaders:C0.replayHeaders,chatgptAccountId:R,routingSessionId:C}});S8.debug("HTTP transport",{pid:process.pid,pathname:_0.pathname,accountId:A});try{let H0=await fetch(j1,w0);return await j8({sessionID:C,transport:"http",phase:"http",bodyText:w0.body,accountId:A,url:j1.toString(),method:w0.method,headers:w0.headers,status:H0.status}),b1(await F8(n4(H0,(k1)=>{if(k1)N0.complete("http")}),D,"event-stream"))}catch(H0){throw await j8({sessionID:C,transport:"http",phase:"http",bodyText:w0.body,accountId:A,url:j1.toString(),method:w0.method,headers:w0.headers,error:H0 instanceof Error?H0.message:String(H0)}),c6(H0,D)}}function y8(B,N){if((N?.method??(B instanceof Request?B.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof N?.body!=="string")return!1;try{let R=B instanceof URL?B.toString():typeof B==="string"?B:B.url;return new URL(R).pathname.endsWith("/responses")}catch{return!1}}function WU(B){return Y0.peekMainForPolicy(B)?.quota}function BX(B,N){for(let D of[B?.primary?.checkedAt,B?.secondary?.checkedAt,B?.checkedAt,N])if(typeof D==="number"&&Number.isFinite(D))return D;return}function f8(B,N,D,R,A){let k=BX(B,N),I=BX(D),f=R===A&&D!=null&&(B===void 0||I!==void 0&&(k===void 0||I>k));return{quota:f?D:B,quotaCheckedAt:f?I:k,source:f?"file":"memory"}}function KX(B,N,D,R,A){let k=B?.quota,I=f8(k,B?.checkedAt,N,R,A),f=I.source,h=I.quota;if(!uZ(h,D))return{exhausted:!1};let i=cZ(h,D);if(!i)return{exhausted:!1};return{exhausted:!0,source:f,...i}}function jX(B,N){B1.debug("admission skip: exhausted account",{accountId:B,source:N.source,resetsAt:N.resetsAt})}function u9(B,N="killswitch",D,R){let A=Date.now(),k=R?R.main:Y0.getMain()?.quota,I=R?R.fallbacks:(B?.accounts??[]).filter((C)=>C.enabled!==!1&&o0(C)).map((C)=>({accountId:C.id,quota:Y0.getFallback(C.id)?.quota})),f=_Z(k,I,A,z(B));if(N==="quota-unknown")f=EZ;else if(N==="quota-exhausted"&&D!==void 0)f=Math.max(1,Math.ceil((D-A)/1000));else if(N==="mid-stream-rate-limit"&&D!==void 0){let C=Math.max(1,Math.ceil((D-A)/1000));f=Math.min(f,C)}let h=Math.floor(f/60),i=f%60,X0=N==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${h}m ${i}s.`:N==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${h}m ${i}s.`:N==="quota-unknown"?`OpenAI quota is not known yet for any available account; checking it now. Retry in ${h}m ${i}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${h}m ${i}s.`;return new Response(JSON.stringify({error:{message:X0,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(f)}})}function OY(B){let N=B?.resetCreditsAvailable;return typeof N==="number"&&Number.isFinite(N)?N:void 0}async function ZU(B){let N=z(B.storage),D=o6(N),R=Date.now(),A=Y0.peekMainForPolicy(B.mainAccountIdentity),k=f8(A?.quota,A?.checkedAt,B.sidebarState.main.quota,B.sidebarState.main.mainAccountId,B.mainAccountIdentity),I=D?l1(A?.quota,N,void 0,R):void 0,f=B.mainUnavailable?[]:[{accountId:"main",wireAccountId:B.mainAccountIdentity,access:B.primaryAccess,keepwarmAccountKey:"main",quota:k.quota,quotaCheckedAt:k.quotaCheckedAt,reservePercent:U6(N),configuredOrder:0,resetCreditsApplicable:OY(k.quota),killswitchPasses:I}],h=await K1.getUsableFallbackAccounts(B.storage);if(!B.storage)return f;for(let i of h){let X0=jY(i);if(!X0)continue;let C=B.sidebarState.fallbacks.find((j1)=>j1.id===i.id),t=Y0.peekFallbackForPolicy(i.id,i.accountId),z0=f8(t?.quota,t?.checkedAt,C?.quota,C?.accountId,i.accountId),_0=D?l1(t?.quota,N,i.id,R):void 0;f.push({accountId:i.id,wireAccountId:i.accountId,access:X0,keepwarmAccountKey:i.id,fallback:i,quota:z0.quota,quotaCheckedAt:z0.quotaCheckedAt,reservePercent:U6(N,i.id),configuredOrder:f.length,resetCreditsApplicable:OY(z0.quota),killswitchPasses:_0})}return f}function NX(B,N,D,R,A){let k=o6(z(A))?B.killswitchPasses:void 0;if(B.accountId==="main"){let i=Y0.peekMainForPolicy(B.wireAccountId),X0=f8(i?.quota,i?.checkedAt,N.main.quota,N.main.mainAccountId,B.wireAccountId);return I3({quota:X0.quota,quotaCheckedAt:X0.quotaCheckedAt,status:D,now:R,killswitchPasses:k})}let I=N.fallbacks.find((i)=>i.id===B.accountId),f=Y0.peekFallbackForPolicy(B.accountId,B.wireAccountId),h=f8(f?.quota,f?.checkedAt,I?.quota,I?.accountId,B.wireAccountId);return I3({quota:h.quota,quotaCheckedAt:h.quotaCheckedAt,status:D,now:R,killswitchPasses:k})}function UU(B){return B.accountId==="main"?"main":B.keepwarmAccountKey}function LX(B){return Y0.isRateLimited(UU(B))}function _Y(B){let N=B.candidates.filter((k)=>!LX(k)),D=new Map(N.map((k)=>[k.accountId,k])),R=new Set(B.excludeAccountIds),A=FX({vaultMode:!1,sessionId:B.sessionId,requestBytes:B.requestBytes,sidebarSnapshot:B.sidebarSnapshot,now:B.now,validPinnedAccountIds:[...D.keys()],excludeAccountIds:B.excludeAccountIds??[],quotaCheckedAtByAccount:Object.fromEntries(N.map((k)=>[k.accountId,k.quotaCheckedAt])),wireAccountIdByAccount:Object.fromEntries(N.map((k)=>[k.accountId,k.wireAccountId])),select:(k)=>{let I=N.filter((f)=>!R.has(f.accountId));if(I.length===0)return;return wW({candidates:I,pendingBytes:k,requestBytes:B.requestBytes,now:B.now,onEmptyWeightedSet:()=>{I1.debug("sticky routing: no fresh weighted candidates; using configured order")}})},persist:!0});return A?D.get(A.accountId):void 0}function FX(B){let N=void 0,D=B.validPinnedAccountIds,R=dZ(P6(B.sidebarSnapshot,c),{sessionId:B.sessionId,requestBytes:B.requestBytes,now:B.now,validPinnedAccountIds:D,excludeAccountIds:B.excludeAccountIds,quotaCheckedAtByAccount:B.quotaCheckedAtByAccount,wireAccountIdByAccount:B.wireAccountIdByAccount,choose:(k)=>{let I=B.select(k);if(!I)return;return N={accountId:I.accountId,source:I.source,pendingBytes:k.get(I.accountId)??0},I}}),A=R.assignment;if(!B.persist)return A;if(N&&A?.accountId===N.accountId)I1.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:u1(B.sessionId),accountId:N.accountId,source:N.source,requestBytes:B.requestBytes,pendingBytes:N.pendingBytes});if(A&&R.next!==void 0){let k=B.vaultMode,I=u1(B.sessionId),f=rZ(c,I,A);i1.enqueue(`pin:${I}`,"sticky-pin",async()=>{await iZ({sessionId:B.sessionId,assignment:A,validPinnedAccountIds:D},a0,{vaultMode:k,canWrite:()=>T.enrolled()===k}),f.persistedAt=Date.now()})}return A}async function HU(B,N){let D=await K1.getUsableFallbackAccounts(B),R=[];if(!B)return{current:[],retained:[],skipped:[]};for(let C of D){let t=jY(C);if(!t)continue;R.push({access:t,accountId:C.accountId,keepwarmAccountKey:C.id,quotaAccountId:C.id,fallback:C})}let A=R.filter((C)=>!Y0.isRateLimited(C.quotaAccountId)),k=z(B),I=o6(k)?A.filter((C)=>l1(Y0.peekFallbackForPolicy(C.quotaAccountId,C.accountId)?.quota,k,C.quotaAccountId,Date.now())):A,f=new Map(N.fallbacks.map((C)=>[C.id,{quota:C.quota,accountId:C.accountId}])),h=[],i=[],X0=Date.now();for(let C of I){let t=f.get(C.quotaAccountId),z0=KX(Y0.peekFallbackForPolicy(C.quotaAccountId,C.accountId),t?.quota,X0,t?.accountId,C.accountId);if(z0.exhausted)i.push({candidate:C,decision:z0});else h.push(C)}return{current:I,retained:h,skipped:i}}function DX(B,N){if(B.retained.length===0&&!N)return B.current;for(let{candidate:D,decision:R}of B.skipped)jX(D.quotaAccountId,R);return B.retained}function OX(B,N){try{let D=a1(B.headers);t6(D,N.access,N.quotaAccountId,void 0,w8(B.headers))}catch{}}async function VU(B,N,D,R){for(let A of R){let k;try{k=await Y8(B,N,A.access,A.accountId,A.keepwarmAccountKey)}catch(I){if((I instanceof Error||I instanceof DOMException)&&I.name==="AbortError")throw I;if(N?.signal?.aborted)throw I;throw I1.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:A.quotaAccountId}),I}if(!b9(k.status,z(D)))return K1.markUsed(A.fallback),{response:k,accessToken:A.access,quotaAccountId:A.quotaAccountId,activeId:A.keepwarmAccountKey};OX(k,A),k.body?.cancel().catch(()=>{})}return}async function BU(B,N,D,R,A){if(!y8(B,N))return{response:D};if(!A.length)return{response:D};let k=D,I;for(let f of A){let h;try{h=await Y8(B,N,f.access,f.accountId,f.keepwarmAccountKey)}catch(i){if((i instanceof Error||i instanceof DOMException)&&i.name==="AbortError")throw i;if(N?.signal?.aborted)throw i;return I1.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:f.quotaAccountId}),{response:k,...I}}if(k.body?.cancel().catch(()=>{}),k=h,I={accessToken:f.access,accountId:f.quotaAccountId},!b9(h.status,z(R)))return K1.markUsed(f.fallback),{response:h,...I};OX(h,f)}return{response:k,...I}}if(g0){let B=[];for(let N of g0.accounts)if(o0(N))B.push(N);Y0.seedFallbacksFromAccounts(B)}if(!n3)if(n3=!0,S1(Y0).catch(()=>{}),B0.then(()=>T.enrolled()?S1(Y0):void 0).catch(()=>{}),!T.enrolled()&&!await A0.active())UY=L8(f9({respectBackoff:!0})).catch((B)=>B1.warn("boot quota seed failed",{pid:process.pid,error:A8(B)}));else UY=Promise.resolve();k9.start(async()=>{if(await T.authority(),T.enrolled()){await S1(Y0);return}if(await A0.active()){let D=await R2(A0,await U(Q),()=>XJ(X));if(D.length>0)await S1(Y0);let R=D.filter((A)=>!A.ok);if(R.length>0)B1.warn("background pool quota poll completed with failures",{pid:process.pid,failures:R});return}let N=(await A2(f9({readSidebarState:async()=>(await M6.read()).state}))).filter((D)=>!D.ok);if(N.length>0)B1.warn("background quota refresh completed with failures",{pid:process.pid,failures:N})},(B)=>{B1.warn("background quota refresh failed",{pid:process.pid,error:B instanceof Error?B.message:String(B)})});async function qY(B,N,D,R,A,k){let I=performance.now()+H9,f=await J1.forRequest(I),h=T.enrolled(),i=h?I:void 0,X0=J1.bindings(),C=z(D).routing?.mode??"main-first",t=h?void 0:A0.peek().rows.find((a)=>a.id==="main"),z0=!t&&!h?await g():void 0,_0=!t&&z0?.type==="oauth"&&u0(z0),j1=!t&&!h&&await zY(Q,z0);if(k===k8)b8=t?.identity;let E6=await M6.get(),N1=wZ(N?.body,c3(B,N).get(f6)??void 0),X1=new URL(B instanceof Request?B.url:String(B)).pathname,{response:n1,servedId:$1}=await WW({configPath:X,warmAccountId:i3(P6(E6,c),R),source:A0,rateLimitMarks:()=>J1.marks(),limitPolicy:{pending:M0,accountKey:(a)=>J1.accountKey(a),activity:()=>R?J1.activity.get(R):void 0,currentAccountKey:()=>R?KY(R):void 0,owner:()=>J1.owner()},...h?{vault:{routes:()=>T.routes(),awaitRoster:async()=>{if(i!==void 0)await V9(i,()=>T.awaitRequestRoster())},noRouteCause:()=>GY(T),send:(a,N0)=>T.send(a,N0,{site:"model",...N?.signal?{signal:N.signal}:{}}),requestReading:(a)=>T.requestReading(a)}}:{},storage:D,mode:C,sessionId:R,requestKind:JSON.stringify([X1,N1?.kind??"auxiliary"]),routingRequest:h?N1:void 0,body:typeof N?.body==="string"?N.body:void 0,replayable:y8(B,N),now:Date.now,send:(a,N0,m0)=>Y8(B,N,N0,a.identity,a.id,m0,f,X0.find((c0)=>c0.account.accountId===a.id),!0,i),recordQuota:(a,N0,m0,c0)=>{try{let C0=a1(a.headers),b1=w8(a.headers);if(!N0.row){if(c0)T.reportUsage(N0.id,{headers:a.headers},c0),T.recordSnapshot(N0.id,C0,b1,c0).then(HX);return}t6(C0,m0,N0.id==="main"?void 0:N0.id,N0.id==="main"?N0.identity:void 0,b1)}catch{}},placePin:(a)=>FX({...a,sidebarSnapshot:E6,vaultMode:h}),blocked:(a,N0,m0)=>{if(a.reason==="no-credential"){if(j1&&!_3(m0))throw Error(H8);return new Response(_3(m0)?QY(m0,T.name):r6[_0?"missing-main":m0??"unusable"],{status:401,headers:{"content-type":"text/plain; charset=utf-8"}})}return u9(D,a.reason,a.resetAtMs,N0)},resetCredits:(a)=>OY(a==="main"?Y0.peekMainForPolicy(t?.identity)?.quota:Y0.peekFallbackForPolicy(a)?.quota),isAbort:(a)=>(a instanceof Error||a instanceof DOMException)&&a.name==="AbortError"||Boolean(N?.signal?.aborted),creditsServing:JU,log:I1});return DY(R,A,$1,C,h?T.routes().map((a)=>({id:a.id})):D?.accounts,P6(E6,c),h),n1}return x=!0,{apiKey:GF,async fetch(B,N){let D=await T.authority(),R=c3(B,N),A=XY(R),k=R.get("x-parent-session-id")?.trim()||void 0,I=D!=="local"?await H(Q):await r3(),f=z(I);if(D!=="local")return N=await u3(B,N),qY(B,N,I,A,k,++k8);let h=await g();if(await T.authority()!=="local")return N=await u3(B,N),qY(B,N,I,A,k,++k8);let i=++k8;if(h.type!=="oauth")return R.delete(f6),fetch(B,{...N,headers:R});N=await u3(B,N);let X0=(await A0.current()).active;if(t0(h)&&X0)return qY(B,N,I,A,k,i);if(X0)T.assertHostSlot(h);let C="",t=!1,z0,_0=t0(h);if(R0?.migrated()&&!_0&&h.refresh?.trim()&&d3(h).kind==="real")R0.noticeRealSlot(h.refresh);let j1=async(K0=I)=>{if(_0=!0,z0=await GX(K0),z0)C=z0.token;else C="",t=!0,I1.warn("main account in the pool has no usable token",{pid:process.pid})};if(_0)await j1();else if(u0(h))t=!0;else{if(!h.access||(h.expires??0)<Date.now()){y9.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(h.access),expiresInMs:h.expires?h.expires-Date.now():void 0});try{let K0=await LY();h.access=K0.access,h.refresh=K0.refresh,h.expires=K0.expires}catch(K0){if(t4(K0))throw K0;if(K0 instanceof V6)await j1(await U(Q))}}if(!_0)C=h.access??""}let E6=_0?xY(I):I,N1=h,X1=z0?.account.accountId??(_0?void 0:N1.accountId)??(C?Z1(W1(C)??{}):void 0);if(i===k8)b8=X1;let n1=f.routing?.mode??"main-first",$1=await M6.get(),a=$1.state;if(n1==="sticky-balanced"&&A&&y8(B,N)&&typeof N?.body==="string"){let K0=Buffer.byteLength(N.body,"utf8"),x0=await ZU({storage:E6,sidebarState:a,primaryAccess:C,mainAccountIdentity:X1,mainUnavailable:t}),b0=_Y({sessionId:A,requestBytes:K0,candidates:x0,sidebarSnapshot:$1,now:Date.now()});if(b0){let qX=LX(b0)?{action:"migrate",reason:"exhausted"}:NX(b0,a,void 0,Date.now(),I);if(qX.action==="migrate"){let Q1=_Y({sessionId:A,requestBytes:K0,candidates:x0,sidebarSnapshot:$1,excludeAccountIds:[b0.accountId],now:Date.now()});if(Q1)I1.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:u1(A),fromAccountId:b0.accountId,toAccountId:Q1.accountId,reason:qX.reason}),b0=Q1}let x1=await Y8(B,N,b0.access,b0.wireAccountId,b0.keepwarmAccountKey),PX=(Q1,T6)=>{try{let KU=a1(Q1.headers);t6(KU,T6.access,T6.accountId==="main"?void 0:T6.accountId,T6.accountId==="main"?T6.wireAccountId:void 0,w8(Q1.headers))}catch{}};PX(x1,b0);let MX=NX(b0,a,x1.status,Date.now(),I);if((x1.status===401||x1.status===403||x1.status===429)&&MX.action==="migrate"){let Q1=_Y({sessionId:A,requestBytes:K0,candidates:x0,sidebarSnapshot:$1,excludeAccountIds:[b0.accountId],now:Date.now()});if(Q1){I1.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:u1(A),fromAccountId:b0.accountId,toAccountId:Q1.accountId,reason:MX.reason});let T6=x1;x1=await Y8(B,N,Q1.access,Q1.wireAccountId,Q1.keepwarmAccountKey),T6.body?.cancel().catch(()=>{}),b0=Q1,PX(x1,b0)}}if(b0.fallback&&!b9(x1.status,f))K1.markUsed(b0.fallback);return DY(A,k,b0.accountId,n1,I?.accounts,P6($1,c)),x1}}let N0=KX(Y0.peekMainForPolicy(X1),a.main.quota,Date.now(),a.main.mainAccountId,X1),m0=o6(f)&&!l1(WU(X1),f,void 0,Date.now()),c0=Y0.isRateLimited("main"),C0,b1=()=>{return C0??=HU(E6,a),C0},w0,H0,k1=!1,L1;if(n1==="fallback-first"&&y8(B,N)){k1=!0;let K0=await b1();L1=DX(K0,!m0&&!c0&&!N0.exhausted);let x0=await VU(B,N,I,L1);if(x0)w0=x0.response,H0={accessToken:x0.accessToken,accountId:x0.quotaAccountId,activeId:x0.activeId}}if(!w0){let K0=N0.exhausted&&y8(B,N)&&(await b1()).retained.length>0;if(m0||c0||K0){let x0=m0?"killswitch":c0?"mid-stream-rate-limit":"quota-exhausted";if(x0==="quota-exhausted"&&N0.exhausted)jX("main",N0);I1.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:x0}),w0=u9(I,x0,x0==="quota-exhausted"&&N0.exhausted?N0.resetAtMs:c0?Y0.rateLimitedUntil("main"):void 0)}else w0=t?new Response(null,{status:401}):await Y8(B,N,C,X1,"main")}let i0=Boolean(H0),_1=w0,z6=H0?.accessToken??C,A6=H0?.accountId,_X=H0?.activeId??"main";if(!H0&&!k1&&b9(w0.status,f)){I1.debug("reactive fallback triggered",{pid:process.pid,status:w0.status}),L1??=DX(await b1(),!1);let K0=await BU(B,N,w0,I,L1),x0=K0.response;if(x0!==w0){if(i0=!0,_1=x0,z6=K0.accessToken??C,A6=K0.accountId,K0.accountId)_X=K0.accountId}}if(_0&&t&&!i0&&await zY(Q,await g()))throw Error(H8);try{let K0=a1(_1.headers);if(i0)t6(K0,z6,A6,void 0,w8(_1.headers));else t6(K0,C,void 0,X1,w8(_1.headers))}catch{}return DY(A,k,_X,n1,I?.accounts,P6($1,c)),_1}}},methods:w1},"chat.headers":async(g,s)=>{if(g.model.providerID!=="openai")return;if(s.headers.originator="opencode",s.headers["User-Agent"]=`${jZ(g1)} (${g3.platform()} ${g3.release()}; ${g3.arch()})`,s.headers["session-id"]=g.sessionID,x)s.headers[f6]=g.agent;if(q&&g.agent==="title")s.headers[Q6.TITLE_HEADER]="true"},"chat.params":async(g,s)=>{if(g.model.providerID!=="openai")return;s.maxOutputTokens=void 0},config:async(g)=>{W0("commands").info("registering commands",{existing:Object.keys(g.command??{}).length,pid:process.pid}),g.command={...g.command??{},[W6]:{template:W6,description:"OpenAI accounts: quota, routing, limits, cache keep-warm, diagnostics and reset credits."}}},"command.execute.before":async(g)=>{if(W0("commands").info("command hook entered",{command:g.command,hasCmdCtx:b!==null,pid:process.pid}),g.command!==W6)return;if(!b)W0("commands").warn("command rejected: context not loaded",{command:g.command,pid:process.pid}),await v9(g.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),HZ();let s=await q2(b,g.sessionID);if(eY(g.sessionID))V4(s,g.sessionID);else await v9(g.sessionID,M2(s.menu));HZ()}}}var DF=async(Y)=>{return FF(Y)},AR={id:"cortexkit-openai-auth",server:DF};
|
|
64
|
-
export{i8 as d,F1 as e,X7 as f,M1 as g,s8 as h,D1 as i,kY as j,H8 as k,j8 as l,$2 as m,U4 as n,Q2 as o,Q9 as p,G2 as q,z2 as r,nY as s,Z2 as t,U2 as u,oY as v,rY as w,sY as x,sO as y,V4 as z,L2 as A,q2 as B,P2 as C,v_ as D,y2 as E,m2 as F,H9 as G,KJ as H,O8 as I,jJ as J,LJ as K,e2 as L,n6 as M,yz as N,ZL as O,HW as P,VW as Q,NW as R,MW as S,I9 as T,y0 as U,fW as V,k3 as W,x3 as X,uW as Y,pW as Z,v3 as _,YY as $,JY as aa,hL as ba,XY as ca,QF as da,qR as ea,zF as fa,WF as ga,PR as ha,MR as ia,ER as ja,NF as ka,FF as la,DF as ma,AR as na};
|