@cortexkit/opencode-openai-auth 1.8.3 → 1.8.5
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 +8 -8
- package/dist/{codex-request-GJkvxv4S.d.ts → codex-request-By530v1D.d.ts} +3 -2
- package/dist/{index-c50p5mem.js → index-5wgxt362.js} +1 -1
- package/dist/{index-rw932qm9.js → index-8x42xzxb.js} +20 -20
- package/dist/{index-g556s1mz.js → index-95s2mw9w.js} +2 -2
- package/dist/{index-bej7x30p.js → index-a7xv52hy.js} +7 -7
- package/dist/{index-hpnj460b.js → index-byz2j6hz.js} +1 -1
- package/dist/{index-z81cged1.js → index-g5hv0tda.js} +2 -2
- package/dist/{index-yt52fztj.js → index-jh90fx7y.js} +2 -2
- package/dist/{index-p8m4yh73.js → index-kphzmgq6.js} +1 -1
- package/dist/index-n12zjwh9.js +8 -0
- package/dist/{index-0v7ar02e.js → index-rmc6hwg6.js} +1 -1
- package/dist/index-zah8t2d2.js +2 -0
- package/dist/{index-dw6yd976.js → index-zf649dj2.js} +2 -2
- package/dist/index-zne9tzy9.js +91 -0
- package/dist/index.d.ts +2 -2
- 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-DkNebAiC.d.ts → sidebar-state-CrRiE9hw.d.ts} +3 -1
- package/dist/sidebar-state.d.ts +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/{token-3vtr29vt.js → token-j2jmx8k7.js} +1 -1
- package/dist/token-util-7n2nfbyc.js +1 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/tui.d.ts +2 -21
- package/dist/v2/server.d.ts +1 -1
- package/dist/v2/server.js +2 -2
- package/package.json +2 -2
- package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +20 -6
- package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +25 -0
- package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +1 -1
- package/src/tui-compiled/raw/shared/352d228be2832bd4-hub.js +55 -5
- package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +1 -1
- package/src/tui-compiled/raw/shared/549daf371622c304-index.tsx +497 -0
- package/src/tui-compiled/raw/shared/7c97ac0cec074ae7-format.js +208 -0
- package/src/tui-compiled/raw/shared/b4ad0d49429f0096-map.js +98 -0
- package/src/tui-compiled/raw/shared/b717cdcce3966455-projection.js +90 -0
- package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +3 -1
- package/src/tui-compiled/raw/sidebar-state.js +10 -6
- package/src/tui-compiled/raw/tui.tsx +232 -623
- package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +20 -6
- package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +25 -0
- package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +1 -1
- package/src/tui-compiled/runtime/shared/352d228be2832bd4-hub.js +55 -5
- package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +1 -1
- package/src/tui-compiled/runtime/shared/549daf371622c304-index.js +550 -0
- package/src/tui-compiled/runtime/shared/7c97ac0cec074ae7-format.js +208 -0
- package/src/tui-compiled/runtime/shared/b4ad0d49429f0096-map.js +98 -0
- package/src/tui-compiled/runtime/shared/b717cdcce3966455-projection.js +90 -0
- package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +3 -1
- package/src/tui-compiled/runtime/sidebar-state.js +10 -6
- package/src/tui-compiled/runtime/tui.js +256 -893
- package/dist/index-03hs0rq7.js +0 -2
- package/dist/index-b0s5cty6.js +0 -91
- package/dist/index-fyrgwfx3.js +0 -8
- package/dist/token-util-erhrf24m.js +0 -1
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{Ab as S$,Bb as J6,Da as $X,Ea as WX,Fa as zX,Fb as I$,Ga as HX,Ha as P6,Hb as b$,Ia as i8,Ib as i$,Ja as x1,Jb as n$,Ka as JY,Kb as o$,La as n1,Lb as x3,Ma as XY,Na as QY,Oa as GY,Pa as $Y,Qa as WY,Sa as IY,Ta as bY,Ua as C6,Va as W3,Wa as z3,Xa as H3,Ya as K3,Za as U3,_a as R6,ab as v1,cb as Q6,db as E6,eb as T$,fb as R$,gb as G0,ib as UX,ja as F6,jb as mJ,ka as mX,kb as cJ,la as K$,lb as ZX,ma as a,mb as C$,nb as r4,ob as w$,pa as _$,pb as a6,qa as O3,qb as m9,ra as _3,rb as K9,sa as P$,sb as U9,ta as q$,tb as D6,ua as k3,ub as Z3,va as XX,vb as t6,wa as KY,wb as s4,xa as QX,xb as VX,ya as GX}from"./index-rw932qm9.js";import{$b as c3,Pb as pY,Rb as aX,Tb as j1,Ub as k$,Xb as x$,ac as h$,bc as v$,cc as y$,hc as c9,ic as u9,jc as g$,kc as f$,nc as m$,oc as c$,pc as u$,rc as z9,sc as H9,tc as p$,uc as l$,vc as U6,wc as d$}from"./index-03hs0rq7.js";import{$c as o4,$d as F$,Dd as c0,Ec as y1,Ed as B$,Fd as w8,Gc as j6,Gd as e6,Hd as L$,Jd as N$,Kd as s0,Mc as W9,Md as j$,Pd as fJ,Qc as j3,Qd as C0,Rd as g6,Sd as o8,Ud as F3,Vd as S8,Wc as gJ,Wd as mY,Xd as I8,Yc as K8,Yd as X9,Zc as Z$,Zd as U8,_c as M1,_d as Z6,ad as V$,ae as D$,bd as nJ,be as $3,cd as oJ,ce as D3,dd as J1,de as B1,ed as X1,ee as r0,fd as a1,fe as r1,gd as rJ,ge as HY,hd as sJ,id as aJ,jd as tJ,je as O$,kd as eJ,ke as q6,ld as YX,le as T1,md as n8,me as R1,nd as X6,ne as P3,od as y6,oe as Z8,pd as SG,pe as E$,qe as q3,rd as sX,re as E3,te as M$,ue as M3,ve as yY,we as A3,xd as JX,xe as T3,ye as R3}from"./index-b0s5cty6.js";import{De as Q9}from"./index-fyrgwfx3.js";import{Je as xX,Ke as hX,Le as vX,Me as t3,Ne as U$,Oe as A1,Pe as e3,Qe as Y2}from"./index-z81cged1.js";import{$e as H0,Xe as EX,Ze as J9,ff as h6,hf as KX}from"./index-dw6yd976.js";import{if as L1,jf as J8,mf as OX,nf as _X,of as LY,pf as PX,sf as qX}from"./index-g556s1mz.js";import{uf as yX,wf as A$}from"./index-c50p5mem.js";import{yf as oY}from"./index-hpnj460b.js";import{createHash as OB,randomUUID as _B}from"node:crypto";import{statSync as PB}from"node:fs";import l4 from"node:os";import{readFile as TW}from"node:fs/promises";import{readFileSync as KW,statSync as UW}from"node:fs";import{homedir as ZW,tmpdir as VW}from"node:os";import{join as u8}from"node:path";var BW="https://chatgpt.com/backend-api/codex/responses",SJ=536870912,LW=H0("config"),IJ=!1,NW="openai-auth.json",Y1={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 jW(){let Y=process.env[Y1.configDir]?.trim();if(Y)return Y;return u8(process.env.XDG_CONFIG_HOME||u8(ZW(),".config"),"opencode")}function Y0(){return process.env[Y1.configFile]?.trim()||u8(jW(),NW)}function bJ(){try{let Y=JSON.parse(KW(Y0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function kJ(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 r6(Y,J,X){let Q=kJ(Y);if(Q!==void 0)return Q;if(typeof J==="boolean")return J;return X}function FW(Y){let J=process.env[Y1.dumpMaxBytes],X=J??Y;if(X===void 0)return SJ;let Q=J?.trim()?Number(J):X;if(typeof Q==="number"&&Number.isSafeInteger(Q)&&Q>=0)return Q;if(!IJ)IJ=!0,LW.warn("Invalid dumpMaxBytes; using the default 512 MiB cap",{env:Y1.dumpMaxBytes});return SJ}function xJ(Y){if(typeof Y.dump==="boolean")return Y.dump;if(Y.dump&&typeof Y.dump==="object")return Y.dump.enabled;return}var o1;function s6(){let Y=kJ(Y1.dump);if(Y!==void 0)return Y;let J=Y0(),X;try{X=UW(J)}catch{}if(o1?.path===J&&o1.mtimeMs===X?.mtimeMs&&o1.ctimeMs===X?.ctimeMs&&o1.size===X?.size)return o1.enabled;let Q=r6(Y1.dump,xJ(bJ()),!1);return o1={path:J,mtimeMs:X?.mtimeMs,ctimeMs:X?.ctimeMs,size:X?.size,enabled:Q},Q}function DW(){let Y=bJ();return{webSockets:r6(Y1.webSockets,Y.webSockets,!1),rawWebSocket:r6(Y1.rawWebSocket,Y.rawWebSocket,!1),responsesLite:r6(Y1.responsesLite,Y.responsesLite,!1),dump:r6(Y1.dump,xJ(Y),!1),dumpDir:process.env[Y1.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():u8(VW(),"opencode-openai-auth-dumps")),dumpMaxBytes:FW(Y.dumpMaxBytes),codexApiEndpoint:process.env[Y1.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():BW)}}var c8;function o0(){if(!c8)c8=DW();return c8}function hJ(){return c8=void 0,o1=void 0,o0()}import{readFileSync as OW}from"node:fs";var _W="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 PW(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 O6(Y,J={}){return F6({provider:"openai",configPath:Y.configPath,statePath:Y.statePath,quota:j6,...J})}function zY(Y){try{let J=JSON.parse(OW(Y,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return!1;return a6(J).migratedAt!==void 0}catch{return!1}}async function p8(Y,J){if(!zY(Y.configPath))return;let X=await J.read();return X.status==="ready"?X.rows:void 0}function l8(Y,J){if(Y===B1)return _W;if(a6(J.config).pending?.rowId===Y)return PW(Y);return}function qW(Y,J){return D6(Y,B1,J.legacyLocks).filter((X)=>X.name===t6)}function E1(Y,J={}){return qW(Y,J)}var _6="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 s1 extends Error{constructor(){super("The main OpenAI account lives in the account pool");this.name="MainAccountInPoolError"}}async function vJ(Y){let J=Y.storage,X=r1(J);if(!J||!X||c0(X))return;let Q=X,G=Y.now(),$=(J.refresh?.refreshBeforeExpiryMinutes??240)*60000;if((!Q.access||!Q.expires||Q.expires-G<=$)&&!M1(Q.lastRefreshError,Q.refresh,G))try{Q=await Y.refreshAccount(Q,J)}catch(K){Y.warn?.("pool main row refresh failed",{error:K instanceof Error?K.message:String(K)})}let H=Q.access?.trim();if(!H)return;if(typeof Q.expires!=="number"||Q.expires<=Y.now())return;return{account:Q,token:H}}import{readFile as uJ}from"node:fs/promises";function d8(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}async function pJ(Y){let J=await fJ(Y.configPath),X=[];try{let G=JSON.parse(await uJ(Y.statePath,"utf8"));if(d8(G)){let $=G.accounts;if(d8($))X=Object.keys($)}}catch(G){if(G.code!=="ENOENT")throw G}return{rosterIds:J?[...J]:[],stateIds:X,orphanStateIds:J?X.filter((G)=>!J.has(G)):[]}}async function EW(Y){try{let J=JSON.parse(await uJ(Y.configPath,"utf8"));return d8(J)&&d8(J.claustrum)&&J.claustrum.mode==="claustrum"}catch{return!1}}var yJ="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 lJ(Y){if(!Y)return;let J=Y.accounts.find((X)=>X.id==="main"&&s0(X));if(J)return J;if(!Y.mainAccountId)return;return Y.accounts.find((X)=>s0(X)&&X.accountId===Y.mainAccountId)}function MW(Y,J){let X=Y.lastRefreshError;return M1(X,Y.refresh,J)&&X!==void 0&&X.nextRetryAt!==void 0&&X.nextRetryAt-X.checkedAt>=gJ}function AW(Y){let J=[],X=[],Q=Y.now??Date.now(),G=lJ(Y.storage),$=!1;if(c0(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. ${yJ}`});else if(r0(Y.auth)){if(!r1(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."}),$=!0;else if(Y.auth.type!=="oauth")J.push({code:"auth-slot-not-oauth",message:"OpenCode's OpenAI auth slot is not OAuth."}),$=!0;else if(G&&(!Y.auth.refresh||G.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."}),$=!0;if($&&G){let K={type:"restore-main-credential"};X.push(K);let U=J.find((V)=>V.code==="auth-slot-missing"||V.code==="auth-slot-not-oauth"||V.code==="main-refresh-not-in-store");if(U)U.repair=K}let W=Y.storage?.accounts??[];if(W.length===0)J.push({code:"no-accounts",message:"The account store has no accounts."});else if(!W.some((K)=>K.enabled!==!1))J.push({code:"no-enabled-accounts",message:"The account store has no enabled accounts."});for(let K of W){if(!s0(K)||!c0(K))continue;J.push({code:"tombstoned-account",accountId:K.id,message:`Account ${K.id} holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${yJ}`})}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 K of W){if(!s0(K))continue;if(!MW(K,Q))continue;let U={type:"clear-refresh-backoff",accountId:K.id};X.push(U),J.push({code:"armed-non-transient-refresh-backoff",accountId:K.id,message:`Account ${K.id} has an armed non-transient refresh backoff.`,repair:U})}let H=[...Y.orphanStateIds??[]];if(H.length>0){let K={type:"prune-orphan-state-ids",ids:H};X.push(K),J.push({code:"orphan-state-ids",message:`State contains ids absent from the config roster: ${H.join(", ")}.`,repair:K})}return{findings:J,repairs:X}}function dJ(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(r0(await Y.readAuth()))return;let Q=lJ(await Y.loadAccounts(Y.paths));if(!Q)return;await Y.setMainAuth({refresh:Q.refresh,access:Q.access??"",expires:Q.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((Q)=>Q,Y.paths)}};return{label:`Clear the refresh backoff of ${X.accountId}`,apply:async()=>{await Y.mutateAccounts((Q)=>{let G=Q.accounts.find(($)=>$.id===X.accountId&&s0($));if(G)G.lastRefreshError=void 0;return Q},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(),EW(Y.paths)]),W=AW({auth:G.type==="missing"?void 0:G,storage:X,orphanStateIds:Q.orphanStateIds,retiredCustodyMode:$,now:Y.now()}),H=await F6({provider:"openai",quota:j6,configPath:Y.paths.configPath,statePath:Y.paths.statePath}).read();if(H.status==="ready")for(let K of H.rows){if(K.disabledReason!==mJ)continue;W.findings.push({code:"slot-transfer-origin-unknown",accountId:K.id,message:`Account ${K.id} was preserved disabled after an interrupted transfer with an untagged placeholder; sole ownership could not be established. ${cJ}`})}return W.findings.map((K)=>{let U=K.repair?J(K.repair):void 0;return{code:K.code,message:K.message,...K.accountId!==void 0?{accountId:K.accountId}:{},...U?{repair:U}:{}}})}}]}var RW=KX,iJ="OpenAI accounts",CW="ChatGPT accounts in the vault",wW="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 SW(){let{redirectUri:Y}=await aJ(),J=await oJ(),X=nJ(crypto.getRandomValues(new Uint8Array(32)).buffer),Q=rJ(Y,J,X),G=tJ(J,X);return{url:Q,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let $=await G;return{type:"success",refresh:$.refresh_token,access:$.access_token,expires:Date.now()+($.expires_in??3600)*1000,accountId:a1($)}}finally{sJ(X)}}}}async function IW(Y){let{deviceData:J,url:X,instructions:Q}=await eJ(Y);return{url:X,instructions:Q,method:"auto",async callback(){try{let G=await YX(J,Y);return{type:"success",refresh:G.refresh_token,access:G.access_token,expires:Date.now()+(G.expires_in??3600)*1000,accountId:a1(G)}}catch{return{type:"failed"}}}}}function BX({client:Y,getAuth:J,getPaths:X=()=>G0(Y0()),fetchImpl:Q=fetch,packageVersion:G=A1,dependencies:$,onMainSlotWritten:W,vault:H}){let K={authorizeBrowser:$?.authorizeBrowser??SW,authorizeHeadless:$?.authorizeHeadless??(()=>IW(G)),beginAccountLogin:$?.beginAccountLogin??n8,loadAccounts:$?.loadAccounts??C0,mutateAccounts:$?.mutateAccounts??o8,readStoreIds:$?.readStoreIds??pJ,openBrowser:$?.openBrowser??RW,now:$?.now??Date.now,openAccountPool:$?.openAccountPool??O6,migrationBlockers:$?.migrationBlockers??(async()=>{let j=await E6({currentVersion:G});return j.open?[]:j.blockers.map((w)=>({pid:w.pid,version:w.version}))}),...$?.terminal?{terminal:$.terminal}:{},...$?.vaultWait?{vaultWait:$.vaultWait}:{}},U=async()=>await J?.().catch(()=>{return})??{type:"missing"},V=async()=>{if(H&&await H.authority()!=="local")return!0;if((await U()).type!=="missing")return!0;let j=X(),w=K.openAccountPool(j);if((await w.read()).status==="ready")return WX(w);return((await K.loadAccounts(j))?.accounts.length??0)>0},O=async(j)=>{if(await ZX(X().configPath,async()=>{if(H&&await H.authority()!=="local")return!1;if(r0(await U()))return!1;return await Y.auth.set({path:{id:"openai"},body:{type:"oauth",...j}}),!0}))await W?.().catch(()=>{})},L=(j)=>({begin:async({headless:w,signal:v})=>{if(H&&await H.authority()!=="local")throw Error(P6);let M=await K.beginAccountLogin({version:G,headless:w,...v?{signal:v}:{}});return{url:M.url,instructions:M.instructions,completion:M.completion.then(async(g)=>{if(H&&await H.authority()!=="local")throw Error(P6);let o=await j.read(),i=o.status==="ready"?o.rows.find((B0)=>B0.id===B1)?.identity:void 0;if(g.accountId&&i&&g.accountId===i)throw Error("that account is already the OpenCode main credential");return{id:g.id,credential:{type:"oauth",refresh:g.refresh,...g.access!==void 0?{access:g.access}:{},...g.expires!==void 0?{expires:g.expires}:{}},...g.accountId!==void 0?{identity:g.accountId}:{},...g.label!==void 0?{label:g.label}:{}}})}},openBrowser:(w)=>K.openBrowser(w)}),B=async(j)=>{if(H&&await H.authority()!=="local")throw Error(P6);let w=j.credential;if(w?.type!=="oauth"||!w.access)throw Error("no usable access token for a quota check");let v=await e6({accessToken:w.access,fetchImpl:Q,now:K.now,...j.identity?{accountId:j.identity}:{},accountKey:j.id});return q6(v,K.now(),!0)},D=(j)=>dJ({paths:X(),migrated:j,readAuth:U,loadAccounts:K.loadAccounts,readStoreIds:K.readStoreIds,mutateAccounts:K.mutateAccounts,setMainAuth:O,now:K.now}),q=(j,w)=>({title:iJ,store:JY(w,{rowLocks:(v)=>D6(j,v)}),...K.terminal?{terminal:K.terminal}:{},login:L(w),protect:(v,M)=>l8(v,M),extraLocks:E1(j),pollQuota:B,doctor:D(!0),status:async()=>{let v=await H?.status();if(H&&await H.authority()!=="local"&&v)return[KY(H.host,H.name,v.enrollment)];return[`Routing: ${(await K.loadAccounts(j))?.routing?.mode??"main-first"}`,...H?[KY(H.host,H.name,(await H.status()).enrollment)]:[]]},...H?{extraActions:[E(H)]}:{}}),E=(j)=>{let w=j.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(v)=>{let M=await j.authority();if(w){if(M!=="local")await j.disconnect();v.print("Disconnected from the Claustrum vault.");return}if(M!=="local"){v.print("Nothing was changed: this host is already connected or its enrollment is unreadable. Reopen the menu to disconnect.");return}v.print(`Asking the Claustrum vault to enroll ${j.name}…`);let g,o=await j.waitForApproval({...K.vaultWait,onPending:(i)=>{let V0=i.state==="pending"?i.requestId??i.retryCode??"":i.state;if(V0===g)return;g=V0;for(let B0 of XX(j.name,i))v.print(B0);v.print("Waiting for the approval… (stop with Ctrl-C; Connect picks the request up again)")}});v.print(QX(j,o).text)}}},T=async()=>{let j=await K.migrationBlockers();return $X({title:iJ,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.",...j.length>0?["These processes still hold the move back:",...j.map((w)=>` ${w.pid==="unknown"?"processes that could not be read":`pid ${w.pid}`}: version ${w.version}`)]:[]],actions:[GX({checks:D(!1)})],...K.terminal?{terminal:K.terminal}:{}})},I=async(j)=>{let w=X(),v=K.openAccountPool(w);if(H&&await H.authority()!=="local")return i8(q(w,v),H);if(await p8(w,v)===void 0)return T();let M=q(w,v);return H?i8(M,H):zX(M)},x=(j)=>async()=>{if(H&&await H.authority()!=="local")throw Error(P6);let w=await j();if(w.method!=="auto")return w;return{...w,callback:async()=>{let v=await w.callback();if(H&&await H.authority()!=="local")return{type:"failed"};return v}}};return[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:HX({hasCredential:V,openMenu:I,login:x(()=>K.authorizeBrowser())})},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:x(()=>K.authorizeHeadless())},{label:"Manually enter API Key",type:"api"},...H?.enrolled()?[{label:CW,type:"oauth",authorize:async()=>({url:"",instructions:wW,method:"auto",callback:async()=>{if(await JX(H.paths,H.name)!=="vault")return{type:"failed"};try{let j=JSON.parse(await TW(VX(),"utf8"));if(!j||typeof j!=="object"||Array.isArray(j)||Object.hasOwn(j,"openai"))return{type:"failed"}}catch(j){if(j.code!=="ENOENT")return{type:"failed"}}return{...UX,type:"success"}}})}]:[]]}var UY=["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 t1(Y){let J={};for(let X of UY)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 sW}from"node:crypto";import{createHash as bW,randomBytes as LX}from"node:crypto";import{chmod as kW,lstat as NX,mkdir as xW,open as hW,readdir as MX,rename as vW,unlink as NY,writeFile as yW}from"node:fs/promises";import{join as r8,resolve as ZY}from"node:path";var gW=100,VY="session-unknown",fW=300000,mW=60000,cW=600000,uW=/\.(body|meta|request|response)\.json$/,pW=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-\d+-\d{6,}-[a-zA-Z0-9._-]+$/,lW=/\.[a-f0-9]{24}\.partial$/;function AX(Y){let J=Y.replace(uW,"");if(J===Y||!pW.test(J))return;return J}function dW(Y){let J=Y.replace(lW,"");return J!==Y&&AX(J)!==void 0}async function jX(Y){let{dir:J,maxBytes:X}=Y,Q=Y.now??Date.now(),G=Y.minAgeMs??mW,$=Y.partialStaleMs??cW,W={removed:0,freedBytes:0};if(!(X>0))return W;try{if(L1)await OX(J,"directory");if((await NX(J)).isSymbolicLink())return W;let H=new Set((Y.protectedPaths??[]).map((E)=>ZY(E))),K=await MX(J,{withFileTypes:!0}),U=[];await Promise.all(K.map(async(E)=>{if(!E.isFile())return;let T=dW(E.name),I=T?void 0:AX(E.name);if(!T&&I===void 0)return;let x=r8(J,E.name);try{let j=await NX(x);if(!j.isFile())return;U.push({path:x,size:j.size,mtimeMs:j.mtimeMs,group:I})}catch{}}));let V=U.reduce((E,T)=>E+T.size,0),O=0,L=0,B=async(E)=>{try{await NY(E.path),V-=E.size,L+=E.size,O+=1}catch{}};for(let E of U){if(E.group!==void 0)continue;if(H.has(ZY(E.path)))continue;if(Q-E.mtimeMs<$)continue;await B(E)}let D=new Map;for(let E of U){if(E.group===void 0)continue;let T=D.get(E.group)??{files:[],newest:0};T.files.push(E),T.newest=Math.max(T.newest,E.mtimeMs),D.set(E.group,T)}let q=[...D.entries()].sort(([E,T],[I,x])=>T.newest-x.newest||E.localeCompare(I));for(let[,E]of q){if(V<=X)break;if(Q-E.newest<G)continue;if(E.files.some((T)=>H.has(ZY(T.path))))continue;for(let T of E.files)await B(T)}if(O>0)Y.logger?.debug("removed old dump files",{removed:O,freedBytes:L});return{removed:O,freedBytes:L}}catch(H){if(H instanceof J8&&H.code==="ERR_PRIVATE_FILES_SECURITY")throw H;return W}}async function iW(Y,J,X){if(L1)return qX(Y,J,{stagePath:`${Y}.${X?X():LX(12).toString("hex")}.partial`});for(let Q=0;;Q+=1){let G=`${Y}.${X?X():LX(12).toString("hex")}.partial`,$=!1,W;try{W=await hW(G,"wx",384),$=!0,await W.writeFile(J,"utf8"),await W.chmod(384),await W.close(),W=void 0,await vW(G,Y);return}catch(H){if(await W?.close().catch(()=>{}),$)await NY(G).catch(()=>{});if(H.code==="EEXIST"&&Q===0)continue;throw H}}}function BY(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function Y8(Y,J){let X=Y.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!X)return J;return X.slice(0,80)}function FX(Y){return bW("sha256").update(Y).digest("hex")}function nW(Y){return Y.toLowerCase().replace(/[-_]/g,"")}function DX(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function oW(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 Q=Y.length-1,G=J.length-1;while(Q>=X&&G>=X&&Y[Q]===J[G])Q--,G--;return{changed:!0,firstByte:X,lastPreviousByte:Q,lastCurrentByte:G,changedPreviousBytes:Q-X+1,changedCurrentBytes:G-X+1,previousBytes:Y.length,currentBytes:J.length}}var rW=0;function TX(Y){let J=Y.enabled===!0,X=Y.pid??process.pid,Q=Y.now??Date.now,G=Y.logger,$=new Set((Y.secretKeys??[]).map(nW)),W=EX({extraSecretKeys:(M)=>$.has(M),extraValuePatterns:[...Y.secretPatterns??[]]}),H=new Set(Y.schemaKeys??["tools"]),K=new Map,U=()=>typeof Y.dir==="function"?Y.dir():Y.dir;function V(M){let g=W.redact({[M]:null})[M];return g===null?void 0:g}function O(M){if(Array.isArray(M))return M.map(O);if(DX(M)){let g={};for(let[o,i]of Object.entries(M)){let V0=V(o);if(H.has(o))g[o]=W.redactStrings(i);else if(V0!==void 0)g[o]=V0;else g[o]=O(i)}return g}return W.redactStrings(M)}function L(M){let g;try{g=JSON.parse(M)}catch{return{text:W.redactStrings(M),parsed:void 0}}let o=O(g),i=JSON.stringify(o);return{text:JSON.stringify(g)===i?M:i,parsed:DX(o)?o:void 0}}async function B(M,g,o,i){let V0=`-${Y8(g,VY)}-${Y8(o,"channel")}`,B0;try{B0=await MX(M)}catch{return}let p=B0.filter((t)=>t.endsWith(".meta.json")&&t.includes(V0)).sort().reverse();for(let t of p)try{if(JSON.parse(await LY(r8(M,t),L1))?.baselineKey!==i)continue;return await LY(r8(M,t.replace(/\.meta\.json$/,".body.json")),L1)}catch(L0){if(L0 instanceof J8&&(L1||L0.code==="ERR_PRIVATE_FILES_SECURITY"))throw L0}return}function D(M,g){if(!K.has(M))while(K.size>=gW){let o=K.keys().next().value;if(o===void 0)break;K.delete(o)}K.set(M,g)}async function q(M){if(!J)return;let g=++rW,o=M.session?.trim()||VY,i=U(),V0=new Date(Q()).toISOString(),B0=[V0.replace(/[:.]/g,"-"),String(X),String(g).padStart(6,"0"),Y8(o,VY),Y8(M.channel,"channel"),...M.phase?[Y8(M.phase,"phase")]:[]].join("-"),p=r8(i,B0),t={body:`${p}.body.json`,metadata:`${p}.meta.json`,request:`${p}.request.json`},L0=FX(`${M.channel}\x00${o}`);try{if(L1)await _X(i);else await xW(i,{recursive:!0,mode:448}),await kW(i,448);let h=K.get(L0),x0=h===void 0?void 0:"memory";if(h===void 0){if(h=await B(i,o,M.channel,L0),h!==void 0)x0="disk"}let R0=L(M.bodyText),U0={id:B0,createdAt:V0,pid:X,session:BY(o),channel:M.channel,...M.phase?{phase:M.phase}:{},accountId:M.accountId,status:M.status,error:M.error===void 0?void 0:W.redactStrings(M.error),baselineKey:L0,bodyBytes:Buffer.byteLength(M.bodyText,"utf8"),bodyHash:FX(M.bodyText),diff:oW(h,R0.text),baselineSource:x0,body:R0.parsed?{parseable:!0,...Y.summarize?.(R0.parsed)}:{parseable:!1},...M.meta?{extra:O(M.meta)}:{},files:t},r=O({url:M.url,method:M.method,accountId:M.accountId,headers:M.headers===void 0?void 0:Object.fromEntries(new Headers(M.headers).entries())}),E0=(d,y)=>L1?PX(d,y):yW(d,y,{encoding:"utf8",mode:384,flag:"wx"}),l=[[t.body,R0.text],[t.metadata,`${JSON.stringify(U0,null,2)}
|
|
1
|
+
import{$a as R6,Bb as S$,Cb as J6,Ea as $X,Fa as WX,Ga as zX,Gb as I$,Ha as HX,Ia as P6,Ib as b$,Ja as i8,Jb as i$,Ka as x1,Kb as n$,La as JY,Lb as o$,Ma as n1,Mb as x3,Na as XY,Oa as QY,Pa as GY,Qa as $Y,Ra as WY,Ta as IY,Ua as bY,Va as C6,Wa as W3,Xa as z3,Ya as H3,Za as K3,_a as U3,bb as v1,db as Q6,eb as E6,fb as T$,gb as R$,hb as G0,ja as F6,jb as UX,ka as mX,kb as mJ,la as K$,lb as cJ,ma as a,mb as ZX,nb as C$,ob as r4,pa as _$,pb as w$,qb as a6,ra as O3,rb as m9,sa as _3,sb as K9,ta as P$,tb as U9,ua as q$,ub as D6,va as k3,vb as Z3,wa as XX,wb as t6,xa as KY,xb as s4,ya as QX,yb as VX,za as GX}from"./index-8x42xzxb.js";import{Qb as pY,Sb as aX,Ub as j1,Vb as k$,Yb as x$,ac as c3,bc as h$,cc as v$,dc as y$,ic as c9,jc as u9,kc as g$,lc as f$,oc as m$,pc as c$,qc as u$,sc as z9,tc as H9,uc as p$,vc as l$,wc as U6,xc as d$}from"./index-zah8t2d2.js";import{$c as M1,$d as Z6,Ed as c0,Fc as y1,Fd as B$,Gd as w8,Hc as j6,Hd as e6,Id as L$,Kd as N$,Ld as s0,Nc as W9,Nd as j$,Qd as fJ,Rc as j3,Rd as C0,Sd as g6,Td as o8,Vd as F3,Wd as S8,Xc as gJ,Xd as mY,Yd as I8,Zc as K8,Zd as X9,_c as Z$,_d as U8,ad as o4,ae as F$,bd as V$,be as D$,cd as nJ,ce as $3,dd as oJ,de as D3,ed as J1,ee as B1,fd as X1,fe as r0,gd as a1,ge as r1,hd as rJ,he as HY,id as sJ,jd as aJ,kd as tJ,ke as O$,ld as eJ,le as q6,md as YX,me as T1,nd as n8,ne as R1,od as X6,oe as P3,pd as y6,pe as Z8,qd as SG,qe as E$,re as q3,sd as sX,se as E3,ue as M$,ve as M3,we as yY,xe as A3,yd as JX,ye as T3,ze as R3}from"./index-zne9tzy9.js";import{Ee as Q9}from"./index-n12zjwh9.js";import{Ke as xX,Le as hX,Me as vX,Ne as t3,Oe as U$,Pe as A1,Qe as e3,Re as Y2}from"./index-g5hv0tda.js";import{Ye as EX,_e as J9,af as H0,gf as h6,if as KX}from"./index-zf649dj2.js";import{jf as L1,kf as J8,nf as OX,of as _X,pf as LY,qf as PX,tf as qX}from"./index-95s2mw9w.js";import{vf as yX,xf as A$}from"./index-5wgxt362.js";import{zf as oY}from"./index-byz2j6hz.js";import{createHash as OB,randomUUID as _B}from"node:crypto";import{statSync as PB}from"node:fs";import l4 from"node:os";import{readFile as TW}from"node:fs/promises";import{readFileSync as KW,statSync as UW}from"node:fs";import{homedir as ZW,tmpdir as VW}from"node:os";import{join as u8}from"node:path";var BW="https://chatgpt.com/backend-api/codex/responses",SJ=536870912,LW=H0("config"),IJ=!1,NW="openai-auth.json",Y1={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 jW(){let Y=process.env[Y1.configDir]?.trim();if(Y)return Y;return u8(process.env.XDG_CONFIG_HOME||u8(ZW(),".config"),"opencode")}function Y0(){return process.env[Y1.configFile]?.trim()||u8(jW(),NW)}function bJ(){try{let Y=JSON.parse(KW(Y0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function kJ(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 r6(Y,J,X){let Q=kJ(Y);if(Q!==void 0)return Q;if(typeof J==="boolean")return J;return X}function FW(Y){let J=process.env[Y1.dumpMaxBytes],X=J??Y;if(X===void 0)return SJ;let Q=J?.trim()?Number(J):X;if(typeof Q==="number"&&Number.isSafeInteger(Q)&&Q>=0)return Q;if(!IJ)IJ=!0,LW.warn("Invalid dumpMaxBytes; using the default 512 MiB cap",{env:Y1.dumpMaxBytes});return SJ}function xJ(Y){if(typeof Y.dump==="boolean")return Y.dump;if(Y.dump&&typeof Y.dump==="object")return Y.dump.enabled;return}var o1;function s6(){let Y=kJ(Y1.dump);if(Y!==void 0)return Y;let J=Y0(),X;try{X=UW(J)}catch{}if(o1?.path===J&&o1.mtimeMs===X?.mtimeMs&&o1.ctimeMs===X?.ctimeMs&&o1.size===X?.size)return o1.enabled;let Q=r6(Y1.dump,xJ(bJ()),!1);return o1={path:J,mtimeMs:X?.mtimeMs,ctimeMs:X?.ctimeMs,size:X?.size,enabled:Q},Q}function DW(){let Y=bJ();return{webSockets:r6(Y1.webSockets,Y.webSockets,!1),rawWebSocket:r6(Y1.rawWebSocket,Y.rawWebSocket,!1),responsesLite:r6(Y1.responsesLite,Y.responsesLite,!1),dump:r6(Y1.dump,xJ(Y),!1),dumpDir:process.env[Y1.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():u8(VW(),"opencode-openai-auth-dumps")),dumpMaxBytes:FW(Y.dumpMaxBytes),codexApiEndpoint:process.env[Y1.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():BW)}}var c8;function o0(){if(!c8)c8=DW();return c8}function hJ(){return c8=void 0,o1=void 0,o0()}import{readFileSync as OW}from"node:fs";var _W="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 PW(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 O6(Y,J={}){return F6({provider:"openai",configPath:Y.configPath,statePath:Y.statePath,quota:j6,...J})}function zY(Y){try{let J=JSON.parse(OW(Y,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return!1;return a6(J).migratedAt!==void 0}catch{return!1}}async function p8(Y,J){if(!zY(Y.configPath))return;let X=await J.read();return X.status==="ready"?X.rows:void 0}function l8(Y,J){if(Y===B1)return _W;if(a6(J.config).pending?.rowId===Y)return PW(Y);return}function qW(Y,J){return D6(Y,B1,J.legacyLocks).filter((X)=>X.name===t6)}function E1(Y,J={}){return qW(Y,J)}var _6="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 s1 extends Error{constructor(){super("The main OpenAI account lives in the account pool");this.name="MainAccountInPoolError"}}async function vJ(Y){let J=Y.storage,X=r1(J);if(!J||!X||c0(X))return;let Q=X,G=Y.now(),$=(J.refresh?.refreshBeforeExpiryMinutes??240)*60000;if((!Q.access||!Q.expires||Q.expires-G<=$)&&!M1(Q.lastRefreshError,Q.refresh,G))try{Q=await Y.refreshAccount(Q,J)}catch(K){Y.warn?.("pool main row refresh failed",{error:K instanceof Error?K.message:String(K)})}let H=Q.access?.trim();if(!H)return;if(typeof Q.expires!=="number"||Q.expires<=Y.now())return;return{account:Q,token:H}}import{readFile as uJ}from"node:fs/promises";function d8(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}async function pJ(Y){let J=await fJ(Y.configPath),X=[];try{let G=JSON.parse(await uJ(Y.statePath,"utf8"));if(d8(G)){let $=G.accounts;if(d8($))X=Object.keys($)}}catch(G){if(G.code!=="ENOENT")throw G}return{rosterIds:J?[...J]:[],stateIds:X,orphanStateIds:J?X.filter((G)=>!J.has(G)):[]}}async function EW(Y){try{let J=JSON.parse(await uJ(Y.configPath,"utf8"));return d8(J)&&d8(J.claustrum)&&J.claustrum.mode==="claustrum"}catch{return!1}}var yJ="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 lJ(Y){if(!Y)return;let J=Y.accounts.find((X)=>X.id==="main"&&s0(X));if(J)return J;if(!Y.mainAccountId)return;return Y.accounts.find((X)=>s0(X)&&X.accountId===Y.mainAccountId)}function MW(Y,J){let X=Y.lastRefreshError;return M1(X,Y.refresh,J)&&X!==void 0&&X.nextRetryAt!==void 0&&X.nextRetryAt-X.checkedAt>=gJ}function AW(Y){let J=[],X=[],Q=Y.now??Date.now(),G=lJ(Y.storage),$=!1;if(c0(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. ${yJ}`});else if(r0(Y.auth)){if(!r1(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."}),$=!0;else if(Y.auth.type!=="oauth")J.push({code:"auth-slot-not-oauth",message:"OpenCode's OpenAI auth slot is not OAuth."}),$=!0;else if(G&&(!Y.auth.refresh||G.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."}),$=!0;if($&&G){let K={type:"restore-main-credential"};X.push(K);let U=J.find((V)=>V.code==="auth-slot-missing"||V.code==="auth-slot-not-oauth"||V.code==="main-refresh-not-in-store");if(U)U.repair=K}let W=Y.storage?.accounts??[];if(W.length===0)J.push({code:"no-accounts",message:"The account store has no accounts."});else if(!W.some((K)=>K.enabled!==!1))J.push({code:"no-enabled-accounts",message:"The account store has no enabled accounts."});for(let K of W){if(!s0(K)||!c0(K))continue;J.push({code:"tombstoned-account",accountId:K.id,message:`Account ${K.id} holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${yJ}`})}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 K of W){if(!s0(K))continue;if(!MW(K,Q))continue;let U={type:"clear-refresh-backoff",accountId:K.id};X.push(U),J.push({code:"armed-non-transient-refresh-backoff",accountId:K.id,message:`Account ${K.id} has an armed non-transient refresh backoff.`,repair:U})}let H=[...Y.orphanStateIds??[]];if(H.length>0){let K={type:"prune-orphan-state-ids",ids:H};X.push(K),J.push({code:"orphan-state-ids",message:`State contains ids absent from the config roster: ${H.join(", ")}.`,repair:K})}return{findings:J,repairs:X}}function dJ(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(r0(await Y.readAuth()))return;let Q=lJ(await Y.loadAccounts(Y.paths));if(!Q)return;await Y.setMainAuth({refresh:Q.refresh,access:Q.access??"",expires:Q.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((Q)=>Q,Y.paths)}};return{label:`Clear the refresh backoff of ${X.accountId}`,apply:async()=>{await Y.mutateAccounts((Q)=>{let G=Q.accounts.find(($)=>$.id===X.accountId&&s0($));if(G)G.lastRefreshError=void 0;return Q},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(),EW(Y.paths)]),W=AW({auth:G.type==="missing"?void 0:G,storage:X,orphanStateIds:Q.orphanStateIds,retiredCustodyMode:$,now:Y.now()}),H=await F6({provider:"openai",quota:j6,configPath:Y.paths.configPath,statePath:Y.paths.statePath}).read();if(H.status==="ready")for(let K of H.rows){if(K.disabledReason!==mJ)continue;W.findings.push({code:"slot-transfer-origin-unknown",accountId:K.id,message:`Account ${K.id} was preserved disabled after an interrupted transfer with an untagged placeholder; sole ownership could not be established. ${cJ}`})}return W.findings.map((K)=>{let U=K.repair?J(K.repair):void 0;return{code:K.code,message:K.message,...K.accountId!==void 0?{accountId:K.accountId}:{},...U?{repair:U}:{}}})}}]}var RW=KX,iJ="OpenAI accounts",CW="ChatGPT accounts in the vault",wW="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 SW(){let{redirectUri:Y}=await aJ(),J=await oJ(),X=nJ(crypto.getRandomValues(new Uint8Array(32)).buffer),Q=rJ(Y,J,X),G=tJ(J,X);return{url:Q,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let $=await G;return{type:"success",refresh:$.refresh_token,access:$.access_token,expires:Date.now()+($.expires_in??3600)*1000,accountId:a1($)}}finally{sJ(X)}}}}async function IW(Y){let{deviceData:J,url:X,instructions:Q}=await eJ(Y);return{url:X,instructions:Q,method:"auto",async callback(){try{let G=await YX(J,Y);return{type:"success",refresh:G.refresh_token,access:G.access_token,expires:Date.now()+(G.expires_in??3600)*1000,accountId:a1(G)}}catch{return{type:"failed"}}}}}function BX({client:Y,getAuth:J,getPaths:X=()=>G0(Y0()),fetchImpl:Q=fetch,packageVersion:G=A1,dependencies:$,onMainSlotWritten:W,vault:H}){let K={authorizeBrowser:$?.authorizeBrowser??SW,authorizeHeadless:$?.authorizeHeadless??(()=>IW(G)),beginAccountLogin:$?.beginAccountLogin??n8,loadAccounts:$?.loadAccounts??C0,mutateAccounts:$?.mutateAccounts??o8,readStoreIds:$?.readStoreIds??pJ,openBrowser:$?.openBrowser??RW,now:$?.now??Date.now,openAccountPool:$?.openAccountPool??O6,migrationBlockers:$?.migrationBlockers??(async()=>{let j=await E6({currentVersion:G});return j.open?[]:j.blockers.map((w)=>({pid:w.pid,version:w.version}))}),...$?.terminal?{terminal:$.terminal}:{},...$?.vaultWait?{vaultWait:$.vaultWait}:{}},U=async()=>await J?.().catch(()=>{return})??{type:"missing"},V=async()=>{if(H&&await H.authority()!=="local")return!0;if((await U()).type!=="missing")return!0;let j=X(),w=K.openAccountPool(j);if((await w.read()).status==="ready")return WX(w);return((await K.loadAccounts(j))?.accounts.length??0)>0},O=async(j)=>{if(await ZX(X().configPath,async()=>{if(H&&await H.authority()!=="local")return!1;if(r0(await U()))return!1;return await Y.auth.set({path:{id:"openai"},body:{type:"oauth",...j}}),!0}))await W?.().catch(()=>{})},L=(j)=>({begin:async({headless:w,signal:v})=>{if(H&&await H.authority()!=="local")throw Error(P6);let A=await K.beginAccountLogin({version:G,headless:w,...v?{signal:v}:{}});return{url:A.url,instructions:A.instructions,completion:A.completion.then(async(g)=>{if(H&&await H.authority()!=="local")throw Error(P6);let o=await j.read(),i=o.status==="ready"?o.rows.find((B0)=>B0.id===B1)?.identity:void 0;if(g.accountId&&i&&g.accountId===i)throw Error("that account is already the OpenCode main credential");return{id:g.id,credential:{type:"oauth",refresh:g.refresh,...g.access!==void 0?{access:g.access}:{},...g.expires!==void 0?{expires:g.expires}:{}},...g.accountId!==void 0?{identity:g.accountId}:{},...g.label!==void 0?{label:g.label}:{}}})}},openBrowser:(w)=>K.openBrowser(w)}),B=async(j)=>{if(H&&await H.authority()!=="local")throw Error(P6);let w=j.credential;if(w?.type!=="oauth"||!w.access)throw Error("no usable access token for a quota check");let v=await e6({accessToken:w.access,fetchImpl:Q,now:K.now,...j.identity?{accountId:j.identity}:{},accountKey:j.id});return q6(v,K.now(),!0)},D=(j)=>dJ({paths:X(),migrated:j,readAuth:U,loadAccounts:K.loadAccounts,readStoreIds:K.readStoreIds,mutateAccounts:K.mutateAccounts,setMainAuth:O,now:K.now}),q=(j,w)=>({title:iJ,store:JY(w,{rowLocks:(v)=>D6(j,v)}),...K.terminal?{terminal:K.terminal}:{},login:L(w),protect:(v,A)=>l8(v,A),extraLocks:E1(j),pollQuota:B,doctor:D(!0),status:async()=>{let v=await H?.status();if(H&&await H.authority()!=="local"&&v)return[KY(H.host,H.name,v.enrollment)];return[`Routing: ${(await K.loadAccounts(j))?.routing?.mode??"main-first"}`,...H?[KY(H.host,H.name,(await H.status()).enrollment)]:[]]},...H?{extraActions:[E(H)]}:{}}),E=(j)=>{let w=j.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(v)=>{let A=await j.authority();if(w){if(A!=="local")await j.disconnect();v.print("Disconnected from the Claustrum vault.");return}if(A!=="local"){v.print("Nothing was changed: this host is already connected or its enrollment is unreadable. Reopen the menu to disconnect.");return}v.print(`Asking the Claustrum vault to enroll ${j.name}…`);let g,o=await j.waitForApproval({...K.vaultWait,onPending:(i)=>{let V0=i.state==="pending"?i.requestId??i.retryCode??"":i.state;if(V0===g)return;g=V0;for(let B0 of XX(j.name,i))v.print(B0);v.print("Waiting for the approval… (stop with Ctrl-C; Connect picks the request up again)")}});v.print(QX(j,o).text)}}},T=async()=>{let j=await K.migrationBlockers();return $X({title:iJ,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.",...j.length>0?["These processes still hold the move back:",...j.map((w)=>` ${w.pid==="unknown"?"processes that could not be read":`pid ${w.pid}`}: version ${w.version}`)]:[]],actions:[GX({checks:D(!1)})],...K.terminal?{terminal:K.terminal}:{}})},I=async(j)=>{let w=X(),v=K.openAccountPool(w);if(H&&await H.authority()!=="local")return i8(q(w,v),H);if(await p8(w,v)===void 0)return T();let A=q(w,v);return H?i8(A,H):zX(A)},x=(j)=>async()=>{if(H&&await H.authority()!=="local")throw Error(P6);let w=await j();if(w.method!=="auto")return w;return{...w,callback:async()=>{let v=await w.callback();if(H&&await H.authority()!=="local")return{type:"failed"};return v}}};return[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:HX({hasCredential:V,openMenu:I,login:x(()=>K.authorizeBrowser())})},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:x(()=>K.authorizeHeadless())},{label:"Manually enter API Key",type:"api"},...H?.enrolled()?[{label:CW,type:"oauth",authorize:async()=>({url:"",instructions:wW,method:"auto",callback:async()=>{if(await JX(H.paths,H.name)!=="vault")return{type:"failed"};try{let j=JSON.parse(await TW(VX(),"utf8"));if(!j||typeof j!=="object"||Array.isArray(j)||Object.hasOwn(j,"openai"))return{type:"failed"}}catch(j){if(j.code!=="ENOENT")return{type:"failed"}}return{...UX,type:"success"}}})}]:[]]}var UY=["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 t1(Y){let J={};for(let X of UY)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 sW}from"node:crypto";import{createHash as bW,randomBytes as LX}from"node:crypto";import{chmod as kW,lstat as NX,mkdir as xW,open as hW,readdir as MX,rename as vW,unlink as NY,writeFile as yW}from"node:fs/promises";import{join as r8,resolve as ZY}from"node:path";var gW=100,VY="session-unknown",fW=300000,mW=60000,cW=600000,uW=/\.(body|meta|request|response)\.json$/,pW=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-\d+-\d{6,}-[a-zA-Z0-9._-]+$/,lW=/\.[a-f0-9]{24}\.partial$/;function AX(Y){let J=Y.replace(uW,"");if(J===Y||!pW.test(J))return;return J}function dW(Y){let J=Y.replace(lW,"");return J!==Y&&AX(J)!==void 0}async function jX(Y){let{dir:J,maxBytes:X}=Y,Q=Y.now??Date.now(),G=Y.minAgeMs??mW,$=Y.partialStaleMs??cW,W={removed:0,freedBytes:0};if(!(X>0))return W;try{if(L1)await OX(J,"directory");if((await NX(J)).isSymbolicLink())return W;let H=new Set((Y.protectedPaths??[]).map((E)=>ZY(E))),K=await MX(J,{withFileTypes:!0}),U=[];await Promise.all(K.map(async(E)=>{if(!E.isFile())return;let T=dW(E.name),I=T?void 0:AX(E.name);if(!T&&I===void 0)return;let x=r8(J,E.name);try{let j=await NX(x);if(!j.isFile())return;U.push({path:x,size:j.size,mtimeMs:j.mtimeMs,group:I})}catch{}}));let V=U.reduce((E,T)=>E+T.size,0),O=0,L=0,B=async(E)=>{try{await NY(E.path),V-=E.size,L+=E.size,O+=1}catch{}};for(let E of U){if(E.group!==void 0)continue;if(H.has(ZY(E.path)))continue;if(Q-E.mtimeMs<$)continue;await B(E)}let D=new Map;for(let E of U){if(E.group===void 0)continue;let T=D.get(E.group)??{files:[],newest:0};T.files.push(E),T.newest=Math.max(T.newest,E.mtimeMs),D.set(E.group,T)}let q=[...D.entries()].sort(([E,T],[I,x])=>T.newest-x.newest||E.localeCompare(I));for(let[,E]of q){if(V<=X)break;if(Q-E.newest<G)continue;if(E.files.some((T)=>H.has(ZY(T.path))))continue;for(let T of E.files)await B(T)}if(O>0)Y.logger?.debug("removed old dump files",{removed:O,freedBytes:L});return{removed:O,freedBytes:L}}catch(H){if(H instanceof J8&&H.code==="ERR_PRIVATE_FILES_SECURITY")throw H;return W}}async function iW(Y,J,X){if(L1)return qX(Y,J,{stagePath:`${Y}.${X?X():LX(12).toString("hex")}.partial`});for(let Q=0;;Q+=1){let G=`${Y}.${X?X():LX(12).toString("hex")}.partial`,$=!1,W;try{W=await hW(G,"wx",384),$=!0,await W.writeFile(J,"utf8"),await W.chmod(384),await W.close(),W=void 0,await vW(G,Y);return}catch(H){if(await W?.close().catch(()=>{}),$)await NY(G).catch(()=>{});if(H.code==="EEXIST"&&Q===0)continue;throw H}}}function BY(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function Y8(Y,J){let X=Y.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!X)return J;return X.slice(0,80)}function FX(Y){return bW("sha256").update(Y).digest("hex")}function nW(Y){return Y.toLowerCase().replace(/[-_]/g,"")}function DX(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function oW(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 Q=Y.length-1,G=J.length-1;while(Q>=X&&G>=X&&Y[Q]===J[G])Q--,G--;return{changed:!0,firstByte:X,lastPreviousByte:Q,lastCurrentByte:G,changedPreviousBytes:Q-X+1,changedCurrentBytes:G-X+1,previousBytes:Y.length,currentBytes:J.length}}var rW=0;function TX(Y){let J=Y.enabled===!0,X=Y.pid??process.pid,Q=Y.now??Date.now,G=Y.logger,$=new Set((Y.secretKeys??[]).map(nW)),W=EX({extraSecretKeys:(A)=>$.has(A),extraValuePatterns:[...Y.secretPatterns??[]]}),H=new Set(Y.schemaKeys??["tools"]),K=new Map,U=()=>typeof Y.dir==="function"?Y.dir():Y.dir;function V(A){let g=W.redact({[A]:null})[A];return g===null?void 0:g}function O(A){if(Array.isArray(A))return A.map(O);if(DX(A)){let g={};for(let[o,i]of Object.entries(A)){let V0=V(o);if(H.has(o))g[o]=W.redactStrings(i);else if(V0!==void 0)g[o]=V0;else g[o]=O(i)}return g}return W.redactStrings(A)}function L(A){let g;try{g=JSON.parse(A)}catch{return{text:W.redactStrings(A),parsed:void 0}}let o=O(g),i=JSON.stringify(o);return{text:JSON.stringify(g)===i?A:i,parsed:DX(o)?o:void 0}}async function B(A,g,o,i){let V0=`-${Y8(g,VY)}-${Y8(o,"channel")}`,B0;try{B0=await MX(A)}catch{return}let p=B0.filter((t)=>t.endsWith(".meta.json")&&t.includes(V0)).sort().reverse();for(let t of p)try{if(JSON.parse(await LY(r8(A,t),L1))?.baselineKey!==i)continue;return await LY(r8(A,t.replace(/\.meta\.json$/,".body.json")),L1)}catch(L0){if(L0 instanceof J8&&(L1||L0.code==="ERR_PRIVATE_FILES_SECURITY"))throw L0}return}function D(A,g){if(!K.has(A))while(K.size>=gW){let o=K.keys().next().value;if(o===void 0)break;K.delete(o)}K.set(A,g)}async function q(A){if(!J)return;let g=++rW,o=A.session?.trim()||VY,i=U(),V0=new Date(Q()).toISOString(),B0=[V0.replace(/[:.]/g,"-"),String(X),String(g).padStart(6,"0"),Y8(o,VY),Y8(A.channel,"channel"),...A.phase?[Y8(A.phase,"phase")]:[]].join("-"),p=r8(i,B0),t={body:`${p}.body.json`,metadata:`${p}.meta.json`,request:`${p}.request.json`},L0=FX(`${A.channel}\x00${o}`);try{if(L1)await _X(i);else await xW(i,{recursive:!0,mode:448}),await kW(i,448);let h=K.get(L0),x0=h===void 0?void 0:"memory";if(h===void 0){if(h=await B(i,o,A.channel,L0),h!==void 0)x0="disk"}let R0=L(A.bodyText),U0={id:B0,createdAt:V0,pid:X,session:BY(o),channel:A.channel,...A.phase?{phase:A.phase}:{},accountId:A.accountId,status:A.status,error:A.error===void 0?void 0:W.redactStrings(A.error),baselineKey:L0,bodyBytes:Buffer.byteLength(A.bodyText,"utf8"),bodyHash:FX(A.bodyText),diff:oW(h,R0.text),baselineSource:x0,body:R0.parsed?{parseable:!0,...Y.summarize?.(R0.parsed)}:{parseable:!1},...A.meta?{extra:O(A.meta)}:{},files:t},r=O({url:A.url,method:A.method,accountId:A.accountId,headers:A.headers===void 0?void 0:Object.fromEntries(new Headers(A.headers).entries())}),E0=(d,y)=>L1?PX(d,y):yW(d,y,{encoding:"utf8",mode:384,flag:"wx"}),l=[[t.body,R0.text],[t.metadata,`${JSON.stringify(U0,null,2)}
|
|
2
2
|
`],[t.request,`${JSON.stringify(r,null,2)}
|
|
3
|
-
`]],S=await Promise.allSettled(l.map(([d,y])=>E0(d,y))),u=S.find((d)=>d.status==="rejected");if(u){if(Y.cleanupFailedDumps)await E(l,S);throw u.reason}return D(L0,R0.text),G?.debug("dumped request",{id:B0,session:BY(o),body:t.body}),w(i,Object.values(t)),{id:B0,files:t,responseFile:`${p}.response.json`}}catch(h){if(h instanceof J8&&(L1||h.code==="ERR_PRIVATE_FILES_SECURITY"))throw h;G?.warn("request dump failed",{session:BY(o),error:h instanceof Error?h.message:String(h)});return}}async function E(
|
|
4
|
-
`,Y.stageName),M.responseFile}catch(i){if(i instanceof J8&&(L1||i.code==="ERR_PRIVATE_FILES_SECURITY"))throw i;G?.warn("response dump failed",{id:M.id,error:i instanceof Error?i.message:String(i)});return}}return{isEnabled:()=>J,setEnabled:(M)=>{J=M},dump:q,dumpResponse:v,sweep:(M)=>jX(j(U(),M))}}var RX=H0("dump"),h1="x-cortexkit-openai-auth-dump-session",aW=["chatgpt-account-id","email","org_name","organization_name"],tW=["tools"];function jY(Y){return sW("sha256").update(JSON.stringify(Y)).digest("hex")}function eW(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function Yz(Y){let J=Array.isArray(Y.input)?Y.input:[],X=Array.isArray(Y.tools)?Y.tools:[],Q=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:jY(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:jY(J[0]),toolsCount:X.length,toolTypes:X.map(eW),toolsHash:jY(X),clientMetadataKeys:Q?Object.keys(Q).sort():[]}}var FY;function CX(){return FY=o0().dumpMaxBytes,TX({dir:()=>o0().dumpDir,maxBytes:FY,logger:RX,secretKeys:aW,schemaKeys:tW,summarize:Yz})}var s8=CX();async function M6(Y){if(!s6()){s8.setEnabled(!1);return}if(o0().dumpMaxBytes!==FY)s8=CX();s8.setEnabled(!0);let J=typeof Y.bodyText==="function"?Y.bodyText():Y.bodyText;await s8.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 e1(Y){if(!s6())return;RX.debug("diagnostic",Y)}function A6(Y){return JSON.stringify(DY(Y))??"undefined"}function DY(Y){if(Array.isArray(Y))return Y.map(DY);if(!a(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((J)=>[J,DY(Y[J])]))}var Jz=512,Xz=2097152;function OY(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(($,W)=>OY($,J[W]));if(Y===null||J===null||typeof Y!=="object"||typeof J!=="object"||Array.isArray(J))return!1;let X=Y,Q=J,G=Object.keys(X);return G.length===Object.keys(Q).length&&G.every(($)=>Object.prototype.propertyIsEnumerable.call(Q,$)&&OY(X[$],Q[$]))}function Y6(Y,J){let X=[],Q=[],G=0;for(let $=0;$<Y.length;$++){let W=J?.texts[$],H=W!==void 0&&OY(J?.snapshots[$],Y[$]),K=H?W:A6(Y[$]);X.push(K),Q.push(H?J?.snapshots[$]:K==="undefined"?void 0:JSON.parse(K)),G+=K.length}return{texts:X,snapshots:Q,retainable:Y.length<=Jz&&G<=Xz}}function X8(Y){return Y.retainable?Y:void 0}function Q8(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 wX=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"]),Qz="terminal_resize_reflow",a8="0.159.0",SX=`codex_exec/${a8} (Debian 12.0.0; aarch64) unknown (codex_exec; ${a8})`,Gz="seccomp",G8="x-openai-auth-agent";function $z(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 $8(Y,J){return a(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===J}function Wz(Y,J,X){if(!Y.input)return J.length>0;let Q=Y.canonicalInput??Y6(Y.input);if(Q8(Q,X)===void 0)return!0;return J.slice(Y.input.length).some(($)=>$8($,"user")||$8($,"developer"))}function zz(Y,J,X){let Q=Array.isArray(J?.input)?J.input:void 0,G=Q?Y6(Q,Y.canonicalInput):void 0;if(Q&&G&&(Wz(Y,Q,G)||!Y.turnID))Y.turnID=(X?.uuid??J6)(),Y.turnStartedAt=(X?.now??Date.now)();else if(!Y.turnStartedAt)Y.turnStartedAt=(X?.now??Date.now)();if(Q&&G)Y.input=Q.slice(),Y.canonicalInput=X8(G)}function IX(Y){let J=Y.headers.get(G8);if(Y.headers.delete(G8),!Y.metadata)return{init:Y.init};let X=$z(Y.init?.body),Q=Y.runtime?.now??Date.now;if(!Y.skipTurnUpdate){if(!Y.websocket)zz(Y.metadata,X,Y.runtime);else if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Q();if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Q()}let G=JSON.stringify({session_id:Y.metadata.threadID,thread_id:Y.metadata.threadID,thread_source:"user",turn_id:Y.metadata.turnID,sandbox:Gz,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",Qz),Y.headers.set("x-codex-turn-metadata",G),Y.headers.set("user-agent",SX),Y.headers.set("version",a8),Y.dumpSessionID)Y.headers.set(h1,Y.dumpSessionID);let $=X;if(!$)return{init:Y.init};let W=Y.responsesLite&&typeof $.model==="string"&&wX.has($.model);if(W&&!Y.websocket)Y.headers.set("x-openai-internal-codex-responses-lite","true");if($.prompt_cache_key=Y.metadata.threadID,$.parallel_tool_calls??=!0,Array.isArray($.tools))$.tools=$.tools.map(Hz);if(Y.applyEffort?.($,Y.metadata,J),W)Y.rewriteLite($);let H={...typeof $.client_metadata==="object"&&$.client_metadata!==null?$.client_metadata:{},"x-codex-installation-id":Y.installationID,"x-codex-window-id":Y.metadata.windowID};if(Y.websocket){if(H["x-codex-turn-metadata"]=G,H["x-codex-ws-stream-request-start-ms"]=String(Q()),W)H.ws_request_header_x_openai_internal_codex_responses_lite="true"}return $.client_metadata=H,Y.headers.delete("content-length"),Y.headers.delete("Content-Length"),{init:{...Y.init,body:JSON.stringify(t1($))}}}function Hz(Y){if(!a(Y)||Y.type!=="function")return Y;let J=a(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:K,...U}=Y.parameters;return U})():Y.parameters,{type:X,name:Q,description:G,strict:$,parameters:W,...H}=Y;return{type:X,name:Q,description:G,strict:$??!1,parameters:J,...H}}import{lstat as bX,opendir as Kz}from"node:fs/promises";import{join as Uz}from"node:path";async function kX(Y){try{if(!(await bX(Y)).isDirectory())return;let J=0,X=!1,Q=[],G=async($)=>{try{let W=await bX(Uz(Y,$));if(W.isFile())J+=W.size}catch(W){if(W.code!=="ENOENT")X=!0}};for await(let $ of await Kz(Y)){if(!$.isFile())continue;if(Q.push(G($.name)),Q.length===32)await Promise.all(Q),Q=[]}return await Promise.all(Q),X?void 0:J}catch(J){return J.code==="ENOENT"?0:void 0}}function _Y(Y){let J=["B","KiB","MiB","GiB","TiB","PiB"],X=0,Q=Y;while(Q>=1024&&X<J.length-1)Q/=1024,X++;return`${Number(Q.toFixed(1))} ${J[X]}`}var PY={rpcRoot:"openai-auth",directoryPrefix:yX,registrationSessionId:"process"},t8=new Map;function SN(Y,J){if(J?.aborted)return Promise.resolve(!1);if(qY(Y))return Promise.resolve(!0);return new Promise((X)=>{let Q=(H)=>{if(clearTimeout($),J?.removeEventListener("abort",G),W.delete(Q),W.size===0)t8.delete(Y);X(H)},G=()=>Q(!1),$=setTimeout(()=>Q(!1),2000),W=t8.get(Y)??new Set;t8.set(Y,W),W.add(Q),J?.addEventListener("abort",G,{once:!0})})}function e8(Y,J){xX(PY,Y,J)}function gX(Y=0,J){let X=hX(PY,Y,J);if(J!==void 0)for(let Q of t8.get(J)??[])Q(!0);return X}function qY(Y){return vX(PY,Y)}var Y9=H0("commands");function T6(Y){return{configPath:Y.accountStoragePath,statePath:Y.accountStatePath}}function EY(Y){return`${String(Y.startHour).padStart(2,"0")}-${String(Y.endHour).padStart(2,"0")}`}function Zz(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]),Q=Number(J[2]);if(X>23||Q>23||X===Q)return{ok:!1,reason:"hours must be integers 0-23 and start ≠ end"};return{ok:!0,startHour:X,endHour:Q}}var Vz="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 Bz(Y){let J=(X)=>n1(Y.store(),E1(T6(Y)),(Q)=>{let G={...Q.cacheKeep??{}};X(G),Q.cacheKeep=G});return{title:"Cache",build:async()=>{let X=Y.cacheKeepManager;if(!X)return{lines:["Keep-warm unavailable"]};let Q=X9(await Y.loadAccounts(T6(Y))),G=Q?.enabled===!0,$=Q?.subagents===!0,W=X.status(),H=W.window?EY(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 ${$?"on":"off"} · sustain ${W.sustain?"on":"off"}`,`Window ${H}`,...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((K)=>({id:K.sessionKey,label:K.sessionKey,group:"Sessions",detail:[K.accountId??"main",`expires in ${Math.ceil((K.cacheExpiresAt-W.generatedAt)/1000)}s`,...K.lastWarmedAt?[`last warm ${Math.ceil((W.generatedAt-K.lastWarmedAt)/1000)}s ago`]:[],...K.backoffUntil&&K.backoffUntil>W.generatedAt?[`backoff ${Math.ceil((K.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:K})=>{let U=K.enabled===!0;if(await J((V)=>{V.enabled=U}),Y.setCacheKeepEnabled?.(U),U)X.start();else X.stop();return Y9.info(U?"cachekeep enabled":"cachekeep disabled"),U?`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:$?"Stop warming subagent sessions":"Warm subagent sessions too",knobs:[{kind:"toggle",id:"subagents",label:"Subagent warming",value:!$}],run:async({values:K})=>{let U=K.subagents===!0;return await J((V)=>{V.subagents=U}),Y.setCacheKeepSubagents?.(U),`Subagent warming is ${U?"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:K})=>{let U=K.sustain===!0;return await J((V)=>{V.sustain=U}),Y.setCacheKeepSustain?.(U),U?Vz:"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:EY(W.window)}:{}}],run:async({values:K})=>{let U=K.window;if(typeof U!=="string"||U.trim()==="")return await J((B)=>{delete B.startHour,delete B.endHour}),Y.setCacheKeepWindow?.(void 0),"Warm window cleared: keep-warm warms at any hour (within idle caps).";let V=Zz(U);if(!V.ok)return{ok:!1,text:`Invalid window: ${V.reason}`};let{startHour:O,endHour:L}=V;return await J((B)=>{B.startHour=O,B.endHour=L}),Y.setCacheKeepWindow?.({startHour:O,endHour:L}),`Warming limited to ${EY(V)} local hours.`}}]}}}}var fX=["error","warn","info","debug","trace"];function Lz(Y){return{title:"Diagnostics",build:async()=>{let J=o0(),X=s6(),G=(await Y.loadAccounts(T6(Y)))?.logging?.level??"info",$=X?await kX(J.dumpDir):void 0,W=$===void 0?"size unavailable":_Y($),H=J.dumpMaxBytes===0?"no cap":`${_Y(J.dumpMaxBytes)} cap`,K=Y.layoutNotice?.();return{lines:[X?`Dumps on (${W} / ${H})`:"Dumps off",`Dump directory: ${J.dumpDir}`,`Log level: ${G}`,...K?[K]:[]],actions:[{id:"dump",label:X?"Turn request dumps off":"Turn request dumps on",knobs:[{kind:"toggle",id:"enabled",label:"Request dumps",value:!X}],run:async({values:U})=>{let V=U.enabled===!0;await n1(Y.store(),E1(T6(Y)),(L)=>{L.dump={...L.dump??{},enabled:V}});let O=hJ();return Y9.info(V?"request dump enabled":"request dump disabled"),V?`Request dumps are on, written to ${O.dumpDir}.
|
|
3
|
+
`]],S=await Promise.allSettled(l.map(([d,y])=>E0(d,y))),u=S.find((d)=>d.status==="rejected");if(u){if(Y.cleanupFailedDumps)await E(l,S);throw u.reason}return D(L0,R0.text),G?.debug("dumped request",{id:B0,session:BY(o),body:t.body}),w(i,Object.values(t)),{id:B0,files:t,responseFile:`${p}.response.json`}}catch(h){if(h instanceof J8&&(L1||h.code==="ERR_PRIVATE_FILES_SECURITY"))throw h;G?.warn("request dump failed",{session:BY(o),error:h instanceof Error?h.message:String(h)});return}}async function E(A,g){await Promise.all(A.map(async([o],i)=>{let V0=g[i];if(V0?.status==="rejected"&&V0.reason?.code==="EEXIST")return;await NY(o).catch(()=>{})}))}let T=Y.maxBytes??0,I=Y.sweepIntervalMs??fW,x=0;function j(A,g){return{dir:A,maxBytes:T,protectedPaths:g,now:Q(),minAgeMs:Y.sweepMinAgeMs,partialStaleMs:Y.partialStaleMs,logger:G}}function w(A,g){if(!(T>0))return;let o=Q();if(o-x<I)return;x=o,jX(j(A,g))}async function v(A,g){if(!A)return;let o=O({status:g.status,requestId:g.requestId,usage:g.usage,...g.fields,complete:g.complete??!0});try{return await iW(A.responseFile,`${JSON.stringify(o,null,2)}
|
|
4
|
+
`,Y.stageName),A.responseFile}catch(i){if(i instanceof J8&&(L1||i.code==="ERR_PRIVATE_FILES_SECURITY"))throw i;G?.warn("response dump failed",{id:A.id,error:i instanceof Error?i.message:String(i)});return}}return{isEnabled:()=>J,setEnabled:(A)=>{J=A},dump:q,dumpResponse:v,sweep:(A)=>jX(j(U(),A))}}var RX=H0("dump"),h1="x-cortexkit-openai-auth-dump-session",aW=["chatgpt-account-id","email","org_name","organization_name"],tW=["tools"];function jY(Y){return sW("sha256").update(JSON.stringify(Y)).digest("hex")}function eW(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function Yz(Y){let J=Array.isArray(Y.input)?Y.input:[],X=Array.isArray(Y.tools)?Y.tools:[],Q=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:jY(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:jY(J[0]),toolsCount:X.length,toolTypes:X.map(eW),toolsHash:jY(X),clientMetadataKeys:Q?Object.keys(Q).sort():[]}}var FY;function CX(){return FY=o0().dumpMaxBytes,TX({dir:()=>o0().dumpDir,maxBytes:FY,logger:RX,secretKeys:aW,schemaKeys:tW,summarize:Yz})}var s8=CX();async function M6(Y){if(!s6()){s8.setEnabled(!1);return}if(o0().dumpMaxBytes!==FY)s8=CX();s8.setEnabled(!0);let J=typeof Y.bodyText==="function"?Y.bodyText():Y.bodyText;await s8.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 e1(Y){if(!s6())return;RX.debug("diagnostic",Y)}function A6(Y){return JSON.stringify(DY(Y))??"undefined"}function DY(Y){if(Array.isArray(Y))return Y.map(DY);if(!a(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((J)=>[J,DY(Y[J])]))}var Jz=512,Xz=2097152;function OY(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(($,W)=>OY($,J[W]));if(Y===null||J===null||typeof Y!=="object"||typeof J!=="object"||Array.isArray(J))return!1;let X=Y,Q=J,G=Object.keys(X);return G.length===Object.keys(Q).length&&G.every(($)=>Object.prototype.propertyIsEnumerable.call(Q,$)&&OY(X[$],Q[$]))}function Y6(Y,J){let X=[],Q=[],G=0;for(let $=0;$<Y.length;$++){let W=J?.texts[$],H=W!==void 0&&OY(J?.snapshots[$],Y[$]),K=H?W:A6(Y[$]);X.push(K),Q.push(H?J?.snapshots[$]:K==="undefined"?void 0:JSON.parse(K)),G+=K.length}return{texts:X,snapshots:Q,retainable:Y.length<=Jz&&G<=Xz}}function X8(Y){return Y.retainable?Y:void 0}function Q8(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 wX=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"]),Qz="terminal_resize_reflow",a8="0.159.0",SX=`codex_exec/${a8} (Debian 12.0.0; aarch64) unknown (codex_exec; ${a8})`,Gz="seccomp",G8="x-openai-auth-agent";function $z(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 $8(Y,J){return a(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===J}function Wz(Y,J,X){if(!Y.input)return J.length>0;let Q=Y.canonicalInput??Y6(Y.input);if(Q8(Q,X)===void 0)return!0;return J.slice(Y.input.length).some(($)=>$8($,"user")||$8($,"developer"))}function zz(Y,J,X){let Q=Array.isArray(J?.input)?J.input:void 0,G=Q?Y6(Q,Y.canonicalInput):void 0;if(Q&&G&&(Wz(Y,Q,G)||!Y.turnID))Y.turnID=(X?.uuid??J6)(),Y.turnStartedAt=(X?.now??Date.now)();else if(!Y.turnStartedAt)Y.turnStartedAt=(X?.now??Date.now)();if(Q&&G)Y.input=Q.slice(),Y.canonicalInput=X8(G)}function IX(Y){let J=Y.headers.get(G8);if(Y.headers.delete(G8),!Y.metadata)return{init:Y.init};let X=$z(Y.init?.body),Q=Y.runtime?.now??Date.now;if(!Y.skipTurnUpdate){if(!Y.websocket)zz(Y.metadata,X,Y.runtime);else if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Q();if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Q()}let G=JSON.stringify({session_id:Y.metadata.threadID,thread_id:Y.metadata.threadID,thread_source:"user",turn_id:Y.metadata.turnID,sandbox:Gz,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",Qz),Y.headers.set("x-codex-turn-metadata",G),Y.headers.set("user-agent",SX),Y.headers.set("version",a8),Y.dumpSessionID)Y.headers.set(h1,Y.dumpSessionID);let $=X;if(!$)return{init:Y.init};let W=Y.responsesLite&&typeof $.model==="string"&&wX.has($.model);if(W&&!Y.websocket)Y.headers.set("x-openai-internal-codex-responses-lite","true");if($.prompt_cache_key=Y.metadata.threadID,$.parallel_tool_calls??=!0,Array.isArray($.tools))$.tools=$.tools.map(Hz);if(Y.applyEffort?.($,Y.metadata,J),W)Y.rewriteLite($);let H={...typeof $.client_metadata==="object"&&$.client_metadata!==null?$.client_metadata:{},"x-codex-installation-id":Y.installationID,"x-codex-window-id":Y.metadata.windowID};if(Y.websocket){if(H["x-codex-turn-metadata"]=G,H["x-codex-ws-stream-request-start-ms"]=String(Q()),W)H.ws_request_header_x_openai_internal_codex_responses_lite="true"}return $.client_metadata=H,Y.headers.delete("content-length"),Y.headers.delete("Content-Length"),{init:{...Y.init,body:JSON.stringify(t1($))}}}function Hz(Y){if(!a(Y)||Y.type!=="function")return Y;let J=a(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:K,...U}=Y.parameters;return U})():Y.parameters,{type:X,name:Q,description:G,strict:$,parameters:W,...H}=Y;return{type:X,name:Q,description:G,strict:$??!1,parameters:J,...H}}import{lstat as bX,opendir as Kz}from"node:fs/promises";import{join as Uz}from"node:path";async function kX(Y){try{if(!(await bX(Y)).isDirectory())return;let J=0,X=!1,Q=[],G=async($)=>{try{let W=await bX(Uz(Y,$));if(W.isFile())J+=W.size}catch(W){if(W.code!=="ENOENT")X=!0}};for await(let $ of await Kz(Y)){if(!$.isFile())continue;if(Q.push(G($.name)),Q.length===32)await Promise.all(Q),Q=[]}return await Promise.all(Q),X?void 0:J}catch(J){return J.code==="ENOENT"?0:void 0}}function _Y(Y){let J=["B","KiB","MiB","GiB","TiB","PiB"],X=0,Q=Y;while(Q>=1024&&X<J.length-1)Q/=1024,X++;return`${Number(Q.toFixed(1))} ${J[X]}`}var PY={rpcRoot:"openai-auth",directoryPrefix:yX,registrationSessionId:"process"},t8=new Map;function SN(Y,J){if(J?.aborted)return Promise.resolve(!1);if(qY(Y))return Promise.resolve(!0);return new Promise((X)=>{let Q=(H)=>{if(clearTimeout($),J?.removeEventListener("abort",G),W.delete(Q),W.size===0)t8.delete(Y);X(H)},G=()=>Q(!1),$=setTimeout(()=>Q(!1),2000),W=t8.get(Y)??new Set;t8.set(Y,W),W.add(Q),J?.addEventListener("abort",G,{once:!0})})}function e8(Y,J){xX(PY,Y,J)}function gX(Y=0,J){let X=hX(PY,Y,J);if(J!==void 0)for(let Q of t8.get(J)??[])Q(!0);return X}function qY(Y){return vX(PY,Y)}var Y9=H0("commands");function T6(Y){return{configPath:Y.accountStoragePath,statePath:Y.accountStatePath}}function EY(Y){return`${String(Y.startHour).padStart(2,"0")}-${String(Y.endHour).padStart(2,"0")}`}function Zz(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]),Q=Number(J[2]);if(X>23||Q>23||X===Q)return{ok:!1,reason:"hours must be integers 0-23 and start ≠ end"};return{ok:!0,startHour:X,endHour:Q}}var Vz="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 Bz(Y){let J=(X)=>n1(Y.store(),E1(T6(Y)),(Q)=>{let G={...Q.cacheKeep??{}};X(G),Q.cacheKeep=G});return{title:"Cache",build:async()=>{let X=Y.cacheKeepManager;if(!X)return{lines:["Keep-warm unavailable"]};let Q=X9(await Y.loadAccounts(T6(Y))),G=Q?.enabled===!0,$=Q?.subagents===!0,W=X.status(),H=W.window?EY(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 ${$?"on":"off"} · sustain ${W.sustain?"on":"off"}`,`Window ${H}`,...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((K)=>({id:K.sessionKey,label:K.sessionKey,group:"Sessions",detail:[K.accountId??"main",`expires in ${Math.ceil((K.cacheExpiresAt-W.generatedAt)/1000)}s`,...K.lastWarmedAt?[`last warm ${Math.ceil((W.generatedAt-K.lastWarmedAt)/1000)}s ago`]:[],...K.backoffUntil&&K.backoffUntil>W.generatedAt?[`backoff ${Math.ceil((K.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:K})=>{let U=K.enabled===!0;if(await J((V)=>{V.enabled=U}),Y.setCacheKeepEnabled?.(U),U)X.start();else X.stop();return Y9.info(U?"cachekeep enabled":"cachekeep disabled"),U?`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:$?"Stop warming subagent sessions":"Warm subagent sessions too",knobs:[{kind:"toggle",id:"subagents",label:"Subagent warming",value:!$}],run:async({values:K})=>{let U=K.subagents===!0;return await J((V)=>{V.subagents=U}),Y.setCacheKeepSubagents?.(U),`Subagent warming is ${U?"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:K})=>{let U=K.sustain===!0;return await J((V)=>{V.sustain=U}),Y.setCacheKeepSustain?.(U),U?Vz:"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:EY(W.window)}:{}}],run:async({values:K})=>{let U=K.window;if(typeof U!=="string"||U.trim()==="")return await J((B)=>{delete B.startHour,delete B.endHour}),Y.setCacheKeepWindow?.(void 0),"Warm window cleared: keep-warm warms at any hour (within idle caps).";let V=Zz(U);if(!V.ok)return{ok:!1,text:`Invalid window: ${V.reason}`};let{startHour:O,endHour:L}=V;return await J((B)=>{B.startHour=O,B.endHour=L}),Y.setCacheKeepWindow?.({startHour:O,endHour:L}),`Warming limited to ${EY(V)} local hours.`}}]}}}}var fX=["error","warn","info","debug","trace"];function Lz(Y){return{title:"Diagnostics",build:async()=>{let J=o0(),X=s6(),G=(await Y.loadAccounts(T6(Y)))?.logging?.level??"info",$=X?await kX(J.dumpDir):void 0,W=$===void 0?"size unavailable":_Y($),H=J.dumpMaxBytes===0?"no cap":`${_Y(J.dumpMaxBytes)} cap`,K=Y.layoutNotice?.();return{lines:[X?`Dumps on (${W} / ${H})`:"Dumps off",`Dump directory: ${J.dumpDir}`,`Log level: ${G}`,...K?[K]:[]],actions:[{id:"dump",label:X?"Turn request dumps off":"Turn request dumps on",knobs:[{kind:"toggle",id:"enabled",label:"Request dumps",value:!X}],run:async({values:U})=>{let V=U.enabled===!0;await n1(Y.store(),E1(T6(Y)),(L)=>{L.dump={...L.dump??{},enabled:V}});let O=hJ();return Y9.info(V?"request dump enabled":"request dump disabled"),V?`Request dumps are on, written to ${O.dumpDir}.
|
|
5
5
|
|
|
6
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:fX.map((U)=>({value:U,label:U})),value:fX.includes(G)?G:"info"}],run:async({values:U})=>{let V=String(U.level);return await n1(Y.store(),E1(T6(Y)),(O)=>{O.logging={...O.logging??{},level:V}}),J9(V),Y9.info("log level changed",{level:V}),`Log level set to ${V}.`}}]}}}}async function Nz(Y){let J=await Y.store().read(),X=J.status==="ready"?J.rows:[];return[...new Set(["main",...X.filter((Q)=>Q.enabled&&Q.type==="oauth").map((Q)=>Q.id)])]}function cX(Y){let J=T6(Y),X=E1(J),Q=Y.quotaManager&&Y.resolveResetTarget&&Y.refreshResetTargetQuota&&Y.fetchImpl&&Y.now&&Y.randomUUID?$Y({configPath:J.configPath,statePath:J.statePath,quotaManager:Y.quotaManager,loadAccounts:Y.loadAccounts,mutateAccounts:XY(Y.store(),X),resolveResetTarget:Y.resolveResetTarget,refreshResetTargetQuota:Y.refreshResetTargetQuota,fetchImpl:Y.fetchImpl,now:Y.now,randomUUID:Y.randomUUID,accountKeys:()=>Nz(Y)}):void 0,G=Y.beginAccountLogin;return WY({store:Y.store(),...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:X,rowLocks:($)=>D6(J,$),migration:Y.migration,...G?{login:{begin:($)=>G({...$,version:Y.packageVersion}),mainIdentity:async()=>{let $=await Y.store().read();if($.status!=="ready")return;return $.rows.find((W)=>W.id==="main")?.identity}}}:{},protect:($,W)=>l8($,W),...Y.refreshAllQuota?{quotaCheck:async($)=>{if($.length===1){let K=Y.store();for(let U of $)await K.requestReading(U);await K.pullsSettled();return}let H=(await Y.refreshAllQuota?.()??[]).filter((K)=>!K.ok);if(H.length>0)throw new mX("quota-check-failed",H.map((K)=>K.permanent?`${K.account}: sign-in no longer accepted — remove and add this account again`:`${K.account}: fetch failed — check again to retry`).join(`
|
|
7
7
|
`))}}:{},cache:Bz(Y),diagnostics:Lz(Y),extras:[...Q?[Q]:[],QY({...Y.getStickyRouting?{getPin:Y.getStickyRouting}:{},...Y.clearStickyRouting?{clearPin:Y.clearStickyRouting}:{}}),...Y.vault?[GY({vault:Y.vault,changed:Y.afterWrite})]:[]],afterApply:async()=>{await Y.afterWrite?.(),await Y.refreshSidebar?.().catch(()=>{})}})}function uX(Y){return(J,X="info")=>{Y9.info("menu notification",{sessionId:Y,kind:X}),e8({command:x1,notify:{message:J,kind:X}},Y)}}function pX(Y,J){return cX(Y).open({...J!==void 0?{sessionId:J}:{},notify:uX(J)})}function lX(Y,J){return cX(Y).apply(J,{...J.sessionId!==void 0?{sessionId:J.sessionId}:{},notify:uX(J.sessionId)})}function dX(Y){let J=[`## ${Y.title}`];for(let X of Y.sections){J.push("",`### ${X.title}`);for(let Q of X.lines)J.push(Q);for(let Q of X.items){let G=Q.detail??Q.status;J.push(`- ${Q.label}${G?`: ${G}`:""}`)}}return J.push("","Open the OpenCode TUI to change these settings."),J.join(`
|
|
8
8
|
`)}var jz=300000,Fz=30000,iX=240000,Dz="bg-quota-refresh",Oz=120000;function MY(Y,J){return Q9({name:Dz,ttlMs:Oz,path:Y,renew:!0,...J})}function nX(Y,J=R6,X=()=>MY(Y.paths.configPath)){return _z(Y,J,X)}function _z(Y,J,X){return oX(async()=>J({...Y,respectBackoff:!0,skipFresherThanMs:iX}),X,[])}async function oX(Y,J,X){let Q;try{Q=await J()}catch{Q=void 0}if(Q===null)return X;try{return await Y()}finally{await Q?.release().catch(()=>{})}}function rX(Y,J,X){return oX(async()=>{return await Y.refreshDueTokens(J),Y.pollRows(J,{skipReadWithinMs:iX})},X,[])}class AY{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)*Fz);if(this.timer=this.setIntervalFn(()=>{let Q=this.run;if(this.stopped||!Q||this.tickPromise)return;let G=Q().catch(($)=>{try{this.onError?.($)}catch{}}).finally(()=>{if(this.tickPromise===G)this.tickPromise=void 0});this.tickPromise=G},jz+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 TY(Y){if(!Y||typeof Y!=="object")return;let J=Y,X=Number(J.startHour),Q=Number(J.endHour);if(!Number.isInteger(X)||!Number.isInteger(Q)||X<0||X>23||Q<0||Q>23||X===Q)return;return{startHour:X,endHour:Q}}function W8(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 Pz=300000,qz=3600000,Ez=1800000,Mz=60000,Az=32,Tz=8388608,Rz=30000,Cz=600000;function N1(Y,J){return typeof Y==="number"&&Number.isFinite(Y)&&Y>0?Y:J}function G9(Y){return Y instanceof Error?Y.message:String(Y)}class z8{targets=new Map;adapter;now;log;ttlMs;leadMs;maxIdleWarmMs;maxSubagentIdleMs;tickIntervalMs;maxTargets;maxBytes;warmTimeoutMs;backoff;getWindow;getSustain;setIntervalImpl;clearIntervalImpl;timer=null;startedAt=null;totalBytes=0;tickPromise=null;disposed=!1;abortController=new AbortController;constructor(Y){this.adapter=Y.adapter,this.now=Y.now,this.log=Y.logger,this.ttlMs=N1(Y.ttlMs,Pz),this.tickIntervalMs=N1(Y.tickIntervalMs,Mz),this.leadMs=N1(Y.leadMs,this.tickIntervalMs+15000),this.maxIdleWarmMs=N1(Y.maxIdleWarmMs,qz),this.maxSubagentIdleMs=N1(Y.maxSubagentIdleMs,Ez),this.maxTargets=N1(Y.maxTargets,Az),this.maxBytes=N1(Y.maxBytes,Tz),this.warmTimeoutMs=N1(Y.warmTimeoutMs,Rz),this.backoff=Y.backoffMs??Cz,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.pruneStale();let Q=Buffer.byteLength(X,"utf8");if(Q>this.maxBytes)return this.log?.debug("cachekeep track skipped (body exceeds maxBytes)",{sessionKey:J,bodyBytes:Q,maxBytes:this.maxBytes}),{tracked:!1,reason:"body-exceeds-max-bytes"};let G=this.getWindow?.();if(G&&!W8(G,new Date(this.now())))return this.log?.debug("cachekeep track skipped (outside window)",{sessionKey:J,startHour:G.startHour,endHour:G.endHour}),{tracked:!1,reason:"outside-window"};this.drop(J);while(this.targets.size>=this.maxTargets||this.totalBytes+Q>this.maxBytes&&this.targets.size>0){let V=this.leastRecentlyTouched();if(V===void 0)break;this.log?.debug("cachekeep evicted least recently used target",{sessionKey:V}),this.drop(V)}let $=Y.isSubagent===!0,W=Y.accountId||void 0,H=this.adapter.profile?.({bodyText:X,isSubagent:$,accountId:W,meta:Y.meta}),K=N1(H?.ttlMs,this.ttlMs),U=this.now();return this.targets.set(J,{bodyText:X,bodyBytes:Q,accountId:W,isSubagent:$,meta:Y.meta,ttlMs:K,maxWarms:H?.maxWarms!==void 0&&H.maxWarms>0?Math.floor(H.maxWarms):void 0,maxIdleMs:H?.maxIdleMs!==void 0?N1(H.maxIdleMs,this.idleDefault($)):void 0,cacheExpiresAt:U+K,lastRealRequestAt:U,failures:0,warmCount:0}),this.totalBytes+=Q,this.log?.debug("cachekeep captured target",{sessionKey:J,accountId:W}),this.start(),{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",{error:G9(Y)})})},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,this.targets.clear(),this.totalBytes=0,this.log?.debug("cachekeep stopped")}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,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?.();if(Y&&!W8(Y,new Date(this.now())))return;let J=this.now(),X=J+this.leadMs;for(let[Q,G]of[...this.targets]){if(this.disposed)return;if(this.targets.get(Q)!==G)continue;if(G.backoffUntil!==void 0&&J<G.backoffUntil)continue;if(G.cacheExpiresAt>X)continue;await this.warm(Q,G)}}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),!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}}fail(Y,J,X,Q={}){if(!this.isCurrent(Y,J))return;J.failures+=1;let G=typeof this.backoff==="function"?this.backoff({sessionKey:Y,failures:J.failures}):this.backoff;J.backoffUntil=this.now()+(Number.isFinite(G)&&G>0?G:0),this.log?.warn(X,{sessionKey:Y,accountId:J.accountId,failures:J.failures,backoffUntil:J.backoffUntil,...Q})}async warm(Y,J){if(this.retireIfExpired(Y,J))return;let X=this.view(Y,J);if(this.adapter.activeAccount){let V;try{V=await this.adapter.activeAccount(Y,X)}catch(O){this.fail(Y,J,"cachekeep skip (active account unknown)",{error:G9(O)});return}if(!this.isCurrent(Y,J))return;if(V!==void 0&&V!==J.accountId){this.log?.debug("cachekeep dropped target (session changed account)",{sessionKey:Y,accountId:J.accountId,activeAccountId:V}),this.drop(Y);return}}let Q;try{Q=await this.adapter.buildBody(X)}catch(V){this.fail(Y,J,"cachekeep skip (replay body unbuildable)",{error:G9(V)});return}if(!this.isCurrent(Y,J))return;if(this.retireIfExpired(Y,J))return;let G=sX([AbortSignal.timeout(this.warmTimeoutMs),this.abortController.signal]),$=G.signal,W,H="";try{W=await this.adapter.send({target:X,body:Q,signal:$}),H=await W.text().catch(()=>"")}catch(V){this.fail(Y,J,"cachekeep failed",{error:G9(V)});return}finally{G.dispose()}if(!this.isCurrent(Y,J))return;if(!W.ok){this.fail(Y,J,"cachekeep failed",{status:W.status,responseBody:H.slice(0,600)});return}let K;try{K=this.adapter.readUsage?.({target:X,response:W,text:H})}catch{}let U=this.now();if(J.cacheExpiresAt=U+J.ttlMs,J.lastWarmedAt=U,J.backoffUntil=void 0,J.failures=0,J.warmCount+=1,this.log?.debug("cachekeep fired",{sessionKey:Y,accountId:J.accountId,warmCount:J.warmCount,...K}),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)}idleDefault(Y){return Y?this.maxSubagentIdleMs:this.maxIdleWarmMs}pruneStale(){let Y=this.now(),J=this.getSustain?.()===!0;for(let[X,Q]of[...this.targets]){if(this.retireIfExpired(X,Q))continue;if(J&&!Q.isSubagent)continue;let G=Q.maxIdleMs??this.idleDefault(Q.isSubagent);if(Q.lastRealRequestAt>=Y-G)continue;this.log?.debug("cachekeep pruned idle target",{sessionKey:X,accountId:Q.accountId,lastRealRequestAt:Q.lastRealRequestAt,maxIdleMs:G}),this.drop(X)}}leastRecentlyTouched(){let Y,J=Number.POSITIVE_INFINITY;for(let[X,Q]of this.targets){let G=Math.max(Q.lastRealRequestAt,Q.lastWarmedAt??0);if(G<J)Y=X,J=G}return Y}drop(Y){let J=this.targets.get(Y);if(!J)return!1;return this.totalBytes-=J.bodyBytes,this.targets.delete(Y),!0}}function RY(Y){if(typeof Y!=="string")return!1;try{let J=JSON.parse(Y);return a(J)&&a(J.client_metadata)&&J.client_metadata.ws_request_header_x_openai_internal_codex_responses_lite==="true"}catch{return!1}}function CY(Y){if(typeof Y!=="string")return Y;try{let J=JSON.parse(Y);if(!a(J)||!a(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 $9(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"),RY(Y.body))J.set("x-openai-internal-codex-responses-lite","true");return{...Y,headers:J,body:CY(Y.body)}}var Gj=Object.freeze({maxTargets:32,maxBytes:8388608});function tX(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.headers.get("session-id")??Y.headers.get("x-opencode-session")??Y.headers.get("x-session-affinity")??void 0;if(!X)return;let Q={};for(let G 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 $=Y.headers.get(G);if($)Q[G]=$}return{sessionKey:X,bodyText:Y.body,replayHeaders:Q,isSubagent:J}}function eX(Y){return TY(Y?.cachekeep)}var wY=1800000,wz=2,Sz=2*wY+900000,Iz=/^gpt-(\d+)(?:\.(\d+))?(?:-|$)/;function bz(Y){try{let X=JSON.parse(Y).model;if(typeof X!=="string")return!1;let Q=Iz.exec(X);if(!Q)return!1;let G=Number(Q[1]),$=Q[2]===void 0?0:Number(Q[2]);return G>5||G===5&&$>=6}catch{return!1}}function kz(Y){if(!bz(Y.bodyText))return;if(!Y.isSubagent)return{ttlMs:wY};return{ttlMs:wY,maxWarms:wz,maxIdleMs:Sz}}function xz(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 SY(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function Y3(Y){if(!Y||typeof Y!=="object")return SY();let J=Y,X=Number(J.input_tokens)||Number(J.prompt_tokens)||0,Q=Number(J.output_tokens)||Number(J.completion_tokens)||0,G=J.input_tokens_details??J.prompt_tokens_details,$=Number(G?.cached_tokens)||Number(J.cached_tokens)||0,W=X>0?$/X:null;return{input_tokens:X,output_tokens:Q,cached_tokens:$,hit_rate:W}}function hz(Y){try{let J=JSON.parse(Y);return Y3(J.usage)}catch{return SY()}}function vz(Y){let J,X=[],Q,G=()=>{if(!X.length)return;let $=X.join(`
|
|
9
|
-
`).trim();X=[];let W=J;if(J=void 0,!$||$==="[DONE]")return;try{let H=JSON.parse($),K=H.type??W;if(K!=="response.completed"&&K!=="response.done")return;let U=H.response;Q=Y3(U?.usage??H.usage)}catch{}};for(let $ of Y.split(/\r?\n/)){if($===""){G();continue}if($.startsWith("event:")){J=$.slice(6).trim();continue}if($.startsWith("data:"))X.push($.slice(5).trim())}return G(),Q??SY()}function J3(Y,J,X=Date.now()){if(!J)return;if(Y.route==="sticky-balanced"){let G=Y.stickyAssignments?.[j1(J)];if(!G)return;if(G.lastSeenAt<X-aX)return;return G.accountId}let Q=Y.activeRouting?.[J];if(!Q||Q.route!==Y.route)return;return Q.activeId}function yz(Y){let J=J1(Y);return J?X1(J):void 0}function gz(Y){let{logger:J,activeAccount:X}=Y;return{buildBody:(Q)=>xz(Q.bodyText),async send({target:Q,body:G,signal:$}){let W=async(L,B,D)=>{if($.throwIfAborted(),Y.verifyCredential)await Y.verifyCredential({target:Q,mode:B?"vault":"local",identity:(B?B.accountIdentity:D)??yz(L)});let q={...Q.meta.replayHeaders,authorization:`Bearer ${L}`,"content-type":"application/json"};if(Q.meta.chatgptAccountId)q["ChatGPT-Account-Id"]=Q.meta.chatgptAccountId;else delete q["ChatGPT-Account-Id"];let E;try{let T=JSON.parse(G);E={warmBodyKeys:Object.keys(T),stream:T.stream,max_output_tokens:T.max_output_tokens,store:T.store,has_stream_options:"stream_options"in T,has_max_tokens:"max_tokens"in T,model:T.model}}catch{}J?.debug("cachekeep warm request",{...E,headerKeys:Object.keys(q),hasChatGptAccountId:"ChatGPT-Account-Id"in q});try{let T=await Y.fetchImpl(Q.meta.url??Y.codexResponsesUrl,$9({method:"POST",headers:q,body:G,signal:$}));return await Q6(T,L,"event-stream")}catch(T){throw v1(T,L)}};if(Q.accountId&&Y.vault?.owns(Q.accountId)){let L=await Y.vault.send(Q.accountId,W,{site:"cachekeep",signal:$});if(!L)throw Error(`vault refused warm for ${Q.accountId}`);return L}if(Y.vault&&await Y.vault.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");let H,K,U,V=Y.resolveLocal?await Y.resolveLocal(Q):Q.accountId&&Q.accountId!=="main"?await Y.refreshFallback(Q.accountId):await Y.getMainToken();if(typeof V==="string")H=V;else H=V.token,K=V.identity,U=V.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 O=await W(H,void 0,K);if(O.status===401)await U?.(O.status);return O},readUsage({response:Q,text:G}){let $=Q.headers.get("content-type")??"",W=$.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(G.slice(0,200));J?.debug("cachekeep warm response",{status:Q.status,contentType:$,bodyLen:G.length,isSse:W});let H=W?vz(G):hz(G),K=X6(Q.headers);return{...H,quota_primary_pct:K.primary?.usedPercent??null,quota_secondary_pct:K.secondary?.usedPercent??null}},profile:kz,...X?{activeAccount:(Q,G)=>X(G.meta.routingSessionId)}:{}}}function X3(Y){let{fetchImpl:J,getMainToken:X,refreshFallback:Q,resolveLocal:G,vault:$,codexResponsesUrl:W,activeAccount:H,verifyCredential:K,logger:U,...V}=Y,O=Y.resolveLocal!==void 0?{resolveLocal:Y.resolveLocal}:{getMainToken:Y.getMainToken,refreshFallback:Y.refreshFallback};return new z8({...V,logger:U,adapter:gz({fetchImpl:J,...O,vault:$,codexResponsesUrl:W,activeAccount:H,verifyCredential:K,logger:U})})}function Q3(Y){let J,X=0,Q=0,G=!1,$;return{read(){let W=Y.path(),H=Y.stat(W);if(H&&J?.path===W&&J.mtimeMs===H.mtimeMs&&J.size===H.size)return J.value;if(!H)J=void 0;let K=++X;return Y.read(W).catch(Y.fallback).then((U)=>{if(K>Q){if(Q=K,$=U,G=!0,H)J={...H,path:W,value:U};return Y.onRead(U),U}return G?$:U})},invalidate(){J=void 0}}}import{readFileSync as fz}from"node:fs";var mz=60000,cz=15000,kY=2000,xY=1e4;async function H8(Y,J){let X,Q=await Promise.race([Y.then(()=>!0,()=>!0),new Promise((G)=>{X=setTimeout(()=>G(!1),J),X.unref?.()})]);return clearTimeout(X),Q}function uz(Y){if(!y1(Y.quota))return;let J=W9(Y.quota);return J.limits.some((X)=>X.kind==="reading")?J.checkedAt:void 0}function pz(Y){if(!Y)return;let J=J1(Y);return J?X1(J):void 0}function G3(Y){try{let J=JSON.parse(fz(Y,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return;return a6(J).migratedAt}catch{return}}function lz(Y){if(Y.type!=="oauth")return!1;return Y.candidate||Y.torn===!0&&Y.enabled}class hY{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;marks=new Map;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??H0("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 H8(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(G3(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 H9(J,this.deps.readBudgetMs??z9,()=>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}|${bY(Y.configPath)}|${bY(Y.statePath)}`}storeFor(Y){if(this.store?.configPath===Y.configPath)return this.store.store;let J=F6({provider:"openai",configPath:Y.configPath,statePath:Y.statePath,quota:j6,coalesceQuota:!0,now:this.now,pull:(X)=>this.coalescedPull(X),onPullFailure:(X,Q)=>{this.pollOutcomes.set(X,{id:X,ok:!1,error:Q.message}),this.log.warn("pool quota poll failed",{rowId:X,kind:Q.kind,error:Q.message})},logger:this.log,...this.deps.store,onStep:async(X,Q)=>{if(await this.deps.store?.onStep?.(X,Q),Q.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,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),Q={key:Y,promise:X};this.inflightRead=Q;let G=()=>{if(this.inflightRead===Q)this.inflightRead=void 0};return X.then(G,G),X}async read(Y,J){let X=this.deps.paths(),Q={active:!1,rows:[],key:Y,readAt:J};try{if(G3(X.configPath)!==void 0){let W=await this.storeFor(X).read();if(W.status==="ready")Q={active:!0,rows:W.rows,key:Y,readAt:J};else this.log.warn("migrated install has no readable account pool",{status:W.status,...W.status==="error"?{reason:W.reason}:{}})}}catch($){return this.log.warn("account pool read failed",{error:$ instanceof Error?$.message:String($)}),this.snapshot}if(this.disposed)return this.snapshot;let G=this.snapshot.active;if(J>=this.snapshot.readAt)this.snapshot={...Q,rows:this.withLocalState(Q.rows)},this.changed();if(this.snapshot.active){if(!G)this.log.info("account pool serves requests");this.pollUnseenRows()}return this.snapshot}withLocalState(Y){let J=this.now();return Y.map((X)=>{let Q=X,G=this.rotated.get(X.id),$=G?.credential;if(G&&G.credentialEpoch!==X.credentialEpoch)this.rotated.delete(X.id);else if($?.type==="oauth"&&X.credential?.type==="oauth"){let W=X.credential.lastRefreshedAt??0,H=$.lastRefreshedAt??0;if(W>=H)this.rotated.delete(X.id);else Q={...Q,credential:$}}return H3(Q,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,H8(Y,this.deps.vaultFirstRosterBackgroundWaitMs??xY).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(!lz(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(),Q=this.lastPull.get(Y);if(!J&&Q!==void 0&&X-Q<(this.deps.pullRetryMs??cz))return this.storeFor(this.deps.paths()).pullsSettled();this.lastPull.set(Y,X);let G=this.storeFor(this.deps.paths());return G.requestReading(Y),G.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 Q=this.pull(Y).finally(()=>this.quotaPulls.delete(J));return this.quotaPulls.set(J,Q),Q}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(Q){throw this.pollOutcomes.set(Y.id,{id:Y.id,ok:!1,error:Q instanceof Error?Q.message:String(Q)}),Q}this.pollOutcomes.set(Y.id,{id:Y.id,ok:!0});let X=this.snapshot.rows.find((Q)=>Q.id===Y.id);if(X&&X.credentialEpoch===Y.credentialEpoch&&X.identity===Y.identity)this.applyObservation(X,J);return J}applyObservation(Y,J){z3(this.pending,Y,J),this.replaceRow(Y.id,(X)=>({...X,quota:W3(X.quota,J),needsFirstReading:!1}))}recordSnapshot(Y,J,X,Q){if(!this.snapshot.active||this.disposed||this.deps.vaultMode?.())return;let G=this.snapshot.rows.find((L)=>L.id===Y);if(G?.type!=="oauth")return;let $=pz(X);if(!($&&G.identity?$===G.identity:C6(G)?.access===X))return;let H=q6(J,this.now(),Q);if(!H)return;if(this.applyObservation(G,H),G.credentialEpoch===void 0)return;let K={credentialEpoch:G.credentialEpoch,...G.identity!==void 0?{identity:G.identity}:{}},U=this.storeFor(this.deps.paths()),O=(this.writes.get(G.id)??Promise.resolve()).then(async()=>{if(this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")return;return U.recordQuota(G.id,K,H)}).catch((L)=>{this.log.warn("pool quota not recorded",{rowId:G.id,error:L instanceof Error?L.message:String(L)})});this.writes.set(G.id,O),O.finally(()=>{if(this.writes.get(G.id)===O)this.writes.delete(G.id)})}markRateLimited(Y,J){let X=this.snapshot.rows.find(($)=>$.id===Y);if(!X)return;let Q=IY(X),G=this.marks.get(Q);if(G!==void 0&&G>J)return;this.marks.set(Q,J)}rateLimitMarks(Y){let J=new Map;for(let X of Y){let Q=this.marks.get(IY(X));if(Q!==void 0)J.set(X.id,Q)}return J}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??kY);let Q=this.now(),G=$3(J),$=[];for(let W of Y){if(!W.candidate||this.vaultOwned(W))continue;let H=C6(W);if(!H)continue;let K=(H.expires??0)-Q;if(!(!H.access||!H.expires||K<=G)||this.refreshBackedOff(W,J,Q))continue;let V=this.refresh(W.id);if(X.waitForAll||!H.access||!H.expires||K<=mz)$.push(V)}await Promise.all($)}refreshBackedOff(Y,J,X=this.now()){let Q=C6(Y);if(!Q)return!1;let G=K8(Q.refresh),$=this.backoff.get(Y.id);if($&&$.tokenHash===G&&$.nextRetryAt>X)return!0;let W=J?.accounts.find((H)=>H.id===Y.id);return Boolean(W?.type==="oauth"&&W.corrupt!==!0&&M1(W.lastRefreshError,Q.refresh,X))}usableToken(Y,J=this.now()){let X=this.snapshot.rows.find((G)=>G.id===Y.id);if(!X?.enabled||!X.candidate||X.type!=="oauth"||X.identity!==Y.identity||X.credentialEpoch!==Y.credentialEpoch||this.vaultOwned(X))return;let Q=C6(X);if(!Q?.access.trim())return;if(typeof Q.expires!=="number"||Q.expires<=J)return;return Q.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((W)=>W.id===Y),Q=X?C6(X)?.refresh:void 0,G,$=(W,H)=>{return G=H.credentialEpoch,this.deps.refreshProvider(W,H)};try{let W=await Z3({paths:J,store:this.storeFor(J),now:this.now,...this.deps.legacyLocks?{legacyLocks:this.deps.legacyLocks}:{}},Y,$);if(W.status==="rotated"){this.backoff.delete(Y),this.rotated.set(Y,{credential:W.credential,credentialEpoch:G}),this.replaceRow(Y,(H)=>H.credentialEpoch!==G?H:{...H,credential:W.credential,...W.identity!==void 0&&H.identity===void 0?{identity:W.identity}:{}});return}if(W.status==="identity-contradicted"){this.backoff.delete(Y),this.replaceRow(Y,(H)=>({...H,enabled:!1,candidate:!1})),this.log.warn("pool row disabled: its refresh returned a different account",{rowId:Y});return}this.recordRefreshFailure(Y,Q,Error(W.reason))}catch(W){this.recordRefreshFailure(Y,Q,W)}}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,K3(J,X,this.now(),this.backoff.get(Y)))}refreshBackoffFor(Y){return U3(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 Q=this.now(),G=X.rows.filter(($)=>{if(!$.candidate||$.type!=="oauth"||this.vaultOwned($))return!1;if(J.ids&&!J.ids.includes($.id))return!1;if(J.skipReadWithinMs===void 0)return!0;let W=uz($);return W===void 0||Q-W>=J.skipReadWithinMs});if(G.length===0)return[];await this.prepareTokens(G,Y,{waitForAll:!0});for(let $ of G)this.pollOutcomes.delete($.id),this.requestReading($.id,!0);return await this.poolStore().pullsSettled(),G.map(($)=>this.pollOutcomes.get($.id)??{id:$.id,ok:!1,error:"the quota poll did not run"})}async accessFor(Y,J){let X=await this.current();if(!X.active)return;let Q=X.rows.find((W)=>W.id===Y);if(!Q?.candidate)return;await this.prepareTokens([Q],J);let G=this.snapshot.rows.find((W)=>W.id===Y)??Q;if(!G.candidate)return;let $=this.usableToken(G);return $?{row:G,token:$}:void 0}async rowAccess(Y,J){let X=await this.current();if(!X.active)return;let Q=X.rows.find(($)=>$.id===Y);if(!Q)return{};let G=await this.accessFor(Y,J);return{row:{id:Q.id,type:Q.type,enabled:Q.enabled,...Q.label!==void 0?{label:Q.label}:{},...Q.identity!==void 0?{identity:Q.identity}:{}},...G?{token:G.token}:{}}}dispose(){return this.disposed=!0,this.disposal??=(async()=>{await Promise.allSettled([...this.writes.values()]),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}}}}var V3=60000,vY=900000,dz={set(Y,J){let X=setTimeout(Y,J);return X.unref?.(),X},clear(Y){clearTimeout(Y)}};function iz(Y){return Y.status==="completed"||Y.status==="already-migrated"||Y.status==="nothing-to-import"||Y.status==="ambiguous"}function B3(Y){return Y.status==="deferred"||Y.status==="retry"||Y.status==="error"}function L3(Y){let J=Y.log??H0("pool-migration"),X=Y.timers??dz,Q=Y.random??Math.random,G=Y.migrate??K9,$=Y.adopt??U9,W=Y.fence??(()=>E6({currentVersion:Y.version})),H=!1,K=new AbortController,U=!1,V=!1,O=0,L,B=Promise.resolve(),D,q,E,T=!1;function I(){if(T)return;T=!0,J.warn(_6,{reason:"placeholder-without-main"})}let x=()=>({paths:Y.paths(),slot:Y.slot,log:J,...Y.runDeps,signal:K.signal});function j(p){let t=B.then(p).catch((L0)=>{J.warn("account pool background run failed",{error:L0 instanceof Error?L0.message:String(L0)})});return B=t,t}function w(p){if(U)return;if(L!==void 0)X.clear(L);L=X.set(()=>{L=void 0,j(V0)},p)}function v(){let p=Math.min(V3*2**Math.min(O,10),vY);return O++,M(p)}let M=(p)=>Math.round(p*(1-0.2*Q()));async function g(){if(!await Y.paused?.())return!1;return w(M(V3)),!0}async function o(){if(U||await g()||U)return;let p;try{p=await G({...x(),fence:W})}catch(t){J.warn("account pool migration failed; it will be tried again",{error:t instanceof Error?t.message:String(t)}),w(v());return}if(p.status==="refused"){if(p.reason==="placeholder-without-main")I();w(M(vY));return}if(iz(p)){if(V=!0,O=0,p.status==="completed")J.info("account pool migration completed",{rowId:p.rowId});await i();return}if(B3(p)){if(p.status!=="deferred")J.warn("account pool migration will be tried again",{outcome:p});w(v())}}async function i(){if(U||await g()||U)return;let p;try{let t=await W();if(U)return;if(!t.open){let L0=JSON.stringify(t.blockers);if(L0!==E)E=L0,J.info("host login adoption waits for older plugin versions",{blockers:t.blockers});w(v());return}p=await $(x())}catch(t){J.warn("adopting the host login into the account pool failed",{error:t instanceof Error?t.message:String(t)}),w(v());return}if(p.status==="not-migrated")return;if(p.status==="slot-read-only")return;if(V=!0,p.status==="completed")J.info("host login adopted into the account pool",{rowId:p.rowId,operation:p.operation});if(B3(p)){J.warn("host login adoption will be tried again",{outcome:p}),w(v());return}if(O=0,V)w(M(vY))}async function V0(){if(U)return;if(V)await i();else await o()}function B0(){if(D)return D;let p=j(async()=>{if(D=void 0,!U)if(V)await i();else await o()});return D=p,p}return{start(){if(H||U)return;H=!0,j(o)},requestAdoption:B0,noticePlaceholderWithoutMain:I,noticeRealSlot(p){if(!V||U||p===q)return;q=p,B0()},dispose(){if(U=!0,K.abort(),L!==void 0)X.clear(L);L=void 0},idle:async()=>{for(;;){let p=B;if(await p,p===B)return}},migrated:()=>V}}var G6={"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.",..._3};function cY(Y){return Y!==void 0&&O3.includes(Y)}function nz(Y,J,X,Q=new Set){return Y.filter((G)=>{if(!G.enabled||!G.candidate||G.type!=="oauth")return!1;if(G.credential?.type!=="oauth")return!1;if(c0(G.credential))return!1;if(G.identity!==void 0&&Q.has(G.identity))return!1;if(G.id===R1)return!0;if(D3(J,{accountId:G.identity}))return!1;return mY(T1(G.quota),J,X)})}function gY(Y){let J=Y.vault;return[...(J?[]:nz(Y.source.peek().rows,Y.storage,Y.now())).map((Q)=>({id:Q.id,kind:"oauth",...Q.identity!==void 0?{identity:Q.identity}:{},...Q.quota!==void 0?{quota:Q.quota}:{},row:Q})),...(J?.routes()??[]).filter((Q)=>mY(T1(Q.quota),Y.storage,Y.now())).map((Q)=>({id:Q.id,kind:Q.kind,...Q.identity!==void 0?{identity:Q.identity}:{},...Q.quota!==void 0?{quota:Q.quota}:{}}))]}function oz(Y){return Y.flatMap((J)=>J.row?[J.row]:[])}function Z9(Y,J){let X=Y.now(),Q=Z8(J,Y.storage,X),G=J.map((K)=>({id:K.id,kind:K.kind,...y1(K.quota)?{quota:K.quota}:{}})),$=oz(J),W=new Set(J.filter((K)=>!K.row).map((K)=>K.id)),H=Y.source.rateLimitMarks($);for(let[K,U]of Y.vault?.rateLimitMarks?.()??[])if(W.has(K)&&U>X)H.set(K,U);return{rows:G,now:X,rateLimitMarks:H,refreshBackoff:Y.source.refreshBackoffFor($),killswitch:Q,requestPull:(K)=>W.has(K)?Y.vault?.requestReading(K):Y.source.requestReading(K)}}function N3(Y){let J=Y.find((X)=>X.id===R1);return{main:J?T1(J.quota):void 0,fallbacks:Y.filter((X)=>X.id!==R1).map((X)=>{let Q=T1(X.quota);return{accountId:X.id,...Q?{quota:Q}:{}}})}}async function fY(Y,J){if(J.row){let X=Y.source.usableToken(J.row);if(!X)return;let Q=await Y.send(J,X);return Y.recordQuota(Q,J,X),Q}return Y.vault?.send(J.id,async(X,Q)=>{let G=await Y.send(J,X,Q);return Y.recordQuota(G,J,X,Q),G})}async function C3(Y){if(Y.vault)await Y.vault.awaitRoster();else await Y.source.current(),await Y.source.prepareTokens(Y.source.peek().rows,Y.storage);let J=gY(Y),X=Y.replayable===!1&&J.some((G)=>G.id===R1)?J.filter((G)=>G.id===R1):J,Q=E3(Z9(Y,X));if(Q)await Q,J=gY(Y);if(Y.mode==="sticky-balanced"&&Y.sessionId&&Y.replayable&&Y.body!==void 0){let G=await sz(Y,J,Y.sessionId,Y.body);if(G)return G}return rz(Y,J)}async function rz(Y,J){let X=q3(Y.mode),Q=Z9(Y,J),G=M3({...Q,placement:X,mainId:Y.vault?Y.mode==="sticky-balanced"?null:P3(Y.vault.routes()):void 0,replayable:Y.replayable});if(G.kind==="block")return Y.log.debug("pool admission blocked the request",{pid:process.pid,reason:G.block.reason}),{response:Y.blocked(G.block,N3(J),Y.vault?J.length===0?Y.vault.noRouteCause():void 0:J.length===0?"no-accounts":"unusable"),servedId:R1};if(G.lastPath)Y.log.debug("pool admission: every account is exhausted; probing anyway",{pid:process.pid,order:G.order});let $=new Map(J.map((O)=>[O.id,O])),W=F3(Y.storage),H=[],K=new Set,U,V=!1;for(;;){let O=j3(G.order.filter((D)=>!K.has(D)),H,W),L=O===void 0?void 0:$.get(O);if(!L)break;let B;try{B=await fY(Y,L)}catch(D){if(Y.isAbort(D)||!U||Y.mode==="fallback-first")throw D;return Y.log.debug("pool fallback attempt threw; stopping",{pid:process.pid,accountId:L.id}),U}if(!B){if(!L.row)V=!0;K.add(L.id);continue}U?.response.body?.cancel().catch(()=>{}),U={response:B,servedId:L.id},H.push({id:L.id,status:B.status})}if(U)return w3(Y,Q,U.servedId),U;return{response:Y.blocked({reason:"no-credential"},N3(J),V?"vault-refused":Y.vault?"vault-empty":"unusable"),servedId:R1}}async function sz(Y,J,X,Q){let G=Buffer.byteLength(Q,"utf8"),$=new Map(J.map((T)=>[T.id,T])),W=Z9(Y,J),H=yY(W),K={requestBytes:G,reservePercent:(T)=>U8(Y.storage,T===R1?void 0:T),resetCredits:Y.resetCredits,onEmptyWeightedSet:()=>{Y.log.debug("sticky routing: no fresh weighted candidates; using configured order")}},U=(T,I)=>(x,j)=>{let w=new Set(x);return Y.placePin({sessionId:X,requestBytes:G,now:T.now,validPinnedAccountIds:T.rows.map((v)=>v.id).filter((v)=>!I.excluded.has(v)),excludeAccountIds:x,quotaCheckedAtByAccount:Object.fromEntries(T.rows.map((v)=>[v.id,I.projections.get(v.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(J.map((v)=>[v.id,v.identity])),select:(v)=>A3(T,K,w,v),persist:j})},V=U(W,H),O=V([],!0);if(!O)return;let L=O.accountId,B=(T)=>{let I=V([L],!0);if(!I)return!1;return Y.log.debug("sticky routing: migrated session pin",{pid:process.pid,fromAccountId:L,toAccountId:I.accountId,reason:T}),L=I.accountId,!0},D=T3(W,K,L);if(D.kind==="none")return;if(D.kind==="move"){if(!B(D.reason)&&D.reason==="killswitch")return}else if(D.kind==="detour"){let T=V([L],!1);if(!T)return;Y.log.debug("sticky routing: pinned account awaits a quota reading",{pid:process.pid,pinnedAccountId:L,servedAccountId:T.accountId}),L=T.accountId}let q=$.get(L);if(!q)return;let E=await fY(Y,q);if(!E)return;if(E.status===401||E.status===403||E.status===429){let T=gY(Y);W=Z9(Y,T),H=yY(W),V=U(W,H);let I=R3(W,H,L,E.status);if(I.action==="migrate"){let x=L;if(B(I.reason)&&L!==x){let j=T.find((v)=>v.id===L),w=j?await fY(Y,j):void 0;if(j&&w){let v=E;E=w,v.body?.cancel().catch(()=>{}),q=j}else L=x}}}return w3(Y,W,q.id),{response:E,servedId:q.id}}function w3(Y,J,X){let Q=Y.log.info;Y.creditsServing?.served(J,X,Q?{info:(G,$)=>Q.call(Y.log,G,$)}:void 0)}var az=new Map([["needs_reauth","needs sign-in"],["retired","turned off in vault"],["corrupt","unavailable"]]);function V8(Y){return typeof Y==="number"&&Number.isFinite(Y)}function tz(Y){if(!y1(Y))return;let J=Y.budget;if(J?.kind!=="reading")return;let{limit:X,used:Q,remaining:G,usedPercent:$,remainingPercent:W}=J;if(!V8(X)||!V8(Q)||!V8(G)||!V8($)||!V8(W))return;return{limit:X,used:Q,remaining:G,usedPercent:$,remainingPercent:W,reached:J.reached,...J.resetsAt!==void 0?{resetsAt:J.resetsAt}:{},...J.unit!==void 0?{unit:J.unit}:{}}}function uY(Y,J){let X=T1(Y),Q=tz(Y),G=y1(Y)?Y.credits:void 0;if(!X&&!Q&&!G)return null;let $=y1(Y)?W9(Y).checkedAt:void 0;return{...$!==void 0?{checkedAt:$}:{},...X?.primary?{primary:X.primary}:{},...X?.secondary?{secondary:X.secondary}:{},...Q?{spendControl:Q}:{},...J!==void 0?{resetCreditsAvailable:J}:{},...G?{credits:{...G}}:{}}}function S3(Y,J,X,Q){let G=Y??[],$=Z8(G.map((W)=>({id:W.routeId,quota:W.quota})),{version:1,accounts:[],...X},Q);return{main:{quota:null,killed:!1},fallbacks:[],vaultDiscovered:Y!==void 0,vaultAccounts:G.map((W)=>{let H=W.quota?.counters?.resetCredits?.value;return{id:W.routeId,credentialId:W.credentialId,label:W.email||W.label||W.routeId,...W.accountIdentity!==void 0?{accountId:W.accountIdentity}:{},quota:uY(W.quota,H),killed:$.get(W.routeId)===!1,enabled:W.enabled,routable:J.has(W.routeId),...W.state!=="active"||W.stale||W.unclaimed||W.enabled&&!J.has(W.routeId)?{vaultState:az.get(W.state)??"unavailable"}:{},...H!==void 0?{resetCredits:H}:{}}}),route:X?.routing?.mode??"main-first",lastUpdated:Q}}function I3(Y,J,X,Q=()=>{return}){let G=Z8(Y,{version:1,accounts:[],...J},X),$=Y.find((H)=>H.id===B1),W=$?Q($.id):void 0;return{main:{quota:$?uY($.quota,W):null,...$?.identity!==void 0?{mainAccountId:$.identity}:{},killed:G.get(B1)===!1,...W!==void 0?{resetCredits:W}:{}},fallbacks:Y.filter((H)=>H.id!==B1&&H.enabled).map((H)=>{let K=Q(H.id);return{id:H.id,label:H.label,...H.identity!==void 0?{accountId:H.identity}:{},quota:uY(H.quota,K),killed:G.get(H.id)===!1,enabled:!0,...K!==void 0?{resetCredits:K}:{}}}),route:J?.routing?.mode??"main-first",lastUpdated:X,accountPool:!0}}import{resolve as V9}from"node:path";import{resolveClaustrumConnectionPath as ez}from"@cortexkit/claustrum-client";var b3=H0("vault"),YH=60000,JH=240000,h3=Symbol.for("@cortexkit/openai-auth/opencode-vaults"),v3=globalThis,B9=v3[h3]??new Map;v3[h3]=B9;function XH(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 y3(Y,J){let X=Boolean(Y.connectScoped||Y.connectEnrollment),Q=V9(Y.stateDir),G=V9((Y.connectionFile??ez)()),$=JSON.stringify([Y.host,Q,G,V9(J.configPath),V9(J.statePath)]),W={reservedRouteIds:Y.reservedRouteIds??(()=>[])},H=B9,K=B9.get($);if(!X&&K!==void 0&&!XH(K)){let L=B9;L.compatibleV1??=new Map,H=L.compatibleV1}let U=X?void 0:H.get($);if(!U){let L=new Set;if(U={protocol:1,vault:new k3({...Y,stateDir:Q,connectionFile:()=>G,...!X?{projectRoot:Q}:{},reservedRouteIds:()=>new Set([...L].flatMap((D)=>[...D.reservedRouteIds()])),afterDisconnect:async()=>{await Y.afterDisconnect?.();try{await x3(Q)}catch(D){b3.warn("could not remove the old vault enrollment state",{error:D instanceof Error?D.message:String(D)})}}}),holders:L,firstRoster:Promise.withResolvers(),started:!1},!X)H.set($,U)}U.holders.add(W);let V=U,O=!1;return{vault:V.vault,firstRoster:V.firstRoster.promise,start(){if(O||V.started)return;V.started=!0;let L=async()=>{try{if(V.holders.size&&await V.vault.authority()!=="local")await V.vault.pollStale(JH)}catch(D){b3.warn("vault background quota poll failed",{error:D instanceof Error?D.message:String(D)})}};V.vault.start(),V.vault.firstRoster().finally(()=>{V.firstRoster.resolve(),L()}),V.quotaPoll=setInterval(L,YH),V.quotaPoll.unref?.()},release(){if(O)return;if(O=!0,V.holders.delete(W),V.holders.size!==0)return;if(V.quotaPoll)clearInterval(V.quotaPoll);if(V.vault.close(),V.firstRoster.resolve(),!X&&H.get($)===V)H.delete($)}}}var u3=900000,QH=0.016666666666666666,g3=0.000001;function lY(Y,J){for(let X of[Y?.primary?.checkedAt,Y?.checkedAt,J])if(typeof X==="number"&&Number.isFinite(X))return X;return}function dY(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let J=lY(Y.quota,Y.quotaCheckedAt);if(J===void 0||!Number.isFinite(J)||Y.now-J>u3)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let X=pY(Y.quota).sort((G,$)=>{let W=G.windowMs,H=$.windowMs,K=typeof W==="number"&&Number.isFinite(W),U=typeof H==="number"&&Number.isFinite(H);if(K!==U)return K?-1:1;if(K&&U)return H-W;return 0});for(let{key:G,window:$}of X)if(Number.isFinite($.remainingPercent)&&$.remainingPercent<=0)return{action:"migrate",reason:"exhausted",windowKey:G,...typeof $.resetsAt==="string"?{resetsAt:$.resetsAt}:{}};let Q=c3(Y.quota,Y.now);if(Q)return{action:"migrate",reason:"exhausted",resetsAt:Q.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 f3(Y,J,X){let Q=Math.max(0,Y.remainingPercent-J);if(Q<=0)return 0;if(!Y.resetsAt)return Q;let G=Date.parse(Y.resetsAt);if(!Number.isFinite(G)||G<=X)return Q;let $=Math.max((G-X)/3600000,QH);return Q/$}function m3(Y,J){if(Y<J)return-1;if(Y>J)return 1;return 0}function GH(Y,J){if(!Y.quota)return;let X=lY(Y.quota,Y.quotaCheckedAt);if(X===void 0||J-X>u3)return;let Q=pY(Y.quota).map(({key:W,window:H})=>{return f3(H,Y.reservePercent[W]??0,J)}),G=Y.quota.spendControl;if(G&&Number.isFinite(G.remainingPercent))Q.push(f3(G,0,J));let $=Q.length>0?Math.min(...Q):0;return $>0?{candidate:Y,quotaCheckedAt:X,weight:$}:void 0}function p3(Y){let J=Y.candidates.filter((G)=>G.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((G)=>GH(G,Y.now)).filter((G)=>G!==void 0);if(X.length>0){X.sort(($,W)=>{let H=((Y.pendingBytes.get($.candidate.accountId)??0)+Y.requestBytes)/Math.max($.weight,g3),K=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,g3);return H-K||$.candidate.configuredOrder-W.candidate.configuredOrder||m3($.candidate.accountId,W.candidate.accountId)});let G=X[0];if(G)return{accountId:G.candidate.accountId,quotaCheckedAt:G.quotaCheckedAt,source:"weighted"}}Y.onEmptyWeightedSet?.();let Q=[...J].sort((G,$)=>{let W=(G.resetCreditsApplicable??0)>0?1:0;return(($.resetCreditsApplicable??0)>0?1:0)-W||G.configuredOrder-$.configuredOrder||m3(G.accountId,$.accountId)})[0];if(!Q)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Q.accountId,quotaCheckedAt:lY(Q.quota,Q.quotaCheckedAt),source:"mode-fallback"}}import{readFile as $H}from"node:fs/promises";import{homedir as WH}from"node:os";import{join as l3}from"node:path";var zH="https://models.dev/api.json",HH="OPENCODE_OPENAI_AUTH_MODELS_CACHE",KH="OPENCODE_MODELS_PATH",UH="OPENCODE_DISABLE_MODELS_FETCH",ZH=1e4,VH=300000;function g1(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function d3(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function iY(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 Q=d3(Y.cache_read),G=d3(Y.cache_write);if(Q===null||G===null)return null;return{input:J,output:X,cache:{read:Q,write:G}}}function BH(Y){let J=g1(Y);if(!J)return null;let X=iY(J);if(!X)return null;let Q=X;if(Array.isArray(J.tiers)){let W=[];for(let H of J.tiers){let K=g1(H);if(!K)continue;let U=g1(K.tier),V=U?.size;if(U?.type!=="context")continue;if(typeof V!=="number"||!Number.isFinite(V)||V<=0)continue;let O=iY(K);if(!O)continue;W.push({...O,tier:{type:"context",size:V}})}if(W.length>0)Q.tiers=W}let G=g1(J.context_over_200k),$=G?iY(G):null;if($)Q.experimentalOver200K=$;return Q}function i3(Y){let J=g1(Y),X=g1(J?.openai),Q=g1(X?.models);if(!Q)return null;let G={};for(let[$,W]of Object.entries(Q)){let H=g1(W),K=BH(H?.cost);if(K)G[$]=K}return Object.keys(G).length>0?G:null}function LH(){let Y=process.env[HH]?.trim();if(Y)return Y;let J=process.env[KH]?.trim();if(J)return J;let X=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||l3(WH(),".cache");return l3(X,"opencode","models.json")}function NH(){let Y=process.env[UH]?.toLowerCase();return Y==="true"||Y==="1"}async function jH(){try{let Y=i3(JSON.parse(await $H(LH(),"utf8")));if(Y)return Y}catch{}if(NH())return null;try{let Y=await fetch(zH,{signal:AbortSignal.timeout(ZH)});if(!Y.ok)return null;return i3(await Y.json())}catch{return null}}var w6;function n3(){let Y=Date.now();if(w6&&w6.expiresAt>Y)return w6.promise;let J={expiresAt:Y+VH,promise:jH()};return w6=J,J.promise.then((X)=>{if(X===null&&w6===J)w6=void 0}),J.promise}function S6(Y){return typeof Y==="object"&&Y!==null}function FH(Y){if(Array.isArray(Y))return Y;if(S6(Y)&&Array.isArray(Y.data))return Y.data;return[]}function DH(Y){if(!S6(Y)||!S6(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function o3(Y){if(!S6(Y)||!S6(Y.info))return null;let J=Y.info,X=S6(J.model)?J.model:void 0,Q=typeof J.agent==="string"?J.agent:void 0,G=typeof X?.providerID==="string"?X.providerID:typeof J.providerID==="string"?J.providerID:void 0,$=typeof X?.modelID==="string"?X.modelID:typeof J.modelID==="string"?J.modelID:void 0,W=typeof X?.variant==="string"?X.variant:typeof J.variant==="string"?J.variant:void 0;if(!Q&&(!G||!$)&&!W)return null;let H={};if(Q)H.agent=Q;if(G&&$)H.model={providerID:G,modelID:$};if(W)H.variant=W;return H}function r3(Y,J){return{agent:Y.agent??J.agent,model:Y.model??J.model,variant:Y.variant??J.variant}}function s3(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function a3(Y,J){if(!Y||!J)return null;let X=Y;if(typeof X.session?.messages!=="function")return null;let Q=[];try{Q=FH(await Promise.resolve(X.session.messages({path:{id:J},query:{limit:100}})))}catch{return null}if(Q.length===0)return null;let G={};for(let $=Q.length-1;$>=0;$--){if(DH(Q[$])!=="assistant")continue;let W=o3(Q[$]);if(!W)continue;if(G=r3(G,W),s3(G))return G}for(let $=Q.length-1;$>=0;$--){let W=o3(Q[$]);if(!W)continue;if(G=r3(G,W),s3(G))return G}if(!G.agent&&!G.model&&!G.variant)return null;return G}var OH=H0("rpc"),J2="__openaiAuthRpcServers";async function X2(Y){let J=await t3({...Y,isManagedDir:Y2,log:OH,drain:(X,Q)=>Y.drain(X,Q),apply:async(X)=>await Y.apply(X)});try{return await e3(Y.dir,{port:J.port,token:J.token,pid:process.pid},{secureDir:Y.secureDir}),J}catch(X){throw await J.stop(),X}}var k1={};oY(k1,{withoutInternalHeaders:()=>tG,sanitizeHttpFallbackBody:()=>CY,orderCodexBody:()=>t1,hasWebSocketResponsesLiteMetadata:()=>RY,createWebSocketFetch:()=>GB,applyTurnId:()=>iG,advanceTurn:()=>p4,TITLE_HEADER:()=>u4,QUOTA_ACCOUNT_HEADER:()=>g9,OpenAIWebSocketPool:()=>k1,CODEX_BODY_KEY_ORDER:()=>UY});import{createHash as eV}from"node:crypto";var _H=Symbol.for("vercel.ai.error"),C1=class Y extends Error{constructor({name:J,message:X,cause:Q}){super(X);this[_H]=!0,this.name=J,this.cause=Q}static isInstance(J){return Y.hasMarker(J,"vercel.ai.error")}static hasMarker(J,X){let Q=Symbol.for(X);return J!=null&&typeof J==="object"&&Q in J&&typeof J[Q]==="boolean"&&J[Q]===!0}},PH="AI_DecisionUnsupportedQuestionTypeError",tj=`vercel.ai.error.${PH}`;var Q2="AI_APICallError",G2=`vercel.ai.error.${Q2}`,qH=Symbol.for(G2),$6=class extends C1{constructor({message:Y,url:J,requestBodyValues:X,statusCode:Q,responseHeaders:G,responseBody:$,cause:W,isRetryable:H=Q!=null&&(Q===408||Q===409||Q===429||Q>=500),data:K}){super({name:Q2,message:Y,cause:W});this[qH]=!0,this.url=J,this.requestBodyValues=X,this.statusCode=Q,this.responseHeaders=G,this.responseBody=$,this.isRetryable=H,this.data=K}static isInstance(Y){return C1.hasMarker(Y,G2)}},EH="AI_EmptyResponseBodyError",ej=`vercel.ai.error.${EH}`;var MH="AI_DecisionRefusalError",YF=`vercel.ai.error.${MH}`;var $2="AI_InvalidArgumentError",W2=`vercel.ai.error.${$2}`,AH=Symbol.for(W2),z2=class extends C1{constructor({message:Y,cause:J,argument:X}){super({name:$2,message:Y,cause:J});this[AH]=!0,this.argument=X}static isInstance(Y){return C1.hasMarker(Y,W2)}},TH="AI_InvalidPromptError",JF=`vercel.ai.error.${TH}`;var RH="AI_InvalidResponseDataError",XF=`vercel.ai.error.${RH}`;var CH="AI_JSONParseError",QF=`vercel.ai.error.${CH}`;var wH="AI_LoadAPIKeyError",GF=`vercel.ai.error.${wH}`;var SH="AI_LoadSettingError",$F=`vercel.ai.error.${SH}`;var IH="AI_NoContentGeneratedError",WF=`vercel.ai.error.${IH}`;var bH="AI_NoSuchModelError",zF=`vercel.ai.error.${bH}`;var kH="AI_NoSuchProviderReferenceError",HF=`vercel.ai.error.${kH}`;var xH="AI_TooManyEmbeddingValuesForCallError",KF=`vercel.ai.error.${xH}`;var hH="AI_TypeValidationError",UF=`vercel.ai.error.${hH}`;var vH="AI_UnsupportedFunctionalityError",ZF=`vercel.ai.error.${vH}`;var NF=Object.freeze({status:"aborted"});function _(Y,J,X){function Q(H,K){var U;Object.defineProperty(H,"_zod",{value:H._zod??{},enumerable:!1}),(U=H._zod).traits??(U.traits=new Set),H._zod.traits.add(Y),J(H,K);for(let V in W.prototype)if(!(V in H))Object.defineProperty(H,V,{value:W.prototype[V].bind(H)});H._zod.constr=W,H._zod.def=K}let G=X?.Parent??Object;class $ extends G{}Object.defineProperty($,"name",{value:Y});function W(H){var K;let U=X?.Parent?new $:this;Q(U,H),(K=U._zod).deferred??(K.deferred=[]);for(let V of U._zod.deferred)V();return U}return Object.defineProperty(W,"init",{value:Q}),Object.defineProperty(W,Symbol.hasInstance,{value:(H)=>{if(X?.Parent&&H instanceof X.Parent)return!0;return H?._zod?.traits?.has(Y)}}),Object.defineProperty(W,"name",{value:Y}),W}var jF=Symbol("zod_brand");class w1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class B8 extends Error{constructor(Y){super(`Encountered unidirectional transform during encode: ${Y}`);this.name="ZodEncodeError"}}var L9={};function F1(Y){if(Y)Object.assign(L9,Y);return L9}var Q0={};oY(Q0,{unwrapMessage:()=>L8,uint8ArrayToHex:()=>HK,uint8ArrayToBase64url:()=>WK,uint8ArrayToBase64:()=>N2,stringifyPrimitive:()=>Z2,shallowClone:()=>K2,safeExtend:()=>YK,required:()=>QK,randomString:()=>nH,propertyKeyTypes:()=>aY,promiseAllObject:()=>iH,primitiveTypes:()=>U2,prefixIssues:()=>I1,pick:()=>aH,partial:()=>XK,optionalKeys:()=>tY,omit:()=>tH,objectClone:()=>pH,numKeys:()=>oH,nullish:()=>j8,normalizeParams:()=>n,mergeDefs:()=>m1,merge:()=>JK,jsonStringifyReplacer:()=>I6,joinValues:()=>uH,issue:()=>k6,isPlainObject:()=>c1,isObject:()=>W6,hexToUint8Array:()=>zK,getSizableOrigin:()=>B2,getParsedType:()=>rH,getLengthableOrigin:()=>D8,getEnumValues:()=>N8,getElementAtPath:()=>dH,floatSafeRemainder:()=>rY,finalizeIssue:()=>$1,extend:()=>eH,escapeRegex:()=>S1,esc:()=>N9,defineLazy:()=>$0,createTransparentProxy:()=>sH,cloneDef:()=>lH,clone:()=>G1,cleanRegex:()=>F8,cleanEnum:()=>GK,captureStackTrace:()=>j9,cached:()=>b6,base64urlToUint8Array:()=>$K,base64ToUint8Array:()=>L2,assignProp:()=>f1,assertNotEqual:()=>gH,assertNever:()=>mH,assertIs:()=>fH,assertEqual:()=>yH,assert:()=>cH,allowsEval:()=>sY,aborted:()=>u1,NUMBER_FORMAT_RANGES:()=>eY,Class:()=>j2,BIGINT_FORMAT_RANGES:()=>V2});function yH(Y){return Y}function gH(Y){return Y}function fH(Y){}function mH(Y){throw Error()}function cH(Y){}function N8(Y){let J=Object.values(Y).filter((Q)=>typeof Q==="number");return Object.entries(Y).filter(([Q,G])=>J.indexOf(+Q)===-1).map(([Q,G])=>G)}function uH(Y,J="|"){return Y.map((X)=>Z2(X)).join(J)}function I6(Y,J){if(typeof J==="bigint")return J.toString();return J}function b6(Y){return{get value(){{let X=Y();return Object.defineProperty(this,"value",{value:X}),X}throw Error("cached value already set")}}}function j8(Y){return Y===null||Y===void 0}function F8(Y){let J=Y.startsWith("^")?1:0,X=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(J,X)}function rY(Y,J){let X=(Y.toString().split(".")[1]||"").length,Q=J.toString(),G=(Q.split(".")[1]||"").length;if(G===0&&/\d?e-\d?/.test(Q)){let K=Q.match(/\d?e-(\d?)/);if(K?.[1])G=Number.parseInt(K[1])}let $=X>G?X:G,W=Number.parseInt(Y.toFixed($).replace(".","")),H=Number.parseInt(J.toFixed($).replace(".",""));return W%H/10**$}var H2=Symbol("evaluating");function $0(Y,J,X){let Q=void 0;Object.defineProperty(Y,J,{get(){if(Q===H2)return;if(Q===void 0)Q=H2,Q=X();return Q},set(G){Object.defineProperty(Y,J,{value:G})},configurable:!0})}function pH(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function f1(Y,J,X){Object.defineProperty(Y,J,{value:X,writable:!0,enumerable:!0,configurable:!0})}function m1(...Y){let J={};for(let X of Y){let Q=Object.getOwnPropertyDescriptors(X);Object.assign(J,Q)}return Object.defineProperties({},J)}function lH(Y){return m1(Y._zod.def)}function dH(Y,J){if(!J)return Y;return J.reduce((X,Q)=>X?.[Q],Y)}function iH(Y){let J=Object.keys(Y),X=J.map((Q)=>Y[Q]);return Promise.all(X).then((Q)=>{let G={};for(let $=0;$<J.length;$++)G[J[$]]=Q[$];return G})}function nH(Y=10){let X="";for(let Q=0;Q<Y;Q++)X+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return X}function N9(Y){return JSON.stringify(Y)}var j9="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function W6(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var sY=b6(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function c1(Y){if(W6(Y)===!1)return!1;let J=Y.constructor;if(J===void 0)return!0;let X=J.prototype;if(W6(X)===!1)return!1;if(Object.prototype.hasOwnProperty.call(X,"isPrototypeOf")===!1)return!1;return!0}function K2(Y){if(c1(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function oH(Y){let J=0;for(let X in Y)if(Object.prototype.hasOwnProperty.call(Y,X))J++;return J}var rH=(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}`)}},aY=new Set(["string","number","symbol"]),U2=new Set(["string","number","bigint","boolean","symbol","undefined"]);function S1(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function G1(Y,J,X){let Q=new Y._zod.constr(J??Y._zod.def);if(!J||X?.parent)Q._zod.parent=Y;return Q}function n(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 sH(Y){let J;return new Proxy({},{get(X,Q,G){return J??(J=Y()),Reflect.get(J,Q,G)},set(X,Q,G,$){return J??(J=Y()),Reflect.set(J,Q,G,$)},has(X,Q){return J??(J=Y()),Reflect.has(J,Q)},deleteProperty(X,Q){return J??(J=Y()),Reflect.deleteProperty(J,Q)},ownKeys(X){return J??(J=Y()),Reflect.ownKeys(J)},getOwnPropertyDescriptor(X,Q){return J??(J=Y()),Reflect.getOwnPropertyDescriptor(J,Q)},defineProperty(X,Q,G){return J??(J=Y()),Reflect.defineProperty(J,Q,G)}})}function Z2(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function tY(Y){return Object.keys(Y).filter((J)=>{return Y[J]._zod.optin==="optional"&&Y[J]._zod.optout==="optional"})}var eY={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]},V2={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function aH(Y,J){let X=Y._zod.def,Q=m1(Y._zod.def,{get shape(){let G={};for(let $ in J){if(!($ in X.shape))throw Error(`Unrecognized key: "${$}"`);if(!J[$])continue;G[$]=X.shape[$]}return f1(this,"shape",G),G},checks:[]});return G1(Y,Q)}function tH(Y,J){let X=Y._zod.def,Q=m1(Y._zod.def,{get shape(){let G={...Y._zod.def.shape};for(let $ in J){if(!($ in X.shape))throw Error(`Unrecognized key: "${$}"`);if(!J[$])continue;delete G[$]}return f1(this,"shape",G),G},checks:[]});return G1(Y,Q)}function eH(Y,J){if(!c1(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 G=m1(Y._zod.def,{get shape(){let $={...Y._zod.def.shape,...J};return f1(this,"shape",$),$},checks:[]});return G1(Y,G)}function YK(Y,J){if(!c1(J))throw Error("Invalid input to safeExtend: expected a plain object");let X={...Y._zod.def,get shape(){let Q={...Y._zod.def.shape,...J};return f1(this,"shape",Q),Q},checks:Y._zod.def.checks};return G1(Y,X)}function JK(Y,J){let X=m1(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape,...J._zod.def.shape};return f1(this,"shape",Q),Q},get catchall(){return J._zod.def.catchall},checks:[]});return G1(Y,X)}function XK(Y,J,X){let Q=m1(J._zod.def,{get shape(){let G=J._zod.def.shape,$={...G};if(X)for(let W in X){if(!(W in G))throw Error(`Unrecognized key: "${W}"`);if(!X[W])continue;$[W]=Y?new Y({type:"optional",innerType:G[W]}):G[W]}else for(let W in G)$[W]=Y?new Y({type:"optional",innerType:G[W]}):G[W];return f1(this,"shape",$),$},checks:[]});return G1(J,Q)}function QK(Y,J,X){let Q=m1(J._zod.def,{get shape(){let G=J._zod.def.shape,$={...G};if(X)for(let W in X){if(!(W in $))throw Error(`Unrecognized key: "${W}"`);if(!X[W])continue;$[W]=new Y({type:"nonoptional",innerType:G[W]})}else for(let W in G)$[W]=new Y({type:"nonoptional",innerType:G[W]});return f1(this,"shape",$),$},checks:[]});return G1(J,Q)}function u1(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 I1(Y,J){return J.map((X)=>{var Q;return(Q=X).path??(Q.path=[]),X.path.unshift(Y),X})}function L8(Y){return typeof Y==="string"?Y:Y?.message}function $1(Y,J,X){let Q={...Y,path:Y.path??[]};if(!Y.message){let G=L8(Y.inst?._zod.def?.error?.(Y))??L8(J?.error?.(Y))??L8(X.customError?.(Y))??L8(X.localeError?.(Y))??"Invalid input";Q.message=G}if(delete Q.inst,delete Q.continue,!J?.reportInput)delete Q.input;return Q}function B2(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function D8(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function k6(...Y){let[J,X,Q]=Y;if(typeof J==="string")return{message:J,code:"custom",input:X,inst:Q};return{...J}}function GK(Y){return Object.entries(Y).filter(([J,X])=>{return Number.isNaN(Number.parseInt(J,10))}).map((J)=>J[1])}function L2(Y){let J=atob(Y),X=new Uint8Array(J.length);for(let Q=0;Q<J.length;Q++)X[Q]=J.charCodeAt(Q);return X}function N2(Y){let J="";for(let X=0;X<Y.length;X++)J+=String.fromCharCode(Y[X]);return btoa(J)}function $K(Y){let J=Y.replace(/-/g,"+").replace(/_/g,"/"),X="=".repeat((4-J.length%4)%4);return L2(J+X)}function WK(Y){return N2(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function zK(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 Q=0;Q<J.length;Q+=2)X[Q/2]=Number.parseInt(J.slice(Q,Q+2),16);return X}function HK(Y){return Array.from(Y).map((J)=>J.toString(16).padStart(2,"0")).join("")}class j2{constructor(...Y){}}var F2=(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,I6,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},F9=_("$ZodError",F2),Y4=_("$ZodError",F2,{Parent:Error});function D2(Y,J=(X)=>X.message){let X={},Q=[];for(let G of Y.issues)if(G.path.length>0)X[G.path[0]]=X[G.path[0]]||[],X[G.path[0]].push(J(G));else Q.push(J(G));return{formErrors:Q,fieldErrors:X}}function O2(Y,J){let X=J||function($){return $.message},Q={_errors:[]},G=($)=>{for(let W of $.issues)if(W.code==="invalid_union"&&W.errors.length)W.errors.map((H)=>G({issues:H}));else if(W.code==="invalid_key")G({issues:W.issues});else if(W.code==="invalid_element")G({issues:W.issues});else if(W.path.length===0)Q._errors.push(X(W));else{let H=Q,K=0;while(K<W.path.length){let U=W.path[K];if(K!==W.path.length-1)H[U]=H[U]||{_errors:[]};else H[U]=H[U]||{_errors:[]},H[U]._errors.push(X(W));H=H[U],K++}}};return G(Y),Q}var D9=(Y)=>(J,X,Q,G)=>{let $=Q?Object.assign(Q,{async:!1}):{async:!1},W=J._zod.run({value:X,issues:[]},$);if(W instanceof Promise)throw new w1;if(W.issues.length){let H=new(G?.Err??Y)(W.issues.map((K)=>$1(K,$,F1())));throw j9(H,G?.callee),H}return W.value};var O9=(Y)=>async(J,X,Q,G)=>{let $=Q?Object.assign(Q,{async:!0}):{async:!0},W=J._zod.run({value:X,issues:[]},$);if(W instanceof Promise)W=await W;if(W.issues.length){let H=new(G?.Err??Y)(W.issues.map((K)=>$1(K,$,F1())));throw j9(H,G?.callee),H}return W.value};var O8=(Y)=>(J,X,Q)=>{let G=Q?{...Q,async:!1}:{async:!1},$=J._zod.run({value:X,issues:[]},G);if($ instanceof Promise)throw new w1;return $.issues.length?{success:!1,error:new(Y??F9)($.issues.map((W)=>$1(W,G,F1())))}:{success:!0,data:$.value}},_2=O8(Y4),_8=(Y)=>async(J,X,Q)=>{let G=Q?Object.assign(Q,{async:!0}):{async:!0},$=J._zod.run({value:X,issues:[]},G);if($ instanceof Promise)$=await $;return $.issues.length?{success:!1,error:new Y($.issues.map((W)=>$1(W,G,F1())))}:{success:!0,data:$.value}},P2=_8(Y4),q2=(Y)=>(J,X,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return D9(Y)(J,X,G)};var E2=(Y)=>(J,X,Q)=>{return D9(Y)(J,X,Q)};var M2=(Y)=>async(J,X,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return O9(Y)(J,X,G)};var A2=(Y)=>async(J,X,Q)=>{return O9(Y)(J,X,Q)};var T2=(Y)=>(J,X,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return O8(Y)(J,X,G)};var R2=(Y)=>(J,X,Q)=>{return O8(Y)(J,X,Q)};var C2=(Y)=>async(J,X,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return _8(Y)(J,X,G)};var w2=(Y)=>async(J,X,Q)=>{return _8(Y)(J,X,Q)};var S2=/^[cC][^\s-]{8,}$/,I2=/^[0-9a-z]+$/,b2=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,k2=/^[0-9a-vA-V]{20}$/,x2=/^[A-Za-z0-9]{27}$/,h2=/^[a-zA-Z0-9_-]{21}$/,v2=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var y2=/^([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})$/,J4=(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 g2=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function f2(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var m2=/^(?:(?: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])$/,c2=/^(([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}|:))$/,u2=/^((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])$/,p2=/^(([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])$/,l2=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,X4=/^[A-Za-z0-9_-]*$/,d2=/^(?=.{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 i2=/^\+(?:[0-9]){6,14}[0-9]$/,n2="(?:(?:\\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])))",o2=new RegExp(`^${n2}$`);function r2(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 s2(Y){return new RegExp(`^${r2(Y)}$`)}function a2(Y){let J=r2({precision:Y.precision}),X=["Z"];if(Y.local)X.push("");if(Y.offset)X.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let Q=`${J}(?:${X.join("|")})`;return new RegExp(`^${n2}T(?:${Q})$`)}var t2=(Y)=>{let J=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${J}$`)};var e2=/^-?\d+$/,Y7=/^-?\d+(?:\.\d+)?/,J7=/^(?:true|false)$/i,X7=/^null$/i;var Q7=/^[^A-Z]*$/,G7=/^[^a-z]*$/;var k0=_("$ZodCheck",(Y,J)=>{var X;Y._zod??(Y._zod={}),Y._zod.def=J,(X=Y._zod).onattach??(X.onattach=[])}),$7={number:"number",bigint:"bigint",object:"date"},Q4=_("$ZodCheckLessThan",(Y,J)=>{k0.init(Y,J);let X=$7[typeof J.value];Y._zod.onattach.push((Q)=>{let G=Q._zod.bag,$=(J.inclusive?G.maximum:G.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(J.value<$)if(J.inclusive)G.maximum=J.value;else G.exclusiveMaximum=J.value}),Y._zod.check=(Q)=>{if(J.inclusive?Q.value<=J.value:Q.value<J.value)return;Q.issues.push({origin:X,code:"too_big",maximum:J.value,input:Q.value,inclusive:J.inclusive,inst:Y,continue:!J.abort})}}),G4=_("$ZodCheckGreaterThan",(Y,J)=>{k0.init(Y,J);let X=$7[typeof J.value];Y._zod.onattach.push((Q)=>{let G=Q._zod.bag,$=(J.inclusive?G.minimum:G.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(J.value>$)if(J.inclusive)G.minimum=J.value;else G.exclusiveMinimum=J.value}),Y._zod.check=(Q)=>{if(J.inclusive?Q.value>=J.value:Q.value>J.value)return;Q.issues.push({origin:X,code:"too_small",minimum:J.value,input:Q.value,inclusive:J.inclusive,inst:Y,continue:!J.abort})}}),W7=_("$ZodCheckMultipleOf",(Y,J)=>{k0.init(Y,J),Y._zod.onattach.push((X)=>{var Q;(Q=X._zod.bag).multipleOf??(Q.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):rY(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})}}),z7=_("$ZodCheckNumberFormat",(Y,J)=>{k0.init(Y,J),J.format=J.format||"float64";let X=J.format?.includes("int"),Q=X?"int":"number",[G,$]=eY[J.format];Y._zod.onattach.push((W)=>{let H=W._zod.bag;if(H.format=J.format,H.minimum=G,H.maximum=$,X)H.pattern=e2}),Y._zod.check=(W)=>{let H=W.value;if(X){if(!Number.isInteger(H)){W.issues.push({expected:Q,format:J.format,code:"invalid_type",continue:!1,input:H,inst:Y});return}if(!Number.isSafeInteger(H)){if(H>0)W.issues.push({input:H,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:Q,continue:!J.abort});else W.issues.push({input:H,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:Q,continue:!J.abort});return}}if(H<G)W.issues.push({origin:"number",input:H,code:"too_small",minimum:G,inclusive:!0,inst:Y,continue:!J.abort});if(H>$)W.issues.push({origin:"number",input:H,code:"too_big",maximum:$,inst:Y})}});var H7=_("$ZodCheckMaxLength",(Y,J)=>{var X;k0.init(Y,J),(X=Y._zod.def).when??(X.when=(Q)=>{let G=Q.value;return!j8(G)&&G.length!==void 0}),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(J.maximum<G)Q._zod.bag.maximum=J.maximum}),Y._zod.check=(Q)=>{let G=Q.value;if(G.length<=J.maximum)return;let W=D8(G);Q.issues.push({origin:W,code:"too_big",maximum:J.maximum,inclusive:!0,input:G,inst:Y,continue:!J.abort})}}),K7=_("$ZodCheckMinLength",(Y,J)=>{var X;k0.init(Y,J),(X=Y._zod.def).when??(X.when=(Q)=>{let G=Q.value;return!j8(G)&&G.length!==void 0}),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(J.minimum>G)Q._zod.bag.minimum=J.minimum}),Y._zod.check=(Q)=>{let G=Q.value;if(G.length>=J.minimum)return;let W=D8(G);Q.issues.push({origin:W,code:"too_small",minimum:J.minimum,inclusive:!0,input:G,inst:Y,continue:!J.abort})}}),U7=_("$ZodCheckLengthEquals",(Y,J)=>{var X;k0.init(Y,J),(X=Y._zod.def).when??(X.when=(Q)=>{let G=Q.value;return!j8(G)&&G.length!==void 0}),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.minimum=J.length,G.maximum=J.length,G.length=J.length}),Y._zod.check=(Q)=>{let G=Q.value,$=G.length;if($===J.length)return;let W=D8(G),H=$>J.length;Q.issues.push({origin:W,...H?{code:"too_big",maximum:J.length}:{code:"too_small",minimum:J.length},inclusive:!0,exact:!0,input:Q.value,inst:Y,continue:!J.abort})}}),P8=_("$ZodCheckStringFormat",(Y,J)=>{var X,Q;if(k0.init(Y,J),Y._zod.onattach.push((G)=>{let $=G._zod.bag;if($.format=J.format,J.pattern)$.patterns??($.patterns=new Set),$.patterns.add(J.pattern)}),J.pattern)(X=Y._zod).check??(X.check=(G)=>{if(J.pattern.lastIndex=0,J.pattern.test(G.value))return;G.issues.push({origin:"string",code:"invalid_format",format:J.format,input:G.value,...J.pattern?{pattern:J.pattern.toString()}:{},inst:Y,continue:!J.abort})});else(Q=Y._zod).check??(Q.check=()=>{})}),Z7=_("$ZodCheckRegex",(Y,J)=>{P8.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})}}),V7=_("$ZodCheckLowerCase",(Y,J)=>{J.pattern??(J.pattern=Q7),P8.init(Y,J)}),B7=_("$ZodCheckUpperCase",(Y,J)=>{J.pattern??(J.pattern=G7),P8.init(Y,J)}),L7=_("$ZodCheckIncludes",(Y,J)=>{k0.init(Y,J);let X=S1(J.includes),Q=new RegExp(typeof J.position==="number"?`^.{${J.position}}${X}`:X);J.pattern=Q,Y._zod.onattach.push((G)=>{let $=G._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(Q)}),Y._zod.check=(G)=>{if(G.value.includes(J.includes,J.position))return;G.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:J.includes,input:G.value,inst:Y,continue:!J.abort})}}),N7=_("$ZodCheckStartsWith",(Y,J)=>{k0.init(Y,J);let X=new RegExp(`^${S1(J.prefix)}.*`);J.pattern??(J.pattern=X),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(X)}),Y._zod.check=(Q)=>{if(Q.value.startsWith(J.prefix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:J.prefix,input:Q.value,inst:Y,continue:!J.abort})}}),j7=_("$ZodCheckEndsWith",(Y,J)=>{k0.init(Y,J);let X=new RegExp(`.*${S1(J.suffix)}$`);J.pattern??(J.pattern=X),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(X)}),Y._zod.check=(Q)=>{if(Q.value.endsWith(J.suffix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:J.suffix,input:Q.value,inst:Y,continue:!J.abort})}});var F7=_("$ZodCheckOverwrite",(Y,J)=>{k0.init(Y,J),Y._zod.check=(X)=>{X.value=J.tx(X.value)}});class $4{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(`
|
|
9
|
+
`).trim();X=[];let W=J;if(J=void 0,!$||$==="[DONE]")return;try{let H=JSON.parse($),K=H.type??W;if(K!=="response.completed"&&K!=="response.done")return;let U=H.response;Q=Y3(U?.usage??H.usage)}catch{}};for(let $ of Y.split(/\r?\n/)){if($===""){G();continue}if($.startsWith("event:")){J=$.slice(6).trim();continue}if($.startsWith("data:"))X.push($.slice(5).trim())}return G(),Q??SY()}function J3(Y,J,X=Date.now()){if(!J)return;if(Y.route==="sticky-balanced"){let G=Y.stickyAssignments?.[j1(J)];if(!G)return;if(G.lastSeenAt<X-aX)return;return G.accountId}let Q=Y.activeRouting?.[J];if(!Q||Q.route!==Y.route)return;return Q.activeId}function yz(Y){let J=J1(Y);return J?X1(J):void 0}function gz(Y){let{logger:J,activeAccount:X}=Y;return{buildBody:(Q)=>xz(Q.bodyText),async send({target:Q,body:G,signal:$}){let W=async(L,B,D)=>{if($.throwIfAborted(),Y.verifyCredential)await Y.verifyCredential({target:Q,mode:B?"vault":"local",identity:(B?B.accountIdentity:D)??yz(L)});let q={...Q.meta.replayHeaders,authorization:`Bearer ${L}`,"content-type":"application/json"};if(Q.meta.chatgptAccountId)q["ChatGPT-Account-Id"]=Q.meta.chatgptAccountId;else delete q["ChatGPT-Account-Id"];let E;try{let T=JSON.parse(G);E={warmBodyKeys:Object.keys(T),stream:T.stream,max_output_tokens:T.max_output_tokens,store:T.store,has_stream_options:"stream_options"in T,has_max_tokens:"max_tokens"in T,model:T.model}}catch{}J?.debug("cachekeep warm request",{...E,headerKeys:Object.keys(q),hasChatGptAccountId:"ChatGPT-Account-Id"in q});try{let T=await Y.fetchImpl(Q.meta.url??Y.codexResponsesUrl,$9({method:"POST",headers:q,body:G,signal:$}));return await Q6(T,L,"event-stream")}catch(T){throw v1(T,L)}};if(Q.accountId&&Y.vault?.owns(Q.accountId)){let L=await Y.vault.send(Q.accountId,W,{site:"cachekeep",signal:$});if(!L)throw Error(`vault refused warm for ${Q.accountId}`);return L}if(Y.vault&&await Y.vault.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");let H,K,U,V=Y.resolveLocal?await Y.resolveLocal(Q):Q.accountId&&Q.accountId!=="main"?await Y.refreshFallback(Q.accountId):await Y.getMainToken();if(typeof V==="string")H=V;else H=V.token,K=V.identity,U=V.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 O=await W(H,void 0,K);if(O.status===401)await U?.(O.status);return O},readUsage({response:Q,text:G}){let $=Q.headers.get("content-type")??"",W=$.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(G.slice(0,200));J?.debug("cachekeep warm response",{status:Q.status,contentType:$,bodyLen:G.length,isSse:W});let H=W?vz(G):hz(G),K=X6(Q.headers);return{...H,quota_primary_pct:K.primary?.usedPercent??null,quota_secondary_pct:K.secondary?.usedPercent??null}},profile:kz,...X?{activeAccount:(Q,G)=>X(G.meta.routingSessionId)}:{}}}function X3(Y){let{fetchImpl:J,getMainToken:X,refreshFallback:Q,resolveLocal:G,vault:$,codexResponsesUrl:W,activeAccount:H,verifyCredential:K,logger:U,...V}=Y,O=Y.resolveLocal!==void 0?{resolveLocal:Y.resolveLocal}:{getMainToken:Y.getMainToken,refreshFallback:Y.refreshFallback};return new z8({...V,logger:U,adapter:gz({fetchImpl:J,...O,vault:$,codexResponsesUrl:W,activeAccount:H,verifyCredential:K,logger:U})})}function Q3(Y){let J,X=0,Q=0,G=!1,$;return{read(){let W=Y.path(),H=Y.stat(W);if(H&&J?.path===W&&J.mtimeMs===H.mtimeMs&&J.size===H.size)return J.value;if(!H)J=void 0;let K=++X;return Y.read(W).catch(Y.fallback).then((U)=>{if(K>Q){if(Q=K,$=U,G=!0,H)J={...H,path:W,value:U};return Y.onRead(U),U}return G?$:U})},invalidate(){J=void 0}}}import{readFileSync as fz}from"node:fs";var mz=60000,cz=15000,kY=2000,xY=1e4;async function H8(Y,J){let X,Q=await Promise.race([Y.then(()=>!0,()=>!0),new Promise((G)=>{X=setTimeout(()=>G(!1),J),X.unref?.()})]);return clearTimeout(X),Q}function uz(Y){if(!y1(Y.quota))return;let J=W9(Y.quota);return J.limits.some((X)=>X.kind==="reading")?J.checkedAt:void 0}function pz(Y){if(!Y)return;let J=J1(Y);return J?X1(J):void 0}function G3(Y){try{let J=JSON.parse(fz(Y,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return;return a6(J).migratedAt}catch{return}}function lz(Y){if(Y.type!=="oauth")return!1;return Y.candidate||Y.torn===!0&&Y.enabled}class hY{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;marks=new Map;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??H0("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 H8(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(G3(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 H9(J,this.deps.readBudgetMs??z9,()=>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}|${bY(Y.configPath)}|${bY(Y.statePath)}`}storeFor(Y){if(this.store?.configPath===Y.configPath)return this.store.store;let J=F6({provider:"openai",configPath:Y.configPath,statePath:Y.statePath,quota:j6,coalesceQuota:!0,now:this.now,pull:(X)=>this.coalescedPull(X),onPullFailure:(X,Q)=>{this.pollOutcomes.set(X,{id:X,ok:!1,error:Q.message}),this.log.warn("pool quota poll failed",{rowId:X,kind:Q.kind,error:Q.message})},logger:this.log,...this.deps.store,onStep:async(X,Q)=>{if(await this.deps.store?.onStep?.(X,Q),Q.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,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),Q={key:Y,promise:X};this.inflightRead=Q;let G=()=>{if(this.inflightRead===Q)this.inflightRead=void 0};return X.then(G,G),X}async read(Y,J){let X=this.deps.paths(),Q={active:!1,rows:[],key:Y,readAt:J};try{if(G3(X.configPath)!==void 0){let W=await this.storeFor(X).read();if(W.status==="ready")Q={active:!0,rows:W.rows,key:Y,readAt:J};else this.log.warn("migrated install has no readable account pool",{status:W.status,...W.status==="error"?{reason:W.reason}:{}})}}catch($){return this.log.warn("account pool read failed",{error:$ instanceof Error?$.message:String($)}),this.snapshot}if(this.disposed)return this.snapshot;let G=this.snapshot.active;if(J>=this.snapshot.readAt)this.snapshot={...Q,rows:this.withLocalState(Q.rows)},this.changed();if(this.snapshot.active){if(!G)this.log.info("account pool serves requests");this.pollUnseenRows()}return this.snapshot}withLocalState(Y){let J=this.now();return Y.map((X)=>{let Q=X,G=this.rotated.get(X.id),$=G?.credential;if(G&&G.credentialEpoch!==X.credentialEpoch)this.rotated.delete(X.id);else if($?.type==="oauth"&&X.credential?.type==="oauth"){let W=X.credential.lastRefreshedAt??0,H=$.lastRefreshedAt??0;if(W>=H)this.rotated.delete(X.id);else Q={...Q,credential:$}}return H3(Q,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,H8(Y,this.deps.vaultFirstRosterBackgroundWaitMs??xY).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(!lz(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(),Q=this.lastPull.get(Y);if(!J&&Q!==void 0&&X-Q<(this.deps.pullRetryMs??cz))return this.storeFor(this.deps.paths()).pullsSettled();this.lastPull.set(Y,X);let G=this.storeFor(this.deps.paths());return G.requestReading(Y),G.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 Q=this.pull(Y).finally(()=>this.quotaPulls.delete(J));return this.quotaPulls.set(J,Q),Q}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(Q){throw this.pollOutcomes.set(Y.id,{id:Y.id,ok:!1,error:Q instanceof Error?Q.message:String(Q)}),Q}this.pollOutcomes.set(Y.id,{id:Y.id,ok:!0});let X=this.snapshot.rows.find((Q)=>Q.id===Y.id);if(X&&X.credentialEpoch===Y.credentialEpoch&&X.identity===Y.identity)this.applyObservation(X,J);return J}applyObservation(Y,J){z3(this.pending,Y,J),this.replaceRow(Y.id,(X)=>({...X,quota:W3(X.quota,J),needsFirstReading:!1}))}recordSnapshot(Y,J,X,Q){if(!this.snapshot.active||this.disposed||this.deps.vaultMode?.())return;let G=this.snapshot.rows.find((L)=>L.id===Y);if(G?.type!=="oauth")return;let $=pz(X);if(!($&&G.identity?$===G.identity:C6(G)?.access===X))return;let H=q6(J,this.now(),Q);if(!H)return;if(this.applyObservation(G,H),G.credentialEpoch===void 0)return;let K={credentialEpoch:G.credentialEpoch,...G.identity!==void 0?{identity:G.identity}:{}},U=this.storeFor(this.deps.paths()),O=(this.writes.get(G.id)??Promise.resolve()).then(async()=>{if(this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")return;return U.recordQuota(G.id,K,H)}).catch((L)=>{this.log.warn("pool quota not recorded",{rowId:G.id,error:L instanceof Error?L.message:String(L)})});this.writes.set(G.id,O),O.finally(()=>{if(this.writes.get(G.id)===O)this.writes.delete(G.id)})}markRateLimited(Y,J){let X=this.snapshot.rows.find(($)=>$.id===Y);if(!X)return;let Q=IY(X),G=this.marks.get(Q);if(G!==void 0&&G>J)return;this.marks.set(Q,J)}rateLimitMarks(Y){let J=new Map;for(let X of Y){let Q=this.marks.get(IY(X));if(Q!==void 0)J.set(X.id,Q)}return J}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??kY);let Q=this.now(),G=$3(J),$=[];for(let W of Y){if(!W.candidate||this.vaultOwned(W))continue;let H=C6(W);if(!H)continue;let K=(H.expires??0)-Q;if(!(!H.access||!H.expires||K<=G)||this.refreshBackedOff(W,J,Q))continue;let V=this.refresh(W.id);if(X.waitForAll||!H.access||!H.expires||K<=mz)$.push(V)}await Promise.all($)}refreshBackedOff(Y,J,X=this.now()){let Q=C6(Y);if(!Q)return!1;let G=K8(Q.refresh),$=this.backoff.get(Y.id);if($&&$.tokenHash===G&&$.nextRetryAt>X)return!0;let W=J?.accounts.find((H)=>H.id===Y.id);return Boolean(W?.type==="oauth"&&W.corrupt!==!0&&M1(W.lastRefreshError,Q.refresh,X))}usableToken(Y,J=this.now()){let X=this.snapshot.rows.find((G)=>G.id===Y.id);if(!X?.enabled||!X.candidate||X.type!=="oauth"||X.identity!==Y.identity||X.credentialEpoch!==Y.credentialEpoch||this.vaultOwned(X))return;let Q=C6(X);if(!Q?.access.trim())return;if(typeof Q.expires!=="number"||Q.expires<=J)return;return Q.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((W)=>W.id===Y),Q=X?C6(X)?.refresh:void 0,G,$=(W,H)=>{return G=H.credentialEpoch,this.deps.refreshProvider(W,H)};try{let W=await Z3({paths:J,store:this.storeFor(J),now:this.now,...this.deps.legacyLocks?{legacyLocks:this.deps.legacyLocks}:{}},Y,$);if(W.status==="rotated"){this.backoff.delete(Y),this.rotated.set(Y,{credential:W.credential,credentialEpoch:G}),this.replaceRow(Y,(H)=>H.credentialEpoch!==G?H:{...H,credential:W.credential,...W.identity!==void 0&&H.identity===void 0?{identity:W.identity}:{}});return}if(W.status==="identity-contradicted"){this.backoff.delete(Y),this.replaceRow(Y,(H)=>({...H,enabled:!1,candidate:!1})),this.log.warn("pool row disabled: its refresh returned a different account",{rowId:Y});return}this.recordRefreshFailure(Y,Q,Error(W.reason))}catch(W){this.recordRefreshFailure(Y,Q,W)}}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,K3(J,X,this.now(),this.backoff.get(Y)))}refreshBackoffFor(Y){return U3(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 Q=this.now(),G=X.rows.filter(($)=>{if(!$.candidate||$.type!=="oauth"||this.vaultOwned($))return!1;if(J.ids&&!J.ids.includes($.id))return!1;if(J.skipReadWithinMs===void 0)return!0;let W=uz($);return W===void 0||Q-W>=J.skipReadWithinMs});if(G.length===0)return[];await this.prepareTokens(G,Y,{waitForAll:!0});for(let $ of G)this.pollOutcomes.delete($.id),this.requestReading($.id,!0);return await this.poolStore().pullsSettled(),G.map(($)=>this.pollOutcomes.get($.id)??{id:$.id,ok:!1,error:"the quota poll did not run"})}async accessFor(Y,J){let X=await this.current();if(!X.active)return;let Q=X.rows.find((W)=>W.id===Y);if(!Q?.candidate)return;await this.prepareTokens([Q],J);let G=this.snapshot.rows.find((W)=>W.id===Y)??Q;if(!G.candidate)return;let $=this.usableToken(G);return $?{row:G,token:$}:void 0}async rowAccess(Y,J){let X=await this.current();if(!X.active)return;let Q=X.rows.find(($)=>$.id===Y);if(!Q)return{};let G=await this.accessFor(Y,J);return{row:{id:Q.id,type:Q.type,enabled:Q.enabled,...Q.label!==void 0?{label:Q.label}:{},...Q.identity!==void 0?{identity:Q.identity}:{}},...G?{token:G.token}:{}}}dispose(){return this.disposed=!0,this.disposal??=(async()=>{await Promise.allSettled([...this.writes.values()]),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}}}}var V3=60000,vY=900000,dz={set(Y,J){let X=setTimeout(Y,J);return X.unref?.(),X},clear(Y){clearTimeout(Y)}};function iz(Y){return Y.status==="completed"||Y.status==="already-migrated"||Y.status==="nothing-to-import"||Y.status==="ambiguous"}function B3(Y){return Y.status==="deferred"||Y.status==="retry"||Y.status==="error"}function L3(Y){let J=Y.log??H0("pool-migration"),X=Y.timers??dz,Q=Y.random??Math.random,G=Y.migrate??K9,$=Y.adopt??U9,W=Y.fence??(()=>E6({currentVersion:Y.version})),H=!1,K=new AbortController,U=!1,V=!1,O=0,L,B=Promise.resolve(),D,q,E,T=!1;function I(){if(T)return;T=!0,J.warn(_6,{reason:"placeholder-without-main"})}let x=()=>({paths:Y.paths(),slot:Y.slot,log:J,...Y.runDeps,signal:K.signal});function j(p){let t=B.then(p).catch((L0)=>{J.warn("account pool background run failed",{error:L0 instanceof Error?L0.message:String(L0)})});return B=t,t}function w(p){if(U)return;if(L!==void 0)X.clear(L);L=X.set(()=>{L=void 0,j(V0)},p)}function v(){let p=Math.min(V3*2**Math.min(O,10),vY);return O++,A(p)}let A=(p)=>Math.round(p*(1-0.2*Q()));async function g(){if(!await Y.paused?.())return!1;return w(A(V3)),!0}async function o(){if(U||await g()||U)return;let p;try{p=await G({...x(),fence:W})}catch(t){J.warn("account pool migration failed; it will be tried again",{error:t instanceof Error?t.message:String(t)}),w(v());return}if(p.status==="refused"){if(p.reason==="placeholder-without-main")I();w(A(vY));return}if(iz(p)){if(V=!0,O=0,p.status==="completed")J.info("account pool migration completed",{rowId:p.rowId});await i();return}if(B3(p)){if(p.status!=="deferred")J.warn("account pool migration will be tried again",{outcome:p});w(v())}}async function i(){if(U||await g()||U)return;let p;try{let t=await W();if(U)return;if(!t.open){let L0=JSON.stringify(t.blockers);if(L0!==E)E=L0,J.info("host login adoption waits for older plugin versions",{blockers:t.blockers});w(v());return}p=await $(x())}catch(t){J.warn("adopting the host login into the account pool failed",{error:t instanceof Error?t.message:String(t)}),w(v());return}if(p.status==="not-migrated")return;if(p.status==="slot-read-only")return;if(V=!0,p.status==="completed")J.info("host login adopted into the account pool",{rowId:p.rowId,operation:p.operation});if(B3(p)){J.warn("host login adoption will be tried again",{outcome:p}),w(v());return}if(O=0,V)w(A(vY))}async function V0(){if(U)return;if(V)await i();else await o()}function B0(){if(D)return D;let p=j(async()=>{if(D=void 0,!U)if(V)await i();else await o()});return D=p,p}return{start(){if(H||U)return;H=!0,j(o)},requestAdoption:B0,noticePlaceholderWithoutMain:I,noticeRealSlot(p){if(!V||U||p===q)return;q=p,B0()},dispose(){if(U=!0,K.abort(),L!==void 0)X.clear(L);L=void 0},idle:async()=>{for(;;){let p=B;if(await p,p===B)return}},migrated:()=>V}}var G6={"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.",..._3};function cY(Y){return Y!==void 0&&O3.includes(Y)}function nz(Y,J,X,Q=new Set){return Y.filter((G)=>{if(!G.enabled||!G.candidate||G.type!=="oauth")return!1;if(G.credential?.type!=="oauth")return!1;if(c0(G.credential))return!1;if(G.identity!==void 0&&Q.has(G.identity))return!1;if(G.id===R1)return!0;if(D3(J,{accountId:G.identity}))return!1;return mY(T1(G.quota),J,X)})}function gY(Y){let J=Y.vault;return[...(J?[]:nz(Y.source.peek().rows,Y.storage,Y.now())).map((Q)=>({id:Q.id,kind:"oauth",...Q.identity!==void 0?{identity:Q.identity}:{},...Q.quota!==void 0?{quota:Q.quota}:{},row:Q})),...(J?.routes()??[]).filter((Q)=>mY(T1(Q.quota),Y.storage,Y.now())).map((Q)=>({id:Q.id,kind:Q.kind,...Q.identity!==void 0?{identity:Q.identity}:{},...Q.quota!==void 0?{quota:Q.quota}:{}}))]}function oz(Y){return Y.flatMap((J)=>J.row?[J.row]:[])}function Z9(Y,J){let X=Y.now(),Q=Z8(J,Y.storage,X),G=J.map((K)=>({id:K.id,kind:K.kind,...y1(K.quota)?{quota:K.quota}:{}})),$=oz(J),W=new Set(J.filter((K)=>!K.row).map((K)=>K.id)),H=Y.source.rateLimitMarks($);for(let[K,U]of Y.vault?.rateLimitMarks?.()??[])if(W.has(K)&&U>X)H.set(K,U);return{rows:G,now:X,rateLimitMarks:H,refreshBackoff:Y.source.refreshBackoffFor($),killswitch:Q,requestPull:(K)=>W.has(K)?Y.vault?.requestReading(K):Y.source.requestReading(K)}}function N3(Y){let J=Y.find((X)=>X.id===R1);return{main:J?T1(J.quota):void 0,fallbacks:Y.filter((X)=>X.id!==R1).map((X)=>{let Q=T1(X.quota);return{accountId:X.id,...Q?{quota:Q}:{}}})}}async function fY(Y,J){if(J.row){let X=Y.source.usableToken(J.row);if(!X)return;let Q=await Y.send(J,X);return Y.recordQuota(Q,J,X),Q}return Y.vault?.send(J.id,async(X,Q)=>{let G=await Y.send(J,X,Q);return Y.recordQuota(G,J,X,Q),G})}async function C3(Y){if(Y.vault)await Y.vault.awaitRoster();else await Y.source.current(),await Y.source.prepareTokens(Y.source.peek().rows,Y.storage);let J=gY(Y),X=Y.replayable===!1&&J.some((G)=>G.id===R1)?J.filter((G)=>G.id===R1):J,Q=E3(Z9(Y,X));if(Q)await Q,J=gY(Y);if(Y.mode==="sticky-balanced"&&Y.sessionId&&Y.replayable&&Y.body!==void 0){let G=await sz(Y,J,Y.sessionId,Y.body);if(G)return G}return rz(Y,J)}async function rz(Y,J){let X=q3(Y.mode),Q=Z9(Y,J),G=M3({...Q,placement:X,mainId:Y.vault?Y.mode==="sticky-balanced"?null:P3(Y.vault.routes()):void 0,replayable:Y.replayable});if(G.kind==="block")return Y.log.debug("pool admission blocked the request",{pid:process.pid,reason:G.block.reason}),{response:Y.blocked(G.block,N3(J),Y.vault?J.length===0?Y.vault.noRouteCause():void 0:J.length===0?"no-accounts":"unusable"),servedId:R1};if(G.lastPath)Y.log.debug("pool admission: every account is exhausted; probing anyway",{pid:process.pid,order:G.order});let $=new Map(J.map((O)=>[O.id,O])),W=F3(Y.storage),H=[],K=new Set,U,V=!1;for(;;){let O=j3(G.order.filter((D)=>!K.has(D)),H,W),L=O===void 0?void 0:$.get(O);if(!L)break;let B;try{B=await fY(Y,L)}catch(D){if(Y.isAbort(D)||!U||Y.mode==="fallback-first")throw D;return Y.log.debug("pool fallback attempt threw; stopping",{pid:process.pid,accountId:L.id}),U}if(!B){if(!L.row)V=!0;K.add(L.id);continue}U?.response.body?.cancel().catch(()=>{}),U={response:B,servedId:L.id},H.push({id:L.id,status:B.status})}if(U)return w3(Y,Q,U.servedId),U;return{response:Y.blocked({reason:"no-credential"},N3(J),V?"vault-refused":Y.vault?"vault-empty":"unusable"),servedId:R1}}async function sz(Y,J,X,Q){let G=Buffer.byteLength(Q,"utf8"),$=new Map(J.map((T)=>[T.id,T])),W=Z9(Y,J),H=yY(W),K={requestBytes:G,reservePercent:(T)=>U8(Y.storage,T===R1?void 0:T),resetCredits:Y.resetCredits,onEmptyWeightedSet:()=>{Y.log.debug("sticky routing: no fresh weighted candidates; using configured order")}},U=(T,I)=>(x,j)=>{let w=new Set(x);return Y.placePin({sessionId:X,requestBytes:G,now:T.now,validPinnedAccountIds:T.rows.map((v)=>v.id).filter((v)=>!I.excluded.has(v)),excludeAccountIds:x,quotaCheckedAtByAccount:Object.fromEntries(T.rows.map((v)=>[v.id,I.projections.get(v.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(J.map((v)=>[v.id,v.identity])),select:(v)=>A3(T,K,w,v),persist:j})},V=U(W,H),O=V([],!0);if(!O)return;let L=O.accountId,B=(T)=>{let I=V([L],!0);if(!I)return!1;return Y.log.debug("sticky routing: migrated session pin",{pid:process.pid,fromAccountId:L,toAccountId:I.accountId,reason:T}),L=I.accountId,!0},D=T3(W,K,L);if(D.kind==="none")return;if(D.kind==="move"){if(!B(D.reason)&&D.reason==="killswitch")return}else if(D.kind==="detour"){let T=V([L],!1);if(!T)return;Y.log.debug("sticky routing: pinned account awaits a quota reading",{pid:process.pid,pinnedAccountId:L,servedAccountId:T.accountId}),L=T.accountId}let q=$.get(L);if(!q)return;let E=await fY(Y,q);if(!E)return;if(E.status===401||E.status===403||E.status===429){let T=gY(Y);W=Z9(Y,T),H=yY(W),V=U(W,H);let I=R3(W,H,L,E.status);if(I.action==="migrate"){let x=L;if(B(I.reason)&&L!==x){let j=T.find((v)=>v.id===L),w=j?await fY(Y,j):void 0;if(j&&w){let v=E;E=w,v.body?.cancel().catch(()=>{}),q=j}else L=x}}}return w3(Y,W,q.id),{response:E,servedId:q.id}}function w3(Y,J,X){let Q=Y.log.info;Y.creditsServing?.served(J,X,Q?{info:(G,$)=>Q.call(Y.log,G,$)}:void 0)}var az=new Map([["needs_reauth","needs sign-in"],["retired","turned off in vault"],["corrupt","unavailable"]]);function V8(Y){return typeof Y==="number"&&Number.isFinite(Y)}function tz(Y){if(!y1(Y))return;let J=Y.budget;if(J?.kind!=="reading")return;let{limit:X,used:Q,remaining:G,usedPercent:$,remainingPercent:W}=J;if(!V8(X)||!V8(Q)||!V8(G)||!V8($)||!V8(W))return;return{limit:X,used:Q,remaining:G,usedPercent:$,remainingPercent:W,reached:J.reached,...J.resetsAt!==void 0?{resetsAt:J.resetsAt}:{},...J.unit!==void 0?{unit:J.unit}:{}}}function uY(Y,J){let X=T1(Y),Q=tz(Y),G=y1(Y)?Y.credits:void 0;if(!X&&!Q&&!G)return null;let $=y1(Y)?W9(Y).checkedAt:void 0;return{...$!==void 0?{checkedAt:$}:{},...X?.primary?{primary:X.primary}:{},...X?.secondary?{secondary:X.secondary}:{},...Q?{spendControl:Q}:{},...J!==void 0?{resetCreditsAvailable:J}:{},...G?{credits:{...G}}:{}}}function S3(Y,J,X,Q){let G=Y??[],$=Z8(G.map((W)=>({id:W.routeId,quota:W.quota})),{version:1,accounts:[],...X},Q);return{main:{quota:null,killed:!1},fallbacks:[],vaultDiscovered:Y!==void 0,vaultAccounts:G.map((W)=>{let H=W.quota?.counters?.resetCredits?.value;return{id:W.routeId,credentialId:W.credentialId,label:W.email||W.label||W.routeId,...W.accountIdentity!==void 0?{accountId:W.accountIdentity}:{},quota:uY(W.quota,H),killed:$.get(W.routeId)===!1,enabled:W.enabled,routable:J.has(W.routeId),...W.state!=="active"||W.stale||W.unclaimed||W.enabled&&!J.has(W.routeId)?{vaultState:az.get(W.state)??"unavailable"}:{},...H!==void 0?{resetCredits:H}:{}}}),route:X?.routing?.mode??"main-first",lastUpdated:Q}}function I3(Y,J,X,Q=()=>{return}){let G=Z8(Y,{version:1,accounts:[],...J},X),$=Y.find((H)=>H.id===B1),W=$?Q($.id):void 0;return{main:{quota:$?uY($.quota,W):null,...$?.identity!==void 0?{mainAccountId:$.identity}:{},killed:G.get(B1)===!1,...W!==void 0?{resetCredits:W}:{}},fallbacks:Y.filter((H)=>H.id!==B1&&H.enabled).map((H)=>{let K=Q(H.id);return{id:H.id,label:H.label,...H.identity!==void 0?{accountId:H.identity}:{},quota:uY(H.quota,K),killed:G.get(H.id)===!1,enabled:!0,...K!==void 0?{resetCredits:K}:{}}}),route:J?.routing?.mode??"main-first",lastUpdated:X,accountPool:!0}}import{resolve as V9}from"node:path";import{resolveClaustrumConnectionPath as ez}from"@cortexkit/claustrum-client";var b3=H0("vault"),YH=60000,JH=240000,h3=Symbol.for("@cortexkit/openai-auth/opencode-vaults"),v3=globalThis,B9=v3[h3]??new Map;v3[h3]=B9;function XH(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 y3(Y,J){let X=Boolean(Y.connectScoped||Y.connectEnrollment),Q=V9(Y.stateDir),G=V9((Y.connectionFile??ez)()),$=JSON.stringify([Y.host,Q,G,V9(J.configPath),V9(J.statePath)]),W={reservedRouteIds:Y.reservedRouteIds??(()=>[])},H=B9,K=B9.get($);if(!X&&K!==void 0&&!XH(K)){let L=B9;L.compatibleV1??=new Map,H=L.compatibleV1}let U=X?void 0:H.get($);if(!U){let L=new Set;if(U={protocol:1,vault:new k3({...Y,stateDir:Q,connectionFile:()=>G,...!X?{projectRoot:Q}:{},reservedRouteIds:()=>new Set([...L].flatMap((D)=>[...D.reservedRouteIds()])),afterDisconnect:async()=>{await Y.afterDisconnect?.();try{await x3(Q)}catch(D){b3.warn("could not remove the old vault enrollment state",{error:D instanceof Error?D.message:String(D)})}}}),holders:L,firstRoster:Promise.withResolvers(),started:!1},!X)H.set($,U)}U.holders.add(W);let V=U,O=!1;return{vault:V.vault,firstRoster:V.firstRoster.promise,start(){if(O||V.started)return;V.started=!0;let L=async()=>{try{if(V.holders.size&&await V.vault.authority()!=="local")await V.vault.pollStale(JH)}catch(D){b3.warn("vault background quota poll failed",{error:D instanceof Error?D.message:String(D)})}};V.vault.start(),V.vault.firstRoster().finally(()=>{V.firstRoster.resolve(),L()}),V.quotaPoll=setInterval(L,YH),V.quotaPoll.unref?.()},release(){if(O)return;if(O=!0,V.holders.delete(W),V.holders.size!==0)return;if(V.quotaPoll)clearInterval(V.quotaPoll);if(V.vault.close(),V.firstRoster.resolve(),!X&&H.get($)===V)H.delete($)}}}var u3=900000,QH=0.016666666666666666,g3=0.000001;function lY(Y,J){for(let X of[Y?.primary?.checkedAt,Y?.checkedAt,J])if(typeof X==="number"&&Number.isFinite(X))return X;return}function dY(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let J=lY(Y.quota,Y.quotaCheckedAt);if(J===void 0||!Number.isFinite(J)||Y.now-J>u3)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let X=pY(Y.quota).sort((G,$)=>{let W=G.windowMs,H=$.windowMs,K=typeof W==="number"&&Number.isFinite(W),U=typeof H==="number"&&Number.isFinite(H);if(K!==U)return K?-1:1;if(K&&U)return H-W;return 0});for(let{key:G,window:$}of X)if(Number.isFinite($.remainingPercent)&&$.remainingPercent<=0)return{action:"migrate",reason:"exhausted",windowKey:G,...typeof $.resetsAt==="string"?{resetsAt:$.resetsAt}:{}};let Q=c3(Y.quota,Y.now);if(Q)return{action:"migrate",reason:"exhausted",resetsAt:Q.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 f3(Y,J,X){let Q=Math.max(0,Y.remainingPercent-J);if(Q<=0)return 0;if(!Y.resetsAt)return Q;let G=Date.parse(Y.resetsAt);if(!Number.isFinite(G)||G<=X)return Q;let $=Math.max((G-X)/3600000,QH);return Q/$}function m3(Y,J){if(Y<J)return-1;if(Y>J)return 1;return 0}function GH(Y,J){if(!Y.quota)return;let X=lY(Y.quota,Y.quotaCheckedAt);if(X===void 0||J-X>u3)return;let Q=pY(Y.quota).map(({key:W,window:H})=>{return f3(H,Y.reservePercent[W]??0,J)}),G=Y.quota.spendControl;if(G&&Number.isFinite(G.remainingPercent))Q.push(f3(G,0,J));let $=Q.length>0?Math.min(...Q):0;return $>0?{candidate:Y,quotaCheckedAt:X,weight:$}:void 0}function p3(Y){let J=Y.candidates.filter((G)=>G.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((G)=>GH(G,Y.now)).filter((G)=>G!==void 0);if(X.length>0){X.sort(($,W)=>{let H=((Y.pendingBytes.get($.candidate.accountId)??0)+Y.requestBytes)/Math.max($.weight,g3),K=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,g3);return H-K||$.candidate.configuredOrder-W.candidate.configuredOrder||m3($.candidate.accountId,W.candidate.accountId)});let G=X[0];if(G)return{accountId:G.candidate.accountId,quotaCheckedAt:G.quotaCheckedAt,source:"weighted"}}Y.onEmptyWeightedSet?.();let Q=[...J].sort((G,$)=>{let W=(G.resetCreditsApplicable??0)>0?1:0;return(($.resetCreditsApplicable??0)>0?1:0)-W||G.configuredOrder-$.configuredOrder||m3(G.accountId,$.accountId)})[0];if(!Q)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Q.accountId,quotaCheckedAt:lY(Q.quota,Q.quotaCheckedAt),source:"mode-fallback"}}import{readFile as $H}from"node:fs/promises";import{homedir as WH}from"node:os";import{join as l3}from"node:path";var zH="https://models.dev/api.json",HH="OPENCODE_OPENAI_AUTH_MODELS_CACHE",KH="OPENCODE_MODELS_PATH",UH="OPENCODE_DISABLE_MODELS_FETCH",ZH=1e4,VH=300000;function g1(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function d3(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function iY(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 Q=d3(Y.cache_read),G=d3(Y.cache_write);if(Q===null||G===null)return null;return{input:J,output:X,cache:{read:Q,write:G}}}function BH(Y){let J=g1(Y);if(!J)return null;let X=iY(J);if(!X)return null;let Q=X;if(Array.isArray(J.tiers)){let W=[];for(let H of J.tiers){let K=g1(H);if(!K)continue;let U=g1(K.tier),V=U?.size;if(U?.type!=="context")continue;if(typeof V!=="number"||!Number.isFinite(V)||V<=0)continue;let O=iY(K);if(!O)continue;W.push({...O,tier:{type:"context",size:V}})}if(W.length>0)Q.tiers=W}let G=g1(J.context_over_200k),$=G?iY(G):null;if($)Q.experimentalOver200K=$;return Q}function i3(Y){let J=g1(Y),X=g1(J?.openai),Q=g1(X?.models);if(!Q)return null;let G={};for(let[$,W]of Object.entries(Q)){let H=g1(W),K=BH(H?.cost);if(K)G[$]=K}return Object.keys(G).length>0?G:null}function LH(){let Y=process.env[HH]?.trim();if(Y)return Y;let J=process.env[KH]?.trim();if(J)return J;let X=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||l3(WH(),".cache");return l3(X,"opencode","models.json")}function NH(){let Y=process.env[UH]?.toLowerCase();return Y==="true"||Y==="1"}async function jH(){try{let Y=i3(JSON.parse(await $H(LH(),"utf8")));if(Y)return Y}catch{}if(NH())return null;try{let Y=await fetch(zH,{signal:AbortSignal.timeout(ZH)});if(!Y.ok)return null;return i3(await Y.json())}catch{return null}}var w6;function n3(){let Y=Date.now();if(w6&&w6.expiresAt>Y)return w6.promise;let J={expiresAt:Y+VH,promise:jH()};return w6=J,J.promise.then((X)=>{if(X===null&&w6===J)w6=void 0}),J.promise}function S6(Y){return typeof Y==="object"&&Y!==null}function FH(Y){if(Array.isArray(Y))return Y;if(S6(Y)&&Array.isArray(Y.data))return Y.data;return[]}function DH(Y){if(!S6(Y)||!S6(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function o3(Y){if(!S6(Y)||!S6(Y.info))return null;let J=Y.info,X=S6(J.model)?J.model:void 0,Q=typeof J.agent==="string"?J.agent:void 0,G=typeof X?.providerID==="string"?X.providerID:typeof J.providerID==="string"?J.providerID:void 0,$=typeof X?.modelID==="string"?X.modelID:typeof J.modelID==="string"?J.modelID:void 0,W=typeof X?.variant==="string"?X.variant:typeof J.variant==="string"?J.variant:void 0;if(!Q&&(!G||!$)&&!W)return null;let H={};if(Q)H.agent=Q;if(G&&$)H.model={providerID:G,modelID:$};if(W)H.variant=W;return H}function r3(Y,J){return{agent:Y.agent??J.agent,model:Y.model??J.model,variant:Y.variant??J.variant}}function s3(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function a3(Y,J){if(!Y||!J)return null;let X=Y;if(typeof X.session?.messages!=="function")return null;let Q=[];try{Q=FH(await Promise.resolve(X.session.messages({path:{id:J},query:{limit:100}})))}catch{return null}if(Q.length===0)return null;let G={};for(let $=Q.length-1;$>=0;$--){if(DH(Q[$])!=="assistant")continue;let W=o3(Q[$]);if(!W)continue;if(G=r3(G,W),s3(G))return G}for(let $=Q.length-1;$>=0;$--){let W=o3(Q[$]);if(!W)continue;if(G=r3(G,W),s3(G))return G}if(!G.agent&&!G.model&&!G.variant)return null;return G}var OH=H0("rpc"),J2="__openaiAuthRpcServers";async function X2(Y){let J=await t3({...Y,isManagedDir:Y2,log:OH,drain:(X,Q)=>Y.drain(X,Q),apply:async(X)=>await Y.apply(X)});try{return await e3(Y.dir,{port:J.port,token:J.token,pid:process.pid},{secureDir:Y.secureDir}),J}catch(X){throw await J.stop(),X}}var k1={};oY(k1,{withoutInternalHeaders:()=>tG,sanitizeHttpFallbackBody:()=>CY,orderCodexBody:()=>t1,hasWebSocketResponsesLiteMetadata:()=>RY,createWebSocketFetch:()=>GB,applyTurnId:()=>iG,advanceTurn:()=>p4,TITLE_HEADER:()=>u4,QUOTA_ACCOUNT_HEADER:()=>g9,OpenAIWebSocketPool:()=>k1,CODEX_BODY_KEY_ORDER:()=>UY});import{createHash as eV}from"node:crypto";var _H=Symbol.for("vercel.ai.error"),C1=class Y extends Error{constructor({name:J,message:X,cause:Q}){super(X);this[_H]=!0,this.name=J,this.cause=Q}static isInstance(J){return Y.hasMarker(J,"vercel.ai.error")}static hasMarker(J,X){let Q=Symbol.for(X);return J!=null&&typeof J==="object"&&Q in J&&typeof J[Q]==="boolean"&&J[Q]===!0}},PH="AI_DecisionUnsupportedQuestionTypeError",tj=`vercel.ai.error.${PH}`;var Q2="AI_APICallError",G2=`vercel.ai.error.${Q2}`,qH=Symbol.for(G2),$6=class extends C1{constructor({message:Y,url:J,requestBodyValues:X,statusCode:Q,responseHeaders:G,responseBody:$,cause:W,isRetryable:H=Q!=null&&(Q===408||Q===409||Q===429||Q>=500),data:K}){super({name:Q2,message:Y,cause:W});this[qH]=!0,this.url=J,this.requestBodyValues=X,this.statusCode=Q,this.responseHeaders=G,this.responseBody=$,this.isRetryable=H,this.data=K}static isInstance(Y){return C1.hasMarker(Y,G2)}},EH="AI_EmptyResponseBodyError",ej=`vercel.ai.error.${EH}`;var MH="AI_DecisionRefusalError",YF=`vercel.ai.error.${MH}`;var $2="AI_InvalidArgumentError",W2=`vercel.ai.error.${$2}`,AH=Symbol.for(W2),z2=class extends C1{constructor({message:Y,cause:J,argument:X}){super({name:$2,message:Y,cause:J});this[AH]=!0,this.argument=X}static isInstance(Y){return C1.hasMarker(Y,W2)}},TH="AI_InvalidPromptError",JF=`vercel.ai.error.${TH}`;var RH="AI_InvalidResponseDataError",XF=`vercel.ai.error.${RH}`;var CH="AI_JSONParseError",QF=`vercel.ai.error.${CH}`;var wH="AI_LoadAPIKeyError",GF=`vercel.ai.error.${wH}`;var SH="AI_LoadSettingError",$F=`vercel.ai.error.${SH}`;var IH="AI_NoContentGeneratedError",WF=`vercel.ai.error.${IH}`;var bH="AI_NoSuchModelError",zF=`vercel.ai.error.${bH}`;var kH="AI_NoSuchProviderReferenceError",HF=`vercel.ai.error.${kH}`;var xH="AI_TooManyEmbeddingValuesForCallError",KF=`vercel.ai.error.${xH}`;var hH="AI_TypeValidationError",UF=`vercel.ai.error.${hH}`;var vH="AI_UnsupportedFunctionalityError",ZF=`vercel.ai.error.${vH}`;var NF=Object.freeze({status:"aborted"});function _(Y,J,X){function Q(H,K){var U;Object.defineProperty(H,"_zod",{value:H._zod??{},enumerable:!1}),(U=H._zod).traits??(U.traits=new Set),H._zod.traits.add(Y),J(H,K);for(let V in W.prototype)if(!(V in H))Object.defineProperty(H,V,{value:W.prototype[V].bind(H)});H._zod.constr=W,H._zod.def=K}let G=X?.Parent??Object;class $ extends G{}Object.defineProperty($,"name",{value:Y});function W(H){var K;let U=X?.Parent?new $:this;Q(U,H),(K=U._zod).deferred??(K.deferred=[]);for(let V of U._zod.deferred)V();return U}return Object.defineProperty(W,"init",{value:Q}),Object.defineProperty(W,Symbol.hasInstance,{value:(H)=>{if(X?.Parent&&H instanceof X.Parent)return!0;return H?._zod?.traits?.has(Y)}}),Object.defineProperty(W,"name",{value:Y}),W}var jF=Symbol("zod_brand");class w1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class B8 extends Error{constructor(Y){super(`Encountered unidirectional transform during encode: ${Y}`);this.name="ZodEncodeError"}}var L9={};function F1(Y){if(Y)Object.assign(L9,Y);return L9}var Q0={};oY(Q0,{unwrapMessage:()=>L8,uint8ArrayToHex:()=>HK,uint8ArrayToBase64url:()=>WK,uint8ArrayToBase64:()=>N2,stringifyPrimitive:()=>Z2,shallowClone:()=>K2,safeExtend:()=>YK,required:()=>QK,randomString:()=>nH,propertyKeyTypes:()=>aY,promiseAllObject:()=>iH,primitiveTypes:()=>U2,prefixIssues:()=>I1,pick:()=>aH,partial:()=>XK,optionalKeys:()=>tY,omit:()=>tH,objectClone:()=>pH,numKeys:()=>oH,nullish:()=>j8,normalizeParams:()=>n,mergeDefs:()=>m1,merge:()=>JK,jsonStringifyReplacer:()=>I6,joinValues:()=>uH,issue:()=>k6,isPlainObject:()=>c1,isObject:()=>W6,hexToUint8Array:()=>zK,getSizableOrigin:()=>B2,getParsedType:()=>rH,getLengthableOrigin:()=>D8,getEnumValues:()=>N8,getElementAtPath:()=>dH,floatSafeRemainder:()=>rY,finalizeIssue:()=>$1,extend:()=>eH,escapeRegex:()=>S1,esc:()=>N9,defineLazy:()=>$0,createTransparentProxy:()=>sH,cloneDef:()=>lH,clone:()=>G1,cleanRegex:()=>F8,cleanEnum:()=>GK,captureStackTrace:()=>j9,cached:()=>b6,base64urlToUint8Array:()=>$K,base64ToUint8Array:()=>L2,assignProp:()=>f1,assertNotEqual:()=>gH,assertNever:()=>mH,assertIs:()=>fH,assertEqual:()=>yH,assert:()=>cH,allowsEval:()=>sY,aborted:()=>u1,NUMBER_FORMAT_RANGES:()=>eY,Class:()=>j2,BIGINT_FORMAT_RANGES:()=>V2});function yH(Y){return Y}function gH(Y){return Y}function fH(Y){}function mH(Y){throw Error()}function cH(Y){}function N8(Y){let J=Object.values(Y).filter((Q)=>typeof Q==="number");return Object.entries(Y).filter(([Q,G])=>J.indexOf(+Q)===-1).map(([Q,G])=>G)}function uH(Y,J="|"){return Y.map((X)=>Z2(X)).join(J)}function I6(Y,J){if(typeof J==="bigint")return J.toString();return J}function b6(Y){return{get value(){{let X=Y();return Object.defineProperty(this,"value",{value:X}),X}throw Error("cached value already set")}}}function j8(Y){return Y===null||Y===void 0}function F8(Y){let J=Y.startsWith("^")?1:0,X=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(J,X)}function rY(Y,J){let X=(Y.toString().split(".")[1]||"").length,Q=J.toString(),G=(Q.split(".")[1]||"").length;if(G===0&&/\d?e-\d?/.test(Q)){let K=Q.match(/\d?e-(\d?)/);if(K?.[1])G=Number.parseInt(K[1])}let $=X>G?X:G,W=Number.parseInt(Y.toFixed($).replace(".","")),H=Number.parseInt(J.toFixed($).replace(".",""));return W%H/10**$}var H2=Symbol("evaluating");function $0(Y,J,X){let Q=void 0;Object.defineProperty(Y,J,{get(){if(Q===H2)return;if(Q===void 0)Q=H2,Q=X();return Q},set(G){Object.defineProperty(Y,J,{value:G})},configurable:!0})}function pH(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function f1(Y,J,X){Object.defineProperty(Y,J,{value:X,writable:!0,enumerable:!0,configurable:!0})}function m1(...Y){let J={};for(let X of Y){let Q=Object.getOwnPropertyDescriptors(X);Object.assign(J,Q)}return Object.defineProperties({},J)}function lH(Y){return m1(Y._zod.def)}function dH(Y,J){if(!J)return Y;return J.reduce((X,Q)=>X?.[Q],Y)}function iH(Y){let J=Object.keys(Y),X=J.map((Q)=>Y[Q]);return Promise.all(X).then((Q)=>{let G={};for(let $=0;$<J.length;$++)G[J[$]]=Q[$];return G})}function nH(Y=10){let X="";for(let Q=0;Q<Y;Q++)X+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return X}function N9(Y){return JSON.stringify(Y)}var j9="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function W6(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var sY=b6(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function c1(Y){if(W6(Y)===!1)return!1;let J=Y.constructor;if(J===void 0)return!0;let X=J.prototype;if(W6(X)===!1)return!1;if(Object.prototype.hasOwnProperty.call(X,"isPrototypeOf")===!1)return!1;return!0}function K2(Y){if(c1(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function oH(Y){let J=0;for(let X in Y)if(Object.prototype.hasOwnProperty.call(Y,X))J++;return J}var rH=(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}`)}},aY=new Set(["string","number","symbol"]),U2=new Set(["string","number","bigint","boolean","symbol","undefined"]);function S1(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function G1(Y,J,X){let Q=new Y._zod.constr(J??Y._zod.def);if(!J||X?.parent)Q._zod.parent=Y;return Q}function n(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 sH(Y){let J;return new Proxy({},{get(X,Q,G){return J??(J=Y()),Reflect.get(J,Q,G)},set(X,Q,G,$){return J??(J=Y()),Reflect.set(J,Q,G,$)},has(X,Q){return J??(J=Y()),Reflect.has(J,Q)},deleteProperty(X,Q){return J??(J=Y()),Reflect.deleteProperty(J,Q)},ownKeys(X){return J??(J=Y()),Reflect.ownKeys(J)},getOwnPropertyDescriptor(X,Q){return J??(J=Y()),Reflect.getOwnPropertyDescriptor(J,Q)},defineProperty(X,Q,G){return J??(J=Y()),Reflect.defineProperty(J,Q,G)}})}function Z2(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function tY(Y){return Object.keys(Y).filter((J)=>{return Y[J]._zod.optin==="optional"&&Y[J]._zod.optout==="optional"})}var eY={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]},V2={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function aH(Y,J){let X=Y._zod.def,Q=m1(Y._zod.def,{get shape(){let G={};for(let $ in J){if(!($ in X.shape))throw Error(`Unrecognized key: "${$}"`);if(!J[$])continue;G[$]=X.shape[$]}return f1(this,"shape",G),G},checks:[]});return G1(Y,Q)}function tH(Y,J){let X=Y._zod.def,Q=m1(Y._zod.def,{get shape(){let G={...Y._zod.def.shape};for(let $ in J){if(!($ in X.shape))throw Error(`Unrecognized key: "${$}"`);if(!J[$])continue;delete G[$]}return f1(this,"shape",G),G},checks:[]});return G1(Y,Q)}function eH(Y,J){if(!c1(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 G=m1(Y._zod.def,{get shape(){let $={...Y._zod.def.shape,...J};return f1(this,"shape",$),$},checks:[]});return G1(Y,G)}function YK(Y,J){if(!c1(J))throw Error("Invalid input to safeExtend: expected a plain object");let X={...Y._zod.def,get shape(){let Q={...Y._zod.def.shape,...J};return f1(this,"shape",Q),Q},checks:Y._zod.def.checks};return G1(Y,X)}function JK(Y,J){let X=m1(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape,...J._zod.def.shape};return f1(this,"shape",Q),Q},get catchall(){return J._zod.def.catchall},checks:[]});return G1(Y,X)}function XK(Y,J,X){let Q=m1(J._zod.def,{get shape(){let G=J._zod.def.shape,$={...G};if(X)for(let W in X){if(!(W in G))throw Error(`Unrecognized key: "${W}"`);if(!X[W])continue;$[W]=Y?new Y({type:"optional",innerType:G[W]}):G[W]}else for(let W in G)$[W]=Y?new Y({type:"optional",innerType:G[W]}):G[W];return f1(this,"shape",$),$},checks:[]});return G1(J,Q)}function QK(Y,J,X){let Q=m1(J._zod.def,{get shape(){let G=J._zod.def.shape,$={...G};if(X)for(let W in X){if(!(W in $))throw Error(`Unrecognized key: "${W}"`);if(!X[W])continue;$[W]=new Y({type:"nonoptional",innerType:G[W]})}else for(let W in G)$[W]=new Y({type:"nonoptional",innerType:G[W]});return f1(this,"shape",$),$},checks:[]});return G1(J,Q)}function u1(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 I1(Y,J){return J.map((X)=>{var Q;return(Q=X).path??(Q.path=[]),X.path.unshift(Y),X})}function L8(Y){return typeof Y==="string"?Y:Y?.message}function $1(Y,J,X){let Q={...Y,path:Y.path??[]};if(!Y.message){let G=L8(Y.inst?._zod.def?.error?.(Y))??L8(J?.error?.(Y))??L8(X.customError?.(Y))??L8(X.localeError?.(Y))??"Invalid input";Q.message=G}if(delete Q.inst,delete Q.continue,!J?.reportInput)delete Q.input;return Q}function B2(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function D8(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function k6(...Y){let[J,X,Q]=Y;if(typeof J==="string")return{message:J,code:"custom",input:X,inst:Q};return{...J}}function GK(Y){return Object.entries(Y).filter(([J,X])=>{return Number.isNaN(Number.parseInt(J,10))}).map((J)=>J[1])}function L2(Y){let J=atob(Y),X=new Uint8Array(J.length);for(let Q=0;Q<J.length;Q++)X[Q]=J.charCodeAt(Q);return X}function N2(Y){let J="";for(let X=0;X<Y.length;X++)J+=String.fromCharCode(Y[X]);return btoa(J)}function $K(Y){let J=Y.replace(/-/g,"+").replace(/_/g,"/"),X="=".repeat((4-J.length%4)%4);return L2(J+X)}function WK(Y){return N2(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function zK(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 Q=0;Q<J.length;Q+=2)X[Q/2]=Number.parseInt(J.slice(Q,Q+2),16);return X}function HK(Y){return Array.from(Y).map((J)=>J.toString(16).padStart(2,"0")).join("")}class j2{constructor(...Y){}}var F2=(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,I6,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},F9=_("$ZodError",F2),Y4=_("$ZodError",F2,{Parent:Error});function D2(Y,J=(X)=>X.message){let X={},Q=[];for(let G of Y.issues)if(G.path.length>0)X[G.path[0]]=X[G.path[0]]||[],X[G.path[0]].push(J(G));else Q.push(J(G));return{formErrors:Q,fieldErrors:X}}function O2(Y,J){let X=J||function($){return $.message},Q={_errors:[]},G=($)=>{for(let W of $.issues)if(W.code==="invalid_union"&&W.errors.length)W.errors.map((H)=>G({issues:H}));else if(W.code==="invalid_key")G({issues:W.issues});else if(W.code==="invalid_element")G({issues:W.issues});else if(W.path.length===0)Q._errors.push(X(W));else{let H=Q,K=0;while(K<W.path.length){let U=W.path[K];if(K!==W.path.length-1)H[U]=H[U]||{_errors:[]};else H[U]=H[U]||{_errors:[]},H[U]._errors.push(X(W));H=H[U],K++}}};return G(Y),Q}var D9=(Y)=>(J,X,Q,G)=>{let $=Q?Object.assign(Q,{async:!1}):{async:!1},W=J._zod.run({value:X,issues:[]},$);if(W instanceof Promise)throw new w1;if(W.issues.length){let H=new(G?.Err??Y)(W.issues.map((K)=>$1(K,$,F1())));throw j9(H,G?.callee),H}return W.value};var O9=(Y)=>async(J,X,Q,G)=>{let $=Q?Object.assign(Q,{async:!0}):{async:!0},W=J._zod.run({value:X,issues:[]},$);if(W instanceof Promise)W=await W;if(W.issues.length){let H=new(G?.Err??Y)(W.issues.map((K)=>$1(K,$,F1())));throw j9(H,G?.callee),H}return W.value};var O8=(Y)=>(J,X,Q)=>{let G=Q?{...Q,async:!1}:{async:!1},$=J._zod.run({value:X,issues:[]},G);if($ instanceof Promise)throw new w1;return $.issues.length?{success:!1,error:new(Y??F9)($.issues.map((W)=>$1(W,G,F1())))}:{success:!0,data:$.value}},_2=O8(Y4),_8=(Y)=>async(J,X,Q)=>{let G=Q?Object.assign(Q,{async:!0}):{async:!0},$=J._zod.run({value:X,issues:[]},G);if($ instanceof Promise)$=await $;return $.issues.length?{success:!1,error:new Y($.issues.map((W)=>$1(W,G,F1())))}:{success:!0,data:$.value}},P2=_8(Y4),q2=(Y)=>(J,X,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return D9(Y)(J,X,G)};var E2=(Y)=>(J,X,Q)=>{return D9(Y)(J,X,Q)};var M2=(Y)=>async(J,X,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return O9(Y)(J,X,G)};var A2=(Y)=>async(J,X,Q)=>{return O9(Y)(J,X,Q)};var T2=(Y)=>(J,X,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return O8(Y)(J,X,G)};var R2=(Y)=>(J,X,Q)=>{return O8(Y)(J,X,Q)};var C2=(Y)=>async(J,X,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return _8(Y)(J,X,G)};var w2=(Y)=>async(J,X,Q)=>{return _8(Y)(J,X,Q)};var S2=/^[cC][^\s-]{8,}$/,I2=/^[0-9a-z]+$/,b2=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,k2=/^[0-9a-vA-V]{20}$/,x2=/^[A-Za-z0-9]{27}$/,h2=/^[a-zA-Z0-9_-]{21}$/,v2=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var y2=/^([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})$/,J4=(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 g2=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function f2(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var m2=/^(?:(?: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])$/,c2=/^(([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}|:))$/,u2=/^((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])$/,p2=/^(([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])$/,l2=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,X4=/^[A-Za-z0-9_-]*$/,d2=/^(?=.{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 i2=/^\+(?:[0-9]){6,14}[0-9]$/,n2="(?:(?:\\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])))",o2=new RegExp(`^${n2}$`);function r2(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 s2(Y){return new RegExp(`^${r2(Y)}$`)}function a2(Y){let J=r2({precision:Y.precision}),X=["Z"];if(Y.local)X.push("");if(Y.offset)X.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let Q=`${J}(?:${X.join("|")})`;return new RegExp(`^${n2}T(?:${Q})$`)}var t2=(Y)=>{let J=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${J}$`)};var e2=/^-?\d+$/,Y7=/^-?\d+(?:\.\d+)?/,J7=/^(?:true|false)$/i,X7=/^null$/i;var Q7=/^[^A-Z]*$/,G7=/^[^a-z]*$/;var k0=_("$ZodCheck",(Y,J)=>{var X;Y._zod??(Y._zod={}),Y._zod.def=J,(X=Y._zod).onattach??(X.onattach=[])}),$7={number:"number",bigint:"bigint",object:"date"},Q4=_("$ZodCheckLessThan",(Y,J)=>{k0.init(Y,J);let X=$7[typeof J.value];Y._zod.onattach.push((Q)=>{let G=Q._zod.bag,$=(J.inclusive?G.maximum:G.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(J.value<$)if(J.inclusive)G.maximum=J.value;else G.exclusiveMaximum=J.value}),Y._zod.check=(Q)=>{if(J.inclusive?Q.value<=J.value:Q.value<J.value)return;Q.issues.push({origin:X,code:"too_big",maximum:J.value,input:Q.value,inclusive:J.inclusive,inst:Y,continue:!J.abort})}}),G4=_("$ZodCheckGreaterThan",(Y,J)=>{k0.init(Y,J);let X=$7[typeof J.value];Y._zod.onattach.push((Q)=>{let G=Q._zod.bag,$=(J.inclusive?G.minimum:G.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(J.value>$)if(J.inclusive)G.minimum=J.value;else G.exclusiveMinimum=J.value}),Y._zod.check=(Q)=>{if(J.inclusive?Q.value>=J.value:Q.value>J.value)return;Q.issues.push({origin:X,code:"too_small",minimum:J.value,input:Q.value,inclusive:J.inclusive,inst:Y,continue:!J.abort})}}),W7=_("$ZodCheckMultipleOf",(Y,J)=>{k0.init(Y,J),Y._zod.onattach.push((X)=>{var Q;(Q=X._zod.bag).multipleOf??(Q.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):rY(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})}}),z7=_("$ZodCheckNumberFormat",(Y,J)=>{k0.init(Y,J),J.format=J.format||"float64";let X=J.format?.includes("int"),Q=X?"int":"number",[G,$]=eY[J.format];Y._zod.onattach.push((W)=>{let H=W._zod.bag;if(H.format=J.format,H.minimum=G,H.maximum=$,X)H.pattern=e2}),Y._zod.check=(W)=>{let H=W.value;if(X){if(!Number.isInteger(H)){W.issues.push({expected:Q,format:J.format,code:"invalid_type",continue:!1,input:H,inst:Y});return}if(!Number.isSafeInteger(H)){if(H>0)W.issues.push({input:H,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:Q,continue:!J.abort});else W.issues.push({input:H,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:Q,continue:!J.abort});return}}if(H<G)W.issues.push({origin:"number",input:H,code:"too_small",minimum:G,inclusive:!0,inst:Y,continue:!J.abort});if(H>$)W.issues.push({origin:"number",input:H,code:"too_big",maximum:$,inst:Y})}});var H7=_("$ZodCheckMaxLength",(Y,J)=>{var X;k0.init(Y,J),(X=Y._zod.def).when??(X.when=(Q)=>{let G=Q.value;return!j8(G)&&G.length!==void 0}),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(J.maximum<G)Q._zod.bag.maximum=J.maximum}),Y._zod.check=(Q)=>{let G=Q.value;if(G.length<=J.maximum)return;let W=D8(G);Q.issues.push({origin:W,code:"too_big",maximum:J.maximum,inclusive:!0,input:G,inst:Y,continue:!J.abort})}}),K7=_("$ZodCheckMinLength",(Y,J)=>{var X;k0.init(Y,J),(X=Y._zod.def).when??(X.when=(Q)=>{let G=Q.value;return!j8(G)&&G.length!==void 0}),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(J.minimum>G)Q._zod.bag.minimum=J.minimum}),Y._zod.check=(Q)=>{let G=Q.value;if(G.length>=J.minimum)return;let W=D8(G);Q.issues.push({origin:W,code:"too_small",minimum:J.minimum,inclusive:!0,input:G,inst:Y,continue:!J.abort})}}),U7=_("$ZodCheckLengthEquals",(Y,J)=>{var X;k0.init(Y,J),(X=Y._zod.def).when??(X.when=(Q)=>{let G=Q.value;return!j8(G)&&G.length!==void 0}),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.minimum=J.length,G.maximum=J.length,G.length=J.length}),Y._zod.check=(Q)=>{let G=Q.value,$=G.length;if($===J.length)return;let W=D8(G),H=$>J.length;Q.issues.push({origin:W,...H?{code:"too_big",maximum:J.length}:{code:"too_small",minimum:J.length},inclusive:!0,exact:!0,input:Q.value,inst:Y,continue:!J.abort})}}),P8=_("$ZodCheckStringFormat",(Y,J)=>{var X,Q;if(k0.init(Y,J),Y._zod.onattach.push((G)=>{let $=G._zod.bag;if($.format=J.format,J.pattern)$.patterns??($.patterns=new Set),$.patterns.add(J.pattern)}),J.pattern)(X=Y._zod).check??(X.check=(G)=>{if(J.pattern.lastIndex=0,J.pattern.test(G.value))return;G.issues.push({origin:"string",code:"invalid_format",format:J.format,input:G.value,...J.pattern?{pattern:J.pattern.toString()}:{},inst:Y,continue:!J.abort})});else(Q=Y._zod).check??(Q.check=()=>{})}),Z7=_("$ZodCheckRegex",(Y,J)=>{P8.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})}}),V7=_("$ZodCheckLowerCase",(Y,J)=>{J.pattern??(J.pattern=Q7),P8.init(Y,J)}),B7=_("$ZodCheckUpperCase",(Y,J)=>{J.pattern??(J.pattern=G7),P8.init(Y,J)}),L7=_("$ZodCheckIncludes",(Y,J)=>{k0.init(Y,J);let X=S1(J.includes),Q=new RegExp(typeof J.position==="number"?`^.{${J.position}}${X}`:X);J.pattern=Q,Y._zod.onattach.push((G)=>{let $=G._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(Q)}),Y._zod.check=(G)=>{if(G.value.includes(J.includes,J.position))return;G.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:J.includes,input:G.value,inst:Y,continue:!J.abort})}}),N7=_("$ZodCheckStartsWith",(Y,J)=>{k0.init(Y,J);let X=new RegExp(`^${S1(J.prefix)}.*`);J.pattern??(J.pattern=X),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(X)}),Y._zod.check=(Q)=>{if(Q.value.startsWith(J.prefix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:J.prefix,input:Q.value,inst:Y,continue:!J.abort})}}),j7=_("$ZodCheckEndsWith",(Y,J)=>{k0.init(Y,J);let X=new RegExp(`.*${S1(J.suffix)}$`);J.pattern??(J.pattern=X),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(X)}),Y._zod.check=(Q)=>{if(Q.value.endsWith(J.suffix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:J.suffix,input:Q.value,inst:Y,continue:!J.abort})}});var F7=_("$ZodCheckOverwrite",(Y,J)=>{k0.init(Y,J),Y._zod.check=(X)=>{X.value=J.tx(X.value)}});class $4{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
10
|
`).filter(($)=>$),Q=Math.min(...X.map(($)=>$.length-$.trimStart().length)),G=X.map(($)=>$.slice(Q)).map(($)=>" ".repeat(this.indent*2)+$);for(let $ of G)this.content.push($)}compile(){let Y=Function,J=this?.args,Q=[...(this?.content??[""]).map((G)=>` ${G}`)];return new Y(...J,Q.join(`
|
|
11
11
|
`))}}var O7={major:4,minor:1,patch:8};var F0=_("$ZodType",(Y,J)=>{var X;Y??(Y={}),Y._zod.def=J,Y._zod.bag=Y._zod.bag||{},Y._zod.version=O7;let Q=[...Y._zod.def.checks??[]];if(Y._zod.traits.has("$ZodCheck"))Q.unshift(Y);for(let G of Q)for(let $ of G._zod.onattach)$(Y);if(Q.length===0)(X=Y._zod).deferred??(X.deferred=[]),Y._zod.deferred?.push(()=>{Y._zod.run=Y._zod.parse});else{let G=(W,H,K)=>{let U=u1(W),V;for(let O of H){if(O._zod.def.when){if(!O._zod.def.when(W))continue}else if(U)continue;let L=W.issues.length,B=O._zod.check(W);if(B instanceof Promise&&K?.async===!1)throw new w1;if(V||B instanceof Promise)V=(V??Promise.resolve()).then(async()=>{if(await B,W.issues.length===L)return;if(!U)U=u1(W,L)});else{if(W.issues.length===L)continue;if(!U)U=u1(W,L)}}if(V)return V.then(()=>{return W});return W},$=(W,H,K)=>{if(u1(W))return W.aborted=!0,W;let U=G(H,Q,K);if(U instanceof Promise){if(K.async===!1)throw new w1;return U.then((V)=>Y._zod.parse(V,K))}return Y._zod.parse(U,K)};Y._zod.run=(W,H)=>{if(H.skipChecks)return Y._zod.parse(W,H);if(H.direction==="backward"){let U=Y._zod.parse({value:W.value,issues:[]},{...H,skipChecks:!0});if(U instanceof Promise)return U.then((V)=>{return $(V,W,H)});return $(U,W,H)}let K=Y._zod.parse(W,H);if(K instanceof Promise){if(H.async===!1)throw new w1;return K.then((U)=>G(U,Q,H))}return G(K,Q,H)}}Y["~standard"]={validate:(G)=>{try{let $=_2(Y,G);return $.success?{value:$.data}:{issues:$.error?.issues}}catch($){return P2(Y,G).then((W)=>W.success?{value:W.data}:{issues:W.error?.issues})}},vendor:"zod",version:1}}),E9=_("$ZodString",(Y,J)=>{F0.init(Y,J),Y._zod.pattern=[...Y?._zod.bag?.patterns??[]].pop()??t2(Y._zod.bag),Y._zod.parse=(X,Q)=>{if(J.coerce)try{X.value=String(X.value)}catch(G){}if(typeof X.value==="string")return X;return X.issues.push({expected:"string",code:"invalid_type",input:X.value,inst:Y}),X}}),D0=_("$ZodStringFormat",(Y,J)=>{P8.init(Y,J),E9.init(Y,J)}),C7=_("$ZodGUID",(Y,J)=>{J.pattern??(J.pattern=y2),D0.init(Y,J)}),w7=_("$ZodUUID",(Y,J)=>{if(J.version){let Q={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[J.version];if(Q===void 0)throw Error(`Invalid UUID version: "${J.version}"`);J.pattern??(J.pattern=J4(Q))}else J.pattern??(J.pattern=J4());D0.init(Y,J)}),S7=_("$ZodEmail",(Y,J)=>{J.pattern??(J.pattern=g2),D0.init(Y,J)}),I7=_("$ZodURL",(Y,J)=>{D0.init(Y,J),Y._zod.check=(X)=>{try{let Q=X.value.trim(),G=new URL(Q);if(J.hostname){if(J.hostname.lastIndex=0,!J.hostname.test(G.hostname))X.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:d2.source,input:X.value,inst:Y,continue:!J.abort})}if(J.protocol){if(J.protocol.lastIndex=0,!J.protocol.test(G.protocol.endsWith(":")?G.protocol.slice(0,-1):G.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=G.href;else X.value=Q;return}catch(Q){X.issues.push({code:"invalid_format",format:"url",input:X.value,inst:Y,continue:!J.abort})}}}),b7=_("$ZodEmoji",(Y,J)=>{J.pattern??(J.pattern=f2()),D0.init(Y,J)}),k7=_("$ZodNanoID",(Y,J)=>{J.pattern??(J.pattern=h2),D0.init(Y,J)}),x7=_("$ZodCUID",(Y,J)=>{J.pattern??(J.pattern=S2),D0.init(Y,J)}),h7=_("$ZodCUID2",(Y,J)=>{J.pattern??(J.pattern=I2),D0.init(Y,J)}),v7=_("$ZodULID",(Y,J)=>{J.pattern??(J.pattern=b2),D0.init(Y,J)}),y7=_("$ZodXID",(Y,J)=>{J.pattern??(J.pattern=k2),D0.init(Y,J)}),g7=_("$ZodKSUID",(Y,J)=>{J.pattern??(J.pattern=x2),D0.init(Y,J)}),f7=_("$ZodISODateTime",(Y,J)=>{J.pattern??(J.pattern=a2(J)),D0.init(Y,J)}),m7=_("$ZodISODate",(Y,J)=>{J.pattern??(J.pattern=o2),D0.init(Y,J)}),c7=_("$ZodISOTime",(Y,J)=>{J.pattern??(J.pattern=s2(J)),D0.init(Y,J)}),u7=_("$ZodISODuration",(Y,J)=>{J.pattern??(J.pattern=v2),D0.init(Y,J)}),p7=_("$ZodIPv4",(Y,J)=>{J.pattern??(J.pattern=m2),D0.init(Y,J),Y._zod.onattach.push((X)=>{let Q=X._zod.bag;Q.format="ipv4"})}),l7=_("$ZodIPv6",(Y,J)=>{J.pattern??(J.pattern=c2),D0.init(Y,J),Y._zod.onattach.push((X)=>{let Q=X._zod.bag;Q.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})}}}),d7=_("$ZodCIDRv4",(Y,J)=>{J.pattern??(J.pattern=u2),D0.init(Y,J)}),i7=_("$ZodCIDRv6",(Y,J)=>{J.pattern??(J.pattern=p2),D0.init(Y,J),Y._zod.check=(X)=>{let Q=X.value.split("/");try{if(Q.length!==2)throw Error();let[G,$]=Q;if(!$)throw Error();let W=Number($);if(`${W}`!==$)throw Error();if(W<0||W>128)throw Error();new URL(`http://[${G}]`)}catch{X.issues.push({code:"invalid_format",format:"cidrv6",input:X.value,inst:Y,continue:!J.abort})}}});function n7(Y){if(Y==="")return!0;if(Y.length%4!==0)return!1;try{return atob(Y),!0}catch{return!1}}var o7=_("$ZodBase64",(Y,J)=>{J.pattern??(J.pattern=l2),D0.init(Y,J),Y._zod.onattach.push((X)=>{X._zod.bag.contentEncoding="base64"}),Y._zod.check=(X)=>{if(n7(X.value))return;X.issues.push({code:"invalid_format",format:"base64",input:X.value,inst:Y,continue:!J.abort})}});function UK(Y){if(!X4.test(Y))return!1;let J=Y.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),X=J.padEnd(Math.ceil(J.length/4)*4,"=");return n7(X)}var r7=_("$ZodBase64URL",(Y,J)=>{J.pattern??(J.pattern=X4),D0.init(Y,J),Y._zod.onattach.push((X)=>{X._zod.bag.contentEncoding="base64url"}),Y._zod.check=(X)=>{if(UK(X.value))return;X.issues.push({code:"invalid_format",format:"base64url",input:X.value,inst:Y,continue:!J.abort})}}),s7=_("$ZodE164",(Y,J)=>{J.pattern??(J.pattern=i2),D0.init(Y,J)});function ZK(Y,J=null){try{let X=Y.split(".");if(X.length!==3)return!1;let[Q]=X;if(!Q)return!1;let G=JSON.parse(atob(Q));if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(J&&(!("alg"in G)||G.alg!==J))return!1;return!0}catch{return!1}}var a7=_("$ZodJWT",(Y,J)=>{D0.init(Y,J),Y._zod.check=(X)=>{if(ZK(X.value,J.alg))return;X.issues.push({code:"invalid_format",format:"jwt",input:X.value,inst:Y,continue:!J.abort})}});var z4=_("$ZodNumber",(Y,J)=>{F0.init(Y,J),Y._zod.pattern=Y._zod.bag.pattern??Y7,Y._zod.parse=(X,Q)=>{if(J.coerce)try{X.value=Number(X.value)}catch(W){}let G=X.value;if(typeof G==="number"&&!Number.isNaN(G)&&Number.isFinite(G))return X;let $=typeof G==="number"?Number.isNaN(G)?"NaN":!Number.isFinite(G)?"Infinity":void 0:void 0;return X.issues.push({expected:"number",code:"invalid_type",input:G,inst:Y,...$?{received:$}:{}}),X}}),t7=_("$ZodNumber",(Y,J)=>{z7.init(Y,J),z4.init(Y,J)}),e7=_("$ZodBoolean",(Y,J)=>{F0.init(Y,J),Y._zod.pattern=J7,Y._zod.parse=(X,Q)=>{if(J.coerce)try{X.value=Boolean(X.value)}catch($){}let G=X.value;if(typeof G==="boolean")return X;return X.issues.push({expected:"boolean",code:"invalid_type",input:G,inst:Y}),X}});var Y5=_("$ZodNull",(Y,J)=>{F0.init(Y,J),Y._zod.pattern=X7,Y._zod.values=new Set([null]),Y._zod.parse=(X,Q)=>{let G=X.value;if(G===null)return X;return X.issues.push({expected:"null",code:"invalid_type",input:G,inst:Y}),X}});var J5=_("$ZodUnknown",(Y,J)=>{F0.init(Y,J),Y._zod.parse=(X)=>X}),X5=_("$ZodNever",(Y,J)=>{F0.init(Y,J),Y._zod.parse=(X,Q)=>{return X.issues.push({expected:"never",code:"invalid_type",input:X.value,inst:Y}),X}});function _7(Y,J,X){if(Y.issues.length)J.issues.push(...I1(X,Y.issues));J.value[X]=Y.value}var Q5=_("$ZodArray",(Y,J)=>{F0.init(Y,J),Y._zod.parse=(X,Q)=>{let G=X.value;if(!Array.isArray(G))return X.issues.push({expected:"array",code:"invalid_type",input:G,inst:Y}),X;X.value=Array(G.length);let $=[];for(let W=0;W<G.length;W++){let H=G[W],K=J.element._zod.run({value:H,issues:[]},Q);if(K instanceof Promise)$.push(K.then((U)=>_7(U,X,W)));else _7(K,X,W)}if($.length)return Promise.all($).then(()=>X);return X}});function q9(Y,J,X,Q){if(Y.issues.length)J.issues.push(...I1(X,Y.issues));if(Y.value===void 0){if(X in Q)J.value[X]=void 0}else J.value[X]=Y.value}function G5(Y){let J=Object.keys(Y.shape);for(let Q of J)if(!Y.shape?.[Q]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${Q}": expected a Zod schema`);let X=tY(Y.shape);return{...Y,keys:J,keySet:new Set(J),numKeys:J.length,optionalKeys:new Set(X)}}function $5(Y,J,X,Q,G,$){let W=[],H=G.keySet,K=G.catchall._zod,U=K.def.type;for(let V of Object.keys(J)){if(H.has(V))continue;if(U==="never"){W.push(V);continue}let O=K.run({value:J[V],issues:[]},Q);if(O instanceof Promise)Y.push(O.then((L)=>q9(L,X,V,J)));else q9(O,X,V,J)}if(W.length)X.issues.push({code:"unrecognized_keys",keys:W,input:J,inst:$});if(!Y.length)return X;return Promise.all(Y).then(()=>{return X})}var VK=_("$ZodObject",(Y,J)=>{F0.init(Y,J);let X=b6(()=>G5(J));$0(Y._zod,"propValues",()=>{let W=J.shape,H={};for(let K in W){let U=W[K]._zod;if(U.values){H[K]??(H[K]=new Set);for(let V of U.values)H[K].add(V)}}return H});let Q=W6,G=J.catchall,$;Y._zod.parse=(W,H)=>{$??($=X.value);let K=W.value;if(!Q(K))return W.issues.push({expected:"object",code:"invalid_type",input:K,inst:Y}),W;W.value={};let U=[],V=$.shape;for(let O of $.keys){let B=V[O]._zod.run({value:K[O],issues:[]},H);if(B instanceof Promise)U.push(B.then((D)=>q9(D,W,O,K)));else q9(B,W,O,K)}if(!G)return U.length?Promise.all(U).then(()=>W):W;return $5(U,K,W,H,X.value,Y)}}),W5=_("$ZodObjectJIT",(Y,J)=>{VK.init(Y,J);let X=Y._zod.parse,Q=b6(()=>G5(J)),G=(L)=>{let B=new $4(["shape","payload","ctx"]),D=Q.value,q=(x)=>{let j=N9(x);return`shape[${j}]._zod.run({ value: input[${j}], issues: [] }, ctx)`};B.write("const input = payload.value;");let E=Object.create(null),T=0;for(let x of D.keys)E[x]=`key_${T++}`;B.write("const newResult = {};");for(let x of D.keys){let j=E[x],w=N9(x);B.write(`const ${j} = ${q(x)};`),B.write(`
|
|
12
12
|
if (${j}.issues.length) {
|
|
@@ -52,12 +52,12 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
52
52
|
`);if(X===-1)return;let Q=J.slice(0,X),G=Q.split(`\r
|
|
53
53
|
`)[0]??"",$=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=R8(G);if(W!==101){if(W===void 0){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:G}),this.emit("error",{message:`WS upgrade failed: ${G}`});return}if(!this.emitRejectedUpgrade())return;this.socket?.destroy?.();return}if(!$||$[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:G}),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:G}),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
54
|
\r
|
|
55
|
-
`);if(J===-1)return!1;let X=v9(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],Q=(J&128)!==0,G=J&15,$=(X&128)!==0,W=X&127,H=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],H=4}else if(W===127){if(Y.length<10)return;W=0;for(let U=0;U<8;U++)W=W*256+Y[2+U];H=10}if($)H+=4;if(Y.length<H+W)return;let K=Y.slice(H,H+W);this.rxBuffer=Y.slice(H+W),this.handleFrame(Q,G,K)}}handleFrame(Y,J,X){if(J===9){this.writeFrame(10,X);return}if(J===10)return;if(J===8){let G=1005,$="";if(X.length>=2)G=X[0]<<8|X[1],$=Buffer.from(X.slice(2)).toString("utf-8");this.readyState=3,this.peerClose={code:G,reason:$};try{this.socket?.end()}catch{}this.log("close_frame",{code:G,reason:$}),this.emitClose(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 Q=IV(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let G=Buffer.from(Q).toString("utf-8");this.emit("message",{data:G})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,J){let X=J.length,Q=crypto.getRandomValues(new Uint8Array(4)),G;if(X<126)G=[128|Y,128|X];else if(X<65536)G=[128|Y,254,X>>8&255,X&255];else{G=[128|Y,255];for(let H=7;H>=0;H--)G.push(X/2**(8*H)&255)}let $=new Uint8Array(X);for(let H=0;H<X;H++)$[H]=J[H]^Q[H%4];let W=new Uint8Array(G.length+4+X);W.set(G,0),W.set(Q,G.length),W.set($,G.length+4);try{this.socket?.write(W)}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 e1({component:"raw-ws-node",event:Y,sessionID:this.sessionID,url:this.url,...J})}}function wV(Y){return Y}function SV(Y,J){let X=new Uint8Array(Y.length+J.length);return X.set(Y,0),X.set(J,Y.length),X}function IV(Y){let J=0;for(let G of Y)J+=G.length;let X=new Uint8Array(J),Q=0;for(let G of Y)X.set(G,Q),Q+=G.length;return X}function bV(){return typeof globalThis.Bun?.connect==="function"}var AG=bV()?v4:y4;function y9(Y){return process.env[Y]??process.env[Y.toLowerCase()]}function kV(Y){let J=y9("NO_PROXY");if(!J)return!1;let X=Y.hostname.toLowerCase(),Q=J.split(",").map((G)=>G.trim().toLowerCase()).filter(Boolean);for(let G of Q){if(G==="*")return!0;if(G.startsWith(".")){if(X===G.slice(1)||X.endsWith(G))return!0}else if(X===G||X.endsWith(`.${G}`))return!0}return!1}function xV(Y){let J=new URL(Y);if(kV(J))return;if(J.protocol==="http:")return y9("HTTP_PROXY");if(J.protocol==="https:")return y9("HTTPS_PROXY")??y9("HTTP_PROXY");return}var TG={getProxyForUrl:xV};var hV=H0("quota"),l1=H0("transport"),IG="responses_websockets=2026-02-06",RG=["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"],vV=new Set([h1,"x-opencode-title"]);function yV(Y){let J=new Map;for(let Q of Object.keys(Y))J.set(Q.toLowerCase(),Q);let X={};for(let Q of RG){let G=J.get(Q),$=G===void 0?void 0:Y[G];if(G!==void 0&&$!==void 0)X[G]=$}for(let[Q,G]of Object.entries(Y))if(!RG.includes(Q.toLowerCase()))X[Q]=G;return X}function gV(Y){let J={};for(let[X,Q]of Object.entries(Y)){if(vV.has(X.toLowerCase()))continue;J[X]=Q}return J}function fV(Y){return Y.replace(/^http/,"ws")}function mV(Y){let J={};if(!Y)return J;if(Y instanceof Headers)return Y.forEach((X,Q)=>{J[Q.toLowerCase()]=X}),J;if(Array.isArray(Y)){for(let[X,Q]of Y)J[X.toLowerCase()]=Q;return J}for(let[X,Q]of Object.entries(Y))if(Q!=null)J[X.toLowerCase()]=String(Q);return J}function m4(Y){return Y instanceof DOMException&&Y.name==="AbortError"}var bG=new WeakSet;function cV(Y){return typeof Y==="object"&&Y!==null&&bG.has(Y)}var kG=new WeakSet;function uV(Y){return typeof Y==="object"&&Y!==null&&kG.has(Y)}function xG(Y){return kG.add(Y),Y}function CG(Y,J){let X=Error(Y,J===void 0?void 0:{cause:J});return bG.add(X),X}function pV(Y){return new Promise((J,X)=>{if(Y.signal?.aborted){X(g4(Y.signal));return}let Q={...Y.headers,"openai-beta":Y.headers["openai-beta"]??IG},G=Q[h1]??Q["session-id"];delete Q["content-length"],Q=yV(gV(Q));let $=typeof Bun>"u"?void 0:TG.getProxyForUrl(Y.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),W=!0,H=Y.rawWebSocket?new AG(Y.url,Q,{sessionID:G}):new globalThis.WebSocket(Y.url,{headers:Q,...$?{proxy:$}:{},perMessageDeflate:W}),K=Y.timeout?setTimeout(()=>{U(),H.close(),X(Error("WebSocket connect timed out"))},Y.timeout):void 0;function U(){if(K)clearTimeout(K);H.removeEventListener("open",V),H.removeEventListener("error",O),H.removeEventListener("close",L),Y.signal?.removeEventListener("abort",B)}function V(){U(),J(H)}function O(D){U(),X(CG(h6(D),D))}function L(D){U(),X(CG(gG("WebSocket closed before open",D.code,D.reason)))}function B(){U(),H.close(),X(g4(Y.signal))}H.addEventListener("open",V,{once:!0}),H.addEventListener("error",O,{once:!0}),H.addEventListener("close",L,{once:!0}),Y.signal?.addEventListener("abort",B,{once:!0})})}function lV(Y){let J=new TextEncoder,X=Y.socket,Q,G=()=>{},$=!1,W=0,H=!1,K=!1,U,V=[],O=12,L=[],B=typeof Y.body.previous_response_id==="string"?Y.body.previous_response_id:void 0,D=typeof Y.body.prompt_cache_key==="string"?Y.body.prompt_cache_key:void 0,q={sessionID:Y.sessionID,codexSessionID:D},E,T=0,I,x=new Set,j={addedItemIds:new Set,reasoningItemIds:new Set,finished:!1,other:!1};function w(){if(U)clearTimeout(U);G(),Y.signal?.removeEventListener("abort",x0)}function v(r=X){r.close()}function
|
|
55
|
+
`);if(J===-1)return!1;let X=v9(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],Q=(J&128)!==0,G=J&15,$=(X&128)!==0,W=X&127,H=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],H=4}else if(W===127){if(Y.length<10)return;W=0;for(let U=0;U<8;U++)W=W*256+Y[2+U];H=10}if($)H+=4;if(Y.length<H+W)return;let K=Y.slice(H,H+W);this.rxBuffer=Y.slice(H+W),this.handleFrame(Q,G,K)}}handleFrame(Y,J,X){if(J===9){this.writeFrame(10,X);return}if(J===10)return;if(J===8){let G=1005,$="";if(X.length>=2)G=X[0]<<8|X[1],$=Buffer.from(X.slice(2)).toString("utf-8");this.readyState=3,this.peerClose={code:G,reason:$};try{this.socket?.end()}catch{}this.log("close_frame",{code:G,reason:$}),this.emitClose(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 Q=IV(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let G=Buffer.from(Q).toString("utf-8");this.emit("message",{data:G})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,J){let X=J.length,Q=crypto.getRandomValues(new Uint8Array(4)),G;if(X<126)G=[128|Y,128|X];else if(X<65536)G=[128|Y,254,X>>8&255,X&255];else{G=[128|Y,255];for(let H=7;H>=0;H--)G.push(X/2**(8*H)&255)}let $=new Uint8Array(X);for(let H=0;H<X;H++)$[H]=J[H]^Q[H%4];let W=new Uint8Array(G.length+4+X);W.set(G,0),W.set(Q,G.length),W.set($,G.length+4);try{this.socket?.write(W)}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 e1({component:"raw-ws-node",event:Y,sessionID:this.sessionID,url:this.url,...J})}}function wV(Y){return Y}function SV(Y,J){let X=new Uint8Array(Y.length+J.length);return X.set(Y,0),X.set(J,Y.length),X}function IV(Y){let J=0;for(let G of Y)J+=G.length;let X=new Uint8Array(J),Q=0;for(let G of Y)X.set(G,Q),Q+=G.length;return X}function bV(){return typeof globalThis.Bun?.connect==="function"}var AG=bV()?v4:y4;function y9(Y){return process.env[Y]??process.env[Y.toLowerCase()]}function kV(Y){let J=y9("NO_PROXY");if(!J)return!1;let X=Y.hostname.toLowerCase(),Q=J.split(",").map((G)=>G.trim().toLowerCase()).filter(Boolean);for(let G of Q){if(G==="*")return!0;if(G.startsWith(".")){if(X===G.slice(1)||X.endsWith(G))return!0}else if(X===G||X.endsWith(`.${G}`))return!0}return!1}function xV(Y){let J=new URL(Y);if(kV(J))return;if(J.protocol==="http:")return y9("HTTP_PROXY");if(J.protocol==="https:")return y9("HTTPS_PROXY")??y9("HTTP_PROXY");return}var TG={getProxyForUrl:xV};var hV=H0("quota"),l1=H0("transport"),IG="responses_websockets=2026-02-06",RG=["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"],vV=new Set([h1,"x-opencode-title"]);function yV(Y){let J=new Map;for(let Q of Object.keys(Y))J.set(Q.toLowerCase(),Q);let X={};for(let Q of RG){let G=J.get(Q),$=G===void 0?void 0:Y[G];if(G!==void 0&&$!==void 0)X[G]=$}for(let[Q,G]of Object.entries(Y))if(!RG.includes(Q.toLowerCase()))X[Q]=G;return X}function gV(Y){let J={};for(let[X,Q]of Object.entries(Y)){if(vV.has(X.toLowerCase()))continue;J[X]=Q}return J}function fV(Y){return Y.replace(/^http/,"ws")}function mV(Y){let J={};if(!Y)return J;if(Y instanceof Headers)return Y.forEach((X,Q)=>{J[Q.toLowerCase()]=X}),J;if(Array.isArray(Y)){for(let[X,Q]of Y)J[X.toLowerCase()]=Q;return J}for(let[X,Q]of Object.entries(Y))if(Q!=null)J[X.toLowerCase()]=String(Q);return J}function m4(Y){return Y instanceof DOMException&&Y.name==="AbortError"}var bG=new WeakSet;function cV(Y){return typeof Y==="object"&&Y!==null&&bG.has(Y)}var kG=new WeakSet;function uV(Y){return typeof Y==="object"&&Y!==null&&kG.has(Y)}function xG(Y){return kG.add(Y),Y}function CG(Y,J){let X=Error(Y,J===void 0?void 0:{cause:J});return bG.add(X),X}function pV(Y){return new Promise((J,X)=>{if(Y.signal?.aborted){X(g4(Y.signal));return}let Q={...Y.headers,"openai-beta":Y.headers["openai-beta"]??IG},G=Q[h1]??Q["session-id"];delete Q["content-length"],Q=yV(gV(Q));let $=typeof Bun>"u"?void 0:TG.getProxyForUrl(Y.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),W=!0,H=Y.rawWebSocket?new AG(Y.url,Q,{sessionID:G}):new globalThis.WebSocket(Y.url,{headers:Q,...$?{proxy:$}:{},perMessageDeflate:W}),K=Y.timeout?setTimeout(()=>{U(),H.close(),X(Error("WebSocket connect timed out"))},Y.timeout):void 0;function U(){if(K)clearTimeout(K);H.removeEventListener("open",V),H.removeEventListener("error",O),H.removeEventListener("close",L),Y.signal?.removeEventListener("abort",B)}function V(){U(),J(H)}function O(D){U(),X(CG(h6(D),D))}function L(D){U(),X(CG(gG("WebSocket closed before open",D.code,D.reason)))}function B(){U(),H.close(),X(g4(Y.signal))}H.addEventListener("open",V,{once:!0}),H.addEventListener("error",O,{once:!0}),H.addEventListener("close",L,{once:!0}),Y.signal?.addEventListener("abort",B,{once:!0})})}function lV(Y){let J=new TextEncoder,X=Y.socket,Q,G=()=>{},$=!1,W=0,H=!1,K=!1,U,V=[],O=12,L=[],B=typeof Y.body.previous_response_id==="string"?Y.body.previous_response_id:void 0,D=typeof Y.body.prompt_cache_key==="string"?Y.body.prompt_cache_key:void 0,q={sessionID:Y.sessionID,codexSessionID:D},E,T=0,I,x=new Set,j={addedItemIds:new Set,reasoningItemIds:new Set,finished:!1,other:!1};function w(){if(U)clearTimeout(U);G(),Y.signal?.removeEventListener("abort",x0)}function v(r=X){r.close()}function A(){w(),Q?.enqueue(J.encode(`data: [DONE]
|
|
56
56
|
|
|
57
57
|
`)),Q?.close()}function g(r){B0(r,r)}function o(){if(!K)return"none";if(j.other)return"other";if(j.finished)return j.reasoningItemIds.size>0?"other":"finished-calls";return j.addedItemIds.size>0?"unfinished-calls":"none"}function i(){Q?.enqueue(J.encode(`data: ${JSON.stringify(tV)}
|
|
58
58
|
|
|
59
|
-
`)),
|
|
59
|
+
`)),A()}function V0(r){let E0={...q,openingFrameTypes:V,openingItemTypes:L,responseID:E,previousResponseID:B,hasContinuation:B!==void 0,framesSinceCreated:T,msSinceLastFrame:I===void 0?void 0:Date.now()-I},l=o();if(l==="finished-calls"){if($)return;l1.warn("stream failed after finished function calls only; ended as completed",{reason:r.message,emittedOutput:!0,outputShape:l,...E0}),$=!0,w(),Y.onConnectionInvalid?.(r),i();return}if(l==="other"){let u=f4;l1.warn("stream failed after output; not retried",{reason:r.message,emittedOutput:!0,outputShape:l,...E0}),B0(Error(u,{cause:r}),new i0(u,{cause:r}));return}let S=j.reasoningItemIds.size;l1.warn(l==="unfinished-calls"?"stream failed after unfinished function calls only; retryable":S>0?"stream failed after reasoning without text only; retryable":"stream failed before output; retryable",{reason:r.message,emittedOutput:K,outputShape:l,emptyReasoningItems:S,...E0}),g(r)}function B0(r,E0){if($)return;$=!0,w(),Y.onConnectionInvalid?.(E0),Q?.error(r)}function p(r){if($)return;if(!Y.idleTimeout)return;if(U)clearTimeout(U);U=setTimeout(()=>V0(new i0(r)),Y.idleTimeout)}async function t(r){if($)return;if(typeof r.data!=="string"){V0(new i0("Unexpected binary WebSocket frame"));return}let E0=r.data,l=(()=>{try{let y=JSON.parse(E0);return typeof y==="object"&&y!==null?y:void 0}catch{return}})();if(l?.type==="codex.rate_limits"){hV.debug("codex.rate_limits frame received",{pid:process.pid}),p("idle timeout waiting for websocket");let y=SG(l);Y.onQuota?.(y);return}let S=o(),u=S==="none"||S==="unfinished-calls"?C8(l):void 0;if(u&&l){$=!0,w(),Y.onRateLimitReached?.(u.window,u.resetAt),Y.onTerminal?.(l),Y.onFirstEvent?.(),Q?.error(new i0(`OpenAI account rate limit reached at admission (${u.window})`));return}if(l?.type==="error"&&Y.onRetryableTerminal){if(G(),U)clearTimeout(U);U=void 0;try{let y=await Y.onRetryableTerminal(l);if($){if(y)v(y);return}if(y){U0(y);return}}catch(y){V0(new i0(y instanceof Error?y.message:String(y),{cause:y}));return}}let d=nV(l,E0);if(d&&l){if(!H)Y.onFirstEvent?.(d);$=!0,w(),Y.onTerminal?.(l);let y=new $6({message:d.message,url:X.url,requestBodyValues:Y.body,statusCode:d.status,responseHeaders:d.headers,responseBody:d.body}),W0=o();if(W0==="none"||W0==="unfinished-calls"){if(W0==="unfinished-calls")l1.warn("protocol error after unfinished function calls only; surfaced as before output",{...q,status:d.status,reason:d.message,outputShape:W0,responseID:E,previousResponseID:B});Q?.error(y);return}if(l1.warn(W0==="finished-calls"?"protocol error after finished function calls only; ended as completed":"protocol error after output; not retried",{...q,status:d.status,reason:d.message,outputShape:W0,responseID:E,previousResponseID:B}),W0==="finished-calls"){i();return}Q?.error(Error(f4,{cause:y}));return}if(a(l)&&l.type==="response.failed"){let y=a(l.response)?l.response.failed:void 0,W0=a(y)?y.rate_limit_reached_type:void 0;if(typeof W0==="string"){$=!0,w(),Y.onRateLimitReached?.(W0),Y.onTerminal?.(l);let P0=o();if(P0!=="none")l1.warn(P0==="other"?"rate limit reached after output; ended without retry":P0==="finished-calls"?"rate limit reached after finished function calls only; ended as completed":"rate limit reached after unfinished function calls only; retryable",{...q,outputShape:P0,responseID:E,previousResponseID:B});if(P0==="none"||P0==="unfinished-calls")Y.onFirstEvent?.(),Q?.error(new i0(`OpenAI account rate limit reached mid-stream (${W0})`));else if(P0==="finished-calls")i();else A();return}}if(!l){if(!H)Y.onFirstEvent?.();p("idle timeout waiting for websocket");return}if(dV(l,x),!H)Y.onFirstEvent?.();if(Q?.enqueue(J.encode(`${E0.split(/\r?\n/).map((y)=>`data: ${y}`).join(`
|
|
60
60
|
`)}
|
|
61
61
|
|
|
62
|
-
`)),H=!0,I=Date.now(),E!==void 0)T++;if(V.length<O)V.push(String(l.type));if(l.type==="response.output_item.added"&&L.length<O)L.push(a(l.item)?String(l.item.type):"unknown");if(l.type==="response.created")E=sV(l),l1.debug("response created",{...q,responseID:E,previousResponseID:B,hasContinuation:B!==void 0});if(!vG(l.type))K=!0,aV(l,j);if(p("idle timeout waiting for websocket"),l.type==="response.completed"||l.type==="response.done"){$=!0,iV(l,x),Y.onComplete?.(l,x),Y.onTerminal?.(l),M();return}if(l.type==="response.failed"||l.type==="response.incomplete"||l.type==="error")$=!0,Y.onTerminal?.(l),M()}function L0(r){V0(new i0(h6(r),{cause:r}))}function h(r){if($)return;let E0=r.code===1009,l=new i0(E0?yG:gG("WebSocket closed before response.completed",r.code,r.reason),{retryable:!E0});if(E0)l1.warn("websocket peer refused the request size",{...q,requestBytes:W,reason:r.reason.toString()});V0(E0?xG(l):l)}function x0(){let r=g4(Y.signal);if($)return;$=!0,w(),v(),Y.onAbort?.(r),Q?.error(r)}function R0(r){if($)return;$=!0,w(),v(),Y.onAbort?.(oV(r))}function U0(r){G(),X=r,X.addEventListener("message",t),X.addEventListener("error",L0,{once:!0}),X.addEventListener("close",h,{once:!0}),G=()=>{X.removeEventListener("message",t),X.removeEventListener("error",L0),X.removeEventListener("close",h)};let{background:E0,...l}=Y.body;p("idle timeout sending websocket request");try{let S=JSON.stringify({type:"response.create",...l});W=S.length,X.send(S),p("idle timeout waiting for websocket")}catch(S){if($)return;g(new i0(S instanceof Error?S.message:String(S),{cause:S}))}}return new Response(new ReadableStream({start(r){if(Q=r,Y.signal?.addEventListener("abort",x0,{once:!0}),Y.signal?.aborted){x0();return}U0(X)},cancel(r){R0(r)}}),{status:200,headers:{"content-type":"text/event-stream"}})}function dV(Y,J){if(Y.type!=="response.output_item.done")return;if(!a(Y.item))return;hG(Y.item,J)}function iV(Y,J){let X=Y.response;if(!a(X)||!Array.isArray(X.output))return;for(let Q of X.output)if(a(Q))hG(Q,J)}function hG(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 nV(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:a(Y.headers)?Object.fromEntries(Object.entries(Y.headers).flatMap(([Q,G])=>typeof G==="string"||typeof G==="number"||typeof G==="boolean"?[[Q,String(G)]]:[])):void 0,body:J,message:a(Y.error)&&typeof Y.error.message==="string"?Y.error.message:`${X}`}}function C8(Y){if(typeof Y==="string")try{return C8(JSON.parse(Y))}catch{return}if(!a(Y))return;let J=C8(Y.cause);if(J)return J;let X=C8(Y.body);if(X)return X;let Q=a(Y.error)?Y.error:Y,G=typeof Q.type==="string"?Q.type:void 0,$=Y.status??Y.status_code;if(G!=="usage_limit_reached"&&$!==429)return;let{resets_at:W,resets_in_seconds:H}=Q,K=typeof W==="number"&&Number.isFinite(W)&&W>0?W*1000:typeof H==="number"&&Number.isFinite(H)&&H>0?Date.now()+H*1000:void 0;return{window:G??"primary",resetAt:K}}function oV(Y){if(m4(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function g4(Y){let J=Y?.reason;if(m4(J))return J;if(rV(J))return J;return new DOMException(J instanceof Error?J.message:"Aborted","AbortError")}function rV(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function sV(Y){let J=Y.response;if(!a(J))return;return typeof J.id==="string"?J.id:void 0}function aV(Y,J){let X=a(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(wG(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(wG(X)&&typeof X?.id==="string"&&J.reasoningItemIds.has(X.id))return;break}J.other=!0}function wG(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 tV={type:"response.completed",response:{status:"completed",incomplete_details:null,usage:{input_tokens:0,output_tokens:0,total_tokens:0}}};function vG(Y){return Y==="response.created"||Y==="response.in_progress"||Y.startsWith("codex.")}var f4="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.",yG="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 gG(Y,J,X){let Q=[`code ${J}`];if(X.length>0)Q.push(X.toString());return`${Y} (${Q.join(": ")})`}var u4="x-opencode-title",g9="x-openai-auth-quota-account",c4=new Set([u4,h1,g9,"x-opencode-session"]),YB=15000,JB=300000,XB=3300000,fG="websocket_connection_limit_reached";function QB(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):"",Q=J?`acct:${J}`:`tok:${X}`;return eV("sha256").update(Q).digest("hex").slice(0,12)}function GB(Y){let J=Y?.httpFetch??globalThis.fetch,X=new Map,Q=Y?.connectTimeout??YB,G=Y?.idleTimeout??JB,$=Y?.maxConnectionAge??XB,W=Y?.streamRetries??5,H=Y?.firstEventGraceMs??250,K=Y?.rawWebSocket??!1,U=Y?.onQuota,V=Y?.onRateLimitReached,O=setInterval(()=>q(),Math.min(G,60000));if(typeof O==="object"&&"unref"in O&&typeof O.unref==="function")O.unref();function L(I,x,j,w){if(!x||!j)return j;p4(I,mG(x),void 0,w);let v=new Headers(j.headers),M=v.get("x-codex-turn-metadata");if(!M)return j;let g=nG(M,I.turnID,I.turnStartedAt);if(!g)return j;return v.set("x-codex-turn-metadata",g),{...j,headers:v}}async function B(I,x){let j=I instanceof URL?I.toString():typeof I==="string"?I:I.url,w=g0.normalizeHeaders(x?.headers),v=tG(x),M=$9(v);if(x?.method!=="POST"||!new URL(j).pathname.endsWith("/responses"))return J(I,M);let g=(()=>{try{if(typeof x?.body!=="string")return;let U0=JSON.parse(x.body);return typeof U0==="object"&&U0!==null?U0:void 0}catch{return}})();if(!g?.stream)return J(I,M);if(w[u4]==="true")return J(I,M);let o=w[h1]??w["x-session-affinity"]??w["session-id"],i=o;if(!o)return J(I,M);let V0=g0.normalizeHeaders(v?.headers),B0=QB(V0),p=`${o}:${B0}:conversation`,t=typeof w[g9]==="string"?w[g9]:void 0,L0=V?(U0,r)=>V(U0,t,r):void 0,h=X.get(p)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};X.set(p,h);let x0=mG(g),R0;if(h.fallback)return J(I,L(h,g,M,R0));if(h.busy)return J(I,L(h,g,M,R0));h.busy=!0,h.lastUsedAt=Date.now();try{R0=v6(h,x0);let U0=g0.normalizeHeaders(v?.headers),r=typeof U0.authorization==="string"&&U0.authorization.startsWith("Bearer ")?U0.authorization.slice(7):"",E0=typeof U0["chatgpt-account-id"]==="string"?U0["chatgpt-account-id"]:void 0,l=U?(q0)=>U(q0,r,t,E0):void 0,S=!h.socket&&!h.continuation?BB(U0):U0;if(h.socket=await HB(h,Y?.url??j,S,Q,$,K,x?.signal),jB(h,x0,R0))await KB(h,x0,G,{signal:x?.signal??void 0,sessionID:i,url:Y?.url??j,headers:v?.headers,onRateLimitReached:L0});let u=()=>{},d=()=>{},y=new Promise((q0,H1)=>{u=q0,d=H1}),W0=NB(h,x0,R0),P0=t1(iG(h,W0,x0,R0)),h0=typeof P0.previous_response_id==="string";await M6({sessionID:i,transport:"websocket",phase:"main",bodyText:()=>JSON.stringify(P0),url:Y?.url??j,method:v?.method,headers:v?.headers});let M0=g0.streamResponsesWebSocket({socket:h.socket,body:P0,sessionID:i??void 0,idleTimeout:G,signal:x?.signal??void 0,onQuota:l,onRateLimitReached:L0,onFirstEvent:(q0)=>u(q0??!0),onComplete:(q0,H1)=>{let b8=pG(q0);e1({component:"ws-pool",event:"main_completed",sessionID:i,responseID:uG(q0),usage:b8}),dG(h,x0,q0,H1,h0,R0)},onTerminal:(q0)=>{if(h.busy=!1,h.lastUsedAt=Date.now(),h.streamFailures=0,q0.type!=="response.completed"&&q0.type!=="response.done")h.continuation=void 0,b1(h)},onConnectionInvalid:(q0)=>{if(h.busy=!1,h.lastUsedAt=Date.now(),g0.isOversizedFrame(q0))h.fallback=!0;if(!h.fallback)D(h);h.continuation=void 0,b1(h),u(!1)},onAbort:(q0)=>{h.busy=!1,h.lastUsedAt=Date.now(),h.streamFailures=0,h.continuation=void 0,b1(h),d(q0)},onRetryableTerminal:async(q0)=>{let H1=cG(q0);if(!H1)return;throw h.fallback=!0,H1}}),p0=await $B(y,H);if(p0!==!1){if(p0===!0||p0.status<200||p0.status>599)return M0;return new Response(p0.body,{status:p0.status,headers:{"content-type":"application/json",...p0.headers}})}let f6=()=>J(I,L(h,g,M,R0));if(!h.fallback)return WB(M0,f6);return f6()}catch(U0){if(h.busy=!1,h.lastUsedAt=Date.now(),g0.isAbortError(U0))throw h.streamFailures=0,h.continuation=void 0,b1(h),U0;let r=g0.parseRateLimitSignal(U0);if(r)L0?.(r.window,r.resetAt);if(g0.isUpgradeFailure(U0)&&!K)h.fallback=!0;if(D(h),h.continuation=void 0,b1(h),h.fallback)return J(I,L(h,g,M,R0));return zB(new i0(U0 instanceof Error?U0.message:String(U0),{cause:U0}))}}function D(I){if(I.streamFailures++,I.streamFailures>W)I.fallback=!0}function q(){let I=Date.now();for(let[x,j]of X){if(j.busy)continue;if(I-j.lastUsedAt<G)continue;b1(j),X.delete(x)}}function E(){clearInterval(O);for(let I of X.values())b1(I);X.clear()}function T(I){let x=`${I}:`;for(let[j,w]of X){if(!j.startsWith(x))continue;b1(w),X.delete(j)}}return Object.assign(B,{close:E,remove:T})}function cG(Y){if(Y.type!=="error"||!a(Y.error)||Y.error.code!==fG)return;return Error(typeof Y.error.message==="string"?Y.error.message:fG)}async function $B(Y,J){if(J<=0)return!1;return new Promise((X,Q)=>{let G=setTimeout(()=>X(!1),J);Y.then(($)=>{clearTimeout(G),X($)},($)=>{clearTimeout(G),Q($)})})}function WB(Y,J){let X=Y.body;if(!X)return Y;let Q=!1,G=new ReadableStream({async start($){let W=X.getReader(),H=async(K)=>{while(!0){let{done:U,value:V}=await K.read();if(U)return;if(V&&V.length>0)Q=!0,$.enqueue(V)}};try{await H(W),$.close()}catch(K){if(Q||!g0.isOversizedFrame(K)){$.error(K);return}try{let U=await J();if(!U.ok){$.error(new i0(`HTTP fallback after an oversized WebSocket frame failed with ${U.status}`));return}if(U.body)await H(U.body.getReader());$.close()}catch(U){$.error(U)}}},cancel($){X.cancel($)}});return new Response(G,{status:Y.status,headers:Y.headers})}function zB(Y){return new Response(new ReadableStream({start(J){J.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function HB(Y,J,X,Q,G,$,W){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<G)return Y.socket;b1(Y);let H=await g0.connectResponsesWebSocket({url:g0.toWebSocketUrl(J),headers:X,timeout:Q,rawWebSocket:$,signal:W??void 0});return Y.connectedAt=Date.now(),H}function b1(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function KB(Y,J,X,Q){if(!Y.socket||!Array.isArray(J.input)||J.input.length===0)return;let G=ZB(J);await M6({sessionID:Q.sessionID,transport:"websocket",phase:"prewarm",bodyText:()=>JSON.stringify(G),url:Q.url,method:"POST",headers:Q.headers});let $=g0.streamResponsesWebSocket({socket:Y.socket,body:G,sessionID:Q.sessionID,idleTimeout:X,signal:Q.signal,onRateLimitReached:Q.onRateLimitReached,onComplete:(W,H)=>{e1({component:"ws-pool",event:"prewarm_completed",sessionID:Q.sessionID,responseID:uG(W),usage:pG(W)}),dG(Y,G,W,H,!1,{input:Y6([]),signature:sG(G),priorInputs:new Map})},onTerminal:(W)=>{if(W.type!=="response.completed"&&W.type!=="response.done")Y.continuation=void 0},onConnectionInvalid:()=>{Y.continuation=void 0},onAbort:()=>{Y.continuation=void 0},onRetryableTerminal:async(W)=>{let H=cG(W);if(!H)return;throw Y.fallback=!0,H}});await UB($)}function uG(Y){let J=Y.response;if(!a(J))return;return typeof J.id==="string"?J.id:void 0}function pG(Y){let J=Y.response;if(!a(J))return;return a(J.usage)?J.usage:void 0}async function UB(Y){let J=Y.body?.getReader();if(!J)return;while(!0)if((await J.read()).done)return}function ZB(Y){return t1({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:VB(Y.client_metadata)})}function lG(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 VB(Y){if(!a(Y))return Y;if(typeof Y["x-codex-turn-metadata"]!=="string")return Y;try{let J=JSON.parse(Y["x-codex-turn-metadata"]);if(!a(J))return Y;return{...Y,"x-codex-turn-metadata":lG(J),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function BB(Y){let J=Y["x-codex-turn-metadata"];if(!J)return Y;try{let X=JSON.parse(J);if(!a(X))return Y;return{...Y,"x-codex-turn-metadata":lG(X)}}catch{return Y}}function mG(Y){let J={...Y};if(Array.isArray(Y.input))J.input=Y.input.map(LB);return J}function LB(Y){if(!a(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 dG(Y,J,X,Q,G,$=v6(Y,J)){let W=X.response,H=a(W)&&typeof W.id==="string"?W.id:void 0;if(!H||!Array.isArray(J.input)){Y.continuation=void 0;return}let K=G?new Set(Y.continuation?.finalizedCallIds):new Set;for(let U of Q)K.add(U);Y.continuation={responseID:H,input:J.input,signature:$.signature,canonical:X8($.input),finalizedCallIds:K}}function p4(Y,J,X=J,Q=v6(Y,{...X,input:Array.isArray(X.input)?X.input:J.input})){let G=Array.isArray(J.input)?J.input:[],$=Array.isArray(X.input)?X.input:G,W=Q.signature,H=Y.turnInput&&Y.turnSignature===W?Q8(oG(Q,Y.turnInput),Q.input):void 0,K=H===void 0?G:$.slice(H);if(K.length>0&&K.some(rG)||!Y.turnID)Y.turnID=J6(),Y.turnStartedAt=Date.now();Y.turnInput=$.slice(),Q.priorInputs.set(Y.turnInput,Q.input),Y.turnSignature=W,Y.turnCanonical=X8(Q.input)}function iG(Y,J,X=J,Q=v6(Y,{...X,input:Array.isArray(X.input)?X.input:J.input})){p4(Y,J,X,Q);let G=J.client_metadata;if(!a(G)||typeof G["x-codex-turn-metadata"]!=="string")return J;let $=nG(G["x-codex-turn-metadata"],Y.turnID,Y.turnStartedAt);if(!$)return J;return{...J,client_metadata:{...G,"x-codex-turn-metadata":$}}}function nG(Y,J,X){let Q;try{Q=JSON.parse(Y)}catch{return}if(!a(Q))return;return JSON.stringify({session_id:Q.session_id,thread_id:Q.thread_id,thread_source:Q.thread_source,turn_id:J,sandbox:Q.sandbox,turn_started_at_unix_ms:X,request_kind:"turn",window_id:Q.window_id})}function v6(Y,J){let X=Array.isArray(J.input)?J.input:[],Q=new Map;if(Y.turnInput&&Y.turnCanonical)Q.set(Y.turnInput,Y.turnCanonical);if(Y.continuation?.canonical)Q.set(Y.continuation.input,Y.continuation.canonical);let G=Y6(X,Y.turnCanonical??Y.continuation?.canonical);return Q.set(X,G),{input:G,signature:sG(J),priorInputs:Q}}function oG(Y,J){let X=Y.priorInputs.get(J);if(!X){for(let[Q,G]of Y.priorInputs)if(Q.length===J.length&&Q.every(($,W)=>$===J[W])){X=G;break}X??=Y6(J),Y.priorInputs.set(J,X)}return X}function NB(Y,J,X=v6(Y,J)){let Q=Array.isArray(J.input)?J.input:void 0;if(!Q||!Y.continuation)return J;if(Y.continuation.signature!==X.signature)return Y.continuation=void 0,J;if(!aG(Y.continuation,X))return Y.continuation=void 0,J;if(Y.continuation.input.length===0)return{...J,previous_response_id:Y.continuation.responseID};let G=Q.slice(Y.continuation.input.length),$=FB(G,Y.continuation.finalizedCallIds);if($.length===0)return J;return{...J,previous_response_id:Y.continuation.responseID,input:$}}function jB(Y,J,X=v6(Y,J)){let Q=Array.isArray(J.input)?J.input:void 0;if(!Y.continuation)return!0;if(!Q)return!1;if(!aG(Y.continuation,X))return!0;return Q.slice(Y.continuation.input.length).some(rG)}function rG(Y){if(!a(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function FB(Y,J){return Y.filter((X)=>{if(!a(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 Q=typeof X.call_id==="string"?X.call_id:typeof X.id==="string"?X.id:void 0;return Q?!J.has(Q):!0}if(X.type==="message")return X.role!=="assistant";if(typeof X.role==="string")return X.role!=="assistant";return!1})}function sG(Y){return A6(DB(Object.fromEntries(Object.entries(Y).filter(([J])=>J!=="input"&&J!=="stream"&&J!=="background"&&J!=="previous_response_id"&&J!=="generate"))))}function DB(Y){if(!a(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 aG(Y,J){if(Y.input.length>=J.input.texts.length)return!1;return Q8(oG(J,Y.input),J.input)!==void 0}function tG(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let J=new Headers(Y.headers);for(let X of c4)J.delete(X);return{...Y,headers:J}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((J)=>!c4.has(J[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([J])=>!c4.has(J.toLowerCase())))}}var qB=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),EB=new Set(["gpt-5.6","gpt-6","gpt-6.1"]);function MB(Y){if(qB.has(Y))return!0;if(EB.has(Y))return!1;let X=Y.match(/^gpt-(\d+(?:\.\d+)?)/)?.[1];return X?parseFloat(X)>5.4:!1}function AB(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"))return{context:872000,input:744000,output:128000};if(Y.includes("gpt-6.1-sol")||Y.includes("gpt-6.1-terra"))return{context:500000,input:372000,output:128000};return}function TB(Y){return Y==="gpt-6.1-terra"?"gpt-6.1-sol":void 0}var RB="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.",CB="opencode-oauth-dummy-key",Hq=()=>t6,wB=120000,SB=90000,IB=4000,eG=50,Y$=3,bB=25,kB=60000,xB="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",a4=!1,p9;function Kq(){return p9}function Uq(){a4=!1,p9=void 0}var J$=H0("models"),X$=!1,Q$=!1;class e4 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 f0 extends Error{code;constructor(Y,J){super(J);this.name="ResetTargetResolutionError",this.code=Y}}function d4(Y,J,X,Q){let G=(X?.refresh?.refreshBeforeExpiryMinutes??240)*60000;return!Y||!J||J-Q<=G}function hB(Y,J){let X=Y==="main",Q=J.row,G=()=>new f0("token_unavailable",X?"Main OpenAI account has no usable access token.":`Fallback account ${Y} has no usable access token.`);if(!Q){if(X)throw G();throw new f0("unknown_account",`Fallback account ${Y} was not found.`)}if(!Q.enabled)throw new f0("disabled_account",`${X?"Main":"Fallback"} account ${Y} is disabled.`);if(Q.type!=="oauth")throw new f0("non_oauth_account",`${X?"Main":"Fallback"} account ${Y} is not an OAuth account.`);if(!J.token)throw G();let $=J1(J.token);return{accountKey:Y,label:X?"Main account":Q.label??Y,accessToken:J.token,chatgptAccountId:Q.identity??($?X1($):void 0)}}function vB(Y){async function J(){let X=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),Q=r1(X);if(!X||!Q||c0(Q))throw new f0("token_unavailable","Main OpenAI account has no usable access token.");let G=Q;if(d4(G.access,G.expires,X,Y.now()))G=await(Y.refreshPoolMainRow??Y.refreshFallbackAccount)(G,X);if(!G.access)throw new f0("token_unavailable","Main OpenAI account has no usable access token.");let $=J1(G.access);return{accountKey:"main",label:"Main account",accessToken:G.access,chatgptAccountId:G.accountId??($?X1($):void 0)}}return async(X)=>{let Q=await Y.poolAccess?.(X);if(Q)return hB(X,Q);if(X==="main"){let V=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),O=await Y.getAuth();if(r0(O))return J();if(O.type!=="oauth")throw new f0("non_oauth_account","Main OpenAI account is not authenticated with OAuth.");if(d4(O.access,O.expires,V,Y.now()))try{O={type:"oauth",...await Y.refreshMainWithLease()}}catch(q){if(q instanceof s1)return J();throw q}if(!O.access)throw new f0("token_unavailable","Main OpenAI account has no usable access token.");let L=J1(O.access),B=L?X1(L):void 0,D=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath});return{accountKey:X,label:"Main account",accessToken:O.access,chatgptAccountId:B??D?.mainAccountId}}let G=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),$=G?.accounts.find((V)=>V.id===X);if(!G||!$)throw new f0("unknown_account",`Fallback account ${X} was not found.`);if($.enabled===!1)throw new f0("disabled_account",`Fallback account ${X} is disabled.`);if(!s0($))throw new f0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);let W=()=>new f0("token_unavailable",`Fallback account ${X} has no usable access token.`);if(c0($))throw W();let H=$;if(d4(H.access,H.expires,G,Y.now()))H=await Y.refreshFallbackAccount(H,G);if(!H.access)throw W();let K=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),U=K?.accounts.find((V)=>V.id===X);if(!K||!U)throw new f0("unknown_account",`Fallback account ${X} was not found.`);if(U.enabled===!1)throw new f0("disabled_account",`Fallback account ${X} is disabled.`);if(!s0(U))throw new f0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);return{accountKey:X,label:H.label??X,accessToken:H.access,chatgptAccountId:U.accountId}}}function yB(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function i4(Y){return Y instanceof e4}function G$(){throw Error(xB)}async function gB(Y,J={}){let X=G0(Y0());if(zY(X.configPath)){await n1(O6(X),J.holdsMainRefreshLock?void 0:E1(X),(Q)=>{if(J.canWrite&&!J.canWrite())throw Error(G6["vault-refused"]);Y(Q)});return}await o8((Q)=>{return Y(Q),Q},X,{canWrite:J.canWrite})}var r$=null;function Zq(){return r$}function fB(Y){return Math.floor(Math.random()*Y)}var mB=!0;function cB(Y,J,X){let Q=Y.get(J);if(Q)return Q;let G=J6(),$={threadID:G,turnID:J6(),windowID:`${G}:0`};return Y.set(J,$),X?.(),$}function $$(){return T$("opencode1")}function uB(Y,J){return Y.find((X)=>X.enabled!==!1&&s0(X)&&(X.id===J||X.accountId===J))}function W$(Y,J){if(!J)return Y;let X={...Y};for(let Q of["resetCreditsAvailable","resetCreditsApplicable"]){let G=J[Q];if(X[Q]===void 0&&G!==void 0)X[Q]=G}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 f9(Y,J){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:J}}function s$(Y,J,X=Date.now(),Q=J.mainAccountId){let G=Y.getMain(),$=G?.quota;return{main:{quota:$?{...$,checkedAt:G.checkedAt,primary:f9($.primary,G.checkedAt),secondary:f9($.secondary,G.checkedAt)}:null,...typeof Q==="string"?{mainAccountId:Q}:{},killed:!Z6($,J,void 0,X),...$?.resetCreditsAvailable!==void 0?{resetCredits:$.resetCreditsAvailable}:{}},fallbacks:J.accounts.filter((W)=>W.enabled).map((W)=>{let H=Y.getFallback(W.id),K=H?.quota;return{id:W.id,label:W.label,accountId:H?.accountId??W.accountId,quota:K?{...K,checkedAt:H.checkedAt,primary:f9(K.primary,H.checkedAt),secondary:f9(K.secondary,H.checkedAt)}:null,killed:!Z6(K,J,W.id,X),enabled:!0,...K?.resetCreditsAvailable!==void 0?{resetCredits:K.resetCreditsAvailable}:{}}}),route:J.routing?.mode??"main-first",lastUpdated:X}}function Vq(Y,J,X,Q=Date.now()){return{...s$(Y,J,Q),activeId:X}}function z$(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 n4(Y,J){if(!(Y instanceof Request))return J;let X=new Request(Y,J),Q=X.method.toUpperCase(),G=Q==="GET"||Q==="HEAD"||X.body===null?void 0:await X.text();return{method:X.method,headers:new Headers(X.headers),body:G,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}}function H$(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}var pB=new Set(["gpt-6-astra","gpt-6-sol","gpt-6-luna","gpt-6.1-sol"]),lB=new Set(["title","compaction","summary"]);function dB(Y,J,X){if(X!==null&&lB.has(X))return;let Q=typeof Y.model==="string"?Y.model:"";if(!pB.has(Q))return;let G=a(Y.reasoning)?Y.reasoning:void 0,$=typeof G?.effort==="string"?G.effort:void 0;if(!$)return;let W=Array.isArray(Y.input)?Y.input:void 0;J.effortUpdates??=[];let H=J.effortUpdates,K=(L)=>OB("sha256").update(A6(L)).digest("hex").slice(0,16);if(J.pinnedEffort===void 0||H.some((L)=>!W||!$8(W[L.anchor],"user")||K(W[L.anchor])!==L.fingerprint)){J.pinnedEffort=$,J.effortUpdates=[];return}if(!W||W.length===0)return;let U=W.findLastIndex((L)=>$8(L,"user")),V=H.at(-1),O=V?.effort??J.pinnedEffort;if(U>=0&&$!==O)if(V?.anchor===U){let L=H.at(-2)?.effort??J.pinnedEffort;if($===L)H.pop();else V.effort=$}else H.push({anchor:U,fingerprint:K(W[U]),effort:$});else if(U<0&&$!==O)return;if(H.some((L,B)=>B>0&&L.anchor<=(H[B-1]?.anchor??-1))){J.pinnedEffort=$,J.effortUpdates=[];return}Y.reasoning={...G,effort:J.pinnedEffort};for(let L=H.length-1;L>=0;L--){let B=H[L];if(!B)continue;W.splice(B.anchor,0,{type:"configuration_update",reasoning:{effort:B.effort}})}}function t4(Y){if(Array.isArray(Y)){let X=Y;for(let Q=0;Q<Y.length;Q++){let G=t4(Y[Q]);if(G===Y[Q])continue;if(X===Y)X=Y.slice();X[Q]=G}return X}if(!a(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 Q=t4(Y[X]);if(Q===Y[X])continue;if(J===Y)J={...Y};J[X]=Q}return J}function iB(Y){let J=a(Y.reasoning)?{...Y.reasoning}:{};J.context="all_turns",Y.reasoning=J,Y.parallel_tool_calls=!1;let X=t4(Array.isArray(Y.input)?Y.input:[]),G=[{type:"additional_tools",role:"developer",tools:Array.isArray(Y.tools)?Y.tools.filter(($)=>!(a($)&&$.type==="web_search")):[]}];if(typeof Y.instructions==="string"&&Y.instructions.length>0)G.push({type:"message",role:"developer",content:[{type:"input_text",text:Y.instructions}]});Y.input=[...G,...X],delete Y.tools,delete Y.instructions}async function nB(Y,J={}){await o$({version:A1,...J.runtimeLayout});let X=J.codexApiEndpoint??o0().codexApiEndpoint,Q=crypto.randomUUID(),G=I$($$()),$=()=>b$($$(),G),W=!1,H=!1,K=[],U=null,V=S$(Y.client),O=new Map,L=new Map,B,D=!1,q,E=new Map,T,I,x=y3({host:"opencode",stateDir:J.vault?.stateDir??_$(G0(Y0()).statePath),...Y.directory?{projectRoot:Y.directory}:{},reservedRouteIds:()=>i?.peek().rows.map((S)=>S.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}:{},fetchImpl:()=>fetch},G0(Y0())),j=x.vault;await j.authority();let w=x.firstRoster,v=Promise.withResolvers(),M=Promise.race([w,v.promise]),g=J.vault?.firstRosterWaitMs??xY,o,i,{enabled:V0,...B0}=J.poolMigration??{},p=V0??mB;if(p&&"reason"in V)(B0.log??H0("pool")).warn("account pool migration is off for this OpenCode client",{reason:V.reason});let t=p&&"slot"in V?L3({paths:()=>G0(Y0()),slot:V.slot,version:A1,...B0,runDeps:{vaultServes:()=>j.serves(),...B0.runDeps},paused:async()=>await j.authority()!=="local",migrate:async(S)=>{let u=await(B0.migrate??K9)(S);return i?.load(),u},adopt:async(S)=>{if(!await H8(M,g))return{status:"retry",reason:"vault-roster-pending"};let u=await(B0.adopt??U9)(S);return i?.load(),u}}):void 0,L0=(S,u="")=>S?async()=>{let d=await S();return{url:d.url,instructions:d.instructions??u,method:"auto",callback:async()=>{try{let y=await d.tokens;return{type:"success",refresh:y.refresh_token,access:y.access_token,expires:Date.now()+(y.expires_in??3600)*1000,accountId:a1(y)}}finally{d.cleanup?.()}}}}:void 0,h=new AY(J.backgroundQuota),x0,R0=BX({client:Y.client,getAuth:async()=>x0?.(),fetchImpl:fetch,dependencies:{...J.login?.authorize?{authorizeBrowser:L0(J.login.authorize.browser,"Complete authorization in your browser. This window will close automatically."),authorizeHeadless:L0(J.login.authorize.headless)}:{}},vault:j,onMainSlotWritten:async()=>{await t?.requestAdoption()}}),U0=(S)=>async(u)=>{let d=await S(u);if(d.method!=="auto")return d;return{...d,callback:async()=>{let y=await d.callback();if(y.type==="success"&&"refresh"in y)r(y.refresh);return y}}};async function r(S){if(!t||!("slot"in V))return;let u=J.login?.sleep??((d)=>Bun.sleep(d));for(let d=0;d<5000;d+=100){try{let y=await V.slot.get({path:{id:"openai"}});if(a(y)&&y.refresh===S){await t.requestAdoption();return}}catch{}await u(100)}}let E0=R0.map((S)=>S.type==="oauth"?{...S,authorize:U0(S.authorize)}:S);async function l(S,u){let d=Y.client.session;if(typeof d?.promptAsync==="function"){let y=await a3(Y.client,S),W0={noReply:!0,parts:[{type:"text",text:u,ignored:!0}]};if(y?.agent)W0.agent=y.agent;if(y?.model)W0.model=y.model;if(y?.variant)W0.variant=y.variant;await d.promptAsync({path:{id:S},body:W0});return}}return{async dispose(){x.release(),t?.dispose(),await i?.dispose(),h.stop(),I?.stop(),B?.stopBackgroundRefresh(),B=void 0;for(let d of K)d.close();K.length=0;let S=globalThis;for(let[d,y]of O)if(S.__openaiAuthCacheKeepManagers?.get(d)===y)y.stop(),S.__openaiAuthCacheKeepManagers.delete(d);O.clear();for(let d of L.values())await d.release().catch(()=>{});L.clear();let u=o;o=void 0,await(await u)?.release()},async event(S){if(S.event.type!=="session.deleted")return;let u=S.event.properties.info,d=G.get(u.id);if(d)U?.cacheKeepManager?.remove(d.threadID);if(G.delete(u.id))$();let y=j1(u.id);if(E.delete(y),I?.cancel(`pin:${y}`),q){let W0=await j.authority()!=="local"?j.routes().map((P0)=>({id:P0.id})):(await C0(G0(Y0())))?.accounts;await f$(u.id,W0,q).catch(()=>{})}for(let W0 of K)W0.remove(u.id)},provider:{id:"openai",async models(S,u){if(u.auth?.type!=="oauth")return S.models;let d=await j.authority()!=="local"?await g6(G0(Y0())):await C0(G0(Y0())),y=!d||j$(d),W0=y?null:await n3();if(!y&&W0&&!X$)X$=!0,J$.debug("restoring OAuth model costs from models.dev catalog");if(!y&&!W0&&!Q$)Q$=!0,J$.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(S.models).filter(([,P0])=>P0.options.reasoningMode!=="pro"&&MB(P0.api.id)).map(([P0,h0])=>{let M0=TB(h0.id),p0=M0?S.models[M0]?.variants:void 0;return[P0,{...h0,...p0?{variants:{...p0,...h0.variants}}:{},cost:y?{input:0,output:0,cache:{read:0,write:0}}:W0?.[h0.api.id]??W0?.[P0]??h0.cost,limit:AB(h0.id)??h0.limit}]}))}},auth:{provider:"openai",async loader(S){await j.authority(),x0=S,o??=i$({version:A1,logger:H0("heartbeat")}),await o,t?.start();let u=await S();if(u.type!=="oauth")return v.resolve(),{};let d=s4(u).kind==="tombstone";x.start();let y=Y.directory?await A$(Y.directory):void 0,W0=y?.dir??Y0();async function P0(Z,N={}){if(await j.authority()!=="local")return;return gB(Z,{...N,canWrite:()=>!j.enrolled()})}let h0=await j.authority()!=="local";if(!d&&!h0)await D$({type:"oauth",access:u.access??"",refresh:u.refresh??"",expires:u.expires??0},G0(Y0()));let M0=await(h0?g6(G0(Y0())):C0(G0(Y0()))).catch(async(Z)=>{if(await j.authority()!=="local")return null;let N=Y0();throw Error(`OpenAI auth store at ${N} is corrupt or unreadable: ${Z instanceof Error?Z.message:String(Z)}. Fix or remove it to continue.`,{cause:Z})});if(!h0&&await m9(G0(Y0()),u)){if(t)t.noticePlaceholderWithoutMain();else if(!D)D=!0,H0("pool-migration").warn(_6,{reason:"placeholder-without-main"})}let p0=M0,f6=!h0,q0=Q3({path:Y0,stat:(Z)=>{try{let N=PB(Z);return{mtimeMs:N.mtimeMs,size:N.size}}catch{return}},read:(Z)=>C0(G0(Z)),fallback:async(Z)=>{if(await j.authority()!=="local")return g6(G0(Y0()));throw Z},onRead:(Z)=>{p0=Z,f6=!0}});function H1(){return q0.read()}async function b8(){if(!f6)return H1();return H9(Promise.resolve(H1()),z9,()=>p0)}function k8(){q0.invalidate()}if(M0&&u.access&&!d&&!h0){let Z=a1({id_token:"",access_token:u.access,refresh_token:u.refresh??""});if(Z&&Z!==M0.mainAccountId)await P0((N)=>{N.mainAccountId=Z}),M0.mainAccountId=Z,k8()}let l9=M0?.logging?.level;if(l9&&typeof l9==="string")J9(l9);let m6=H0("transport"),Q1=H0("quota"),x8=H0("refresh"),K1=H0("accounts"),a$=new M$;m6.info("codex auth loader ready",{codexApiEndpoint:X,transport:o0().rawWebSocket?"raw-websocket":o0().webSockets?"websocket":"http"});let X0=new N$({storage:M0,configPath:Y0(),fetchQuotaFn:void 0}),c6,u6=0;await i?.dispose();let A0=new hY({paths:()=>G0(Y0()),refreshProvider:async(Z)=>{let N=await w8({refreshToken:Z.refresh,fetchImpl:fetch,now:Date.now}),F=a1({id_token:"",access_token:N.access,refresh_token:N.refresh});return{...N,...F?{identity:F}:{}}},pullQuota:async(Z)=>{let N=Z.credential;if(N.type!=="oauth"||!N.access)throw Error("the row holds no access token to poll with");let F=await e6({accessToken:N.access,fetchImpl:fetch,now:Date.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,logger:Q1}),R=Date.now(),P={quota:F,refreshAfter:R+300000,checkedAt:R};if(Z.id==="main")X0.setMain(N.access,P,Z.identity,!0);else X0.setFallback(Z.id,P,N.access,!0,Z.identity);return q6(F,R,!0)},vaultIdentities:()=>j.identities(),vaultMode:()=>j.enrolled(),vaultAuthority:()=>j.authority(),vaultFirstRoster:w,vaultFirstRosterBackgroundWaitMs:g,log:H0("pool")});if(i=A0,!h0)await A0.load();let e0=new O$({paths:G0(Y0()),refreshFn:async(Z)=>{if(await j.authority()!=="local")throw Error(G6["vault-refused"]);return w8({refreshToken:Z.refreshToken,fetchImpl:Z.fetchImpl,now:Z.now})},quotaManager:X0,canWrite:()=>!j.enrolled(),onFallbackStorageChanged:k8,backgroundRefreshPaused:async()=>j.enrolled()||await A0.active()});if(M0&&M0.accounts.length>0)e0.startBackgroundRefresh();function d9(Z){if(c0(Z))return;return Z.access||void 0}function h8(Z={}){let{readSidebarState:N,respectBackoff:F,skipFresherThanMs:R}=Z;return{getAuth:S,codexRefreshFn:w8,refreshMainWithLease:UJ,fallbackManager:e0,quotaManager:X0,loadAccounts:C0,writeSidebarState:(P)=>U1(P),client:Y.client,fetchImpl:fetch,now:Date.now,paths:G0(Y0()),readSidebarState:N??(()=>x$(l0)),storageMainAccountId:M0?.mainAccountId,isOAuthAccountFn:s0,whamFn:e6,...F===void 0?{}:{respectBackoff:F},...R===void 0?{}:{skipFresherThanMs:R}}}async function YJ(Z){return(await A0.pollRows(await C0(G0(Y0())),Z?{ids:Z}:{})).map((F)=>({account:F.id,ok:F.ok,...F.error!==void 0?{error:F.error}:{}}))}async function JJ(Z){return A0.accessFor(Z,await C0(G0(Y0())))}let XJ=H0("cachekeep"),v8=X9(M0),QJ=v8?.enabled===!0,GJ=v8?.subagents===!0,$J=v8?.sustain===!0,WJ=eX(M0?{...M0,cachekeep:v8}:M0),y8;async function t$(Z){await new Promise((N)=>setTimeout(N,Z))}async function e$(Z){let N;for(let F=1;F<=Y$;F++){if(await j.authority()!=="local")throw Error(G6["vault-refused"]);try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:Z.refresh,access:Z.access,expires:Z.expires}});return}catch(R){if(N=R,F<Y$)await t$(bB*F)}}throw new e4(N)}async function g8(Z){await P0((N)=>{N.refresh=N.refresh??{},Z(N)},{holdsMainRefreshLock:!0}),k8()}async function i9(Z){let N=Date.now()+IB;while(Date.now()<N){await new Promise((P)=>setTimeout(P,eG+fB(eG)));let F=await S();if(r0(F))throw new s1;if(F.type!=="oauth"||!F.access)continue;if((F.access!==Z.access||F.refresh!==Z.refresh||(F.expires??0)>(Z.expires??0)+60000)&&(!F.expires||F.expires>Date.now()))return x8.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:F.expires?F.expires-Date.now():void 0}),{access:F.access,refresh:F.refresh??Z.refresh??"",expires:F.expires??0}}return null}function zJ(Z){if(r0(Z))throw new s1;if(Z.type!=="oauth")throw Error("not oauth");if(c0(Z))throw new B$;if(!Z.refresh)throw Error("Token refresh failed: missing refresh token");return Z.refresh}async function n9(){if(!y8)y8=(async()=>{let Z=await S(),N=zJ(Z);if(Z.type!=="oauth")throw Error("not oauth");let F=K8(N),R=await C0(G0(Y0())),P=R?.refresh?.mainLastRefreshError;if(P&&M1(P,N,Date.now()))throw Error(o4(P,Date.now()));if(R?.refresh?.mainRefreshLeaseUntil&&R.refresh.mainRefreshLeaseUntil>Date.now()&&R.refresh.mainRefreshLeaseTokenHash===F){let f=await i9(Z);if(f)return f;throw Error("Codex OAuth refresh is already in progress")}let b=await Q9({name:t6,ttlMs:wB,path:Y0(),renew:!0});if(!b){let f=await i9(Z);if(f)return f;throw Error("Codex OAuth refresh is already in progress")}let A;try{let f=await S(),J0=zJ(f);if(f.type!=="oauth")throw Error("not oauth");if(J0!==N){if(f.access&&(f.expires??0)>Date.now())return x8.debug("main token rotated while awaiting the lock",{pid:process.pid}),await b.release().catch(()=>{}),{access:f.access,refresh:J0,expires:f.expires??0};let v0=(await C0(G0(Y0())))?.refresh?.mainLastRefreshError;if(v0&&M1(v0,J0,Date.now()))throw Error(o4(v0,Date.now()))}A={...f,refresh:J0}}catch(f){throw await b.release().catch(()=>{}),f}await w$(G0(Y0()),A.refresh,A.access!==void 0?{slotAccess:A.access}:{}).catch(()=>!1);let C=K8(A.refresh),m=crypto.randomUUID(),s=C;try{await g8((z0)=>{if(C$(Y0(),A.refresh))throw new r4;z0.refresh=z0.refresh??{},z0.refresh.mainRefreshLeaseId=m,z0.refresh.mainRefreshLeaseUntil=Date.now()+SB,z0.refresh.mainRefreshLeaseTokenHash=C});let f=await C0(G0(Y0()));if(f?.refresh?.mainRefreshLeaseId!==m||f.refresh.mainRefreshLeaseTokenHash!==C)throw Error("Codex OAuth refresh is already in progress");if(await j.authority()!=="local")throw Error(G6["vault-refused"]);let J0=await w8({refreshToken:A.refresh,fetchImpl:fetch,now:Date.now});return await e$(J0),await g8((z0)=>{if(z0.refresh=z0.refresh??{},z0.refresh.mainLastRefreshError=void 0,z0.refresh.mainRefreshLeaseId===m)z0.refresh.mainRefreshLeaseId=void 0,z0.refresh.mainRefreshLeaseUntil=void 0,z0.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),s=void 0,J0}catch(f){if(!(f instanceof r4)){if(!i4(f))await g8((J0)=>{J0.refresh=J0.refresh??{},J0.refresh.mainLastRefreshError=Z$({error:f,now:Date.now(),refreshToken:A.refresh,previous:J0.refresh.mainLastRefreshError})}).catch(()=>{});throw f}}finally{if(s)await g8((f)=>{if(f.refresh?.mainRefreshLeaseId===m&&f.refresh.mainRefreshLeaseTokenHash===s)f.refresh.mainRefreshLeaseId=void 0,f.refresh.mainRefreshLeaseUntil=void 0,f.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await b.release().catch(()=>{})}let c=await i9(A);if(c)return c;throw Error("Codex OAuth refresh is already in progress")})().finally(()=>{y8=void 0});return y8}function HJ(Z){return vJ({storage:Z,now:Date.now,refreshAccount:(N,F)=>e0.refreshAccount(N,F,{asPoolMain:!0}),warn:(N,F)=>x8.warn(N,{pid:process.pid,...F})})}async function KJ(){let Z=await HJ(await C0(G0(Y0())));if(!Z)throw Error("The main OpenAI account has no usable token in the account pool");return{access:Z.token,refresh:Z.account.refresh,expires:Z.account.expires??0}}async function UJ(){try{return await n9()}catch(Z){if(Z instanceof s1)return KJ();throw Z}}let ZJ=globalThis,o9=ZJ.__openaiAuthCacheKeepManagers??new Map;ZJ.__openaiAuthCacheKeepManagers=o9,o9.get(W0)?.stop();let p6=X3({fetchImpl:fetch,vault:j,getMainToken:async()=>{if(await j.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(await A0.active()){let N=await JJ("main");if(!N)throw Error("main pool row has no usable token");return N.token}let Z=await S();if(await j.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(r0(Z))return(await KJ()).access;if(Z.type!=="oauth")throw Error("not oauth");if(!Z.access||(Z.expires??0)<Date.now())try{return(await UJ()).access}catch(N){if(i4(N))throw N;if(Z.access)return Z.access;throw Error("main token refresh failed")}return Z.access},refreshFallback:async(Z)=>{if(await j.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(await A0.active()){let A=await JJ(Z);if(!A)throw Error(`no access token for ${Z}`);return{token:A.token}}let N=await b8(),F=N?uB(N.accounts,Z):void 0;if(!F)throw Error(`fallback account ${Z} not found`);let R=N??{version:1,accounts:[F]},P=c0(F)?F:await e0.refreshAccount(F,R),b=d9(P);if(!b)throw Error(`no access token for ${Z}`);return{token:b}},codexResponsesUrl:X,activeAccount:async(Z)=>J3(U6(await d1.read(),E),Z),logger:XJ,now:Date.now,getWindow:()=>WJ,getSustain:()=>$J});o9.set(W0,p6),O.set(W0,p6);function V6(Z,N,F,R,P=!1){try{YW(Z,N,F,R,P)}catch(b){Q1.warn("quota push failed",{pid:process.pid,accountId:F??"main",error:h6(b)})}}function YW(Z,N,F,R,P){if(Object.keys(Z).length===0&&!P)return;let b=Date.now(),A=Z,C={quota:A,refreshAfter:b+300000,checkedAt:b},m;if(F&&F!=="main"){let c=N?J1(N):null,f=c?X1(c):void 0,J0=X0.peekFallbackForPolicy(F)?.quota,z0=W$(A,J0);C={...C,quota:z0},X0.setFallback(F,C,N,P,f)}else{if(m=R,!m&&N){let J0=J1(N);m=J0?X1(J0):void 0}if(m&&c6&&m!==c6){Q1.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:m,currentMainIdentity:c6});return}let c=X0.peekMainForPolicy(m)?.quota,f=W$(A,c);C={...C,quota:f},X0.setMain(N,C,m,P)}Q1.debug("quota pushed",{pid:process.pid,accountId:F??"main",snapshot:C.quota}),A0.recordSnapshot(F&&F!=="main"?F:"main",Z,N,P);let s=Boolean(F&&F!=="main");D1.enqueue("machine-state","quota",()=>U1(X0,s?void 0:m))}function JW(Z,N,F){let R=T1(j.routes().find((P)=>P.id===Z)?.quota)??(Z==="main"?X0.peekMainForPolicy()?.quota:X0.peekFallbackForPolicy(Z)?.quota);return L$(R,N,Date.now(),kB,F)}let f8=new Map,l6=new Map;function VJ(){if(!j.enrolled())return;D1.enqueue("machine-state","quota",()=>U1(X0))}let B6=J.experimentalWebSockets?k1.createWebSocketFetch({httpFetch:fetch,rawWebSocket:o0().rawWebSocket,onQuota:(Z,N,F,R)=>{let P=F?f8.get(F):void 0;if(P){j.recordSnapshot(P.id,Z,!0,P.receipt).then(VJ);return}V6(Z,N,F,!F||F==="main"?R:void 0,!0)},onRateLimitReached:(Z,N,F)=>{if(!N)Q1.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:Z});let R=N?f8.get(N):void 0,P=R?.id??N??"main",b=JW(P,Z,F);if(X0.markRateLimited(P,b),R)l6.set(P,Math.max(l6.get(P)??0,b));else A0.markRateLimited(P,b);Q1.debug("mid-stream rate limit mark",{pid:process.pid,accountId:P,window:Z})}}):void 0;if(B6)K.push(B6),W=!0;let l0=k$();q=l0;async function U1(Z,N){if(j.enrolled()){q0.invalidate();let A=await g6(G0(Y0()));await c9(S3(j.snapshot()?.rows,new Set(j.routes().map((C)=>C.id)),A,Date.now()),l0,{canWrite:()=>j.enrolled()});return}let F=H1(),R=F instanceof Promise?await F.catch(()=>p0):F,P=N??R?.mainAccountId,b=await A0.current();if(b.active){await c9(I3(b.rows,R,Date.now(),(A)=>(A==="main"?Z.getMain():Z.getFallback(A))?.quota?.resetCreditsAvailable),l0,{canWrite:()=>!j.enrolled()});return}if(!R)return;await c9(s$(Z,R,Date.now(),P),l0,{canWrite:()=>!j.enrolled()})}let d1=p$(l0);d1.read(),I?.stop();let D1=d$({logger:m6,onWritten:()=>d1.refreshInBackground()});if(I=D1,T!==l0)E.clear(),T=l0;function r9(Z,N,F,R,P,b,A=!1){let C={canWrite:()=>j.enrolled()===A},m={activeId:F,route:R,updatedAt:Date.now()};if(!Z){D1.enqueue("routing:legacy","routing",()=>g$(m,l0,C));return}if(D1.enqueue(`routing:${Z}`,"routing",()=>u9({sessionId:Z,...m},P,l0,C)),!N||N===Z)return;if(R==="sticky-balanced"){let s=b.stickyAssignments?.[j1(N)]?.accountId,c=P===void 0||s==="main"||P.some((f)=>f.enabled!==!1&&f.id===s);if(!s||!c)return;D1.enqueue(`routing:${N}`,"routing",()=>u9({sessionId:N,activeId:s,route:R,updatedAt:Date.now()},P,l0,C));return}D1.enqueue(`routing:${N}`,"routing",()=>u9({sessionId:N,...m},P,l0,C))}B?.stopBackgroundRefresh(),B=e0;let d6=G0(Y0());if(U=r$={accountStoragePath:d6.configPath,accountStatePath:d6.statePath,packageVersion:A1,layoutNotice:n$,quotaManager:X0,loadAccounts:C0,beginAccountLogin:n8,store:()=>O6(d6),migration:async()=>{if(await p8(d6,O6(d6))!==void 0)return{migrated:!0};let Z=await(B0.fence??(()=>E6({currentVersion:A1})))();return{migrated:!1,blockers:Z.open?[]:Z.blockers.map((N)=>({pid:N.pid,version:N.version}))}},afterWrite:()=>A0.load(),vault:j,resolveResetTarget:vB({getAuth:S,refreshMainWithLease:n9,refreshFallbackAccount:(Z,N)=>e0.refreshAccount(Z,N),refreshPoolMainRow:(Z,N)=>e0.refreshAccount(Z,N,{asPoolMain:!0}),poolAccess:async(Z)=>A0.rowAccess(Z,await C0(G0(Y0()))),loadAccounts:C0,accountStoragePath:Y0(),accountStatePath:R$(Y0()),now:Date.now}),...yB(),cacheKeepManager:p6,setCacheKeepEnabled:(Z)=>{QJ=Z},setCacheKeepSubagents:(Z)=>{GJ=Z},setCacheKeepSustain:(Z)=>{$J=Z},setCacheKeepWindow:(Z)=>{WJ=Z},clearStickyRouting:async(Z)=>{let N=j1(Z),F=E.delete(N);return D1.cancel(`pin:${N}`),await u$(Z,l0)||F},getStickyRouting:async(Z)=>y$(U6(await d1.read(),E),Z),refreshSidebar:async()=>{k8(),await U1(X0)},refreshAllQuota:async()=>{if(await j.authority(),j.enrolled()){let Z=await j.pollStale(0);return await U1(X0),Z.map((N)=>({account:N.id,ok:N.ok,...N.error!==void 0?{error:N.error}:{}}))}if(await A0.active()){let[Z,N]=await Promise.all([YJ(),j.pollStale(0)]);return await U1(X0),[...Z,...N.map((F)=>({account:F.id,ok:F.ok,...F.error!==void 0?{error:F.error}:{}}))]}return R6(h8())},refreshResetTargetQuota:async(Z)=>{if(await j.authority(),j.enrolled())return{account:Z,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};if(await A0.active()){let[F]=await YJ([Z]);return F??{account:Z,ok:!1,error:"targeted quota refresh returned no result"}}return(await R6(h8({respectBackoff:!1}),{accountKey:Z})).find((F)=>F.account===Z)??{account:Z,ok:!1,error:"targeted quota refresh returned no result"}}},y){let Z=y;try{let N=await U$(J2,Z.dir,()=>X2({dir:Z.dir,secureDir:Z.secureDir,sweepRoot:Z.sweepRoot,drain:gX,apply:async(F)=>{let R=K$(F);if(!R)throw Error("not an /openai apply request");return lX(U,R)}}));L.set(Z.dir,N)}catch{}}async function L6(Z,N,F,R,P="main",b){if(!F.trim())throw m6.warn("refusing to send a request with no access token",{account:P,accountId:R}),Error(RB);if(!b&&await j.authority()!=="local")return Response.json({error:{message:G6["vault-refused"]}},{status:400});let A=z$(Z,N);if(A.delete("x-api-key"),A.delete("api-key"),A.set("authorization",`Bearer ${F}`),R)A.set("ChatGPT-Account-Id",R);A.set(k1.QUOTA_ACCOUNT_HEADER,P);let C=H$(A),m=C?cB(G,C,$):void 0,s=Z instanceof URL?Z:new URL(typeof Z==="string"?Z:Z.url),c=s.pathname.includes("/v1/responses")||s.pathname.includes("/chat/completions")?new URL(X):s,J0=IX({rewriteLite:iB,applyEffort:dB,init:{...N,headers:A},headers:A,metadata:m,installationID:Q,websocket:Boolean(B6&&s.pathname.endsWith("/responses")),responsesLite:J.responsesLite??!1,dumpSessionID:C}).init,z0=QJ,v0=new Headers(J0?.headers),e=tX({enabled:z0,includeSubagents:GJ,headers:v0,body:J0?.body});if(z0)XJ.trace("cachekeep headers",{pid:process.pid,hasParent:v0.has("x-parent-session-id"),sessionKey:e?.sessionKey,captured:Boolean(e),affinity:v0.get("x-session-affinity"),opencodeSession:v0.get("x-opencode-session"),sessionId:v0.get("session-id")});if(B6&&s.pathname.endsWith("/responses")){if(m6.debug("WS transport",{pid:process.pid,pathname:s.pathname,accountId:P}),e)p6.track({sessionKey:e.sessionKey,bodyText:e.bodyText,accountId:P,isSubagent:e.isSubagent,meta:{replayHeaders:e.replayHeaders,chatgptAccountId:R,routingSessionId:C}});if(!b)try{return await Q6(await B6(c,J0),F,"event-stream")}catch(T0){throw v1(T0,F)}let K0=`vault-stream:${_B()}`;f8.set(K0,{id:P,receipt:b});let Z1=new Headers(J0?.headers);Z1.set(k1.QUOTA_ACCOUNT_HEADER,K0);let m0=()=>f8.delete(K0);try{let T0=await B6(c,{...J0,headers:Z1});if(!T0.body)return m0(),T0;let O1=T0.body.getReader();return await Q6(new Response(new ReadableStream({async pull(_1){try{let P1=await O1.read();if(P1.done)m0(),_1.close();else _1.enqueue(P1.value)}catch(P1){m0(),_1.error(v1(P1,F))}},cancel(_1){return m0(),O1.cancel(_1)}}),{status:T0.status,statusText:T0.statusText,headers:T0.headers}),F,"event-stream")}catch(T0){throw m0(),v1(T0,F)}}let N0=k1.withoutInternalHeaders(J0);if(typeof N0?.body!=="string")try{return await Q6(await fetch(c,N0),F,"event-stream")}catch(K0){throw v1(K0,F)}if(e)p6.track({sessionKey:e.sessionKey,bodyText:e.bodyText,accountId:P,isSubagent:e.isSubagent,meta:{replayHeaders:e.replayHeaders,chatgptAccountId:R,routingSessionId:C}});m6.debug("HTTP transport",{pid:process.pid,pathname:s.pathname,accountId:P});try{let K0=await fetch(c,N0);return await M6({sessionID:C,transport:"http",phase:"http",bodyText:N0.body,accountId:P,url:c.toString(),method:N0.method,headers:N0.headers,status:K0.status}),await Q6(K0,F,"event-stream")}catch(K0){throw await M6({sessionID:C,transport:"http",phase:"http",bodyText:N0.body,accountId:P,url:c.toString(),method:N0.method,headers:N0.headers,error:K0 instanceof Error?K0.message:String(K0)}),v1(K0,F)}}function i6(Z,N){if((N?.method??(Z instanceof Request?Z.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof N?.body!=="string")return!1;try{let R=Z instanceof URL?Z.toString():typeof Z==="string"?Z:Z.url;return new URL(R).pathname.endsWith("/responses")}catch{return!1}}function XW(Z){return X0.peekMainForPolicy(Z)?.quota}function BJ(Z,N){for(let F of[Z?.primary?.checkedAt,Z?.secondary?.checkedAt,Z?.checkedAt,N])if(typeof F==="number"&&Number.isFinite(F))return F;return}function n6(Z,N,F,R,P){let b=BJ(Z,N),A=BJ(F),C=R===P&&F!=null&&(Z===void 0||A!==void 0&&(b===void 0||A>b));return{quota:C?F:Z,quotaCheckedAt:C?A:b,source:C?"file":"memory"}}function LJ(Z,N,F,R,P){let b=Z?.quota,A=n6(b,Z?.checkedAt,N,R,P),C=A.source,m=A.quota;if(!v$(m,F))return{exhausted:!1};let s=h$(m,F);if(!s)return{exhausted:!1};return{exhausted:!0,source:C,...s}}function NJ(Z,N){Q1.debug("admission skip: exhausted account",{accountId:Z,source:N.source,resetsAt:N.resetsAt})}function jJ(Z,N="killswitch",F,R){let P=Date.now(),b=R?R.main:X0.getMain()?.quota,A=R?R.fallbacks:(Z?.accounts??[]).filter((f)=>f.enabled!==!1&&s0(f)).map((f)=>({accountId:f.id,quota:X0.getFallback(f.id)?.quota})),C=F$(b,A,P,Z);if(N==="quota-unknown")C=E$;else if(N==="quota-exhausted"&&F!==void 0)C=Math.max(1,Math.ceil((F-P)/1000));else if(N==="mid-stream-rate-limit"&&F!==void 0){let f=Math.max(1,Math.ceil((F-P)/1000));C=Math.min(C,f)}let m=Math.floor(C/60),s=C%60,c=N==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${m}m ${s}s.`:N==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${m}m ${s}s.`:N==="quota-unknown"?`OpenAI quota is not known yet for any available account; checking it now. Retry in ${m}m ${s}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${m}m ${s}s.`;return new Response(JSON.stringify({error:{message:c,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(C)}})}function s9(Z){let N=Z?.resetCreditsAvailable;return typeof N==="number"&&Number.isFinite(N)?N:void 0}async function QW(Z){let N=I8(Z.storage),F=Date.now(),R=X0.peekMainForPolicy(Z.mainAccountIdentity),P=n6(R?.quota,R?.checkedAt,Z.sidebarState.main.quota,Z.sidebarState.main.mainAccountId,Z.mainAccountIdentity),b=N?Z6(R?.quota,Z.storage,void 0,F):void 0,A=Z.mainUnavailable?[]:[{accountId:"main",wireAccountId:Z.mainAccountIdentity,access:Z.primaryAccess,keepwarmAccountKey:"main",quota:P.quota,quotaCheckedAt:P.quotaCheckedAt,reservePercent:U8(Z.storage),configuredOrder:0,resetCreditsApplicable:s9(P.quota),killswitchPasses:b}],C=await e0.getUsableFallbackAccounts(Z.storage);if(!Z.storage)return A;for(let m of C){let s=d9(m);if(!s)continue;let c=Z.sidebarState.fallbacks.find((v0)=>v0.id===m.id),f=X0.peekFallbackForPolicy(m.id,m.accountId),J0=n6(f?.quota,f?.checkedAt,c?.quota,c?.accountId,m.accountId),z0=N?Z6(f?.quota,Z.storage,m.id,F):void 0;A.push({accountId:m.id,wireAccountId:m.accountId,access:s,keepwarmAccountKey:m.id,fallback:m,quota:J0.quota,quotaCheckedAt:J0.quotaCheckedAt,reservePercent:U8(Z.storage,m.id),configuredOrder:A.length,resetCreditsApplicable:s9(J0.quota),killswitchPasses:z0})}return A}function FJ(Z,N,F,R,P){let b=I8(P)?Z.killswitchPasses:void 0;if(Z.accountId==="main"){let s=X0.peekMainForPolicy(Z.wireAccountId),c=n6(s?.quota,s?.checkedAt,N.main.quota,N.main.mainAccountId,Z.wireAccountId);return dY({quota:c.quota,quotaCheckedAt:c.quotaCheckedAt,status:F,now:R,killswitchPasses:b})}let A=N.fallbacks.find((s)=>s.id===Z.accountId),C=X0.peekFallbackForPolicy(Z.accountId,Z.wireAccountId),m=n6(C?.quota,C?.checkedAt,A?.quota,A?.accountId,Z.wireAccountId);return dY({quota:m.quota,quotaCheckedAt:m.quotaCheckedAt,status:F,now:R,killswitchPasses:b})}function GW(Z){return Z.accountId==="main"?"main":Z.keepwarmAccountKey}function DJ(Z){return X0.isRateLimited(GW(Z))}function a9(Z){let N=Z.candidates.filter((b)=>!DJ(b)),F=new Map(N.map((b)=>[b.accountId,b])),R=new Set(Z.excludeAccountIds),P=OJ({sessionId:Z.sessionId,requestBytes:Z.requestBytes,sidebarSnapshot:Z.sidebarSnapshot,now:Z.now,validPinnedAccountIds:[...F.keys()],excludeAccountIds:Z.excludeAccountIds??[],quotaCheckedAtByAccount:Object.fromEntries(N.map((b)=>[b.accountId,b.quotaCheckedAt])),wireAccountIdByAccount:Object.fromEntries(N.map((b)=>[b.accountId,b.wireAccountId])),select:(b)=>{let A=N.filter((C)=>!R.has(C.accountId));if(A.length===0)return;return p3({candidates:A,pendingBytes:b,requestBytes:Z.requestBytes,now:Z.now,onEmptyWeightedSet:()=>{K1.debug("sticky routing: no fresh weighted candidates; using configured order")}})},persist:!0});return P?F.get(P.accountId):void 0}function OJ(Z){let N=void 0,F=Z.validPinnedAccountIds,R=m$(U6(Z.sidebarSnapshot,E),{sessionId:Z.sessionId,requestBytes:Z.requestBytes,now:Z.now,validPinnedAccountIds:F,excludeAccountIds:Z.excludeAccountIds,quotaCheckedAtByAccount:Z.quotaCheckedAtByAccount,wireAccountIdByAccount:Z.wireAccountIdByAccount,choose:(b)=>{let A=Z.select(b);if(!A)return;return N={accountId:A.accountId,source:A.source,pendingBytes:b.get(A.accountId)??0},A}}),P=R.assignment;if(!Z.persist)return P;if(N&&P?.accountId===N.accountId)K1.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:j1(Z.sessionId),accountId:N.accountId,source:N.source,requestBytes:Z.requestBytes,pendingBytes:N.pendingBytes});if(P&&R.next!==void 0){let b=j1(Z.sessionId),A=l$(E,b,P);D1.enqueue(`pin:${b}`,"sticky-pin",async()=>{await c$({sessionId:Z.sessionId,assignment:P,validPinnedAccountIds:F},l0),A.persistedAt=Date.now()})}return P}async function $W(Z,N){let F=await e0.getUsableFallbackAccounts(Z),R=[];if(!Z)return{current:[],retained:[],skipped:[]};for(let c of F){let f=d9(c);if(!f)continue;R.push({access:f,accountId:c.accountId,keepwarmAccountKey:c.id,quotaAccountId:c.id,fallback:c})}let P=R.filter((c)=>!X0.isRateLimited(c.quotaAccountId)),b=I8(Z)?P.filter((c)=>Z6(X0.peekFallbackForPolicy(c.quotaAccountId,c.accountId)?.quota,Z,c.quotaAccountId,Date.now())):P,A=new Map(N.fallbacks.map((c)=>[c.id,{quota:c.quota,accountId:c.accountId}])),C=[],m=[],s=Date.now();for(let c of b){let f=A.get(c.quotaAccountId),J0=LJ(X0.peekFallbackForPolicy(c.quotaAccountId,c.accountId),f?.quota,s,f?.accountId,c.accountId);if(J0.exhausted)m.push({candidate:c,decision:J0});else C.push(c)}return{current:b,retained:C,skipped:m}}function _J(Z,N){if(Z.retained.length===0&&!N)return Z.current;for(let{candidate:F,decision:R}of Z.skipped)NJ(F.quotaAccountId,R);return Z.retained}function PJ(Z,N){try{let F=X6(Z.headers);V6(F,N.access,N.quotaAccountId,void 0,y6(Z.headers))}catch{}}async function WW(Z,N,F,R){for(let P of R){let b;try{b=await L6(Z,N,P.access,P.accountId,P.keepwarmAccountKey)}catch(A){if((A instanceof Error||A instanceof DOMException)&&A.name==="AbortError")throw A;if(N?.signal?.aborted)throw A;throw K1.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:P.quotaAccountId}),A}if(!S8(b.status,F))return e0.markUsed(P.fallback),{response:b,accessToken:P.access,quotaAccountId:P.quotaAccountId,activeId:P.keepwarmAccountKey};PJ(b,P),b.body?.cancel().catch(()=>{})}return}async function zW(Z,N,F,R,P){if(!i6(Z,N))return{response:F};if(!P.length)return{response:F};let b=F,A;for(let C of P){let m;try{m=await L6(Z,N,C.access,C.accountId,C.keepwarmAccountKey)}catch(s){if((s instanceof Error||s instanceof DOMException)&&s.name==="AbortError")throw s;if(N?.signal?.aborted)throw s;return K1.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:C.quotaAccountId}),{response:b,...A}}if(b.body?.cancel().catch(()=>{}),b=m,A={accessToken:C.access,accountId:C.quotaAccountId},!S8(m.status,R))return e0.markUsed(C.fallback),{response:m,...A};PJ(m,C)}return{response:b,...A}}if(M0){let Z=[];for(let N of M0.accounts)if(s0(N))Z.push(N);X0.seedFallbacksFromAccounts(Z)}if(!a4)if(a4=!0,U1(X0).catch(()=>{}),w.then(()=>j.enrolled()?U1(X0):void 0).catch(()=>{}),!j.enrolled()&&!await A0.active())p9=R6(h8({respectBackoff:!0})).catch((Z)=>Q1.warn("boot quota seed failed",{pid:process.pid,error:h6(Z)}));else p9=Promise.resolve();h.start(async()=>{if(await j.authority(),j.enrolled()){await U1(X0);return}if(await A0.active()){let F=await rX(A0,await C0(G0(Y0())),()=>MY(Y0()));if(F.length>0)await U1(X0);let R=F.filter((P)=>!P.ok);if(R.length>0)Q1.warn("background pool quota poll completed with failures",{pid:process.pid,failures:R});return}let N=(await nX(h8({readSidebarState:async()=>(await d1.read()).state}))).filter((F)=>!F.ok);if(N.length>0)Q1.warn("background quota refresh completed with failures",{pid:process.pid,failures:N})},(Z)=>{Q1.warn("background quota refresh failed",{pid:process.pid,error:Z instanceof Error?Z.message:String(Z)})});async function t9(Z,N,F,R,P,b){let A=F?.routing?.mode??"main-first",C=j.enrolled(),m=C?void 0:A0.peek().rows.find((e)=>e.id==="main"),s=!m&&!C?await S():void 0,c=!m&&s?.type==="oauth"&&c0(s),f=!m&&!C&&await m9(G0(Y0()),s);if(b===u6)c6=m?.identity;let J0=await d1.get(),{response:z0,servedId:v0}=await C3({source:A0,...C?{vault:{routes:()=>j.routes(),awaitRoster:async()=>{await H8(j.awaitRequestRoster(),kY)},noRouteCause:()=>q$(j),send:(e,N0)=>j.send(e,N0,{site:"model",...N?.signal?{signal:N.signal}:{}}),requestReading:(e)=>j.requestReading(e),rateLimitMarks:()=>{for(let[e,N0]of l6)if(N0<=Date.now())l6.delete(e);return l6}}}:{},storage:F,mode:A,sessionId:R,body:typeof N?.body==="string"?N.body:void 0,replayable:i6(Z,N),now:Date.now,send:(e,N0,K0)=>L6(Z,N,N0,e.identity,e.id,K0),recordQuota:(e,N0,K0,Z1)=>{try{let m0=X6(e.headers),T0=y6(e.headers);if(!N0.row){if(Z1)j.recordSnapshot(N0.id,m0,T0,Z1).then(VJ);return}V6(m0,K0,N0.id==="main"?void 0:N0.id,N0.id==="main"?N0.identity:void 0,T0)}catch{}},placePin:(e)=>OJ({...e,sidebarSnapshot:J0}),blocked:(e,N0,K0)=>{if(e.reason==="no-credential"){if(f&&!cY(K0))throw Error(_6);return new Response(cY(K0)?P$(K0,j.name):G6[c?"missing-main":K0??"unusable"],{status:401,headers:{"content-type":"text/plain; charset=utf-8"}})}return jJ(F,e.reason,e.resetAtMs,N0)},resetCredits:(e)=>s9(e==="main"?X0.peekMainForPolicy(m?.identity)?.quota:X0.peekFallbackForPolicy(e)?.quota),isAbort:(e)=>(e instanceof Error||e instanceof DOMException)&&e.name==="AbortError"||Boolean(N?.signal?.aborted),creditsServing:a$,log:K1});return r9(R,P,v0,A,C?j.routes().map((e)=>({id:e.id})):F?.accounts,U6(J0,E),C),z0}return H=!0,{apiKey:CB,async fetch(Z,N){let F=await j.authority(),R=z$(Z,N),P=H$(R),b=R.get("x-parent-session-id")?.trim()||void 0,A=F!=="local"?await g6(G0(Y0())):await b8();if(F!=="local")return N=await n4(Z,N),t9(Z,N,A,P,b,++u6);let C=await S();if(await j.authority()!=="local")return N=await n4(Z,N),t9(Z,N,A,P,b,++u6);let m=++u6;if(C.type!=="oauth")return R.delete(G8),fetch(Z,{...N,headers:R});N=await n4(Z,N);let s=(await A0.current()).active;if(r0(C)&&s)return t9(Z,N,A,P,b,m);if(s)j.assertHostSlot(C);let c="",f=!1,J0,z0=r0(C);if(t?.migrated()&&!z0&&C.refresh?.trim()&&s4(C).kind==="real")t.noticeRealSlot(C.refresh);let v0=async(j0=A)=>{if(z0=!0,J0=await HJ(j0),J0)c=J0.token;else c="",f=!0,K1.warn("main account in the pool has no usable token",{pid:process.pid})};if(z0)await v0();else if(c0(C))f=!0;else{if(!C.access||(C.expires??0)<Date.now()){x8.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(C.access),expiresInMs:C.expires?C.expires-Date.now():void 0});try{let j0=await n9();C.access=j0.access,C.refresh=j0.refresh,C.expires=j0.expires}catch(j0){if(i4(j0))throw j0;if(j0 instanceof s1)await v0(await C0(G0(Y0())))}}if(!z0)c=C.access??""}let e=z0?HY(A):A,N0=C,K0=J0?.account.accountId??(z0?void 0:N0.accountId)??(c?X1(J1(c)??{}):void 0);if(m===u6)c6=K0;let Z1=A?.routing?.mode??"main-first",m0=await d1.get(),T0=m0.state;if(Z1==="sticky-balanced"&&P&&i6(Z,N)&&typeof N?.body==="string"){let j0=Buffer.byteLength(N.body,"utf8"),b0=await QW({storage:e,sidebarState:T0,primaryAccess:c,mainAccountIdentity:K0,mainUnavailable:f}),I0=a9({sessionId:P,requestBytes:j0,candidates:b0,sidebarSnapshot:m0,now:Date.now()});if(I0){let RJ=DJ(I0)?{action:"migrate",reason:"exhausted"}:FJ(I0,T0,void 0,Date.now(),A);if(RJ.action==="migrate"){let n0=a9({sessionId:P,requestBytes:j0,candidates:b0,sidebarSnapshot:m0,excludeAccountIds:[I0.accountId],now:Date.now()});if(n0)K1.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:j1(P),fromAccountId:I0.accountId,toAccountId:n0.accountId,reason:RJ.reason}),I0=n0}let V1=await L6(Z,N,I0.access,I0.wireAccountId,I0.keepwarmAccountKey),CJ=(n0,i1)=>{try{let HW=X6(n0.headers);V6(HW,i1.access,i1.accountId==="main"?void 0:i1.accountId,i1.accountId==="main"?i1.wireAccountId:void 0,y6(n0.headers))}catch{}};CJ(V1,I0);let wJ=FJ(I0,T0,V1.status,Date.now(),A);if((V1.status===401||V1.status===403||V1.status===429)&&wJ.action==="migrate"){let n0=a9({sessionId:P,requestBytes:j0,candidates:b0,sidebarSnapshot:m0,excludeAccountIds:[I0.accountId],now:Date.now()});if(n0){K1.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:j1(P),fromAccountId:I0.accountId,toAccountId:n0.accountId,reason:wJ.reason});let i1=V1;V1=await L6(Z,N,n0.access,n0.wireAccountId,n0.keepwarmAccountKey),i1.body?.cancel().catch(()=>{}),I0=n0,CJ(V1,I0)}}if(I0.fallback&&!S8(V1.status,A))e0.markUsed(I0.fallback);return r9(P,b,I0.accountId,Z1,A?.accounts,U6(m0,E)),V1}}let O1=LJ(X0.peekMainForPolicy(K0),T0.main.quota,Date.now(),T0.main.mainAccountId,K0),_1=I8(A)&&!Z6(XW(K0),A,void 0,Date.now()),P1=X0.isRateLimited("main"),qJ,e9=()=>{return qJ??=$W(e,T0),qJ},q1,N6,EJ=!1,m8;if(Z1==="fallback-first"&&i6(Z,N)){EJ=!0;let j0=await e9();m8=_J(j0,!_1&&!P1&&!O1.exhausted);let b0=await WW(Z,N,A,m8);if(b0)q1=b0.response,N6={accessToken:b0.accessToken,accountId:b0.quotaAccountId,activeId:b0.activeId}}if(!q1){let j0=O1.exhausted&&i6(Z,N)&&(await e9()).retained.length>0;if(_1||P1||j0){let b0=_1?"killswitch":P1?"mid-stream-rate-limit":"quota-exhausted";if(b0==="quota-exhausted"&&O1.exhausted)NJ("main",O1);K1.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:b0}),q1=jJ(A,b0,b0==="quota-exhausted"&&O1.exhausted?O1.resetAtMs:P1?X0.rateLimitedUntil("main"):void 0)}else q1=f?new Response(null,{status:401}):await L6(Z,N,c,K0,"main")}let YY=Boolean(N6),o6=q1,MJ=N6?.accessToken??c,AJ=N6?.accountId,TJ=N6?.activeId??"main";if(!N6&&!EJ&&S8(q1.status,A)){K1.debug("reactive fallback triggered",{pid:process.pid,status:q1.status}),m8??=_J(await e9(),!1);let j0=await zW(Z,N,q1,A,m8),b0=j0.response;if(b0!==q1){if(YY=!0,o6=b0,MJ=j0.accessToken??c,AJ=j0.accountId,j0.accountId)TJ=j0.accountId}}if(z0&&f&&!YY&&await m9(G0(Y0()),await S()))throw Error(_6);try{let j0=X6(o6.headers);if(YY)V6(j0,MJ,AJ,void 0,y6(o6.headers));else V6(j0,c,void 0,K0,y6(o6.headers))}catch{}return r9(P,b,TJ,Z1,A?.accounts,U6(m0,E)),o6}}},methods:E0},"chat.headers":async(S,u)=>{if(S.model.providerID!=="openai")return;if(u.headers.originator="opencode",u.headers["User-Agent"]=`${V$(A1)} (${l4.platform()} ${l4.release()}; ${l4.arch()})`,u.headers["session-id"]=S.sessionID,H)u.headers[G8]=S.agent;if(W&&S.agent==="title")u.headers[k1.TITLE_HEADER]="true"},"chat.params":async(S,u)=>{if(S.model.providerID!=="openai")return;u.maxOutputTokens=void 0},config:async(S)=>{H0("commands").info("registering commands",{existing:Object.keys(S.command??{}).length,pid:process.pid}),S.command={...S.command??{},[x1]:{template:x1,description:"OpenAI accounts: quota, routing, limits, cache keep-warm, diagnostics and reset credits."}}},"command.execute.before":async(S)=>{if(H0("commands").info("command hook entered",{command:S.command,hasCmdCtx:U!==null,pid:process.pid}),S.command!==x1)return;if(!U)H0("commands").warn("command rejected: context not loaded",{command:S.command,pid:process.pid}),await l(S.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),G$();let u=await pX(U,S.sessionID);if(qY(S.sessionID))e8(u,S.sessionID);else await l(S.sessionID,dX(u.menu));G$()}}}var oB=async(Y)=>{let J=o0();return nB(Y,{codexApiEndpoint:J.codexApiEndpoint,experimentalWebSockets:J.webSockets,responsesLite:J.responsesLite})},Bq={id:"cortexkit-openai-auth",server:oB};
|
|
62
|
+
`)),H=!0,I=Date.now(),E!==void 0)T++;if(V.length<O)V.push(String(l.type));if(l.type==="response.output_item.added"&&L.length<O)L.push(a(l.item)?String(l.item.type):"unknown");if(l.type==="response.created")E=sV(l),l1.debug("response created",{...q,responseID:E,previousResponseID:B,hasContinuation:B!==void 0});if(!vG(l.type))K=!0,aV(l,j);if(p("idle timeout waiting for websocket"),l.type==="response.completed"||l.type==="response.done"){$=!0,iV(l,x),Y.onComplete?.(l,x),Y.onTerminal?.(l),A();return}if(l.type==="response.failed"||l.type==="response.incomplete"||l.type==="error")$=!0,Y.onTerminal?.(l),A()}function L0(r){V0(new i0(h6(r),{cause:r}))}function h(r){if($)return;let E0=r.code===1009,l=new i0(E0?yG:gG("WebSocket closed before response.completed",r.code,r.reason),{retryable:!E0});if(E0)l1.warn("websocket peer refused the request size",{...q,requestBytes:W,reason:r.reason.toString()});V0(E0?xG(l):l)}function x0(){let r=g4(Y.signal);if($)return;$=!0,w(),v(),Y.onAbort?.(r),Q?.error(r)}function R0(r){if($)return;$=!0,w(),v(),Y.onAbort?.(oV(r))}function U0(r){G(),X=r,X.addEventListener("message",t),X.addEventListener("error",L0,{once:!0}),X.addEventListener("close",h,{once:!0}),G=()=>{X.removeEventListener("message",t),X.removeEventListener("error",L0),X.removeEventListener("close",h)};let{background:E0,...l}=Y.body;p("idle timeout sending websocket request");try{let S=JSON.stringify({type:"response.create",...l});W=S.length,X.send(S),p("idle timeout waiting for websocket")}catch(S){if($)return;g(new i0(S instanceof Error?S.message:String(S),{cause:S}))}}return new Response(new ReadableStream({start(r){if(Q=r,Y.signal?.addEventListener("abort",x0,{once:!0}),Y.signal?.aborted){x0();return}U0(X)},cancel(r){R0(r)}}),{status:200,headers:{"content-type":"text/event-stream"}})}function dV(Y,J){if(Y.type!=="response.output_item.done")return;if(!a(Y.item))return;hG(Y.item,J)}function iV(Y,J){let X=Y.response;if(!a(X)||!Array.isArray(X.output))return;for(let Q of X.output)if(a(Q))hG(Q,J)}function hG(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 nV(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:a(Y.headers)?Object.fromEntries(Object.entries(Y.headers).flatMap(([Q,G])=>typeof G==="string"||typeof G==="number"||typeof G==="boolean"?[[Q,String(G)]]:[])):void 0,body:J,message:a(Y.error)&&typeof Y.error.message==="string"?Y.error.message:`${X}`}}function C8(Y){if(typeof Y==="string")try{return C8(JSON.parse(Y))}catch{return}if(!a(Y))return;let J=C8(Y.cause);if(J)return J;let X=C8(Y.body);if(X)return X;let Q=a(Y.error)?Y.error:Y,G=typeof Q.type==="string"?Q.type:void 0,$=Y.status??Y.status_code;if(G!=="usage_limit_reached"&&$!==429)return;let{resets_at:W,resets_in_seconds:H}=Q,K=typeof W==="number"&&Number.isFinite(W)&&W>0?W*1000:typeof H==="number"&&Number.isFinite(H)&&H>0?Date.now()+H*1000:void 0;return{window:G??"primary",resetAt:K}}function oV(Y){if(m4(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function g4(Y){let J=Y?.reason;if(m4(J))return J;if(rV(J))return J;return new DOMException(J instanceof Error?J.message:"Aborted","AbortError")}function rV(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function sV(Y){let J=Y.response;if(!a(J))return;return typeof J.id==="string"?J.id:void 0}function aV(Y,J){let X=a(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(wG(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(wG(X)&&typeof X?.id==="string"&&J.reasoningItemIds.has(X.id))return;break}J.other=!0}function wG(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 tV={type:"response.completed",response:{status:"completed",incomplete_details:null,usage:{input_tokens:0,output_tokens:0,total_tokens:0}}};function vG(Y){return Y==="response.created"||Y==="response.in_progress"||Y.startsWith("codex.")}var f4="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.",yG="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 gG(Y,J,X){let Q=[`code ${J}`];if(X.length>0)Q.push(X.toString());return`${Y} (${Q.join(": ")})`}var u4="x-opencode-title",g9="x-openai-auth-quota-account",c4=new Set([u4,h1,g9,"x-opencode-session"]),YB=15000,JB=300000,XB=3300000,fG="websocket_connection_limit_reached";function QB(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):"",Q=J?`acct:${J}`:`tok:${X}`;return eV("sha256").update(Q).digest("hex").slice(0,12)}function GB(Y){let J=Y?.httpFetch??globalThis.fetch,X=new Map,Q=Y?.connectTimeout??YB,G=Y?.idleTimeout??JB,$=Y?.maxConnectionAge??XB,W=Y?.streamRetries??5,H=Y?.firstEventGraceMs??250,K=Y?.rawWebSocket??!1,U=Y?.onQuota,V=Y?.onRateLimitReached,O=setInterval(()=>q(),Math.min(G,60000));if(typeof O==="object"&&"unref"in O&&typeof O.unref==="function")O.unref();function L(I,x,j,w){if(!x||!j)return j;p4(I,mG(x),void 0,w);let v=new Headers(j.headers),A=v.get("x-codex-turn-metadata");if(!A)return j;let g=nG(A,I.turnID,I.turnStartedAt);if(!g)return j;return v.set("x-codex-turn-metadata",g),{...j,headers:v}}async function B(I,x){let j=I instanceof URL?I.toString():typeof I==="string"?I:I.url,w=g0.normalizeHeaders(x?.headers),v=tG(x),A=$9(v);if(x?.method!=="POST"||!new URL(j).pathname.endsWith("/responses"))return J(I,A);let g=(()=>{try{if(typeof x?.body!=="string")return;let U0=JSON.parse(x.body);return typeof U0==="object"&&U0!==null?U0:void 0}catch{return}})();if(!g?.stream)return J(I,A);if(w[u4]==="true")return J(I,A);let o=w[h1]??w["x-session-affinity"]??w["session-id"],i=o;if(!o)return J(I,A);let V0=g0.normalizeHeaders(v?.headers),B0=QB(V0),p=`${o}:${B0}:conversation`,t=typeof w[g9]==="string"?w[g9]:void 0,L0=V?(U0,r)=>V(U0,t,r):void 0,h=X.get(p)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};X.set(p,h);let x0=mG(g),R0;if(h.fallback)return J(I,L(h,g,A,R0));if(h.busy)return J(I,L(h,g,A,R0));h.busy=!0,h.lastUsedAt=Date.now();try{R0=v6(h,x0);let U0=g0.normalizeHeaders(v?.headers),r=typeof U0.authorization==="string"&&U0.authorization.startsWith("Bearer ")?U0.authorization.slice(7):"",E0=typeof U0["chatgpt-account-id"]==="string"?U0["chatgpt-account-id"]:void 0,l=U?(q0)=>U(q0,r,t,E0):void 0,S=!h.socket&&!h.continuation?BB(U0):U0;if(h.socket=await HB(h,Y?.url??j,S,Q,$,K,x?.signal),jB(h,x0,R0))await KB(h,x0,G,{signal:x?.signal??void 0,sessionID:i,url:Y?.url??j,headers:v?.headers,onRateLimitReached:L0});let u=()=>{},d=()=>{},y=new Promise((q0,H1)=>{u=q0,d=H1}),W0=NB(h,x0,R0),P0=t1(iG(h,W0,x0,R0)),h0=typeof P0.previous_response_id==="string";await M6({sessionID:i,transport:"websocket",phase:"main",bodyText:()=>JSON.stringify(P0),url:Y?.url??j,method:v?.method,headers:v?.headers});let M0=g0.streamResponsesWebSocket({socket:h.socket,body:P0,sessionID:i??void 0,idleTimeout:G,signal:x?.signal??void 0,onQuota:l,onRateLimitReached:L0,onFirstEvent:(q0)=>u(q0??!0),onComplete:(q0,H1)=>{let b8=pG(q0);e1({component:"ws-pool",event:"main_completed",sessionID:i,responseID:uG(q0),usage:b8}),dG(h,x0,q0,H1,h0,R0)},onTerminal:(q0)=>{if(h.busy=!1,h.lastUsedAt=Date.now(),h.streamFailures=0,q0.type!=="response.completed"&&q0.type!=="response.done")h.continuation=void 0,b1(h)},onConnectionInvalid:(q0)=>{if(h.busy=!1,h.lastUsedAt=Date.now(),g0.isOversizedFrame(q0))h.fallback=!0;if(!h.fallback)D(h);h.continuation=void 0,b1(h),u(!1)},onAbort:(q0)=>{h.busy=!1,h.lastUsedAt=Date.now(),h.streamFailures=0,h.continuation=void 0,b1(h),d(q0)},onRetryableTerminal:async(q0)=>{let H1=cG(q0);if(!H1)return;throw h.fallback=!0,H1}}),p0=await $B(y,H);if(p0!==!1){if(p0===!0||p0.status<200||p0.status>599)return M0;return new Response(p0.body,{status:p0.status,headers:{"content-type":"application/json",...p0.headers}})}let f6=()=>J(I,L(h,g,A,R0));if(!h.fallback)return WB(M0,f6);return f6()}catch(U0){if(h.busy=!1,h.lastUsedAt=Date.now(),g0.isAbortError(U0))throw h.streamFailures=0,h.continuation=void 0,b1(h),U0;let r=g0.parseRateLimitSignal(U0);if(r)L0?.(r.window,r.resetAt);if(g0.isUpgradeFailure(U0)&&!K)h.fallback=!0;if(D(h),h.continuation=void 0,b1(h),h.fallback)return J(I,L(h,g,A,R0));return zB(new i0(U0 instanceof Error?U0.message:String(U0),{cause:U0}))}}function D(I){if(I.streamFailures++,I.streamFailures>W)I.fallback=!0}function q(){let I=Date.now();for(let[x,j]of X){if(j.busy)continue;if(I-j.lastUsedAt<G)continue;b1(j),X.delete(x)}}function E(){clearInterval(O);for(let I of X.values())b1(I);X.clear()}function T(I){let x=`${I}:`;for(let[j,w]of X){if(!j.startsWith(x))continue;b1(w),X.delete(j)}}return Object.assign(B,{close:E,remove:T})}function cG(Y){if(Y.type!=="error"||!a(Y.error)||Y.error.code!==fG)return;return Error(typeof Y.error.message==="string"?Y.error.message:fG)}async function $B(Y,J){if(J<=0)return!1;return new Promise((X,Q)=>{let G=setTimeout(()=>X(!1),J);Y.then(($)=>{clearTimeout(G),X($)},($)=>{clearTimeout(G),Q($)})})}function WB(Y,J){let X=Y.body;if(!X)return Y;let Q=!1,G=new ReadableStream({async start($){let W=X.getReader(),H=async(K)=>{while(!0){let{done:U,value:V}=await K.read();if(U)return;if(V&&V.length>0)Q=!0,$.enqueue(V)}};try{await H(W),$.close()}catch(K){if(Q||!g0.isOversizedFrame(K)){$.error(K);return}try{let U=await J();if(!U.ok){$.error(new i0(`HTTP fallback after an oversized WebSocket frame failed with ${U.status}`));return}if(U.body)await H(U.body.getReader());$.close()}catch(U){$.error(U)}}},cancel($){X.cancel($)}});return new Response(G,{status:Y.status,headers:Y.headers})}function zB(Y){return new Response(new ReadableStream({start(J){J.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function HB(Y,J,X,Q,G,$,W){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<G)return Y.socket;b1(Y);let H=await g0.connectResponsesWebSocket({url:g0.toWebSocketUrl(J),headers:X,timeout:Q,rawWebSocket:$,signal:W??void 0});return Y.connectedAt=Date.now(),H}function b1(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function KB(Y,J,X,Q){if(!Y.socket||!Array.isArray(J.input)||J.input.length===0)return;let G=ZB(J);await M6({sessionID:Q.sessionID,transport:"websocket",phase:"prewarm",bodyText:()=>JSON.stringify(G),url:Q.url,method:"POST",headers:Q.headers});let $=g0.streamResponsesWebSocket({socket:Y.socket,body:G,sessionID:Q.sessionID,idleTimeout:X,signal:Q.signal,onRateLimitReached:Q.onRateLimitReached,onComplete:(W,H)=>{e1({component:"ws-pool",event:"prewarm_completed",sessionID:Q.sessionID,responseID:uG(W),usage:pG(W)}),dG(Y,G,W,H,!1,{input:Y6([]),signature:sG(G),priorInputs:new Map})},onTerminal:(W)=>{if(W.type!=="response.completed"&&W.type!=="response.done")Y.continuation=void 0},onConnectionInvalid:()=>{Y.continuation=void 0},onAbort:()=>{Y.continuation=void 0},onRetryableTerminal:async(W)=>{let H=cG(W);if(!H)return;throw Y.fallback=!0,H}});await UB($)}function uG(Y){let J=Y.response;if(!a(J))return;return typeof J.id==="string"?J.id:void 0}function pG(Y){let J=Y.response;if(!a(J))return;return a(J.usage)?J.usage:void 0}async function UB(Y){let J=Y.body?.getReader();if(!J)return;while(!0)if((await J.read()).done)return}function ZB(Y){return t1({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:VB(Y.client_metadata)})}function lG(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 VB(Y){if(!a(Y))return Y;if(typeof Y["x-codex-turn-metadata"]!=="string")return Y;try{let J=JSON.parse(Y["x-codex-turn-metadata"]);if(!a(J))return Y;return{...Y,"x-codex-turn-metadata":lG(J),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function BB(Y){let J=Y["x-codex-turn-metadata"];if(!J)return Y;try{let X=JSON.parse(J);if(!a(X))return Y;return{...Y,"x-codex-turn-metadata":lG(X)}}catch{return Y}}function mG(Y){let J={...Y};if(Array.isArray(Y.input))J.input=Y.input.map(LB);return J}function LB(Y){if(!a(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 dG(Y,J,X,Q,G,$=v6(Y,J)){let W=X.response,H=a(W)&&typeof W.id==="string"?W.id:void 0;if(!H||!Array.isArray(J.input)){Y.continuation=void 0;return}let K=G?new Set(Y.continuation?.finalizedCallIds):new Set;for(let U of Q)K.add(U);Y.continuation={responseID:H,input:J.input,signature:$.signature,canonical:X8($.input),finalizedCallIds:K}}function p4(Y,J,X=J,Q=v6(Y,{...X,input:Array.isArray(X.input)?X.input:J.input})){let G=Array.isArray(J.input)?J.input:[],$=Array.isArray(X.input)?X.input:G,W=Q.signature,H=Y.turnInput&&Y.turnSignature===W?Q8(oG(Q,Y.turnInput),Q.input):void 0,K=H===void 0?G:$.slice(H);if(K.length>0&&K.some(rG)||!Y.turnID)Y.turnID=J6(),Y.turnStartedAt=Date.now();Y.turnInput=$.slice(),Q.priorInputs.set(Y.turnInput,Q.input),Y.turnSignature=W,Y.turnCanonical=X8(Q.input)}function iG(Y,J,X=J,Q=v6(Y,{...X,input:Array.isArray(X.input)?X.input:J.input})){p4(Y,J,X,Q);let G=J.client_metadata;if(!a(G)||typeof G["x-codex-turn-metadata"]!=="string")return J;let $=nG(G["x-codex-turn-metadata"],Y.turnID,Y.turnStartedAt);if(!$)return J;return{...J,client_metadata:{...G,"x-codex-turn-metadata":$}}}function nG(Y,J,X){let Q;try{Q=JSON.parse(Y)}catch{return}if(!a(Q))return;return JSON.stringify({session_id:Q.session_id,thread_id:Q.thread_id,thread_source:Q.thread_source,turn_id:J,sandbox:Q.sandbox,turn_started_at_unix_ms:X,request_kind:"turn",window_id:Q.window_id})}function v6(Y,J){let X=Array.isArray(J.input)?J.input:[],Q=new Map;if(Y.turnInput&&Y.turnCanonical)Q.set(Y.turnInput,Y.turnCanonical);if(Y.continuation?.canonical)Q.set(Y.continuation.input,Y.continuation.canonical);let G=Y6(X,Y.turnCanonical??Y.continuation?.canonical);return Q.set(X,G),{input:G,signature:sG(J),priorInputs:Q}}function oG(Y,J){let X=Y.priorInputs.get(J);if(!X){for(let[Q,G]of Y.priorInputs)if(Q.length===J.length&&Q.every(($,W)=>$===J[W])){X=G;break}X??=Y6(J),Y.priorInputs.set(J,X)}return X}function NB(Y,J,X=v6(Y,J)){let Q=Array.isArray(J.input)?J.input:void 0;if(!Q||!Y.continuation)return J;if(Y.continuation.signature!==X.signature)return Y.continuation=void 0,J;if(!aG(Y.continuation,X))return Y.continuation=void 0,J;if(Y.continuation.input.length===0)return{...J,previous_response_id:Y.continuation.responseID};let G=Q.slice(Y.continuation.input.length),$=FB(G,Y.continuation.finalizedCallIds);if($.length===0)return J;return{...J,previous_response_id:Y.continuation.responseID,input:$}}function jB(Y,J,X=v6(Y,J)){let Q=Array.isArray(J.input)?J.input:void 0;if(!Y.continuation)return!0;if(!Q)return!1;if(!aG(Y.continuation,X))return!0;return Q.slice(Y.continuation.input.length).some(rG)}function rG(Y){if(!a(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function FB(Y,J){return Y.filter((X)=>{if(!a(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 Q=typeof X.call_id==="string"?X.call_id:typeof X.id==="string"?X.id:void 0;return Q?!J.has(Q):!0}if(X.type==="message")return X.role!=="assistant";if(typeof X.role==="string")return X.role!=="assistant";return!1})}function sG(Y){return A6(DB(Object.fromEntries(Object.entries(Y).filter(([J])=>J!=="input"&&J!=="stream"&&J!=="background"&&J!=="previous_response_id"&&J!=="generate"))))}function DB(Y){if(!a(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 aG(Y,J){if(Y.input.length>=J.input.texts.length)return!1;return Q8(oG(J,Y.input),J.input)!==void 0}function tG(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let J=new Headers(Y.headers);for(let X of c4)J.delete(X);return{...Y,headers:J}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((J)=>!c4.has(J[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([J])=>!c4.has(J.toLowerCase())))}}var qB=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),EB=new Set(["gpt-5.6","gpt-6","gpt-6.1"]);function MB(Y){if(qB.has(Y))return!0;if(EB.has(Y))return!1;let X=Y.match(/^gpt-(\d+(?:\.\d+)?)/)?.[1];return X?parseFloat(X)>5.4:!1}function AB(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"))return{context:872000,input:744000,output:128000};if(Y.includes("gpt-6.1-sol")||Y.includes("gpt-6.1-terra"))return{context:500000,input:372000,output:128000};return}function TB(Y){return Y==="gpt-6.1-terra"?"gpt-6.1-sol":void 0}var RB="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.",CB="opencode-oauth-dummy-key",Hq=()=>t6,wB=120000,SB=90000,IB=4000,eG=50,Y$=3,bB=25,kB=60000,xB="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",a4=!1,p9;function Kq(){return p9}function Uq(){a4=!1,p9=void 0}var J$=H0("models"),X$=!1,Q$=!1;class e4 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 f0 extends Error{code;constructor(Y,J){super(J);this.name="ResetTargetResolutionError",this.code=Y}}function d4(Y,J,X,Q){let G=(X?.refresh?.refreshBeforeExpiryMinutes??240)*60000;return!Y||!J||J-Q<=G}function hB(Y,J){let X=Y==="main",Q=J.row,G=()=>new f0("token_unavailable",X?"Main OpenAI account has no usable access token.":`Fallback account ${Y} has no usable access token.`);if(!Q){if(X)throw G();throw new f0("unknown_account",`Fallback account ${Y} was not found.`)}if(!Q.enabled)throw new f0("disabled_account",`${X?"Main":"Fallback"} account ${Y} is disabled.`);if(Q.type!=="oauth")throw new f0("non_oauth_account",`${X?"Main":"Fallback"} account ${Y} is not an OAuth account.`);if(!J.token)throw G();let $=J1(J.token);return{accountKey:Y,label:X?"Main account":Q.label??Y,accessToken:J.token,chatgptAccountId:Q.identity??($?X1($):void 0)}}function vB(Y){async function J(){let X=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),Q=r1(X);if(!X||!Q||c0(Q))throw new f0("token_unavailable","Main OpenAI account has no usable access token.");let G=Q;if(d4(G.access,G.expires,X,Y.now()))G=await(Y.refreshPoolMainRow??Y.refreshFallbackAccount)(G,X);if(!G.access)throw new f0("token_unavailable","Main OpenAI account has no usable access token.");let $=J1(G.access);return{accountKey:"main",label:"Main account",accessToken:G.access,chatgptAccountId:G.accountId??($?X1($):void 0)}}return async(X)=>{let Q=await Y.poolAccess?.(X);if(Q)return hB(X,Q);if(X==="main"){let V=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),O=await Y.getAuth();if(r0(O))return J();if(O.type!=="oauth")throw new f0("non_oauth_account","Main OpenAI account is not authenticated with OAuth.");if(d4(O.access,O.expires,V,Y.now()))try{O={type:"oauth",...await Y.refreshMainWithLease()}}catch(q){if(q instanceof s1)return J();throw q}if(!O.access)throw new f0("token_unavailable","Main OpenAI account has no usable access token.");let L=J1(O.access),B=L?X1(L):void 0,D=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath});return{accountKey:X,label:"Main account",accessToken:O.access,chatgptAccountId:B??D?.mainAccountId}}let G=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),$=G?.accounts.find((V)=>V.id===X);if(!G||!$)throw new f0("unknown_account",`Fallback account ${X} was not found.`);if($.enabled===!1)throw new f0("disabled_account",`Fallback account ${X} is disabled.`);if(!s0($))throw new f0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);let W=()=>new f0("token_unavailable",`Fallback account ${X} has no usable access token.`);if(c0($))throw W();let H=$;if(d4(H.access,H.expires,G,Y.now()))H=await Y.refreshFallbackAccount(H,G);if(!H.access)throw W();let K=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),U=K?.accounts.find((V)=>V.id===X);if(!K||!U)throw new f0("unknown_account",`Fallback account ${X} was not found.`);if(U.enabled===!1)throw new f0("disabled_account",`Fallback account ${X} is disabled.`);if(!s0(U))throw new f0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);return{accountKey:X,label:H.label??X,accessToken:H.access,chatgptAccountId:U.accountId}}}function yB(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function i4(Y){return Y instanceof e4}function G$(){throw Error(xB)}async function gB(Y,J={}){let X=G0(Y0());if(zY(X.configPath)){await n1(O6(X),J.holdsMainRefreshLock?void 0:E1(X),(Q)=>{if(J.canWrite&&!J.canWrite())throw Error(G6["vault-refused"]);Y(Q)});return}await o8((Q)=>{return Y(Q),Q},X,{canWrite:J.canWrite})}var r$=null;function Zq(){return r$}function fB(Y){return Math.floor(Math.random()*Y)}var mB=!0;function cB(Y,J,X){let Q=Y.get(J);if(Q)return Q;let G=J6(),$={threadID:G,turnID:J6(),windowID:`${G}:0`};return Y.set(J,$),X?.(),$}function $$(){return T$("opencode1")}function uB(Y,J){return Y.find((X)=>X.enabled!==!1&&s0(X)&&(X.id===J||X.accountId===J))}function W$(Y,J){if(!J)return Y;let X={...Y};for(let Q of["resetCreditsAvailable","resetCreditsApplicable"]){let G=J[Q];if(X[Q]===void 0&&G!==void 0)X[Q]=G}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 f9(Y,J){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:J}}function s$(Y,J,X=Date.now(),Q=J.mainAccountId){let G=Y.getMain(),$=G?.quota;return{main:{quota:$?{...$,checkedAt:G.checkedAt,primary:f9($.primary,G.checkedAt),secondary:f9($.secondary,G.checkedAt)}:null,...typeof Q==="string"?{mainAccountId:Q}:{},killed:!Z6($,J,void 0,X),...$?.resetCreditsAvailable!==void 0?{resetCredits:$.resetCreditsAvailable}:{}},fallbacks:J.accounts.filter((W)=>W.enabled).map((W)=>{let H=Y.getFallback(W.id),K=H?.quota;return{id:W.id,label:W.label,accountId:H?.accountId??W.accountId,quota:K?{...K,checkedAt:H.checkedAt,primary:f9(K.primary,H.checkedAt),secondary:f9(K.secondary,H.checkedAt)}:null,killed:!Z6(K,J,W.id,X),enabled:!0,...K?.resetCreditsAvailable!==void 0?{resetCredits:K.resetCreditsAvailable}:{}}}),route:J.routing?.mode??"main-first",lastUpdated:X}}function Vq(Y,J,X,Q=Date.now()){return{...s$(Y,J,Q),activeId:X}}function z$(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 n4(Y,J){if(!(Y instanceof Request))return J;let X=new Request(Y,J),Q=X.method.toUpperCase(),G=Q==="GET"||Q==="HEAD"||X.body===null?void 0:await X.text();return{method:X.method,headers:new Headers(X.headers),body:G,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}}function H$(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}var pB=new Set(["gpt-6-astra","gpt-6-sol","gpt-6-luna","gpt-6.1-sol"]),lB=new Set(["title","compaction","summary"]);function dB(Y,J,X){if(X!==null&&lB.has(X))return;let Q=typeof Y.model==="string"?Y.model:"";if(!pB.has(Q))return;let G=a(Y.reasoning)?Y.reasoning:void 0,$=typeof G?.effort==="string"?G.effort:void 0;if(!$)return;let W=Array.isArray(Y.input)?Y.input:void 0;J.effortUpdates??=[];let H=J.effortUpdates,K=(L)=>OB("sha256").update(A6(L)).digest("hex").slice(0,16);if(J.pinnedEffort===void 0||H.some((L)=>!W||!$8(W[L.anchor],"user")||K(W[L.anchor])!==L.fingerprint)){J.pinnedEffort=$,J.effortUpdates=[];return}if(!W||W.length===0)return;let U=W.findLastIndex((L)=>$8(L,"user")),V=H.at(-1),O=V?.effort??J.pinnedEffort;if(U>=0&&$!==O)if(V?.anchor===U){let L=H.at(-2)?.effort??J.pinnedEffort;if($===L)H.pop();else V.effort=$}else H.push({anchor:U,fingerprint:K(W[U]),effort:$});else if(U<0&&$!==O)return;if(H.some((L,B)=>B>0&&L.anchor<=(H[B-1]?.anchor??-1))){J.pinnedEffort=$,J.effortUpdates=[];return}Y.reasoning={...G,effort:J.pinnedEffort};for(let L=H.length-1;L>=0;L--){let B=H[L];if(!B)continue;W.splice(B.anchor,0,{type:"configuration_update",reasoning:{effort:B.effort}})}}function t4(Y){if(Array.isArray(Y)){let X=Y;for(let Q=0;Q<Y.length;Q++){let G=t4(Y[Q]);if(G===Y[Q])continue;if(X===Y)X=Y.slice();X[Q]=G}return X}if(!a(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 Q=t4(Y[X]);if(Q===Y[X])continue;if(J===Y)J={...Y};J[X]=Q}return J}function iB(Y){let J=a(Y.reasoning)?{...Y.reasoning}:{};J.context="all_turns",Y.reasoning=J,Y.parallel_tool_calls=!1;let X=t4(Array.isArray(Y.input)?Y.input:[]),G=[{type:"additional_tools",role:"developer",tools:Array.isArray(Y.tools)?Y.tools.filter(($)=>!(a($)&&$.type==="web_search")):[]}];if(typeof Y.instructions==="string"&&Y.instructions.length>0)G.push({type:"message",role:"developer",content:[{type:"input_text",text:Y.instructions}]});Y.input=[...G,...X],delete Y.tools,delete Y.instructions}async function nB(Y,J={}){await o$({version:A1,...J.runtimeLayout});let X=J.codexApiEndpoint??o0().codexApiEndpoint,Q=crypto.randomUUID(),G=I$($$()),$=()=>b$($$(),G),W=!1,H=!1,K=[],U=null,V=S$(Y.client),O=new Map,L=new Map,B,D=!1,q,E=new Map,T,I,x=y3({host:"opencode",stateDir:J.vault?.stateDir??_$(G0(Y0()).statePath),...Y.directory?{projectRoot:Y.directory}:{},reservedRouteIds:()=>i?.peek().rows.map((S)=>S.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}:{},fetchImpl:()=>fetch},G0(Y0())),j=x.vault;await j.authority();let w=x.firstRoster,v=Promise.withResolvers(),A=Promise.race([w,v.promise]),g=J.vault?.firstRosterWaitMs??xY,o,i,{enabled:V0,...B0}=J.poolMigration??{},p=V0??mB;if(p&&"reason"in V)(B0.log??H0("pool")).warn("account pool migration is off for this OpenCode client",{reason:V.reason});let t=p&&"slot"in V?L3({paths:()=>G0(Y0()),slot:V.slot,version:A1,...B0,runDeps:{vaultServes:()=>j.serves(),...B0.runDeps},paused:async()=>await j.authority()!=="local",migrate:async(S)=>{let u=await(B0.migrate??K9)(S);return i?.load(),u},adopt:async(S)=>{if(!await H8(A,g))return{status:"retry",reason:"vault-roster-pending"};let u=await(B0.adopt??U9)(S);return i?.load(),u}}):void 0,L0=(S,u="")=>S?async()=>{let d=await S();return{url:d.url,instructions:d.instructions??u,method:"auto",callback:async()=>{try{let y=await d.tokens;return{type:"success",refresh:y.refresh_token,access:y.access_token,expires:Date.now()+(y.expires_in??3600)*1000,accountId:a1(y)}}finally{d.cleanup?.()}}}}:void 0,h=new AY(J.backgroundQuota),x0,R0=BX({client:Y.client,getAuth:async()=>x0?.(),fetchImpl:fetch,dependencies:{...J.login?.authorize?{authorizeBrowser:L0(J.login.authorize.browser,"Complete authorization in your browser. This window will close automatically."),authorizeHeadless:L0(J.login.authorize.headless)}:{}},vault:j,onMainSlotWritten:async()=>{await t?.requestAdoption()}}),U0=(S)=>async(u)=>{let d=await S(u);if(d.method!=="auto")return d;return{...d,callback:async()=>{let y=await d.callback();if(y.type==="success"&&"refresh"in y)r(y.refresh);return y}}};async function r(S){if(!t||!("slot"in V))return;let u=J.login?.sleep??((d)=>Bun.sleep(d));for(let d=0;d<5000;d+=100){try{let y=await V.slot.get({path:{id:"openai"}});if(a(y)&&y.refresh===S){await t.requestAdoption();return}}catch{}await u(100)}}let E0=R0.map((S)=>S.type==="oauth"?{...S,authorize:U0(S.authorize)}:S);async function l(S,u){let d=Y.client.session;if(typeof d?.promptAsync==="function"){let y=await a3(Y.client,S),W0={noReply:!0,parts:[{type:"text",text:u,ignored:!0}]};if(y?.agent)W0.agent=y.agent;if(y?.model)W0.model=y.model;if(y?.variant)W0.variant=y.variant;await d.promptAsync({path:{id:S},body:W0});return}}return{async dispose(){x.release(),t?.dispose(),await i?.dispose(),h.stop(),I?.stop(),B?.stopBackgroundRefresh(),B=void 0;for(let d of K)d.close();K.length=0;let S=globalThis;for(let[d,y]of O)if(S.__openaiAuthCacheKeepManagers?.get(d)===y)y.stop(),S.__openaiAuthCacheKeepManagers.delete(d);O.clear();for(let d of L.values())await d.release().catch(()=>{});L.clear();let u=o;o=void 0,await(await u)?.release()},async event(S){if(S.event.type!=="session.deleted")return;let u=S.event.properties.info,d=G.get(u.id);if(d)U?.cacheKeepManager?.remove(d.threadID);if(G.delete(u.id))$();let y=j1(u.id);if(E.delete(y),I?.cancel(`pin:${y}`),q){let W0=await j.authority()!=="local"?j.routes().map((P0)=>({id:P0.id})):(await C0(G0(Y0())))?.accounts;await f$(u.id,W0,q).catch(()=>{})}for(let W0 of K)W0.remove(u.id)},provider:{id:"openai",async models(S,u){if(u.auth?.type!=="oauth")return S.models;let d=await j.authority()!=="local"?await g6(G0(Y0())):await C0(G0(Y0())),y=!d||j$(d),W0=y?null:await n3();if(!y&&W0&&!X$)X$=!0,J$.debug("restoring OAuth model costs from models.dev catalog");if(!y&&!W0&&!Q$)Q$=!0,J$.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(S.models).filter(([,P0])=>P0.options.reasoningMode!=="pro"&&MB(P0.api.id)).map(([P0,h0])=>{let M0=TB(h0.id),p0=M0?S.models[M0]?.variants:void 0;return[P0,{...h0,...p0?{variants:{...p0,...h0.variants}}:{},cost:y?{input:0,output:0,cache:{read:0,write:0}}:W0?.[h0.api.id]??W0?.[P0]??h0.cost,limit:AB(h0.id)??h0.limit}]}))}},auth:{provider:"openai",async loader(S){await j.authority(),x0=S,o??=i$({version:A1,logger:H0("heartbeat")}),await o,t?.start();let u=await S();if(u.type!=="oauth")return v.resolve(),{};let d=s4(u).kind==="tombstone";x.start();let y=Y.directory?await A$(Y.directory):void 0,W0=y?.dir??Y0();async function P0(Z,N={}){if(await j.authority()!=="local")return;return gB(Z,{...N,canWrite:()=>!j.enrolled()})}let h0=await j.authority()!=="local";if(!d&&!h0)await D$({type:"oauth",access:u.access??"",refresh:u.refresh??"",expires:u.expires??0},G0(Y0()));let M0=await(h0?g6(G0(Y0())):C0(G0(Y0()))).catch(async(Z)=>{if(await j.authority()!=="local")return null;let N=Y0();throw Error(`OpenAI auth store at ${N} is corrupt or unreadable: ${Z instanceof Error?Z.message:String(Z)}. Fix or remove it to continue.`,{cause:Z})});if(!h0&&await m9(G0(Y0()),u)){if(t)t.noticePlaceholderWithoutMain();else if(!D)D=!0,H0("pool-migration").warn(_6,{reason:"placeholder-without-main"})}let p0=M0,f6=!h0,q0=Q3({path:Y0,stat:(Z)=>{try{let N=PB(Z);return{mtimeMs:N.mtimeMs,size:N.size}}catch{return}},read:(Z)=>C0(G0(Z)),fallback:async(Z)=>{if(await j.authority()!=="local")return g6(G0(Y0()));throw Z},onRead:(Z)=>{p0=Z,f6=!0}});function H1(){return q0.read()}async function b8(){if(!f6)return H1();return H9(Promise.resolve(H1()),z9,()=>p0)}function k8(){q0.invalidate()}if(M0&&u.access&&!d&&!h0){let Z=a1({id_token:"",access_token:u.access,refresh_token:u.refresh??""});if(Z&&Z!==M0.mainAccountId)await P0((N)=>{N.mainAccountId=Z}),M0.mainAccountId=Z,k8()}let l9=M0?.logging?.level;if(l9&&typeof l9==="string")J9(l9);let m6=H0("transport"),Q1=H0("quota"),x8=H0("refresh"),K1=H0("accounts"),a$=new M$;m6.info("codex auth loader ready",{codexApiEndpoint:X,transport:o0().rawWebSocket?"raw-websocket":o0().webSockets?"websocket":"http"});let X0=new N$({storage:M0,configPath:Y0(),fetchQuotaFn:void 0}),c6,u6=0;await i?.dispose();let A0=new hY({paths:()=>G0(Y0()),refreshProvider:async(Z)=>{let N=await w8({refreshToken:Z.refresh,fetchImpl:fetch,now:Date.now}),F=a1({id_token:"",access_token:N.access,refresh_token:N.refresh});return{...N,...F?{identity:F}:{}}},pullQuota:async(Z)=>{let N=Z.credential;if(N.type!=="oauth"||!N.access)throw Error("the row holds no access token to poll with");let F=await e6({accessToken:N.access,fetchImpl:fetch,now:Date.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,logger:Q1}),R=Date.now(),P={quota:F,refreshAfter:R+300000,checkedAt:R};if(Z.id==="main")X0.setMain(N.access,P,Z.identity,!0);else X0.setFallback(Z.id,P,N.access,!0,Z.identity);return q6(F,R,!0)},vaultIdentities:()=>j.identities(),vaultMode:()=>j.enrolled(),vaultAuthority:()=>j.authority(),vaultFirstRoster:w,vaultFirstRosterBackgroundWaitMs:g,log:H0("pool")});if(i=A0,!h0)await A0.load();let e0=new O$({paths:G0(Y0()),refreshFn:async(Z)=>{if(await j.authority()!=="local")throw Error(G6["vault-refused"]);return w8({refreshToken:Z.refreshToken,fetchImpl:Z.fetchImpl,now:Z.now})},quotaManager:X0,canWrite:()=>!j.enrolled(),onFallbackStorageChanged:k8,backgroundRefreshPaused:async()=>j.enrolled()||await A0.active()});if(M0&&M0.accounts.length>0)e0.startBackgroundRefresh();function d9(Z){if(c0(Z))return;return Z.access||void 0}function h8(Z={}){let{readSidebarState:N,respectBackoff:F,skipFresherThanMs:R}=Z;return{getAuth:S,codexRefreshFn:w8,refreshMainWithLease:UJ,fallbackManager:e0,quotaManager:X0,loadAccounts:C0,writeSidebarState:(P)=>U1(P),client:Y.client,fetchImpl:fetch,now:Date.now,paths:G0(Y0()),readSidebarState:N??(()=>x$(l0)),storageMainAccountId:M0?.mainAccountId,isOAuthAccountFn:s0,whamFn:e6,...F===void 0?{}:{respectBackoff:F},...R===void 0?{}:{skipFresherThanMs:R}}}async function YJ(Z){return(await A0.pollRows(await C0(G0(Y0())),Z?{ids:Z}:{})).map((F)=>({account:F.id,ok:F.ok,...F.error!==void 0?{error:F.error}:{}}))}async function JJ(Z){return A0.accessFor(Z,await C0(G0(Y0())))}let XJ=H0("cachekeep"),v8=X9(M0),QJ=v8?.enabled===!0,GJ=v8?.subagents===!0,$J=v8?.sustain===!0,WJ=eX(M0?{...M0,cachekeep:v8}:M0),y8;async function t$(Z){await new Promise((N)=>setTimeout(N,Z))}async function e$(Z){let N;for(let F=1;F<=Y$;F++){if(await j.authority()!=="local")throw Error(G6["vault-refused"]);try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:Z.refresh,access:Z.access,expires:Z.expires}});return}catch(R){if(N=R,F<Y$)await t$(bB*F)}}throw new e4(N)}async function g8(Z){await P0((N)=>{N.refresh=N.refresh??{},Z(N)},{holdsMainRefreshLock:!0}),k8()}async function i9(Z){let N=Date.now()+IB;while(Date.now()<N){await new Promise((P)=>setTimeout(P,eG+fB(eG)));let F=await S();if(r0(F))throw new s1;if(F.type!=="oauth"||!F.access)continue;if((F.access!==Z.access||F.refresh!==Z.refresh||(F.expires??0)>(Z.expires??0)+60000)&&(!F.expires||F.expires>Date.now()))return x8.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:F.expires?F.expires-Date.now():void 0}),{access:F.access,refresh:F.refresh??Z.refresh??"",expires:F.expires??0}}return null}function zJ(Z){if(r0(Z))throw new s1;if(Z.type!=="oauth")throw Error("not oauth");if(c0(Z))throw new B$;if(!Z.refresh)throw Error("Token refresh failed: missing refresh token");return Z.refresh}async function n9(){if(!y8)y8=(async()=>{let Z=await S(),N=zJ(Z);if(Z.type!=="oauth")throw Error("not oauth");let F=K8(N),R=await C0(G0(Y0())),P=R?.refresh?.mainLastRefreshError;if(P&&M1(P,N,Date.now()))throw Error(o4(P,Date.now()));if(R?.refresh?.mainRefreshLeaseUntil&&R.refresh.mainRefreshLeaseUntil>Date.now()&&R.refresh.mainRefreshLeaseTokenHash===F){let f=await i9(Z);if(f)return f;throw Error("Codex OAuth refresh is already in progress")}let b=await Q9({name:t6,ttlMs:wB,path:Y0(),renew:!0});if(!b){let f=await i9(Z);if(f)return f;throw Error("Codex OAuth refresh is already in progress")}let M;try{let f=await S(),J0=zJ(f);if(f.type!=="oauth")throw Error("not oauth");if(J0!==N){if(f.access&&(f.expires??0)>Date.now())return x8.debug("main token rotated while awaiting the lock",{pid:process.pid}),await b.release().catch(()=>{}),{access:f.access,refresh:J0,expires:f.expires??0};let v0=(await C0(G0(Y0())))?.refresh?.mainLastRefreshError;if(v0&&M1(v0,J0,Date.now()))throw Error(o4(v0,Date.now()))}M={...f,refresh:J0}}catch(f){throw await b.release().catch(()=>{}),f}await w$(G0(Y0()),M.refresh,M.access!==void 0?{slotAccess:M.access}:{}).catch(()=>!1);let C=K8(M.refresh),m=crypto.randomUUID(),s=C;try{await g8((z0)=>{if(C$(Y0(),M.refresh))throw new r4;z0.refresh=z0.refresh??{},z0.refresh.mainRefreshLeaseId=m,z0.refresh.mainRefreshLeaseUntil=Date.now()+SB,z0.refresh.mainRefreshLeaseTokenHash=C});let f=await C0(G0(Y0()));if(f?.refresh?.mainRefreshLeaseId!==m||f.refresh.mainRefreshLeaseTokenHash!==C)throw Error("Codex OAuth refresh is already in progress");if(await j.authority()!=="local")throw Error(G6["vault-refused"]);let J0=await w8({refreshToken:M.refresh,fetchImpl:fetch,now:Date.now});return await e$(J0),await g8((z0)=>{if(z0.refresh=z0.refresh??{},z0.refresh.mainLastRefreshError=void 0,z0.refresh.mainRefreshLeaseId===m)z0.refresh.mainRefreshLeaseId=void 0,z0.refresh.mainRefreshLeaseUntil=void 0,z0.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),s=void 0,J0}catch(f){if(!(f instanceof r4)){if(!i4(f))await g8((J0)=>{J0.refresh=J0.refresh??{},J0.refresh.mainLastRefreshError=Z$({error:f,now:Date.now(),refreshToken:M.refresh,previous:J0.refresh.mainLastRefreshError})}).catch(()=>{});throw f}}finally{if(s)await g8((f)=>{if(f.refresh?.mainRefreshLeaseId===m&&f.refresh.mainRefreshLeaseTokenHash===s)f.refresh.mainRefreshLeaseId=void 0,f.refresh.mainRefreshLeaseUntil=void 0,f.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await b.release().catch(()=>{})}let c=await i9(M);if(c)return c;throw Error("Codex OAuth refresh is already in progress")})().finally(()=>{y8=void 0});return y8}function HJ(Z){return vJ({storage:Z,now:Date.now,refreshAccount:(N,F)=>e0.refreshAccount(N,F,{asPoolMain:!0}),warn:(N,F)=>x8.warn(N,{pid:process.pid,...F})})}async function KJ(){let Z=await HJ(await C0(G0(Y0())));if(!Z)throw Error("The main OpenAI account has no usable token in the account pool");return{access:Z.token,refresh:Z.account.refresh,expires:Z.account.expires??0}}async function UJ(){try{return await n9()}catch(Z){if(Z instanceof s1)return KJ();throw Z}}let ZJ=globalThis,o9=ZJ.__openaiAuthCacheKeepManagers??new Map;ZJ.__openaiAuthCacheKeepManagers=o9,o9.get(W0)?.stop();let p6=X3({fetchImpl:fetch,vault:j,getMainToken:async()=>{if(await j.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(await A0.active()){let N=await JJ("main");if(!N)throw Error("main pool row has no usable token");return N.token}let Z=await S();if(await j.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(r0(Z))return(await KJ()).access;if(Z.type!=="oauth")throw Error("not oauth");if(!Z.access||(Z.expires??0)<Date.now())try{return(await UJ()).access}catch(N){if(i4(N))throw N;if(Z.access)return Z.access;throw Error("main token refresh failed")}return Z.access},refreshFallback:async(Z)=>{if(await j.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(await A0.active()){let M=await JJ(Z);if(!M)throw Error(`no access token for ${Z}`);return{token:M.token}}let N=await b8(),F=N?uB(N.accounts,Z):void 0;if(!F)throw Error(`fallback account ${Z} not found`);let R=N??{version:1,accounts:[F]},P=c0(F)?F:await e0.refreshAccount(F,R),b=d9(P);if(!b)throw Error(`no access token for ${Z}`);return{token:b}},codexResponsesUrl:X,activeAccount:async(Z)=>J3(U6(await d1.read(),E),Z),logger:XJ,now:Date.now,getWindow:()=>WJ,getSustain:()=>$J});o9.set(W0,p6),O.set(W0,p6);function V6(Z,N,F,R,P=!1){try{YW(Z,N,F,R,P)}catch(b){Q1.warn("quota push failed",{pid:process.pid,accountId:F??"main",error:h6(b)})}}function YW(Z,N,F,R,P){if(Object.keys(Z).length===0&&!P)return;let b=Date.now(),M=Z,C={quota:M,refreshAfter:b+300000,checkedAt:b},m;if(F&&F!=="main"){let c=N?J1(N):null,f=c?X1(c):void 0,J0=X0.peekFallbackForPolicy(F)?.quota,z0=W$(M,J0);C={...C,quota:z0},X0.setFallback(F,C,N,P,f)}else{if(m=R,!m&&N){let J0=J1(N);m=J0?X1(J0):void 0}if(m&&c6&&m!==c6){Q1.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:m,currentMainIdentity:c6});return}let c=X0.peekMainForPolicy(m)?.quota,f=W$(M,c);C={...C,quota:f},X0.setMain(N,C,m,P)}Q1.debug("quota pushed",{pid:process.pid,accountId:F??"main",snapshot:C.quota}),A0.recordSnapshot(F&&F!=="main"?F:"main",Z,N,P);let s=Boolean(F&&F!=="main");D1.enqueue("machine-state","quota",()=>U1(X0,s?void 0:m))}function JW(Z,N,F){let R=T1(j.routes().find((P)=>P.id===Z)?.quota)??(Z==="main"?X0.peekMainForPolicy()?.quota:X0.peekFallbackForPolicy(Z)?.quota);return L$(R,N,Date.now(),kB,F)}let f8=new Map,l6=new Map;function VJ(){if(!j.enrolled())return;D1.enqueue("machine-state","quota",()=>U1(X0))}let B6=J.experimentalWebSockets?k1.createWebSocketFetch({httpFetch:fetch,rawWebSocket:o0().rawWebSocket,onQuota:(Z,N,F,R)=>{let P=F?f8.get(F):void 0;if(P){j.recordSnapshot(P.id,Z,!0,P.receipt).then(VJ);return}V6(Z,N,F,!F||F==="main"?R:void 0,!0)},onRateLimitReached:(Z,N,F)=>{if(!N)Q1.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:Z});let R=N?f8.get(N):void 0,P=R?.id??N??"main",b=JW(P,Z,F);if(X0.markRateLimited(P,b),R)l6.set(P,Math.max(l6.get(P)??0,b));else A0.markRateLimited(P,b);Q1.debug("mid-stream rate limit mark",{pid:process.pid,accountId:P,window:Z})}}):void 0;if(B6)K.push(B6),W=!0;let l0=k$();q=l0;async function U1(Z,N){if(j.enrolled()){q0.invalidate();let M=await g6(G0(Y0()));await c9(S3(j.snapshot()?.rows,new Set(j.routes().map((C)=>C.id)),M,Date.now()),l0,{canWrite:()=>j.enrolled()});return}let F=H1(),R=F instanceof Promise?await F.catch(()=>p0):F,P=N??R?.mainAccountId,b=await A0.current();if(b.active){await c9(I3(b.rows,R,Date.now(),(M)=>(M==="main"?Z.getMain():Z.getFallback(M))?.quota?.resetCreditsAvailable),l0,{canWrite:()=>!j.enrolled()});return}if(!R)return;await c9(s$(Z,R,Date.now(),P),l0,{canWrite:()=>!j.enrolled()})}let d1=p$(l0);d1.read(),I?.stop();let D1=d$({logger:m6,onWritten:()=>d1.refreshInBackground()});if(I=D1,T!==l0)E.clear(),T=l0;function r9(Z,N,F,R,P,b,M=!1){let C={vaultMode:M,canWrite:()=>j.enrolled()===M},m={activeId:F,route:R,updatedAt:Date.now()};if(!Z){D1.enqueue("routing:legacy","routing",()=>g$(m,l0,C));return}if(D1.enqueue(`routing:${Z}`,"routing",()=>u9({sessionId:Z,...m},P,l0,C)),!N||N===Z)return;if(R==="sticky-balanced"){let s=b.stickyAssignments?.[j1(N)]?.accountId,c=P===void 0||s==="main"||P.some((f)=>f.enabled!==!1&&f.id===s);if(!s||!c)return;D1.enqueue(`routing:${N}`,"routing",()=>u9({sessionId:N,activeId:s,route:R,updatedAt:Date.now()},P,l0,C));return}D1.enqueue(`routing:${N}`,"routing",()=>u9({sessionId:N,...m},P,l0,C))}B?.stopBackgroundRefresh(),B=e0;let d6=G0(Y0());if(U=r$={accountStoragePath:d6.configPath,accountStatePath:d6.statePath,packageVersion:A1,layoutNotice:n$,quotaManager:X0,loadAccounts:C0,beginAccountLogin:n8,store:()=>O6(d6),migration:async()=>{if(await p8(d6,O6(d6))!==void 0)return{migrated:!0};let Z=await(B0.fence??(()=>E6({currentVersion:A1})))();return{migrated:!1,blockers:Z.open?[]:Z.blockers.map((N)=>({pid:N.pid,version:N.version}))}},afterWrite:()=>A0.load(),vault:j,resolveResetTarget:vB({getAuth:S,refreshMainWithLease:n9,refreshFallbackAccount:(Z,N)=>e0.refreshAccount(Z,N),refreshPoolMainRow:(Z,N)=>e0.refreshAccount(Z,N,{asPoolMain:!0}),poolAccess:async(Z)=>A0.rowAccess(Z,await C0(G0(Y0()))),loadAccounts:C0,accountStoragePath:Y0(),accountStatePath:R$(Y0()),now:Date.now}),...yB(),cacheKeepManager:p6,setCacheKeepEnabled:(Z)=>{QJ=Z},setCacheKeepSubagents:(Z)=>{GJ=Z},setCacheKeepSustain:(Z)=>{$J=Z},setCacheKeepWindow:(Z)=>{WJ=Z},clearStickyRouting:async(Z)=>{let N=j1(Z),F=E.delete(N);return D1.cancel(`pin:${N}`),await u$(Z,l0)||F},getStickyRouting:async(Z)=>y$(U6(await d1.read(),E),Z),refreshSidebar:async()=>{k8(),await U1(X0)},refreshAllQuota:async()=>{if(await j.authority(),j.enrolled()){let Z=await j.pollStale(0);return await U1(X0),Z.map((N)=>({account:N.id,ok:N.ok,...N.error!==void 0?{error:N.error}:{}}))}if(await A0.active()){let[Z,N]=await Promise.all([YJ(),j.pollStale(0)]);return await U1(X0),[...Z,...N.map((F)=>({account:F.id,ok:F.ok,...F.error!==void 0?{error:F.error}:{}}))]}return R6(h8())},refreshResetTargetQuota:async(Z)=>{if(await j.authority(),j.enrolled())return{account:Z,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};if(await A0.active()){let[F]=await YJ([Z]);return F??{account:Z,ok:!1,error:"targeted quota refresh returned no result"}}return(await R6(h8({respectBackoff:!1}),{accountKey:Z})).find((F)=>F.account===Z)??{account:Z,ok:!1,error:"targeted quota refresh returned no result"}}},y){let Z=y;try{let N=await U$(J2,Z.dir,()=>X2({dir:Z.dir,secureDir:Z.secureDir,sweepRoot:Z.sweepRoot,drain:gX,apply:async(F)=>{let R=K$(F);if(!R)throw Error("not an /openai apply request");return lX(U,R)}}));L.set(Z.dir,N)}catch{}}async function L6(Z,N,F,R,P="main",b){if(!F.trim())throw m6.warn("refusing to send a request with no access token",{account:P,accountId:R}),Error(RB);if(!b&&await j.authority()!=="local")return Response.json({error:{message:G6["vault-refused"]}},{status:400});let M=z$(Z,N);if(M.delete("x-api-key"),M.delete("api-key"),M.set("authorization",`Bearer ${F}`),R)M.set("ChatGPT-Account-Id",R);M.set(k1.QUOTA_ACCOUNT_HEADER,P);let C=H$(M),m=C?cB(G,C,$):void 0,s=Z instanceof URL?Z:new URL(typeof Z==="string"?Z:Z.url),c=s.pathname.includes("/v1/responses")||s.pathname.includes("/chat/completions")?new URL(X):s,J0=IX({rewriteLite:iB,applyEffort:dB,init:{...N,headers:M},headers:M,metadata:m,installationID:Q,websocket:Boolean(B6&&s.pathname.endsWith("/responses")),responsesLite:J.responsesLite??!1,dumpSessionID:C}).init,z0=QJ,v0=new Headers(J0?.headers),e=tX({enabled:z0,includeSubagents:GJ,headers:v0,body:J0?.body});if(z0)XJ.trace("cachekeep headers",{pid:process.pid,hasParent:v0.has("x-parent-session-id"),sessionKey:e?.sessionKey,captured:Boolean(e),affinity:v0.get("x-session-affinity"),opencodeSession:v0.get("x-opencode-session"),sessionId:v0.get("session-id")});if(B6&&s.pathname.endsWith("/responses")){if(m6.debug("WS transport",{pid:process.pid,pathname:s.pathname,accountId:P}),e)p6.track({sessionKey:e.sessionKey,bodyText:e.bodyText,accountId:P,isSubagent:e.isSubagent,meta:{replayHeaders:e.replayHeaders,chatgptAccountId:R,routingSessionId:C}});if(!b)try{return await Q6(await B6(c,J0),F,"event-stream")}catch(T0){throw v1(T0,F)}let K0=`vault-stream:${_B()}`;f8.set(K0,{id:P,receipt:b});let Z1=new Headers(J0?.headers);Z1.set(k1.QUOTA_ACCOUNT_HEADER,K0);let m0=()=>f8.delete(K0);try{let T0=await B6(c,{...J0,headers:Z1});if(!T0.body)return m0(),T0;let O1=T0.body.getReader();return await Q6(new Response(new ReadableStream({async pull(_1){try{let P1=await O1.read();if(P1.done)m0(),_1.close();else _1.enqueue(P1.value)}catch(P1){m0(),_1.error(v1(P1,F))}},cancel(_1){return m0(),O1.cancel(_1)}}),{status:T0.status,statusText:T0.statusText,headers:T0.headers}),F,"event-stream")}catch(T0){throw m0(),v1(T0,F)}}let N0=k1.withoutInternalHeaders(J0);if(typeof N0?.body!=="string")try{return await Q6(await fetch(c,N0),F,"event-stream")}catch(K0){throw v1(K0,F)}if(e)p6.track({sessionKey:e.sessionKey,bodyText:e.bodyText,accountId:P,isSubagent:e.isSubagent,meta:{replayHeaders:e.replayHeaders,chatgptAccountId:R,routingSessionId:C}});m6.debug("HTTP transport",{pid:process.pid,pathname:s.pathname,accountId:P});try{let K0=await fetch(c,N0);return await M6({sessionID:C,transport:"http",phase:"http",bodyText:N0.body,accountId:P,url:c.toString(),method:N0.method,headers:N0.headers,status:K0.status}),await Q6(K0,F,"event-stream")}catch(K0){throw await M6({sessionID:C,transport:"http",phase:"http",bodyText:N0.body,accountId:P,url:c.toString(),method:N0.method,headers:N0.headers,error:K0 instanceof Error?K0.message:String(K0)}),v1(K0,F)}}function i6(Z,N){if((N?.method??(Z instanceof Request?Z.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof N?.body!=="string")return!1;try{let R=Z instanceof URL?Z.toString():typeof Z==="string"?Z:Z.url;return new URL(R).pathname.endsWith("/responses")}catch{return!1}}function XW(Z){return X0.peekMainForPolicy(Z)?.quota}function BJ(Z,N){for(let F of[Z?.primary?.checkedAt,Z?.secondary?.checkedAt,Z?.checkedAt,N])if(typeof F==="number"&&Number.isFinite(F))return F;return}function n6(Z,N,F,R,P){let b=BJ(Z,N),M=BJ(F),C=R===P&&F!=null&&(Z===void 0||M!==void 0&&(b===void 0||M>b));return{quota:C?F:Z,quotaCheckedAt:C?M:b,source:C?"file":"memory"}}function LJ(Z,N,F,R,P){let b=Z?.quota,M=n6(b,Z?.checkedAt,N,R,P),C=M.source,m=M.quota;if(!v$(m,F))return{exhausted:!1};let s=h$(m,F);if(!s)return{exhausted:!1};return{exhausted:!0,source:C,...s}}function NJ(Z,N){Q1.debug("admission skip: exhausted account",{accountId:Z,source:N.source,resetsAt:N.resetsAt})}function jJ(Z,N="killswitch",F,R){let P=Date.now(),b=R?R.main:X0.getMain()?.quota,M=R?R.fallbacks:(Z?.accounts??[]).filter((f)=>f.enabled!==!1&&s0(f)).map((f)=>({accountId:f.id,quota:X0.getFallback(f.id)?.quota})),C=F$(b,M,P,Z);if(N==="quota-unknown")C=E$;else if(N==="quota-exhausted"&&F!==void 0)C=Math.max(1,Math.ceil((F-P)/1000));else if(N==="mid-stream-rate-limit"&&F!==void 0){let f=Math.max(1,Math.ceil((F-P)/1000));C=Math.min(C,f)}let m=Math.floor(C/60),s=C%60,c=N==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${m}m ${s}s.`:N==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${m}m ${s}s.`:N==="quota-unknown"?`OpenAI quota is not known yet for any available account; checking it now. Retry in ${m}m ${s}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${m}m ${s}s.`;return new Response(JSON.stringify({error:{message:c,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(C)}})}function s9(Z){let N=Z?.resetCreditsAvailable;return typeof N==="number"&&Number.isFinite(N)?N:void 0}async function QW(Z){let N=I8(Z.storage),F=Date.now(),R=X0.peekMainForPolicy(Z.mainAccountIdentity),P=n6(R?.quota,R?.checkedAt,Z.sidebarState.main.quota,Z.sidebarState.main.mainAccountId,Z.mainAccountIdentity),b=N?Z6(R?.quota,Z.storage,void 0,F):void 0,M=Z.mainUnavailable?[]:[{accountId:"main",wireAccountId:Z.mainAccountIdentity,access:Z.primaryAccess,keepwarmAccountKey:"main",quota:P.quota,quotaCheckedAt:P.quotaCheckedAt,reservePercent:U8(Z.storage),configuredOrder:0,resetCreditsApplicable:s9(P.quota),killswitchPasses:b}],C=await e0.getUsableFallbackAccounts(Z.storage);if(!Z.storage)return M;for(let m of C){let s=d9(m);if(!s)continue;let c=Z.sidebarState.fallbacks.find((v0)=>v0.id===m.id),f=X0.peekFallbackForPolicy(m.id,m.accountId),J0=n6(f?.quota,f?.checkedAt,c?.quota,c?.accountId,m.accountId),z0=N?Z6(f?.quota,Z.storage,m.id,F):void 0;M.push({accountId:m.id,wireAccountId:m.accountId,access:s,keepwarmAccountKey:m.id,fallback:m,quota:J0.quota,quotaCheckedAt:J0.quotaCheckedAt,reservePercent:U8(Z.storage,m.id),configuredOrder:M.length,resetCreditsApplicable:s9(J0.quota),killswitchPasses:z0})}return M}function FJ(Z,N,F,R,P){let b=I8(P)?Z.killswitchPasses:void 0;if(Z.accountId==="main"){let s=X0.peekMainForPolicy(Z.wireAccountId),c=n6(s?.quota,s?.checkedAt,N.main.quota,N.main.mainAccountId,Z.wireAccountId);return dY({quota:c.quota,quotaCheckedAt:c.quotaCheckedAt,status:F,now:R,killswitchPasses:b})}let M=N.fallbacks.find((s)=>s.id===Z.accountId),C=X0.peekFallbackForPolicy(Z.accountId,Z.wireAccountId),m=n6(C?.quota,C?.checkedAt,M?.quota,M?.accountId,Z.wireAccountId);return dY({quota:m.quota,quotaCheckedAt:m.quotaCheckedAt,status:F,now:R,killswitchPasses:b})}function GW(Z){return Z.accountId==="main"?"main":Z.keepwarmAccountKey}function DJ(Z){return X0.isRateLimited(GW(Z))}function a9(Z){let N=Z.candidates.filter((b)=>!DJ(b)),F=new Map(N.map((b)=>[b.accountId,b])),R=new Set(Z.excludeAccountIds),P=OJ({vaultMode:!1,sessionId:Z.sessionId,requestBytes:Z.requestBytes,sidebarSnapshot:Z.sidebarSnapshot,now:Z.now,validPinnedAccountIds:[...F.keys()],excludeAccountIds:Z.excludeAccountIds??[],quotaCheckedAtByAccount:Object.fromEntries(N.map((b)=>[b.accountId,b.quotaCheckedAt])),wireAccountIdByAccount:Object.fromEntries(N.map((b)=>[b.accountId,b.wireAccountId])),select:(b)=>{let M=N.filter((C)=>!R.has(C.accountId));if(M.length===0)return;return p3({candidates:M,pendingBytes:b,requestBytes:Z.requestBytes,now:Z.now,onEmptyWeightedSet:()=>{K1.debug("sticky routing: no fresh weighted candidates; using configured order")}})},persist:!0});return P?F.get(P.accountId):void 0}function OJ(Z){let N=void 0,F=Z.validPinnedAccountIds,R=m$(U6(Z.sidebarSnapshot,E),{sessionId:Z.sessionId,requestBytes:Z.requestBytes,now:Z.now,validPinnedAccountIds:F,excludeAccountIds:Z.excludeAccountIds,quotaCheckedAtByAccount:Z.quotaCheckedAtByAccount,wireAccountIdByAccount:Z.wireAccountIdByAccount,choose:(b)=>{let M=Z.select(b);if(!M)return;return N={accountId:M.accountId,source:M.source,pendingBytes:b.get(M.accountId)??0},M}}),P=R.assignment;if(!Z.persist)return P;if(N&&P?.accountId===N.accountId)K1.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:j1(Z.sessionId),accountId:N.accountId,source:N.source,requestBytes:Z.requestBytes,pendingBytes:N.pendingBytes});if(P&&R.next!==void 0){let b=Z.vaultMode,M=j1(Z.sessionId),C=l$(E,M,P);D1.enqueue(`pin:${M}`,"sticky-pin",async()=>{await c$({sessionId:Z.sessionId,assignment:P,validPinnedAccountIds:F},l0,{vaultMode:b,canWrite:()=>j.enrolled()===b}),C.persistedAt=Date.now()})}return P}async function $W(Z,N){let F=await e0.getUsableFallbackAccounts(Z),R=[];if(!Z)return{current:[],retained:[],skipped:[]};for(let c of F){let f=d9(c);if(!f)continue;R.push({access:f,accountId:c.accountId,keepwarmAccountKey:c.id,quotaAccountId:c.id,fallback:c})}let P=R.filter((c)=>!X0.isRateLimited(c.quotaAccountId)),b=I8(Z)?P.filter((c)=>Z6(X0.peekFallbackForPolicy(c.quotaAccountId,c.accountId)?.quota,Z,c.quotaAccountId,Date.now())):P,M=new Map(N.fallbacks.map((c)=>[c.id,{quota:c.quota,accountId:c.accountId}])),C=[],m=[],s=Date.now();for(let c of b){let f=M.get(c.quotaAccountId),J0=LJ(X0.peekFallbackForPolicy(c.quotaAccountId,c.accountId),f?.quota,s,f?.accountId,c.accountId);if(J0.exhausted)m.push({candidate:c,decision:J0});else C.push(c)}return{current:b,retained:C,skipped:m}}function _J(Z,N){if(Z.retained.length===0&&!N)return Z.current;for(let{candidate:F,decision:R}of Z.skipped)NJ(F.quotaAccountId,R);return Z.retained}function PJ(Z,N){try{let F=X6(Z.headers);V6(F,N.access,N.quotaAccountId,void 0,y6(Z.headers))}catch{}}async function WW(Z,N,F,R){for(let P of R){let b;try{b=await L6(Z,N,P.access,P.accountId,P.keepwarmAccountKey)}catch(M){if((M instanceof Error||M instanceof DOMException)&&M.name==="AbortError")throw M;if(N?.signal?.aborted)throw M;throw K1.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:P.quotaAccountId}),M}if(!S8(b.status,F))return e0.markUsed(P.fallback),{response:b,accessToken:P.access,quotaAccountId:P.quotaAccountId,activeId:P.keepwarmAccountKey};PJ(b,P),b.body?.cancel().catch(()=>{})}return}async function zW(Z,N,F,R,P){if(!i6(Z,N))return{response:F};if(!P.length)return{response:F};let b=F,M;for(let C of P){let m;try{m=await L6(Z,N,C.access,C.accountId,C.keepwarmAccountKey)}catch(s){if((s instanceof Error||s instanceof DOMException)&&s.name==="AbortError")throw s;if(N?.signal?.aborted)throw s;return K1.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:C.quotaAccountId}),{response:b,...M}}if(b.body?.cancel().catch(()=>{}),b=m,M={accessToken:C.access,accountId:C.quotaAccountId},!S8(m.status,R))return e0.markUsed(C.fallback),{response:m,...M};PJ(m,C)}return{response:b,...M}}if(M0){let Z=[];for(let N of M0.accounts)if(s0(N))Z.push(N);X0.seedFallbacksFromAccounts(Z)}if(!a4)if(a4=!0,U1(X0).catch(()=>{}),w.then(()=>j.enrolled()?U1(X0):void 0).catch(()=>{}),!j.enrolled()&&!await A0.active())p9=R6(h8({respectBackoff:!0})).catch((Z)=>Q1.warn("boot quota seed failed",{pid:process.pid,error:h6(Z)}));else p9=Promise.resolve();h.start(async()=>{if(await j.authority(),j.enrolled()){await U1(X0);return}if(await A0.active()){let F=await rX(A0,await C0(G0(Y0())),()=>MY(Y0()));if(F.length>0)await U1(X0);let R=F.filter((P)=>!P.ok);if(R.length>0)Q1.warn("background pool quota poll completed with failures",{pid:process.pid,failures:R});return}let N=(await nX(h8({readSidebarState:async()=>(await d1.read()).state}))).filter((F)=>!F.ok);if(N.length>0)Q1.warn("background quota refresh completed with failures",{pid:process.pid,failures:N})},(Z)=>{Q1.warn("background quota refresh failed",{pid:process.pid,error:Z instanceof Error?Z.message:String(Z)})});async function t9(Z,N,F,R,P,b){let M=F?.routing?.mode??"main-first",C=j.enrolled(),m=C?void 0:A0.peek().rows.find((e)=>e.id==="main"),s=!m&&!C?await S():void 0,c=!m&&s?.type==="oauth"&&c0(s),f=!m&&!C&&await m9(G0(Y0()),s);if(b===u6)c6=m?.identity;let J0=await d1.get(),{response:z0,servedId:v0}=await C3({source:A0,...C?{vault:{routes:()=>j.routes(),awaitRoster:async()=>{await H8(j.awaitRequestRoster(),kY)},noRouteCause:()=>q$(j),send:(e,N0)=>j.send(e,N0,{site:"model",...N?.signal?{signal:N.signal}:{}}),requestReading:(e)=>j.requestReading(e),rateLimitMarks:()=>{for(let[e,N0]of l6)if(N0<=Date.now())l6.delete(e);return l6}}}:{},storage:F,mode:M,sessionId:R,body:typeof N?.body==="string"?N.body:void 0,replayable:i6(Z,N),now:Date.now,send:(e,N0,K0)=>L6(Z,N,N0,e.identity,e.id,K0),recordQuota:(e,N0,K0,Z1)=>{try{let m0=X6(e.headers),T0=y6(e.headers);if(!N0.row){if(Z1)j.recordSnapshot(N0.id,m0,T0,Z1).then(VJ);return}V6(m0,K0,N0.id==="main"?void 0:N0.id,N0.id==="main"?N0.identity:void 0,T0)}catch{}},placePin:(e)=>OJ({...e,sidebarSnapshot:J0,vaultMode:C}),blocked:(e,N0,K0)=>{if(e.reason==="no-credential"){if(f&&!cY(K0))throw Error(_6);return new Response(cY(K0)?P$(K0,j.name):G6[c?"missing-main":K0??"unusable"],{status:401,headers:{"content-type":"text/plain; charset=utf-8"}})}return jJ(F,e.reason,e.resetAtMs,N0)},resetCredits:(e)=>s9(e==="main"?X0.peekMainForPolicy(m?.identity)?.quota:X0.peekFallbackForPolicy(e)?.quota),isAbort:(e)=>(e instanceof Error||e instanceof DOMException)&&e.name==="AbortError"||Boolean(N?.signal?.aborted),creditsServing:a$,log:K1});return r9(R,P,v0,M,C?j.routes().map((e)=>({id:e.id})):F?.accounts,U6(J0,E),C),z0}return H=!0,{apiKey:CB,async fetch(Z,N){let F=await j.authority(),R=z$(Z,N),P=H$(R),b=R.get("x-parent-session-id")?.trim()||void 0,M=F!=="local"?await g6(G0(Y0())):await b8();if(F!=="local")return N=await n4(Z,N),t9(Z,N,M,P,b,++u6);let C=await S();if(await j.authority()!=="local")return N=await n4(Z,N),t9(Z,N,M,P,b,++u6);let m=++u6;if(C.type!=="oauth")return R.delete(G8),fetch(Z,{...N,headers:R});N=await n4(Z,N);let s=(await A0.current()).active;if(r0(C)&&s)return t9(Z,N,M,P,b,m);if(s)j.assertHostSlot(C);let c="",f=!1,J0,z0=r0(C);if(t?.migrated()&&!z0&&C.refresh?.trim()&&s4(C).kind==="real")t.noticeRealSlot(C.refresh);let v0=async(j0=M)=>{if(z0=!0,J0=await HJ(j0),J0)c=J0.token;else c="",f=!0,K1.warn("main account in the pool has no usable token",{pid:process.pid})};if(z0)await v0();else if(c0(C))f=!0;else{if(!C.access||(C.expires??0)<Date.now()){x8.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(C.access),expiresInMs:C.expires?C.expires-Date.now():void 0});try{let j0=await n9();C.access=j0.access,C.refresh=j0.refresh,C.expires=j0.expires}catch(j0){if(i4(j0))throw j0;if(j0 instanceof s1)await v0(await C0(G0(Y0())))}}if(!z0)c=C.access??""}let e=z0?HY(M):M,N0=C,K0=J0?.account.accountId??(z0?void 0:N0.accountId)??(c?X1(J1(c)??{}):void 0);if(m===u6)c6=K0;let Z1=M?.routing?.mode??"main-first",m0=await d1.get(),T0=m0.state;if(Z1==="sticky-balanced"&&P&&i6(Z,N)&&typeof N?.body==="string"){let j0=Buffer.byteLength(N.body,"utf8"),b0=await QW({storage:e,sidebarState:T0,primaryAccess:c,mainAccountIdentity:K0,mainUnavailable:f}),I0=a9({sessionId:P,requestBytes:j0,candidates:b0,sidebarSnapshot:m0,now:Date.now()});if(I0){let RJ=DJ(I0)?{action:"migrate",reason:"exhausted"}:FJ(I0,T0,void 0,Date.now(),M);if(RJ.action==="migrate"){let n0=a9({sessionId:P,requestBytes:j0,candidates:b0,sidebarSnapshot:m0,excludeAccountIds:[I0.accountId],now:Date.now()});if(n0)K1.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:j1(P),fromAccountId:I0.accountId,toAccountId:n0.accountId,reason:RJ.reason}),I0=n0}let V1=await L6(Z,N,I0.access,I0.wireAccountId,I0.keepwarmAccountKey),CJ=(n0,i1)=>{try{let HW=X6(n0.headers);V6(HW,i1.access,i1.accountId==="main"?void 0:i1.accountId,i1.accountId==="main"?i1.wireAccountId:void 0,y6(n0.headers))}catch{}};CJ(V1,I0);let wJ=FJ(I0,T0,V1.status,Date.now(),M);if((V1.status===401||V1.status===403||V1.status===429)&&wJ.action==="migrate"){let n0=a9({sessionId:P,requestBytes:j0,candidates:b0,sidebarSnapshot:m0,excludeAccountIds:[I0.accountId],now:Date.now()});if(n0){K1.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:j1(P),fromAccountId:I0.accountId,toAccountId:n0.accountId,reason:wJ.reason});let i1=V1;V1=await L6(Z,N,n0.access,n0.wireAccountId,n0.keepwarmAccountKey),i1.body?.cancel().catch(()=>{}),I0=n0,CJ(V1,I0)}}if(I0.fallback&&!S8(V1.status,M))e0.markUsed(I0.fallback);return r9(P,b,I0.accountId,Z1,M?.accounts,U6(m0,E)),V1}}let O1=LJ(X0.peekMainForPolicy(K0),T0.main.quota,Date.now(),T0.main.mainAccountId,K0),_1=I8(M)&&!Z6(XW(K0),M,void 0,Date.now()),P1=X0.isRateLimited("main"),qJ,e9=()=>{return qJ??=$W(e,T0),qJ},q1,N6,EJ=!1,m8;if(Z1==="fallback-first"&&i6(Z,N)){EJ=!0;let j0=await e9();m8=_J(j0,!_1&&!P1&&!O1.exhausted);let b0=await WW(Z,N,M,m8);if(b0)q1=b0.response,N6={accessToken:b0.accessToken,accountId:b0.quotaAccountId,activeId:b0.activeId}}if(!q1){let j0=O1.exhausted&&i6(Z,N)&&(await e9()).retained.length>0;if(_1||P1||j0){let b0=_1?"killswitch":P1?"mid-stream-rate-limit":"quota-exhausted";if(b0==="quota-exhausted"&&O1.exhausted)NJ("main",O1);K1.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:b0}),q1=jJ(M,b0,b0==="quota-exhausted"&&O1.exhausted?O1.resetAtMs:P1?X0.rateLimitedUntil("main"):void 0)}else q1=f?new Response(null,{status:401}):await L6(Z,N,c,K0,"main")}let YY=Boolean(N6),o6=q1,MJ=N6?.accessToken??c,AJ=N6?.accountId,TJ=N6?.activeId??"main";if(!N6&&!EJ&&S8(q1.status,M)){K1.debug("reactive fallback triggered",{pid:process.pid,status:q1.status}),m8??=_J(await e9(),!1);let j0=await zW(Z,N,q1,M,m8),b0=j0.response;if(b0!==q1){if(YY=!0,o6=b0,MJ=j0.accessToken??c,AJ=j0.accountId,j0.accountId)TJ=j0.accountId}}if(z0&&f&&!YY&&await m9(G0(Y0()),await S()))throw Error(_6);try{let j0=X6(o6.headers);if(YY)V6(j0,MJ,AJ,void 0,y6(o6.headers));else V6(j0,c,void 0,K0,y6(o6.headers))}catch{}return r9(P,b,TJ,Z1,M?.accounts,U6(m0,E)),o6}}},methods:E0},"chat.headers":async(S,u)=>{if(S.model.providerID!=="openai")return;if(u.headers.originator="opencode",u.headers["User-Agent"]=`${V$(A1)} (${l4.platform()} ${l4.release()}; ${l4.arch()})`,u.headers["session-id"]=S.sessionID,H)u.headers[G8]=S.agent;if(W&&S.agent==="title")u.headers[k1.TITLE_HEADER]="true"},"chat.params":async(S,u)=>{if(S.model.providerID!=="openai")return;u.maxOutputTokens=void 0},config:async(S)=>{H0("commands").info("registering commands",{existing:Object.keys(S.command??{}).length,pid:process.pid}),S.command={...S.command??{},[x1]:{template:x1,description:"OpenAI accounts: quota, routing, limits, cache keep-warm, diagnostics and reset credits."}}},"command.execute.before":async(S)=>{if(H0("commands").info("command hook entered",{command:S.command,hasCmdCtx:U!==null,pid:process.pid}),S.command!==x1)return;if(!U)H0("commands").warn("command rejected: context not loaded",{command:S.command,pid:process.pid}),await l(S.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),G$();let u=await pX(U,S.sessionID);if(qY(S.sessionID))e8(u,S.sessionID);else await l(S.sessionID,dX(u.menu));G$()}}}var oB=async(Y)=>{let J=o0();return nB(Y,{codexApiEndpoint:J.codexApiEndpoint,experimentalWebSockets:J.webSockets,responsesLite:J.responsesLite})},Bq={id:"cortexkit-openai-auth",server:oB};
|
|
63
63
|
export{Y0 as d,s6 as e,o0 as f,zY as g,_6 as h,M6 as i,wX as j,a8 as k,SX as l,$8 as m,IX as n,SN as o,e8 as p,gX as q,pX as r,lX as s,Gj as t,eX as u,X3 as v,kY as w,xY as x,H8 as y,hY as z,L3 as A,nz as B,S3 as C,I3 as D,y3 as E,J2 as F,X2 as G,C8 as H,vG as I,qB as J,EB as K,MB as L,AB as M,TB as N,RB as O,Hq as P,wB as Q,SB as R,Kq as S,Uq as T,e4 as U,f0 as V,hB as W,vB as X,yB as Y,Zq as Z,mB as _,uB as $,W$ as aa,s$ as ba,Vq as ca,H$ as da,pB as ea,iB as fa,nB as ga,oB as ha,Bq as ia};
|