@cortexkit/opencode-openai-auth 1.0.4 → 1.1.0
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 +9 -8
- package/dist/{pool-lifecycle-DqKq8Eej.d.ts → codex-request-BXDXToyt.d.ts} +158 -27
- package/dist/index-0yh85bwb.js +69 -0
- package/dist/{index-jye6vccc.js → index-4c8yw54k.js} +2 -2
- package/dist/{index-k4eacw7x.js → index-7c6sxtd6.js} +2 -2
- package/dist/index-7eb3dw37.js +90 -0
- package/dist/index-8re8rprk.js +2 -0
- package/dist/{index-bgq9d21h.js → index-csky2xpg.js} +1 -1
- package/dist/index-edbdscy7.js +65 -0
- package/dist/{index-45qgkb0m.js → index-f2fmb596.js} +1 -1
- package/dist/{index-envpbt0k.js → index-j8v2xwq6.js} +1 -1
- package/dist/{index-egrty6tz.js → index-k6cydkgt.js} +2 -2
- package/dist/{index-dryydk6b.js → index-m5qmvr6c.js} +2 -2
- package/dist/index-msx2m78k.js +8 -0
- package/dist/{index-yeyp8t0k.js → index-zpm95mt5.js} +1 -1
- package/dist/index.d.ts +15 -7
- package/dist/index.js +1 -1
- package/dist/{map-CCbSZIhT.d.ts → map-Buq-GW7l.d.ts} +1 -1
- package/dist/{protocol-CSIDDBDf.d.ts → model-YRg7Uowo.d.ts} +67 -25
- package/dist/{port-file-CZ9MIdy2.d.ts → port-file-CxEpgSHY.d.ts} +1 -1
- package/dist/protocol-CDV1Pc6h.d.ts +29 -0
- package/dist/rpc/port-file.d.ts +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.d.ts +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.d.ts +3 -3
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/{sidebar-state-BCxFpH68.d.ts → sidebar-state-DjTWUbmf.d.ts} +15 -9
- package/dist/sidebar-state.d.ts +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/{token-vykm9bxh.js → token-rz4t3ay6.js} +1 -1
- package/dist/token-util-tpy2c7h6.js +1 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/tui.d.ts +20 -2
- package/dist/v2/server.d.ts +73 -1
- package/dist/v2/server.js +3 -3
- package/package.json +2 -2
- package/src/tui-compiled/raw/shared/0332701351b3eeec-format.js +78 -42
- package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +354 -0
- package/src/tui-compiled/raw/shared/134b008900698fe0-backoff.js +92 -0
- package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +393 -0
- package/src/tui-compiled/raw/shared/2577ec69f9973ae9-quota-normalize.js +154 -0
- package/src/tui-compiled/raw/shared/2dce6e9613993329-quota-manager.js +473 -0
- package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +566 -0
- package/src/tui-compiled/raw/shared/43fc9e6b994519c7-refresh-lock.js +0 -1
- package/src/tui-compiled/raw/shared/4593a4d71edf69fd-tombstone.js +25 -0
- package/src/tui-compiled/raw/shared/4d05c2d7a531aece-oauth.js +500 -0
- package/src/tui-compiled/raw/shared/6371b24a0573d79e-any-signal.js +42 -0
- package/src/tui-compiled/raw/shared/7c140680fc81be92-interlock.js +29 -0
- package/src/tui-compiled/raw/shared/85512cc5263ba259-provider.js +87 -0
- package/src/tui-compiled/raw/shared/abd062d633e29fd2-pool-routing.js +192 -0
- package/src/tui-compiled/raw/shared/b9588ad4725c1d10-enrollment.js +806 -0
- package/src/tui-compiled/raw/shared/bfbdd0f9aae56b47-pool-quota.js +85 -0
- package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +0 -1
- package/src/tui-compiled/raw/shared/ca0fccaba1d87af4-errors.js +8 -0
- package/src/tui-compiled/raw/shared/d0f0b6be200311af-insula.js +152 -0
- package/src/tui-compiled/raw/shared/d5a8f1061ee2f114-index.js +1 -1
- package/src/tui-compiled/raw/shared/d9d2892a4c371301-host-slot.js +72 -0
- package/src/tui-compiled/raw/shared/dbc61cd405941828-accounts.js +1470 -0
- package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +26 -12
- package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +24 -0
- package/src/tui-compiled/raw/sidebar-state.js +41 -14
- package/src/tui-compiled/raw/tui/command-dialogs.tsx +3 -34
- package/src/tui-compiled/raw/tui/section-text.js +21 -0
- package/src/tui-compiled/raw/tui/v2-dialog.js +137 -0
- package/src/tui-compiled/raw/tui/v2.tsx +133 -0
- package/src/tui-compiled/raw/tui.tsx +146 -40
- package/src/tui-compiled/runtime/shared/0332701351b3eeec-format.js +78 -42
- package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +354 -0
- package/src/tui-compiled/runtime/shared/134b008900698fe0-backoff.js +92 -0
- package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +393 -0
- package/src/tui-compiled/runtime/shared/2577ec69f9973ae9-quota-normalize.js +154 -0
- package/src/tui-compiled/runtime/shared/2dce6e9613993329-quota-manager.js +473 -0
- package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +566 -0
- package/src/tui-compiled/runtime/shared/43fc9e6b994519c7-refresh-lock.js +0 -1
- package/src/tui-compiled/runtime/shared/4593a4d71edf69fd-tombstone.js +25 -0
- package/src/tui-compiled/runtime/shared/4d05c2d7a531aece-oauth.js +500 -0
- package/src/tui-compiled/runtime/shared/6371b24a0573d79e-any-signal.js +42 -0
- package/src/tui-compiled/runtime/shared/7c140680fc81be92-interlock.js +29 -0
- package/src/tui-compiled/runtime/shared/85512cc5263ba259-provider.js +87 -0
- package/src/tui-compiled/runtime/shared/abd062d633e29fd2-pool-routing.js +192 -0
- package/src/tui-compiled/runtime/shared/b9588ad4725c1d10-enrollment.js +806 -0
- package/src/tui-compiled/runtime/shared/bfbdd0f9aae56b47-pool-quota.js +85 -0
- package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +0 -1
- package/src/tui-compiled/runtime/shared/ca0fccaba1d87af4-errors.js +8 -0
- package/src/tui-compiled/runtime/shared/d0f0b6be200311af-insula.js +152 -0
- package/src/tui-compiled/runtime/shared/d5a8f1061ee2f114-index.js +1 -1
- package/src/tui-compiled/runtime/shared/d9d2892a4c371301-host-slot.js +72 -0
- package/src/tui-compiled/runtime/shared/dbc61cd405941828-accounts.js +1470 -0
- package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +26 -12
- package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +24 -0
- package/src/tui-compiled/runtime/sidebar-state.js +41 -14
- package/src/tui-compiled/runtime/tui/command-dialogs.js +3 -15
- package/src/tui-compiled/runtime/tui/section-text.js +21 -0
- package/src/tui-compiled/runtime/tui/v2-dialog.js +137 -0
- package/src/tui-compiled/runtime/tui/v2.js +95 -0
- package/src/tui-compiled/runtime/tui.js +255 -163
- package/dist/index-2hch7e8n.js +0 -8
- package/dist/index-5dg931q0.js +0 -65
- package/dist/index-99esnzg0.js +0 -157
- package/dist/index-9reyazwh.js +0 -2
- package/dist/index-yf6arn5w.js +0 -2
- package/dist/token-util-gmn5yaqc.js +0 -1
package/dist/index-5dg931q0.js
DELETED
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
import{$a as J6,Aa as rX,Ba as d9,Bb as YJ,Ca as a8,Cb as XJ,Da as f6,Db as JJ,Ea as MG,Eb as QJ,Fa as TJ,Fb as M6,Gb as l9,Hb as k8,Ia as sX,Ib as a1,Jb as n8,Ka as c0,Kb as t1,La as z$,Lb as e1,Ma as R9,Mb as YY,Na as t6,Nb as XY,Oa as K$,Ob as JY,Pa as U$,Qa as a0,Qb as jY,Ra as H$,Rb as FY,Sa as xX,Sb as C6,Ta as A0,Tb as xJ,Ua as i9,Ub as vJ,Va as W3,Vb as hJ,Wa as C9,Wb as yJ,Xa as TY,Xb as gJ,Ya as X6,Yb as R6,Za as s9,_a as Q9,_b as h8,ab as Z$,ac as t8,ba as G1,bb as V$,bc as j$,ca as lJ,cb as kJ,cc as U0,da as dJ,db as z3,ea as $3,eb as M8,ec as $J,fa as iJ,fb as s0,fc as vX,ga as nJ,gb as o8,gc as hX,ha as D6,hb as GY,hc as WJ,ia as jJ,ib as B$,ic as F$,ja as Q$,jb as s,jc as i4,ka as kX,kb as A6,kc as D$,la as J9,lb as Q8,lc as s6,ma as $$,mc as v1,na as T8,nc as J1,oa as d4,ob as L$,oc as Q1,pa as W$,pb as RY,pc as O6,qa as uX,qb as N$,qc as fJ,ra as pX,rb as j3,rc as a6,sa as N8,sb as aX,sc as n4,ta as j8,tb as WY,tc as zJ,ua as s8,ub as tX,va as lX,vb as eX,wa as dX,wc as O$,xa as iX,ya as nX,za as oX}from"./index-99esnzg0.js";import{Ac as RJ,Cc as L8,Dc as P$,Gc as q$,Kc as E3,Lc as E$,Mc as M$,Nc as A$,Sc as h1,Tc as y1,Uc as T$,Vc as R$,Yc as C$,Zc as w$,_c as S$,ad as Y1,bd as X1,cd as I$,dd as b$,ed as V6,fd as k$,yc as IY}from"./index-9reyazwh.js";import{nd as e8,pd as F6,td as Y6}from"./index-yf6arn5w.js";import{Bd as a9}from"./index-2hch7e8n.js";import{Gd as UJ,Hd as HJ,Id as ZJ,Jd as r3,Kd as G$,Ld as u9}from"./index-jye6vccc.js";import{Sd as v3,Td as r9,Vd as B0,_d as y6,ae as GJ}from"./index-k4eacw7x.js";import{be as F8,ce as z9,fe as I3,ge as b3,he as yY,ie as k3,le as x3}from"./index-dryydk6b.js";import{ne as VJ,pe as _$}from"./index-45qgkb0m.js";import{re as dY}from"./index-bgq9d21h.js";import{createHash as UB,randomUUID as HB}from"node:crypto";import{mkdirSync as ZB,readFileSync as VB,renameSync as BB,statSync as LB,writeFileSync as NB}from"node:fs";import c4 from"node:os";import{join as jB}from"node:path";import{readFile as FW}from"node:fs/promises";import{readFileSync as o$}from"node:fs";import{homedir as r$,tmpdir as s$}from"node:os";import{join as g9}from"node:path";var a$="https://chatgpt.com/backend-api/codex/responses",t$="openai-auth.json",x8={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",codexApiEndpoint:"CORTEXKIT_OPENAI_AUTH_CODEX_ENDPOINT",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function f9(){let Y=process.env[x8.configDir]?.trim();if(Y)return Y;return g9(process.env.XDG_CONFIG_HOME||g9(r$(),".config"),"opencode")}function Y0(){return process.env[x8.configFile]?.trim()||g9(f9(),t$)}function e$(){try{let Y=JSON.parse(o$(Y0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function YW(Y){let X=process.env[Y];if(X===void 0)return;let J=X.trim().toLowerCase();if(J==="1"||J==="true"||J==="yes"||J==="on")return!0;if(J===""||J==="0"||J==="false"||J==="no"||J==="off")return!1;return}function h9(Y,X,J){let Q=YW(Y);if(Q!==void 0)return Q;if(typeof X==="boolean")return X;return J}function XW(){let Y=e$(),X;if(Y.dump!==void 0&&Y.dump!==null){if(typeof Y.dump==="object")X=Y.dump.enabled;else if(typeof Y.dump==="boolean")X=Y.dump}return{webSockets:h9(x8.webSockets,Y.webSockets,!1),rawWebSocket:h9(x8.rawWebSocket,Y.rawWebSocket,!1),responsesLite:h9(x8.responsesLite,Y.responsesLite,!1),dump:h9(x8.dump,X,!1),dumpDir:process.env[x8.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():g9(s$(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[x8.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():a$)}}var y9;function r0(){if(!y9)y9=XW();return y9}function CX(){return y9=void 0,r0()}import{readFileSync as JW}from"node:fs";var QW="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 GW(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 _6(Y,X={}){return D6({provider:"openai",configPath:Y.configPath,statePath:Y.statePath,quota:F6,...X})}function QY(Y){try{let X=JSON.parse(JW(Y,"utf8"));if(!X||typeof X!=="object"||Array.isArray(X))return!1;return s6(X).migratedAt!==void 0}catch{return!1}}async function m9(Y,X){if(!QY(Y.configPath))return;let J=await X.read();return J.status==="ready"?J.rows:void 0}function c9(Y,X){if(Y===M8)return QW;if(s6(X.config).pending?.rowId===Y)return GW(Y);return}function $W(Y,X){return O6(Y,M8,X.legacyLocks).filter((J)=>J.name===a6)}function A8(Y,X={}){return $W(Y,X)}var P6="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 r8 extends Error{constructor(){super("The main OpenAI account lives in the account pool");this.name="MainAccountInPoolError"}}async function wX(Y){let X=Y.storage,J=o8(X);if(!X||!J||c0(J))return;let Q=J,G=Y.now(),$=(X.refresh?.refreshBeforeExpiryMinutes??240)*60000;if((!Q.access||!Q.expires||Q.expires-G<=$)&&!T8(Q.lastRefreshError,Q.refresh,G))try{Q=await Y.refreshAccount(Q,X)}catch(U){Y.warn?.("pool main row refresh failed",{error:U instanceof Error?U.message:String(U)})}let K=Q.access?.trim();if(!K)return;if(typeof Q.expires!=="number"||Q.expires<=Y.now())return;return{account:Q,token:K}}import{readdir as WW,readFile as zW}from"node:fs/promises";import{homedir as KW}from"node:os";import{join as q6}from"node:path";function IX(){return process.env.XDG_STATE_HOME||q6(KW(),".local","state")}function UW(Y=IX()){return q6(Y,"cortexkit","openai-auth","processes")}function HW(Y=IX()){return q6(Y,"cortexkit","openai-auth","rpc")}function ZW(Y){try{return process.kill(Y,0),!0}catch(X){return X.code==="EPERM"}}function SX(Y){let X=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z.-]+)?$/.exec(Y.trim());if(!X)return;return{core:[Number(X[1]),Number(X[2]),Number(X[3])],pre:X[4]?X[4].split("."):[]}}function VW(Y,X){let J=SX(Y),Q=SX(X);if(!J||!Q)return;for(let G=0;G<3;G++){let $=J.core[G]-Q.core[G];if($!==0)return Math.sign($)}if(J.pre.length===0||Q.pre.length===0)return Math.sign(Q.pre.length-J.pre.length);for(let G=0;G<Math.max(J.pre.length,Q.pre.length);G++){let $=J.pre[G],W=Q.pre[G];if($===void 0)return-1;if(W===void 0)return 1;let K=/^\d+$/.test($),U=/^\d+$/.test(W);if(K&&U){let Z=Number($)-Number(W);if(Z!==0)return Math.sign(Z)}else if(K!==U)return K?-1:1;else if($!==W)return $<W?-1:1}return 0}async function $Y(Y){try{return{ok:!0,names:await WW(Y)}}catch(X){let J=X.code;if(J==="ENOENT")return{ok:!0,names:[]};return{ok:!1,code:J,error:`${Y}: ${String(X)}`}}}async function BW(Y,X){let J;try{J=await zW(Y,"utf8")}catch(Q){if(Q.code==="ENOENT")return{kind:"gone"};return{kind:"unreadable"}}try{let Q=JSON.parse(J);if(Q!==null&&typeof Q==="object"&&Q.pid===X&&typeof Q.version==="string")return{kind:"ok",version:Q.version}}catch{}return{kind:"unreadable"}}async function E6(Y){let X=Y.isAlive??ZW,J=Y.selfPid??process.pid,Q=new Map,G=(V)=>{let D=V.pid==="unknown"?`dir:${V.detail}`:V.pid;if(!Q.has(D))Q.set(D,V)},$=(V)=>{try{return X(V)}catch{return!0}},W=(V,D)=>{let E=D.exec(V),P=E?Number(E[1]):Number.NaN;return Number.isSafeInteger(P)&&P>=1?P:void 0},K=UW(Y.stateHome),U=new Set,Z=await $Y(K);if(!Z.ok)G({pid:"unknown",version:"unknown",detail:Z.error});for(let V of Z.ok?Z.names:[]){let D=W(V,/^(\d+)\.json$/);if(D===void 0||D===J)continue;let E=q6(K,V),P=await BW(E,D);if(P.kind==="gone")continue;if(U.add(D),!$(D))continue;if(P.kind==="unreadable"){G({pid:D,version:"unknown",detail:E});continue}let T=VW(P.version,Y.currentVersion);if(T===void 0||T<0)G({pid:D,version:P.version,detail:E})}let B=Y.rpcDir??HW(Y.stateHome),O=await $Y(B);if(!O.ok)G({pid:"unknown",version:"unknown",detail:O.error});for(let V of O.ok?O.names:[]){if(!u9(V))continue;let D=q6(B,V),E=await $Y(D);if(!E.ok){if(E.code==="ENOTDIR")continue;G({pid:"unknown",version:"unknown",detail:E.error});continue}for(let P of E.names){let T=W(P,/^port-(\d+)\.json$/);if(T===void 0||T===J||U.has(T))continue;if($(T))G({pid:T,version:"unknown",detail:q6(D,P)})}}let N=(V)=>V.pid==="unknown"?Number.POSITIVE_INFINITY:V.pid;return Q.size===0?{open:!0}:{open:!1,blockers:[...Q.values()].sort((V,D)=>N(V)-N(D))}}var v8="1.0.4";import{readFile as yX}from"node:fs/promises";function p9(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}async function gX(Y){let X=await xX(Y.configPath),J=[];try{let G=JSON.parse(await yX(Y.statePath,"utf8"));if(p9(G)){let $=G.accounts;if(p9($))J=Object.keys($)}}catch(G){if(G.code!=="ENOENT")throw G}return{rosterIds:X?[...X]:[],stateIds:J,orphanStateIds:X?J.filter((G)=>!X.has(G)):[]}}async function LW(Y){try{let X=JSON.parse(await yX(Y.configPath,"utf8"));return p9(X)&&p9(X.claustrum)&&X.claustrum.mode==="claustrum"}catch{return!1}}var bX="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 fX(Y){if(!Y)return;let X=Y.accounts.find((J)=>J.id==="main"&&a0(J));if(X)return X;if(!Y.mainAccountId)return;return Y.accounts.find((J)=>a0(J)&&J.accountId===Y.mainAccountId)}function NW(Y,X){let J=Y.lastRefreshError;return T8(J,Y.refresh,X)&&J!==void 0&&J.nextRetryAt!==void 0&&J.nextRetryAt-J.checkedAt>=kX}function jW(Y){let X=[],J=[],Q=Y.now??Date.now(),G=fX(Y.storage),$=!1;if(c0(Y.auth))X.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. ${bX}`});else if(s0(Y.auth)){if(!o8(Y.storage))X.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)X.push({code:"auth-slot-missing",message:"OpenCode's OpenAI auth slot is missing."}),$=!0;else if(Y.auth.type!=="oauth")X.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))X.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 U={type:"restore-main-credential"};J.push(U);let Z=X.find((B)=>B.code==="auth-slot-missing"||B.code==="auth-slot-not-oauth"||B.code==="main-refresh-not-in-store");if(Z)Z.repair=U}let W=Y.storage?.accounts??[];if(W.length===0)X.push({code:"no-accounts",message:"The account store has no accounts."});else if(!W.some((U)=>U.enabled!==!1))X.push({code:"no-enabled-accounts",message:"The account store has no enabled accounts."});for(let U of W){if(!a0(U)||!c0(U))continue;X.push({code:"tombstoned-account",accountId:U.id,message:`Account ${U.id} holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${bX}`})}if(Y.retiredCustodyMode)X.push({code:"retired-custody-mode",message:"The config still selects the vault custody mode of an older version (`claustrum.mode`). It is ignored, and dropped at the next settings write; vault accounts are served once this host is connected to the Claustrum vault."});for(let U of W){if(!a0(U))continue;if(!NW(U,Q))continue;let Z={type:"clear-refresh-backoff",accountId:U.id};J.push(Z),X.push({code:"armed-non-transient-refresh-backoff",accountId:U.id,message:`Account ${U.id} has an armed non-transient refresh backoff.`,repair:Z})}let K=[...Y.orphanStateIds??[]];if(K.length>0){let U={type:"prune-orphan-state-ids",ids:K};J.push(U),X.push({code:"orphan-state-ids",message:`State contains ids absent from the config roster: ${K.join(", ")}.`,repair:U})}return{findings:X,repairs:J}}function mX(Y){let X=(J)=>{if(J.type==="restore-main-credential")return{label:"Copy the stored main credential back into OpenCode's slot",apply:async()=>{if(s0(await Y.readAuth()))return;let Q=fX(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(J.type==="prune-orphan-state-ids")return{label:`Drop the state entries of ${J.ids.join(", ")}`,apply:async()=>{await Y.mutateAccounts((Q)=>Q,Y.paths)}};return{label:`Clear the refresh backoff of ${J.accountId}`,apply:async()=>{await Y.mutateAccounts((Q)=>{let G=Q.accounts.find(($)=>$.id===J.accountId&&a0($));if(G)G.lastRefreshError=void 0;return Q},Y.paths)}}};return[{id:"openai-auth",run:async()=>{let[J,Q,G,$]=await Promise.all([Y.loadAccounts(Y.paths),Y.readStoreIds(Y.paths),Y.readAuth(),LW(Y.paths)]),W=jW({auth:G.type==="missing"?void 0:G,storage:J,orphanStateIds:Q.orphanStateIds,retiredCustodyMode:$,now:Y.now()}),K=await D6({provider:"openai",quota:F6,configPath:Y.paths.configPath,statePath:Y.paths.statePath}).read();if(K.status==="ready")for(let U of K.rows){if(U.disabledReason!==vX)continue;W.findings.push({code:"slot-transfer-origin-unknown",accountId:U.id,message:`Account ${U.id} was preserved disabled after an interrupted transfer with an untagged placeholder; sole ownership could not be established. ${hX}`})}return W.findings.map((U)=>{let Z=U.repair?X(U.repair):void 0;return{code:U.code,message:U.message,...U.accountId!==void 0?{accountId:U.accountId}:{},...Z?{repair:Z}:{}}})}}]}var DW=GJ,cX="OpenAI accounts",OW="ChatGPT accounts in the vault",_W="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 PW(){let{redirectUri:Y}=await iX(),X=await pX(),J=uX(crypto.getRandomValues(new Uint8Array(32)).buffer),Q=lX(Y,X,J),G=nX(X,J);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:s8($)}}finally{dX(J)}}}}async function qW(Y){let{deviceData:X,url:J,instructions:Q}=await oX(Y);return{url:J,instructions:Q,method:"auto",async callback(){try{let G=await rX(X,Y);return{type:"success",refresh:G.refresh_token,access:G.access_token,expires:Date.now()+(G.expires_in??3600)*1000,accountId:s8(G)}}catch{return{type:"failed"}}}}}function KJ({client:Y,getAuth:X,getPaths:J=()=>U0(Y0()),fetchImpl:Q=fetch,packageVersion:G=v8,dependencies:$,onMainSlotWritten:W,vault:K}){let U={authorizeBrowser:$?.authorizeBrowser??PW,authorizeHeadless:$?.authorizeHeadless??(()=>qW(G)),beginAccountLogin:$?.beginAccountLogin??d9,loadAccounts:$?.loadAccounts??A0,mutateAccounts:$?.mutateAccounts??i9,readStoreIds:$?.readStoreIds??gX,openBrowser:$?.openBrowser??DW,now:$?.now??Date.now,openAccountPool:$?.openAccountPool??_6,migrationBlockers:$?.migrationBlockers??(async()=>{let j=await E6({currentVersion:G});return j.open?[]:j.blockers.map((S)=>({pid:S.pid,version:S.version}))}),...$?.terminal?{terminal:$.terminal}:{},...$?.vaultWait?{vaultWait:$.vaultWait}:{}},Z=async()=>await X?.().catch(()=>{return})??{type:"missing"},B=async()=>{if(K&&await K.authority()!=="local")return!0;if((await Z()).type!=="missing")return!0;let j=J(),S=U.openAccountPool(j);if((await S.read()).status==="ready")return XJ(S);return((await U.loadAccounts(j))?.accounts.length??0)>0},O=async(j)=>{if(await WJ(J().configPath,async()=>{if(K&&await K.authority()!=="local")return!1;if(s0(await Z()))return!1;return await Y.auth.set({path:{id:"openai"},body:{type:"oauth",...j}}),!0}))await W?.().catch(()=>{})},N=(j)=>({begin:async({headless:S,signal:h})=>{if(K&&await K.authority()!=="local")throw Error(M6);let M=await U.beginAccountLogin({version:G,headless:S,...h?{signal:h}:{}});return{url:M.url,instructions:M.instructions,completion:M.completion.then(async(y)=>{if(K&&await K.authority()!=="local")throw Error(M6);let n=await j.read(),o=n.status==="ready"?n.rows.find((u)=>u.id===M8)?.identity:void 0;if(y.accountId&&o&&y.accountId===o)throw Error("that account is already the OpenCode main credential");return{id:y.id,credential:{type:"oauth",refresh:y.refresh,...y.access!==void 0?{access:y.access}:{},...y.expires!==void 0?{expires:y.expires}:{}},...y.accountId!==void 0?{identity:y.accountId}:{},...y.label!==void 0?{label:y.label}:{}}})}},openBrowser:(S)=>U.openBrowser(S)}),V=async(j)=>{if(K&&await K.authority()!=="local")throw Error(M6);let S=j.credential;if(S?.type!=="oauth"||!S.access)throw Error("no usable access token for a quota check");let h=await t6({accessToken:S.access,fetchImpl:Q,now:U.now,...j.identity?{accountId:j.identity}:{},accountKey:j.id});return A6(h,U.now(),!0)},D=(j)=>mX({paths:J(),migrated:j,readAuth:Z,loadAccounts:U.loadAccounts,readStoreIds:U.readStoreIds,mutateAccounts:U.mutateAccounts,setMainAuth:O,now:U.now}),E=(j,S)=>({title:cX,store:a1(S,{rowLocks:(h)=>O6(j,h)}),...U.terminal?{terminal:U.terminal}:{},login:N(S),protect:(h,M)=>c9(h,M),extraLocks:A8(j),pollQuota:V,doctor:D(!0),status:async()=>{let h=await K?.status();if(K&&await K.authority()!=="local"&&h)return[WY(K.host,K.name,h.enrollment)];return[`Routing: ${(await U.loadAccounts(j))?.routing?.mode??"main-first"}`,...K?[WY(K.host,K.name,(await K.status()).enrollment)]:[]]},...K?{extraActions:[P(K)]}:{}}),P=(j)=>{let S=j.enrolled();return{id:S?"vault-disconnect":"vault-connect",label:S?"Disconnect from the Claustrum vault":"Connect to the Claustrum vault",hint:"serve OpenAI accounts held in the vault",run:async(h)=>{let M=await j.authority();if(S){if(M!=="local")await j.disconnect();h.print("Disconnected from the Claustrum vault.");return}if(M!=="local"){h.print("Nothing was changed: this host is already connected or its enrollment is unreadable. Reopen the menu to disconnect.");return}h.print(`Asking the Claustrum vault to enroll ${j.name}…`);let y,n=await j.waitForApproval({...U.vaultWait,onPending:(o)=>{let V0=o.state==="pending"?o.requestId??o.retryCode??"":o.state;if(V0===y)return;y=V0;for(let u of aX(j.name,o))h.print(u);h.print("Waiting for the approval… (stop with Ctrl-C; Connect picks the request up again)")}});h.print(tX(j,n).text)}}},T=async()=>{let j=await U.migrationBlockers();return YJ({title:cX,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((S)=>` ${S.pid==="unknown"?"processes that could not be read":`pid ${S.pid}`}: version ${S.version}`)]:[]],actions:[eX({checks:D(!1)})],...U.terminal?{terminal:U.terminal}:{}})},w=async(j)=>{let S=J(),h=U.openAccountPool(S);if(K&&await K.authority()!=="local")return l9(E(S,h),K);if(await m9(S,h)===void 0)return T();let M=E(S,h);return K?l9(M,K):JJ(M)},x=(j)=>async()=>{if(K&&await K.authority()!=="local")throw Error(M6);let S=await j();if(S.method!=="auto")return S;return{...S,callback:async()=>{let h=await S.callback();if(K&&await K.authority()!=="local")return{type:"failed"};return h}}};return[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:QJ({hasCredential:B,openMenu:w,login:x(()=>U.authorizeBrowser())})},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:x(()=>U.authorizeHeadless())},{label:"Manually enter API Key",type:"api"},...K?.enrolled()?[{label:OW,type:"oauth",authorize:async()=>({url:"",instructions:_W,method:"auto",callback:async()=>{if(await sX(K.paths,K.name)!=="vault")return{type:"failed"};try{let j=JSON.parse(await FW(zJ(),"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{...$J,type:"success"}}})}]:[]]}var zY={rpcRoot:"openai-auth",directoryPrefix:VJ,registrationSessionId:"process"};function n9(Y,X){UJ(zY,Y,X)}function BJ(Y=0,X){return HJ(zY,Y,X)}function LJ(Y){return ZJ(zY,Y)}var o9=B0("commands");function T6(Y){return{configPath:Y.accountStoragePath,statePath:Y.accountStatePath}}function KY(Y){return`${String(Y.startHour).padStart(2,"0")}-${String(Y.endHour).padStart(2,"0")}`}function EW(Y){let X=/^(\d{1,2})-(\d{1,2})$/.exec(Y.trim());if(!X)return{ok:!1,reason:"expected HH-HH, e.g. 9-18 or 22-6"};let J=Number(X[1]),Q=Number(X[2]);if(J>23||Q>23||J===Q)return{ok:!1,reason:"hours must be integers 0-23 and start ≠ end"};return{ok:!0,startHour:J,endHour:Q}}var MW="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 AW(Y){let X=(J)=>n8(Y.store(),A8(T6(Y)),(Q)=>{let G={...Q.cacheKeep??{}};J(G),Q.cacheKeep=G});return{title:"Cache",build:async()=>{let J=Y.cacheKeepManager;if(!J)return{lines:["Keep-warm unavailable"]};let Q=s9(await Y.loadAccounts(T6(Y))),G=Q?.enabled===!0,$=Q?.subagents===!0,W=J.status(),K=W.window?KY(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 ${K}`,`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((U)=>({id:U.sessionKey,label:U.sessionKey,group:"Sessions",detail:[U.accountId??"main",`expires in ${Math.ceil((U.cacheExpiresAt-W.generatedAt)/1000)}s`,...U.lastWarmedAt?[`last warm ${Math.ceil((W.generatedAt-U.lastWarmedAt)/1000)}s ago`]:[],...U.backoffUntil&&U.backoffUntil>W.generatedAt?[`backoff ${Math.ceil((U.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:U})=>{let Z=U.enabled===!0;if(await X((B)=>{B.enabled=Z}),Y.setCacheKeepEnabled?.(Z),Z)J.start();else J.stop();return o9.info(Z?"cachekeep enabled":"cachekeep disabled"),Z?`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:U})=>{let Z=U.subagents===!0;return await X((B)=>{B.subagents=Z}),Y.setCacheKeepSubagents?.(Z),`Subagent warming is ${Z?"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:U})=>{let Z=U.sustain===!0;return await X((B)=>{B.sustain=Z}),Y.setCacheKeepSustain?.(Z),Z?MW:"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:KY(W.window)}:{}}],run:async({values:U})=>{let Z=U.window;if(typeof Z!=="string"||Z.trim()==="")return await X((V)=>{delete V.startHour,delete V.endHour}),Y.setCacheKeepWindow?.(void 0),"Warm window cleared: keep-warm warms at any hour (within idle caps).";let B=EW(Z);if(!B.ok)return{ok:!1,text:`Invalid window: ${B.reason}`};let{startHour:O,endHour:N}=B;return await X((V)=>{V.startHour=O,V.endHour=N}),Y.setCacheKeepWindow?.({startHour:O,endHour:N}),`Warming limited to ${KY(B)} local hours.`}}]}}}}var NJ=["error","warn","info","debug","trace"];function TW(Y){return{title:"Diagnostics",build:async()=>{let X=r0(),Q=(await Y.loadAccounts(T6(Y)))?.logging?.level??"info";return{lines:[`Dumps ${X.dump?"on":"off"}`,`Dump directory: ${X.dumpDir}`,`Log level: ${Q}`],actions:[{id:"dump",label:X.dump?"Turn request dumps off":"Turn request dumps on",knobs:[{kind:"toggle",id:"enabled",label:"Request dumps",value:!X.dump}],run:async({values:G})=>{let $=G.enabled===!0;await n8(Y.store(),A8(T6(Y)),(K)=>{K.dump={...K.dump??{},enabled:$}});let W=CX();return o9.info($?"request dump enabled":"request dump disabled"),$?`Request dumps are on, written to ${W.dumpDir}.
|
|
2
|
-
|
|
3
|
-
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:NJ.map((G)=>({value:G,label:G})),value:NJ.includes(Q)?Q:"info"}],run:async({values:G})=>{let $=String(G.level);return await n8(Y.store(),A8(T6(Y)),(W)=>{W.logging={...W.logging??{},level:$}}),r9($),o9.info("log level changed",{level:$}),`Log level set to ${$}.`}}]}}}}async function RW(Y){let X=await Y.store().read(),J=X.status==="ready"?X.rows:[];return[...new Set(["main",...J.filter((Q)=>Q.enabled&&Q.type==="oauth").map((Q)=>Q.id)])]}function FJ(Y){let X=T6(Y),J=A8(X),Q=Y.resolveResetTarget&&Y.refreshResetTargetQuota&&Y.fetchImpl&&Y.now&&Y.randomUUID?XY({configPath:X.configPath,statePath:X.statePath,quotaManager:Y.quotaManager,loadAccounts:Y.loadAccounts,mutateAccounts:t1(Y.store(),J),resolveResetTarget:Y.resolveResetTarget,refreshResetTargetQuota:Y.refreshResetTargetQuota,fetchImpl:Y.fetchImpl,now:Y.now,randomUUID:Y.randomUUID,accountKeys:()=>RW(Y)}):void 0,G=Y.beginAccountLogin;return JY({store:Y.store(),...Y.vault?{vault:Y.vault}:{},...Y.now?{now:Y.now}:{},extraLocks:J,rowLocks:($)=>O6(X,$),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)=>c9($,W),...Y.refreshAllQuota?{quotaCheck:async($)=>{if($.length===1){let U=Y.store();for(let Z of $)await U.requestReading(Z);await U.pullsSettled();return}let K=(await Y.refreshAllQuota?.()??[]).filter((U)=>!U.ok);if(K.length>0)throw new jJ("quota-check-failed",K.map((U)=>U.permanent?`${U.account}: sign-in no longer accepted — remove and add this account again`:`${U.account}: fetch failed — check again to retry`).join(`
|
|
4
|
-
`))}}:{},cache:AW(Y),diagnostics:TW(Y),extras:[...Q?[Q]:[],e1({...Y.getStickyRouting?{getPin:Y.getStickyRouting}:{},...Y.clearStickyRouting?{clearPin:Y.clearStickyRouting}:{}}),...Y.vault?[YY({vault:Y.vault,changed:Y.afterWrite})]:[]],afterApply:async()=>{await Y.afterWrite?.(),await Y.refreshSidebar?.().catch(()=>{})}})}function DJ(Y){return(X,J="info")=>{o9.info("menu notification",{sessionId:Y,kind:J}),n9({command:k8,notify:{message:X,kind:J}},Y)}}function OJ(Y,X){return FJ(Y).open({...X!==void 0?{sessionId:X}:{},notify:DJ(X)})}function _J(Y,X){return FJ(Y).apply(X,{...X.sessionId!==void 0?{sessionId:X.sessionId}:{},notify:DJ(X.sessionId)})}function PJ(Y){let X=[`## ${Y.title}`];for(let J of Y.sections){X.push("",`### ${J.title}`);for(let Q of J.lines)X.push(Q);for(let Q of J.items){let G=Q.detail??Q.status;X.push(`- ${Q.label}${G?`: ${G}`:""}`)}}return X.push("","Open the OpenCode TUI to change these settings."),X.join(`
|
|
5
|
-
`)}var CW=300000,wW=30000,qJ=240000,SW="bg-quota-refresh",IW=120000;function UY(Y,X){return a9({name:SW,ttlMs:IW,path:Y,renew:!0,...X})}function EJ(Y,X=R6,J=()=>UY(Y.paths.configPath)){return bW(Y,X,J)}function bW(Y,X,J){return MJ(async()=>X({...Y,respectBackoff:!0,skipFresherThanMs:qJ}),J,[])}async function MJ(Y,X,J){let Q;try{Q=await X()}catch{Q=void 0}if(Q===null)return J;try{return await Y()}finally{await Q?.release().catch(()=>{})}}function AJ(Y,X,J){return MJ(async()=>{return await Y.refreshDueTokens(X),Y.pollRows(X,{skipReadWithinMs:qJ})},J,[])}class HY{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,X=this.onError){if(this.run=Y,this.onError=X,this.stopped=!1,this.timer)return;let J=Math.round((this.random()*2-1)*wW);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},CW+J),"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 ZY(Y){if(!Y||typeof Y!=="object")return;let X=Y,J=Number(X.startHour),Q=Number(X.endHour);if(!Number.isInteger(J)||!Number.isInteger(Q)||J<0||J>23||Q<0||Q>23||J===Q)return;return{startHour:J,endHour:Q}}function e6(Y,X=new Date){if(!Y)return!1;let J=X.getHours();if(Y.startHour<Y.endHour)return J>=Y.startHour&&J<Y.endHour;return J>=Y.startHour||J<Y.endHour}var kW=300000,xW=3600000,vW=1800000,hW=60000,yW=32,gW=8388608,fW=30000,mW=600000;function B8(Y,X){return typeof Y==="number"&&Number.isFinite(Y)&&Y>0?Y:X}function t9(Y){return Y instanceof Error?Y.message:String(Y)}class Y9{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=B8(Y.ttlMs,kW),this.tickIntervalMs=B8(Y.tickIntervalMs,hW),this.leadMs=B8(Y.leadMs,this.tickIntervalMs+15000),this.maxIdleWarmMs=B8(Y.maxIdleWarmMs,xW),this.maxSubagentIdleMs=B8(Y.maxSubagentIdleMs,vW),this.maxTargets=B8(Y.maxTargets,yW),this.maxBytes=B8(Y.maxBytes,gW),this.warmTimeoutMs=B8(Y.warmTimeoutMs,fW),this.backoff=Y.backoffMs??mW,this.getWindow=Y.getWindow,this.getSustain=Y.getSustain,this.setIntervalImpl=Y.setIntervalImpl??globalThis.setInterval,this.clearIntervalImpl=Y.clearIntervalImpl??globalThis.clearInterval}track(Y){let{sessionKey:X,bodyText:J}=Y;this.pruneStale();let Q=Buffer.byteLength(J,"utf8");if(Q>this.maxBytes)return this.log?.debug("cachekeep track skipped (body exceeds maxBytes)",{sessionKey:X,bodyBytes:Q,maxBytes:this.maxBytes}),{tracked:!1,reason:"body-exceeds-max-bytes"};let G=this.getWindow?.();if(G&&!e6(G,new Date(this.now())))return this.log?.debug("cachekeep track skipped (outside window)",{sessionKey:X,startHour:G.startHour,endHour:G.endHour}),{tracked:!1,reason:"outside-window"};this.drop(X);while(this.targets.size>=this.maxTargets||this.totalBytes+Q>this.maxBytes&&this.targets.size>0){let B=this.leastRecentlyTouched();if(B===void 0)break;this.log?.debug("cachekeep evicted least recently used target",{sessionKey:B}),this.drop(B)}let $=Y.isSubagent===!0,W=Y.accountId||void 0,K=this.adapter.profile?.({bodyText:J,isSubagent:$,accountId:W,meta:Y.meta}),U=B8(K?.ttlMs,this.ttlMs),Z=this.now();return this.targets.set(X,{bodyText:J,bodyBytes:Q,accountId:W,isSubagent:$,meta:Y.meta,ttlMs:U,maxWarms:K?.maxWarms!==void 0&&K.maxWarms>0?Math.floor(K.maxWarms):void 0,maxIdleMs:K?.maxIdleMs!==void 0?B8(K.maxIdleMs,this.idleDefault($)):void 0,cacheExpiresAt:Z+U,lastRealRequestAt:Z,failures:0,warmCount:0}),this.totalBytes+=Q,this.log?.debug("cachekeep captured target",{sessionKey:X,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:t9(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(([X,J])=>({sessionKey:X,accountId:J.accountId,isSubagent:J.isSubagent,cacheExpiresAt:J.cacheExpiresAt,lastRealRequestAt:J.lastRealRequestAt,...J.lastWarmedAt!==void 0?{lastWarmedAt:J.lastWarmedAt}:{},...J.backoffUntil!==void 0?{backoffUntil:J.backoffUntil}:{},failures:J.failures,warmCount:J.warmCount,ttlMs:J.ttlMs,bodyBytes:J.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&&!e6(Y,new Date(this.now())))return;let X=this.now(),J=X+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&&X<G.backoffUntil)continue;if(G.cacheExpiresAt>J)continue;await this.warm(Q,G)}}retireIfExpired(Y,X){if(this.now()<X.cacheExpiresAt)return!1;return this.log?.debug("cachekeep retired target (cache lifetime ended)",{sessionKey:Y,accountId:X.accountId,cacheExpiresAt:X.cacheExpiresAt,failures:X.failures}),this.drop(Y),!0}isCurrent(Y,X){return!this.disposed&&this.targets.get(Y)===X}view(Y,X){return{sessionKey:Y,accountId:X.accountId,bodyText:X.bodyText,isSubagent:X.isSubagent,meta:X.meta,warmCount:X.warmCount,ttlMs:X.ttlMs}}fail(Y,X,J,Q={}){if(!this.isCurrent(Y,X))return;X.failures+=1;let G=typeof this.backoff==="function"?this.backoff({sessionKey:Y,failures:X.failures}):this.backoff;X.backoffUntil=this.now()+(Number.isFinite(G)&&G>0?G:0),this.log?.warn(J,{sessionKey:Y,accountId:X.accountId,failures:X.failures,backoffUntil:X.backoffUntil,...Q})}async warm(Y,X){if(this.retireIfExpired(Y,X))return;let J=this.view(Y,X);if(this.adapter.activeAccount){let B;try{B=await this.adapter.activeAccount(Y,J)}catch(O){this.fail(Y,X,"cachekeep skip (active account unknown)",{error:t9(O)});return}if(!this.isCurrent(Y,X))return;if(B!==void 0&&B!==X.accountId){this.log?.debug("cachekeep dropped target (session changed account)",{sessionKey:Y,accountId:X.accountId,activeAccountId:B}),this.drop(Y);return}}let Q;try{Q=await this.adapter.buildBody(J)}catch(B){this.fail(Y,X,"cachekeep skip (replay body unbuildable)",{error:t9(B)});return}if(!this.isCurrent(Y,X))return;if(this.retireIfExpired(Y,X))return;let G=TJ([AbortSignal.timeout(this.warmTimeoutMs),this.abortController.signal]),$=G.signal,W,K="";try{W=await this.adapter.send({target:J,body:Q,signal:$}),K=await W.text().catch(()=>"")}catch(B){this.fail(Y,X,"cachekeep failed",{error:t9(B)});return}finally{G.dispose()}if(!this.isCurrent(Y,X))return;if(!W.ok){this.fail(Y,X,"cachekeep failed",{status:W.status,responseBody:K.slice(0,600)});return}let U;try{U=this.adapter.readUsage?.({target:J,response:W,text:K})}catch{}let Z=this.now();if(X.cacheExpiresAt=Z+X.ttlMs,X.lastWarmedAt=Z,X.backoffUntil=void 0,X.failures=0,X.warmCount+=1,this.log?.debug("cachekeep fired",{sessionKey:Y,accountId:X.accountId,warmCount:X.warmCount,...U}),X.maxWarms!==void 0&&X.warmCount>=X.maxWarms)this.log?.debug("cachekeep retired target (warm cap reached)",{sessionKey:Y,warmCount:X.warmCount}),this.drop(Y)}idleDefault(Y){return Y?this.maxSubagentIdleMs:this.maxIdleWarmMs}pruneStale(){let Y=this.now(),X=this.getSustain?.()===!0;for(let[J,Q]of[...this.targets]){if(this.retireIfExpired(J,Q))continue;if(X&&!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:J,accountId:Q.accountId,lastRealRequestAt:Q.lastRealRequestAt,maxIdleMs:G}),this.drop(J)}}leastRecentlyTouched(){let Y,X=Number.POSITIVE_INFINITY;for(let[J,Q]of this.targets){let G=Math.max(Q.lastRealRequestAt,Q.lastWarmedAt??0);if(G<X)Y=J,X=G}return Y}drop(Y){let X=this.targets.get(Y);if(!X)return!1;return this.totalBytes-=X.bodyBytes,this.targets.delete(Y),!0}}function VY(Y){if(typeof Y!=="string")return!1;try{let X=JSON.parse(Y);return s(X)&&s(X.client_metadata)&&X.client_metadata.ws_request_header_x_openai_internal_codex_responses_lite==="true"}catch{return!1}}function BY(Y){if(typeof Y!=="string")return Y;try{let X=JSON.parse(Y);if(!s(X)||!s(X.client_metadata))return Y;if(!(("x-codex-turn-metadata"in X.client_metadata)||("x-codex-ws-stream-request-start-ms"in X.client_metadata)||("ws_request_header_x_openai_internal_codex_responses_lite"in X.client_metadata)))return Y;let J={...X.client_metadata};return delete J["x-codex-turn-metadata"],delete J["x-codex-ws-stream-request-start-ms"],delete J.ws_request_header_x_openai_internal_codex_responses_lite,JSON.stringify({...X,client_metadata:J})}catch{return Y}}function e9(Y){if(Y?.method?.toUpperCase()!=="POST")return Y;let X=new Headers(Y.headers);if(X.set("accept","text/event-stream"),X.set("content-type","application/json"),VY(Y.body))X.set("x-openai-internal-codex-responses-lite","true");return{...Y,headers:X,body:BY(Y.body)}}function CJ(Y){if(!Y.enabled||typeof Y.body!=="string")return;let X=Y.headers.has("x-parent-session-id");if(X&&!Y.includeSubagents)return;let J=Y.headers.get("session-id")??Y.headers.get("x-opencode-session")??Y.headers.get("x-session-affinity")??void 0;if(!J)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:J,bodyText:Y.body,replayHeaders:Q,isSubagent:X}}function wJ(Y){return ZY(Y?.cachekeep)}var LY=1800000,cW=2,uW=2*LY+900000,pW=/^gpt-(\d+)(?:\.(\d+))?(?:-|$)/;function lW(Y){try{let J=JSON.parse(Y).model;if(typeof J!=="string")return!1;let Q=pW.exec(J);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 dW(Y){if(!lW(Y.bodyText))return;if(!Y.isSubagent)return{ttlMs:LY};return{ttlMs:LY,maxWarms:cW,maxIdleMs:uW}}function iW(Y){let J=JSON.parse(Y);return J.store=!1,delete J.max_output_tokens,delete J.max_tokens,delete J.max_completion_tokens,JSON.stringify(J)}function NY(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function SJ(Y){if(!Y||typeof Y!=="object")return NY();let X=Y,J=Number(X.input_tokens)||Number(X.prompt_tokens)||0,Q=Number(X.output_tokens)||Number(X.completion_tokens)||0,G=X.input_tokens_details??X.prompt_tokens_details,$=Number(G?.cached_tokens)||Number(X.cached_tokens)||0,W=J>0?$/J:null;return{input_tokens:J,output_tokens:Q,cached_tokens:$,hit_rate:W}}function nW(Y){try{let X=JSON.parse(Y);return SJ(X.usage)}catch{return NY()}}function oW(Y){let X,J=[],Q,G=()=>{if(!J.length)return;let $=J.join(`
|
|
6
|
-
`).trim();J=[];let W=X;if(X=void 0,!$||$==="[DONE]")return;try{let K=JSON.parse($),U=K.type??W;if(U!=="response.completed"&&U!=="response.done")return;let Z=K.response;Q=SJ(Z?.usage??K.usage)}catch{}};for(let $ of Y.split(/\r?\n/)){if($===""){G();continue}if($.startsWith("event:")){X=$.slice(6).trim();continue}if($.startsWith("data:"))J.push($.slice(5).trim())}return G(),Q??NY()}function IJ(Y,X,J=Date.now()){if(!X)return;if(Y.route==="sticky-balanced"){let G=Y.stickyAssignments?.[L8(X)];if(!G)return;if(G.lastSeenAt<J-RJ)return;return G.accountId}let Q=Y.activeRouting?.[X];if(!Q||Q.route!==Y.route)return;return Q.activeId}function rW(Y){let{logger:X,activeAccount:J}=Y;return{buildBody:(Q)=>iW(Q.bodyText),async send({target:Q,body:G,signal:$}){let W=async(B)=>{$.throwIfAborted();let O={...Q.meta.replayHeaders,authorization:`Bearer ${B}`,"content-type":"application/json"};if(Q.meta.chatgptAccountId)O["ChatGPT-Account-Id"]=Q.meta.chatgptAccountId;else delete O["ChatGPT-Account-Id"];let N;try{let V=JSON.parse(G);N={warmBodyKeys:Object.keys(V),stream:V.stream,max_output_tokens:V.max_output_tokens,store:V.store,has_stream_options:"stream_options"in V,has_max_tokens:"max_tokens"in V,model:V.model}}catch{}X?.debug("cachekeep warm request",{...N,headerKeys:Object.keys(O),hasChatGptAccountId:"ChatGPT-Account-Id"in O});try{let V=await Y.fetchImpl(Y.codexResponsesUrl,e9({method:"POST",headers:O,body:G,signal:$}));return await t8(V,B,"event-stream")}catch(V){throw h8(V,B)}};if(Q.accountId&&Y.vault?.owns(Q.accountId)){let B=await Y.vault.send(Q.accountId,W,{site:"cachekeep",signal:$});if(!B)throw Error(`vault refused warm for ${Q.accountId}`);return B}if(Y.vault&&await Y.vault.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");let K,U;if(Q.accountId&&Q.accountId!=="main"){let B=await Y.refreshFallback(Q.accountId);if(typeof B==="string")K=B;else K=B.token,U=B.onAuthFailure}else K=await Y.getMainToken();if(Y.vault&&await Y.vault.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");let Z=await W(K);if(Z.status===401)await U?.(Z.status);return Z},readUsage({response:Q,text:G}){let $=Q.headers.get("content-type")??"",W=$.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(G.slice(0,200));X?.debug("cachekeep warm response",{status:Q.status,contentType:$,bodyLen:G.length,isSse:W});let K=W?oW(G):nW(G),U=a8(Q.headers);return{...K,quota_primary_pct:U.primary?.usedPercent??null,quota_secondary_pct:U.secondary?.usedPercent??null}},profile:dW,...J?{activeAccount:(Q,G)=>J(G.meta.routingSessionId)}:{}}}function bJ(Y){let{fetchImpl:X,getMainToken:J,refreshFallback:Q,vault:G,codexResponsesUrl:$,activeAccount:W,logger:K,...U}=Y;return new Y9({...U,logger:K,adapter:rW({fetchImpl:X,getMainToken:J,refreshFallback:Q,vault:G,codexResponsesUrl:$,activeAccount:W,logger:K})})}import{readFileSync as sW}from"node:fs";var aW=60000,tW=15000,DY=2000,OY=1e4;async function X9(Y,X){let J,Q=await Promise.race([Y.then(()=>!0,()=>!0),new Promise((G)=>{J=setTimeout(()=>G(!1),X),J.unref?.()})]);return clearTimeout(J),Q}function eW(Y){if(!e8(Y.quota))return;let X=Y6(Y.quota);return X.limits.some((J)=>J.kind==="reading")?X.checkedAt:void 0}function Yz(Y){if(!Y)return;let X=N8(Y);return X?j8(X):void 0}function Xz(Y){try{let X=JSON.parse(sW(Y,"utf8"));if(!X||typeof X!=="object"||Array.isArray(X))return;return s6(X).migratedAt}catch{return}}function Jz(Y){if(Y.type!=="oauth")return!1;return Y.candidate||Y.torn===!0&&Y.enabled}class _Y{deps;now;log;snapshot={active:!1,rows:[],key:void 0,readAt:0};inflightRead;store;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??B0("pool"),this.vaultRosterSettled=Y.vaultFirstRoster===void 0;let X=()=>{this.vaultRosterSettled=!0};Y.vaultFirstRoster?.then(X,X)}async awaitVaultRoster(Y){let X=this.deps.vaultFirstRoster;if(this.vaultRosterSettled||!X)return;await X9(X,Y)}peek(){return{active:this.snapshot.active,rows:this.snapshot.rows}}async current(){if(this.disposed)return this.peek();let Y=this.filesKey();if(this.snapshot.key===Y)return this.peek();let X=this.startRead(Y),J=await X1(X,this.deps.readBudgetMs??Y1,()=>this.snapshot);return{active:J.active,rows:J.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}|${FY(Y.configPath)}|${FY(Y.statePath)}`}storeFor(Y){if(this.store?.configPath===Y.configPath)return this.store.store;let X=D6({provider:"openai",configPath:Y.configPath,statePath:Y.statePath,quota:F6,now:this.now,pull:(J)=>this.coalescedPull(J),onPullFailure:(J,Q)=>{this.pollOutcomes.set(J,{id:J,ok:!1,error:Q.message}),this.log.warn("pool quota poll failed",{rowId:J,kind:Q.kind,error:Q.message})},logger:this.log,...this.deps.store,onStep:async(J,Q)=>{if(await this.deps.store?.onStep?.(J,Q),Q.operation!=="updateSettings"&&J.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:X},X}startRead(Y){if(this.disposed)return Promise.resolve(this.snapshot);if(this.inflightRead?.key===Y)return this.inflightRead.promise;let X=this.now(),J=this.read(Y,X),Q={key:Y,promise:J};this.inflightRead=Q;let G=()=>{if(this.inflightRead===Q)this.inflightRead=void 0};return J.then(G,G),J}async read(Y,X){let J=this.deps.paths(),Q={active:!1,rows:[],key:Y,readAt:X};try{if(Xz(J.configPath)!==void 0){let W=await this.storeFor(J).read();if(W.status==="ready")Q={active:!0,rows:W.rows,key:Y,readAt:X};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(X>=this.snapshot.readAt)this.snapshot={...Q,rows:this.withLocalState(Q.rows)};if(this.snapshot.active){if(!G)this.log.info("account pool serves requests");this.pollUnseenRows()}return this.snapshot}withLocalState(Y){let X=this.now();return Y.map((J)=>{let Q=J,G=this.rotated.get(J.id),$=G?.credential;if(G&&G.credentialEpoch!==J.credentialEpoch)this.rotated.delete(J.id);else if($?.type==="oauth"&&J.credential?.type==="oauth"){let W=J.credential.lastRefreshedAt??0,K=$.lastRefreshedAt??0;if(W>=K)this.rotated.delete(J.id);else Q={...Q,credential:$}}return hJ(Q,this.pending,X)})}replaceRow(Y,X){this.snapshot={...this.snapshot,rows:this.snapshot.rows.map((J)=>J.id===Y?X(J):J)}}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,X9(Y,this.deps.vaultFirstRosterBackgroundWaitMs??OY).then((X)=>{if(this.pollsAwaitVault=!1,X)this.pollUnseenRows();else this.log.info("first quota polls skipped: the vault has not read its accounts yet")});return}for(let X of this.snapshot.rows){if(!Jz(X)||this.vaultOwned(X))continue;let J=`${X.id}\x00${X.credentialEpoch??0}\x00${X.identity??""}`;if(this.polled.has(J))continue;this.polled.add(J),this.requestReading(X.id,!0)}}requestReading(Y,X=!1){if(this.disposed||this.deps.vaultMode?.())return;let J=this.now(),Q=this.lastPull.get(Y);if(!X&&Q!==void 0&&J-Q<(this.deps.pullRetryMs??tW))return this.storeFor(this.deps.paths()).pullsSettled();this.lastPull.set(Y,J);let G=this.storeFor(this.deps.paths());return G.requestReading(Y),G.pullsSettled()}coalescedPull(Y){let X=JSON.stringify([this.deps.paths().configPath,Y.id,Y.credentialEpoch,Y.identity]),J=this.quotaPulls.get(X);if(J)return J;let Q=this.pull(Y).finally(()=>this.quotaPulls.delete(X));return this.quotaPulls.set(X,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 X;try{if(X=await this.deps.pullQuota(Y),!X)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 J=this.snapshot.rows.find((Q)=>Q.id===Y.id);if(J&&J.credentialEpoch===Y.credentialEpoch&&J.identity===Y.identity)this.applyObservation(J,X);return X}applyObservation(Y,X){vJ(this.pending,Y,X),this.replaceRow(Y.id,(J)=>({...J,quota:xJ(J.quota,X),needsFirstReading:!1}))}recordSnapshot(Y,X,J,Q){if(!this.snapshot.active||this.disposed||this.deps.vaultMode?.())return;let G=this.snapshot.rows.find((N)=>N.id===Y);if(G?.type!=="oauth")return;let $=Yz(J);if(!($&&G.identity?$===G.identity:C6(G)?.access===J))return;let K=A6(X,this.now(),Q);if(!K)return;if(this.applyObservation(G,K),G.credentialEpoch===void 0)return;let U={credentialEpoch:G.credentialEpoch,...G.identity!==void 0?{identity:G.identity}:{}},Z=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 Z.recordQuota(G.id,U,K)}).catch((N)=>{this.log.warn("pool quota not recorded",{rowId:G.id,error:N instanceof Error?N.message:String(N)})});this.writes.set(G.id,O),O.finally(()=>{if(this.writes.get(G.id)===O)this.writes.delete(G.id)})}markRateLimited(Y,X){let J=this.snapshot.rows.find(($)=>$.id===Y);if(!J)return;let Q=jY(J),G=this.marks.get(Q);if(G!==void 0&&G>X)return;this.marks.set(Q,X)}rateLimitMarks(Y){let X=new Map;for(let J of Y){let Q=this.marks.get(jY(J));if(Q!==void 0)X.set(J.id,Q)}return X}async prepareTokens(Y,X,J={}){if(this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")return;if(!this.deps.vaultMode?.())await this.awaitVaultRoster(this.deps.vaultFirstRosterWaitMs??DY);let Q=this.now(),G=kJ(X),$=[];for(let W of Y){if(!W.candidate||this.vaultOwned(W))continue;let K=C6(W);if(!K)continue;let U=(K.expires??0)-Q;if(!(!K.access||!K.expires||U<=G)||this.refreshBackedOff(W,X,Q))continue;let B=this.refresh(W.id);if(J.waitForAll||!K.access||!K.expires||U<=aW)$.push(B)}await Promise.all($)}refreshBackedOff(Y,X,J=this.now()){let Q=C6(Y);if(!Q)return!1;let G=J9(Q.refresh),$=this.backoff.get(Y.id);if($&&$.tokenHash===G&&$.nextRetryAt>J)return!0;let W=X?.accounts.find((K)=>K.id===Y.id);return Boolean(W?.type==="oauth"&&W.corrupt!==!0&&T8(W.lastRefreshError,Q.refresh,J))}usableToken(Y,X=this.now()){let J=this.snapshot.rows.find((G)=>G.id===Y.id);if(!J?.enabled||!J.candidate||J.type!=="oauth"||J.identity!==Y.identity||J.credentialEpoch!==Y.credentialEpoch||this.vaultOwned(J))return;let Q=C6(J);if(!Q?.access.trim())return;if(typeof Q.expires!=="number"||Q.expires<=X)return;return Q.access}refresh(Y){let X=this.refreshing.get(Y);if(X)return X;let J=this.runRefresh(Y).finally(()=>{if(this.refreshing.get(Y)===J)this.refreshing.delete(Y)});return this.refreshing.set(Y,J),J}async runRefresh(Y){if(this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")return;let X=this.deps.paths(),J=this.snapshot.rows.find((W)=>W.id===Y),Q=J?C6(J)?.refresh:void 0,G,$=(W,K)=>{return G=K.credentialEpoch,this.deps.refreshProvider(W,K)};try{let W=await fJ({paths:X,store:this.storeFor(X),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,(K)=>K.credentialEpoch!==G?K:{...K,credential:W.credential,...W.identity!==void 0&&K.identity===void 0?{identity:W.identity}:{}});return}if(W.status==="identity-contradicted"){this.backoff.delete(Y),this.replaceRow(Y,(K)=>({...K,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,X,J){if(this.log.warn("pool row refresh failed",{rowId:Y,error:J instanceof Error?J.message:String(J)}),!X)return;this.backoff.set(Y,yJ(X,J,this.now(),this.backoff.get(Y)))}refreshBackoffFor(Y){return gJ(Y,this.backoff,this.now(),(X,J)=>this.usableToken(X,J))}async active(){return(await this.current()).active}poolStore(){return this.storeFor(this.deps.paths())}async refreshDueTokens(Y){let X=await this.current();if(!X.active||this.disposed)return;await this.prepareTokens(X.rows,Y,{waitForAll:!0})}async pollRows(Y,X={}){let J=await this.load();if(!J.active||this.disposed)return[];let Q=this.now(),G=J.rows.filter(($)=>{if(!$.candidate||$.type!=="oauth"||this.vaultOwned($))return!1;if(X.ids&&!X.ids.includes($.id))return!1;if(X.skipReadWithinMs===void 0)return!0;let W=eW($);return W===void 0||Q-W>=X.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,X){let J=await this.current();if(!J.active)return;let Q=J.rows.find((W)=>W.id===Y);if(!Q?.candidate)return;await this.prepareTokens([Q],X);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,X){let J=await this.current();if(!J.active)return;let Q=J.rows.find(($)=>$.id===Y);if(!Q)return{};let G=await this.accessFor(Y,X);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(){this.disposed=!0}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)return}}}var mJ=60000,PY=900000,Qz={set(Y,X){let J=setTimeout(Y,X);return J.unref?.(),J},clear(Y){clearTimeout(Y)}};function Gz(Y){return Y.status==="completed"||Y.status==="already-migrated"||Y.status==="nothing-to-import"||Y.status==="ambiguous"}function cJ(Y){return Y.status==="deferred"||Y.status==="retry"||Y.status==="error"}function uJ(Y){let X=Y.log??B0("pool-migration"),J=Y.timers??Qz,Q=Y.random??Math.random,G=Y.migrate??J1,$=Y.adopt??Q1,W=Y.fence??(()=>E6({currentVersion:Y.version})),K=!1,U=!1,Z=!1,B=0,O,N=Promise.resolve(),V,D,E,P=!1;function T(){if(P)return;P=!0,X.warn(P6,{reason:"placeholder-without-main"})}let w=()=>({paths:Y.paths(),slot:Y.slot,log:X,...Y.runDeps});function x(u){let G0=N.then(u).catch((J0)=>{X.warn("account pool background run failed",{error:J0 instanceof Error?J0.message:String(J0)})});return N=G0,G0}function j(u){if(U)return;if(O!==void 0)J.clear(O);O=J.set(()=>{O=void 0,x(o)},u)}function S(){let u=Math.min(mJ*2**Math.min(B,10),PY);return B++,h(u)}let h=(u)=>Math.round(u*(1-0.2*Q()));async function M(){if(!await Y.paused?.())return!1;return j(h(mJ)),!0}async function y(){if(U||await M()||U)return;let u;try{u=await G({...w(),fence:W})}catch(G0){X.warn("account pool migration failed; it will be tried again",{error:G0 instanceof Error?G0.message:String(G0)}),j(S());return}if(u.status==="refused"){if(u.reason==="placeholder-without-main")T();j(h(PY));return}if(Gz(u)){if(Z=!0,B=0,u.status==="completed")X.info("account pool migration completed",{rowId:u.rowId});await n();return}if(cJ(u)){if(u.status!=="deferred")X.warn("account pool migration will be tried again",{outcome:u});j(S())}}async function n(){if(U||await M()||U)return;let u;try{let G0=await W();if(U)return;if(!G0.open){let J0=JSON.stringify(G0.blockers);if(J0!==E)E=J0,X.info("host login adoption waits for older plugin versions",{blockers:G0.blockers});j(S());return}u=await $(w())}catch(G0){X.warn("adopting the host login into the account pool failed",{error:G0 instanceof Error?G0.message:String(G0)}),j(S());return}if(u.status==="not-migrated")return;if(u.status==="slot-read-only")return;if(Z=!0,u.status==="completed")X.info("host login adopted into the account pool",{rowId:u.rowId,operation:u.operation});if(cJ(u)){X.warn("host login adoption will be tried again",{outcome:u}),j(S());return}if(B=0,Z)j(h(PY))}async function o(){if(U)return;if(Z)await n();else await y()}function V0(){if(V)return V;let u=x(async()=>{if(V=void 0,!U)if(Z)await n();else await y()});return V=u,u}return{start(){if(K||U)return;K=!0,x(y)},requestAdoption:V0,noticePlaceholderWithoutMain:T,noticeRealSlot(u){if(!Z||U||u===D)return;D=u,V0()},dispose(){if(U=!0,O!==void 0)J.clear(O);O=void 0},idle:async()=>{for(;;){let u=N;if(await u,u===N)return}},migrated:()=>Z}}var u0="main";function oJ(Y,X,J){let Q=new Map;if(X6(X))for(let G of Y)Q.set(G.id,J6(Q8(G.quota),X,G.id===u0?void 0:G.id,J));return Q}var rJ=5,$z=5000;function sJ(Y){if(Y==="ordered")return"roster";return Y==="fallback-first"?"fallback-first":"main-first"}function aJ(Y,X=$z){let J=Y.rows.filter((W)=>W.kind==="oauth"&&Y.killswitch.get(W.id)!==!1&&Y6(W.quota).limits.length===0);if(J.length===0)return;if(G1({rows:Y.rows,now:Y.now,rateLimitMarks:Y.rateLimitMarks,refreshBackoff:Y.refreshBackoff,requestPull:()=>{}}).admitted.some((W)=>Y.killswitch.get(W.id)!==!1))return;let G=[];if(G1({rows:J,now:Y.now,rateLimitMarks:Y.rateLimitMarks,refreshBackoff:Y.refreshBackoff,requestPull:(W)=>{let K=Y.requestPull(W);if(K)G.push(K.catch(()=>{}))}}),G.length===0)return;let $;return Promise.race([Promise.all(G),new Promise((W)=>{$=setTimeout(W,X)})]).then(()=>{}).finally(()=>clearTimeout($))}function qY(Y){return Y.reason==="exhausted"||Y.reason==="budget-spent"}function tJ(Y,X,J){if(Y===void 0)return{reason:"no-credential"};if(J.get(Y)===!1)return{reason:"killswitch"};let Q=X.excluded.find(($)=>$.id===Y);if(Q?.reason==="rate-limited")return{reason:"mid-stream-rate-limit",resetAtMs:Q.until};if(Q)return{reason:"no-credential"};let G=X.refused.find(($)=>$.id===Y);if(G&&"resetAtMs"in G)return{reason:"quota-exhausted",resetAtMs:G.resetAtMs};if(G)return{reason:"quota-unknown"};return{reason:"no-credential"}}function pJ(Y,X,J){if(X.refused.find((G)=>!qY(G)&&J.get(G.id)!==!1))return{reason:"quota-unknown"};return tJ(Y[0],X,J)}function eJ(Y){let X=Y.replayable!==!1,J=X?Y.placement:"main-first",Q=dJ({rows:Y.rows,placement:J,formerMainId:u0,killswitch:Y.killswitch,rateLimitMarks:Y.rateLimitMarks,refreshBackoff:Y.refreshBackoff,now:Y.now,requestPull:Y.requestPull}),G=lJ(Y.rows.map((K)=>K.id),J,u0),$=new Set(Q.admission.refused.filter((K)=>qY(K)&&Y.killswitch.get(K.id)!==!1).map((K)=>K.id)),W=G.filter((K)=>$.has(K));if(!X){let K=G.includes(u0),U=K?u0:Q.order[0]??W[0];if(U!==void 0&&Q.order.includes(U))return{kind:"send",order:[U],lastPath:!1};if(U!==void 0&&$.has(U))return{kind:"send",order:[U],lastPath:!0};return{kind:"block",block:K?tJ(u0,Q.admission,Y.killswitch):pJ(G,Q.admission,Y.killswitch)}}if(Q.order.length>0)return{kind:"send",order:Q.order,lastPath:!1};if(W.length>0)return{kind:"send",order:W,lastPath:!0};return{kind:"block",block:pJ(G,Q.admission,Y.killswitch)}}function EY(Y){let X=G1({rows:Y.rows,rateLimitMarks:Y.rateLimitMarks,refreshBackoff:Y.refreshBackoff,now:Y.now,requestPull:Y.requestPull}),J=new Map;for(let Q of Y.rows)J.set(Q.id,Y6(Q.quota));for(let Q of X.admitted)if(Q.projection)J.set(Q.id,Q.projection);return{projections:J,excluded:new Set(X.excluded.map((Q)=>Q.id))}}function Y3(Y,X,J){let Q=J.exclude,G=Q?Y.rows.filter((W)=>!Q.has(W.id)):Y.rows,$=new Map;for(let W of G){let K=X.resetCredits(W.id);if(K!==void 0)$.set(W.id,K)}return nJ({rows:G,now:Y.now,rateLimitMarks:Y.rateLimitMarks,refreshBackoff:Y.refreshBackoff,requestPull:Y.requestPull,killswitch:Y.killswitch,requestBytes:X.requestBytes,...J.pendingBytes?{pendingBytes:J.pendingBytes}:{},rowReservePercent:(W)=>X.reservePercent(W.id),refusedPinPolicy:"move-on-confirmed-exhaustion",resetCreditsApplicable:$,...J.pin===void 0?{}:{pin:{accountId:J.pin}},...X.onEmptyWeightedSet?{onEmptyWeightedSet:X.onEmptyWeightedSet}:{}})}function X3(Y,X,J,Q){let G=Y3(Y,X,{exclude:J,pendingBytes:Q});if(G.outcome!=="dispatch"||G.source==="pin")return;return{accountId:G.accountId,source:G.source,...G.quotaCheckedAt===void 0?{}:{quotaCheckedAt:G.quotaCheckedAt}}}function J3(Y,X,J){let Q=Y.killswitch.get(J)===!1,G=Y3(Y,X,{pin:J});if(G.outcome==="dispatch"){if(G.pin.action==="assign")return{kind:"move",reason:Q?"killswitch":"exhausted"};return G.accountId===J?{kind:"serve"}:{kind:"detour"}}let $=G.admission.refused.find((W)=>W.id===J);if(!Q&&$&&qY($))return{kind:"last-path"};return{kind:"none"}}function Q3(Y,X,J,Q){let G=Y.killswitch.get(J);return iJ({quota:X.projections.get(J),now:Y.now,...Q===void 0?{}:{status:Q},...G===void 0?{}:{killswitchPasses:G}})}var Q6={"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.",...RY};function CY(Y){return Y!==void 0&&Y in RY}function Wz(Y,X,J,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===u0)return!0;if(z3(X,{accountId:G.identity}))return!1;return TY(Q8(G.quota),X,J)})}function MY(Y){let X=Y.vault;return[...(X?[]:Wz(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})),...(X?.routes()??[]).filter((Q)=>TY(Q8(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 zz(Y){return Y.flatMap((X)=>X.row?[X.row]:[])}function $1(Y,X){let J=Y.now(),Q=oJ(X,Y.storage,J),G=X.map((U)=>({id:U.id,kind:U.kind,...e8(U.quota)?{quota:U.quota}:{}})),$=zz(X),W=new Set(X.filter((U)=>!U.row).map((U)=>U.id)),K=Y.source.rateLimitMarks($);for(let[U,Z]of Y.vault?.rateLimitMarks?.()??[])if(W.has(U)&&Z>J)K.set(U,Z);return{rows:G,now:J,rateLimitMarks:K,refreshBackoff:Y.source.refreshBackoffFor($),killswitch:Q,requestPull:(U)=>W.has(U)?Y.vault?.requestReading(U):Y.source.requestReading(U)}}function G3(Y){let X=Y.find((J)=>J.id===u0);return{main:X?Q8(X.quota):void 0,fallbacks:Y.filter((J)=>J.id!==u0).map((J)=>{let Q=Q8(J.quota);return{accountId:J.id,...Q?{quota:Q}:{}}})}}async function AY(Y,X){if(X.row){let J=Y.source.usableToken(X.row);if(!J)return;let Q=await Y.send(X,J);return Y.recordQuota(Q,X,J),Q}return Y.vault?.send(X.id,async(J,Q)=>{let G=await Y.send(X,J,Q);return Y.recordQuota(G,X,J,Q),G})}async function K3(Y){if(Y.vault)await Y.vault.awaitRoster();else await Y.source.current(),await Y.source.prepareTokens(Y.source.peek().rows,Y.storage);let X=MY(Y),J=Y.replayable===!1&&X.some((G)=>G.id===u0)?X.filter((G)=>G.id===u0):X,Q=aJ($1(Y,J));if(Q)await Q,X=MY(Y);if(Y.mode==="sticky-balanced"&&Y.sessionId&&Y.replayable&&Y.body!==void 0){let G=await Uz(Y,X,Y.sessionId,Y.body);if(G)return G}return Kz(Y,X)}async function Kz(Y,X){let J=sJ(Y.mode),Q=eJ({...$1(Y,X),placement:J,replayable:Y.replayable});if(Q.kind==="block")return Y.log.debug("pool admission blocked the request",{pid:process.pid,reason:Q.block.reason}),{response:Y.blocked(Q.block,G3(X),Y.vault?X.length===0?Y.vault.noRouteCause():void 0:X.length===0?"no-accounts":"unusable"),servedId:u0};if(Q.lastPath)Y.log.debug("pool admission: every account is exhausted; probing anyway",{pid:process.pid,order:Q.order});let G=new Map(X.map((B)=>[B.id,B])),$=W3(Y.storage),W=[],K=new Set,U,Z=!1;for(;;){let B=$3(Q.order.filter((V)=>!K.has(V)),W,$),O=B===void 0?void 0:G.get(B);if(!O)break;let N;try{N=await AY(Y,O)}catch(V){if(Y.isAbort(V)||!U||Y.mode==="fallback-first")throw V;return Y.log.debug("pool fallback attempt threw; stopping",{pid:process.pid,accountId:O.id}),U}if(!N){if(!O.row)Z=!0;K.add(O.id);continue}U?.response.body?.cancel().catch(()=>{}),U={response:N,servedId:O.id},W.push({id:O.id,status:N.status})}if(U)return U;return{response:Y.blocked({reason:"no-credential"},G3(X),Z?"vault-refused":Y.vault?"vault-empty":"unusable"),servedId:u0}}async function Uz(Y,X,J,Q){let G=Buffer.byteLength(Q,"utf8"),$=new Map(X.map((T)=>[T.id,T])),W=$1(Y,X),K=EY(W),U={requestBytes:G,reservePercent:(T)=>Q9(Y.storage,T===u0?void 0:T),resetCredits:Y.resetCredits,onEmptyWeightedSet:()=>{Y.log.debug("sticky routing: no fresh weighted candidates; using configured order")}},Z=(T,w)=>(x,j)=>{let S=new Set(x);return Y.placePin({sessionId:J,requestBytes:G,now:T.now,validPinnedAccountIds:T.rows.map((h)=>h.id).filter((h)=>!w.excluded.has(h)),excludeAccountIds:x,quotaCheckedAtByAccount:Object.fromEntries(T.rows.map((h)=>[h.id,w.projections.get(h.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(X.map((h)=>[h.id,h.identity])),select:(h)=>X3(T,U,S,h),persist:j})},B=Z(W,K),O=B([],!0);if(!O)return;let N=O.accountId,V=(T)=>{let w=B([N],!0);if(!w)return!1;return Y.log.debug("sticky routing: migrated session pin",{pid:process.pid,fromAccountId:N,toAccountId:w.accountId,reason:T}),N=w.accountId,!0},D=J3(W,U,N);if(D.kind==="none")return;if(D.kind==="move"){if(!V(D.reason)&&D.reason==="killswitch")return}else if(D.kind==="detour"){let T=B([N],!1);if(!T)return;Y.log.debug("sticky routing: pinned account awaits a quota reading",{pid:process.pid,pinnedAccountId:N,servedAccountId:T.accountId}),N=T.accountId}let E=$.get(N);if(!E)return;let P=await AY(Y,E);if(!P)return;if(P.status===401||P.status===403||P.status===429){let T=MY(Y);W=$1(Y,T),K=EY(W),B=Z(W,K);let w=Q3(W,K,N,P.status);if(w.action==="migrate"){let x=N;if(V(w.reason)&&N!==x){let j=T.find((h)=>h.id===N),S=j?await AY(Y,j):void 0;if(j&&S){let h=P;P=S,h.body?.cancel().catch(()=>{}),E=j}else N=x}}}return{response:P,servedId:E.id}}function G9(Y){return typeof Y==="number"&&Number.isFinite(Y)}function Hz(Y){if(!e8(Y))return;let X=Y.budget;if(X?.kind!=="reading")return;let{limit:J,used:Q,remaining:G,usedPercent:$,remainingPercent:W}=X;if(!G9(J)||!G9(Q)||!G9(G)||!G9($)||!G9(W))return;return{limit:J,used:Q,remaining:G,usedPercent:$,remainingPercent:W,reached:X.reached,...X.resetsAt!==void 0?{resetsAt:X.resetsAt}:{},...X.unit!==void 0?{unit:X.unit}:{}}}function wY(Y,X){let J=Q8(Y),Q=Hz(Y);if(!J&&!Q)return null;let G=e8(Y)?Y6(Y).checkedAt:void 0;return{...G!==void 0?{checkedAt:G}:{},...J?.primary?{primary:J.primary}:{},...J?.secondary?{secondary:J.secondary}:{},...Q?{spendControl:Q}:{},...X!==void 0?{resetCreditsAvailable:X}:{}}}function U3(Y,X,J,Q){return{main:{quota:null,killed:!1},fallbacks:[],vaultAccounts:Y.map((G)=>{let $=G.quota?.counters?.resetCredits?.value;return{id:G.routeId,label:G.email||G.label||G.routeId,...G.accountIdentity!==void 0?{accountId:G.accountIdentity}:{},quota:wY(G.quota,$),killed:!1,enabled:X.has(G.routeId),...$!==void 0?{resetCredits:$}:{}}}),route:J?.routing?.mode??"main-first",lastUpdated:Q}}function H3(Y,X,J,Q=()=>{return}){let G=Y.find((W)=>W.id===M8),$=G?Q(G.id):void 0;return{main:{quota:G?wY(G.quota,$):null,...G?.identity!==void 0?{mainAccountId:G.identity}:{},killed:!1,...$!==void 0?{resetCredits:$}:{}},fallbacks:Y.filter((W)=>W.id!==M8&&W.enabled).map((W)=>{let K=Q(W.id);return{id:W.id,label:W.label,...W.identity!==void 0?{accountId:W.identity}:{},quota:wY(W.quota,K),killed:!1,enabled:!0,...K!==void 0?{resetCredits:K}:{}}}),route:X?.routing?.mode??"main-first",lastUpdated:J,accountPool:!0}}import{randomUUID as Zz}from"node:crypto";import{chmod as Vz,mkdir as Bz,rename as Lz,rm as V3,writeFile as Nz}from"node:fs/promises";import{homedir as jz}from"node:os";import{join as SY}from"node:path";function B3(){let Y=process.env.XDG_STATE_HOME||SY(jz(),".local","state");return SY(Y,"cortexkit","openai-auth","processes")}function L3(Y=process.pid,X=B3()){return SY(X,`${Y}.json`)}var W1=0,Z3;async function Fz(Y,X){await Bz(Y,{recursive:!0,mode:448}),await Vz(Y,448);let J=L3(X.pid,Y),Q=`${J}.${Zz()}.tmp`;try{await Nz(Q,`${JSON.stringify(X)}
|
|
7
|
-
`,{mode:384}),await Lz(Q,J)}catch(G){throw await V3(Q,{force:!0}).catch(()=>{}),G}return J}async function N3(Y){let X=Y.pid??process.pid,J=Y.dir??B3();Z3??=(Y.now??Date.now)(),W1++;let Q;try{Q=await Fz(J,{pid:X,version:Y.version,startedAt:Z3})}catch($){Y.logger.warn("process heartbeat not written",{dir:J,error:$ instanceof Error?$.message:String($)})}let G=!1;return{path:Q,async release(){if(G)return;if(G=!0,W1=Math.max(0,W1-1),W1>0)return;await V3(L3(X,J),{force:!0}).catch(($)=>{Y.logger.warn("process heartbeat not removed",{dir:J,error:$ instanceof Error?$.message:String($)})})}}}import{resolve as z1}from"node:path";import{resolveClaustrumConnectionPath as Dz}from"@cortexkit/claustrum-client";var Oz=60000,_z=240000,F3=Symbol.for("@cortexkit/openai-auth/opencode-vaults"),D3=globalThis,$9=D3[F3]??new Map;D3[F3]=$9;function O3(Y,X){let J=Boolean(Y.connectScoped||Y.connectEnrollment),Q=z1(Y.stateDir),G=z1((Y.connectionFile??Dz)()),$=JSON.stringify([Y.host,Q,G,z1(X.configPath),z1(X.statePath)]),W={reservedRouteIds:Y.reservedRouteIds??(()=>[])},K=J?void 0:$9.get($);if(!K){let B=new Set;if(K={vault:new j3({...Y,stateDir:Q,connectionFile:()=>G,...!J?{projectRoot:Q}:{},reservedRouteIds:()=>new Set([...B].flatMap((N)=>[...N.reservedRouteIds()]))}),holders:B,firstRoster:Promise.withResolvers(),started:!1},!J)$9.set($,K)}K.holders.add(W);let U=K,Z=!1;return{vault:U.vault,firstRoster:U.firstRoster.promise,start(){if(Z||U.started)return;U.started=!0;let B=async()=>{if(U.holders.size&&await U.vault.authority()!=="local")await U.vault.pollStale(_z)};U.vault.start(),U.vault.firstRoster().finally(()=>{U.firstRoster.resolve(),B()}),U.quotaPoll=setInterval(B,Oz),U.quotaPoll.unref?.()},release(){if(Z)return;if(Z=!0,U.holders.delete(W),U.holders.size!==0)return;if(U.quotaPoll)clearInterval(U.quotaPoll);if(U.vault.close(),U.firstRoster.resolve(),!J&&$9.get($)===U)$9.delete($)}}}var M3=900000,Pz=0.016666666666666666,_3=0.000001;function bY(Y,X){for(let J of[Y?.primary?.checkedAt,Y?.checkedAt,X])if(typeof J==="number"&&Number.isFinite(J))return J;return}function kY(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let X=bY(Y.quota,Y.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||Y.now-X>M3)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let J=IY(Y.quota).sort((G,$)=>{let W=G.windowMs,K=$.windowMs,U=typeof W==="number"&&Number.isFinite(W),Z=typeof K==="number"&&Number.isFinite(K);if(U!==Z)return U?-1:1;if(U&&Z)return K-W;return 0});for(let{key:G,window:$}of J)if(Number.isFinite($.remainingPercent)&&$.remainingPercent<=0)return{action:"migrate",reason:"exhausted",windowKey:G,...typeof $.resetsAt==="string"?{resetsAt:$.resetsAt}:{}};let Q=E3(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 P3(Y,X,J){let Q=Math.max(0,Y.remainingPercent-X);if(Q<=0)return 0;if(!Y.resetsAt)return Q;let G=Date.parse(Y.resetsAt);if(!Number.isFinite(G)||G<=J)return Q;let $=Math.max((G-J)/3600000,Pz);return Q/$}function q3(Y,X){if(Y<X)return-1;if(Y>X)return 1;return 0}function qz(Y,X){if(!Y.quota)return;let J=bY(Y.quota,Y.quotaCheckedAt);if(J===void 0||X-J>M3)return;let Q=IY(Y.quota).map(({key:W,window:K})=>{return P3(K,Y.reservePercent[W]??0,X)}),G=Y.quota.spendControl;if(G&&Number.isFinite(G.remainingPercent))Q.push(P3(G,0,X));let $=Q.length>0?Math.min(...Q):0;return $>0?{candidate:Y,quotaCheckedAt:J,weight:$}:void 0}function A3(Y){let X=Y.candidates.filter((G)=>G.killswitchPasses!==!1);if(Y.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if(X.length===0)return;let J=X.map((G)=>qz(G,Y.now)).filter((G)=>G!==void 0);if(J.length>0){J.sort(($,W)=>{let K=((Y.pendingBytes.get($.candidate.accountId)??0)+Y.requestBytes)/Math.max($.weight,_3),U=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,_3);return K-U||$.candidate.configuredOrder-W.candidate.configuredOrder||q3($.candidate.accountId,W.candidate.accountId)});let G=J[0];if(G)return{accountId:G.candidate.accountId,quotaCheckedAt:G.quotaCheckedAt,source:"weighted"}}Y.onEmptyWeightedSet?.();let Q=[...X].sort((G,$)=>{let W=(G.resetCreditsApplicable??0)>0?1:0;return(($.resetCreditsApplicable??0)>0?1:0)-W||G.configuredOrder-$.configuredOrder||q3(G.accountId,$.accountId)})[0];if(!Q)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Q.accountId,quotaCheckedAt:bY(Q.quota,Q.quotaCheckedAt),source:"mode-fallback"}}import{createHash as cz}from"node:crypto";import{createHash as Ez,randomBytes as T3}from"node:crypto";import{chmod as Mz,lstat as R3,mkdir as Az,open as Tz,readdir as h3,rename as Rz,unlink as gY,writeFile as Cz}from"node:fs/promises";import{join as K1,resolve as xY}from"node:path";var wz=100,vY="session-unknown",Sz=300000,Iz=60000,bz=600000,kz=/\.(body|meta|request|response)\.json$/,xz=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-\d+-\d{6,}-[a-zA-Z0-9._-]+$/,vz=/\.[a-f0-9]{24}\.partial$/;function y3(Y){let X=Y.replace(kz,"");if(X===Y||!xz.test(X))return;return X}function hz(Y){let X=Y.replace(vz,"");return X!==Y&&y3(X)!==void 0}async function C3(Y){let{dir:X,maxBytes:J}=Y,Q=Y.now??Date.now(),G=Y.minAgeMs??Iz,$=Y.partialStaleMs??bz,W={removed:0,freedBytes:0};if(!(J>0))return W;try{if(F8)await I3(X,"directory");if((await R3(X)).isSymbolicLink())return W;let K=new Set((Y.protectedPaths??[]).map((P)=>xY(P))),U=await h3(X,{withFileTypes:!0}),Z=[];await Promise.all(U.map(async(P)=>{if(!P.isFile())return;let T=hz(P.name),w=T?void 0:y3(P.name);if(!T&&w===void 0)return;let x=K1(X,P.name);try{let j=await R3(x);if(!j.isFile())return;Z.push({path:x,size:j.size,mtimeMs:j.mtimeMs,group:w})}catch{}}));let B=Z.reduce((P,T)=>P+T.size,0),O=0,N=0,V=async(P)=>{try{await gY(P.path),B-=P.size,N+=P.size,O+=1}catch{}};for(let P of Z){if(P.group!==void 0)continue;if(K.has(xY(P.path)))continue;if(Q-P.mtimeMs<$)continue;await V(P)}let D=new Map;for(let P of Z){if(P.group===void 0)continue;let T=D.get(P.group)??{files:[],newest:0};T.files.push(P),T.newest=Math.max(T.newest,P.mtimeMs),D.set(P.group,T)}let E=[...D.entries()].sort(([P,T],[w,x])=>T.newest-x.newest||P.localeCompare(w));for(let[,P]of E){if(B<=J)break;if(Q-P.newest<G)continue;if(P.files.some((T)=>K.has(xY(T.path))))continue;for(let T of P.files)await V(T)}if(O>0)Y.logger?.debug("removed old dump files",{removed:O,freedBytes:N});return{removed:O,freedBytes:N}}catch(K){if(K instanceof z9&&K.code==="ERR_PRIVATE_FILES_SECURITY")throw K;return W}}async function yz(Y,X,J){if(F8)return x3(Y,X,{stagePath:`${Y}.${J?J():T3(12).toString("hex")}.partial`});for(let Q=0;;Q+=1){let G=`${Y}.${J?J():T3(12).toString("hex")}.partial`,$=!1,W;try{W=await Tz(G,"wx",384),$=!0,await W.writeFile(X,"utf8"),await W.chmod(384),await W.close(),W=void 0,await Rz(G,Y);return}catch(K){if(await W?.close().catch(()=>{}),$)await gY(G).catch(()=>{});if(K.code==="EEXIST"&&Q===0)continue;throw K}}}function hY(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function W9(Y,X){let J=Y.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!J)return X;return J.slice(0,80)}function w3(Y){return Ez("sha256").update(Y).digest("hex")}function gz(Y){return Y.toLowerCase().replace(/[-_]/g,"")}function S3(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function fz(Y,X){if(Y===void 0)return null;if(Y===X)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:Y.length,currentBytes:X.length};let J=0;while(J<Y.length&&J<X.length&&Y[J]===X[J])J++;let Q=Y.length-1,G=X.length-1;while(Q>=J&&G>=J&&Y[Q]===X[G])Q--,G--;return{changed:!0,firstByte:J,lastPreviousByte:Q,lastCurrentByte:G,changedPreviousBytes:Q-J+1,changedCurrentBytes:G-J+1,previousBytes:Y.length,currentBytes:X.length}}var mz=0;function g3(Y){let X=Y.enabled===!0,J=Y.pid??process.pid,Q=Y.now??Date.now,G=Y.logger,$=new Set((Y.secretKeys??[]).map(gz)),W=v3({extraSecretKeys:(M)=>$.has(M),extraValuePatterns:[...Y.secretPatterns??[]]}),K=new Set(Y.schemaKeys??["tools"]),U=new Map,Z=()=>typeof Y.dir==="function"?Y.dir():Y.dir;function B(M){let y=W.redact({[M]:null})[M];return y===null?void 0:y}function O(M){if(Array.isArray(M))return M.map(O);if(S3(M)){let y={};for(let[n,o]of Object.entries(M)){let V0=B(n);if(K.has(n))y[n]=W.redactStrings(o);else if(V0!==void 0)y[n]=V0;else y[n]=O(o)}return y}return W.redactStrings(M)}function N(M){let y;try{y=JSON.parse(M)}catch{return{text:W.redactStrings(M),parsed:void 0}}let n=O(y),o=JSON.stringify(n);return{text:JSON.stringify(y)===o?M:o,parsed:S3(n)?n:void 0}}async function V(M,y,n,o){let V0=`-${W9(y,vY)}-${W9(n,"channel")}`,u;try{u=await h3(M)}catch{return}let G0=u.filter((J0)=>J0.endsWith(".meta.json")&&J0.includes(V0)).sort().reverse();for(let J0 of G0)try{if(JSON.parse(await yY(K1(M,J0),F8))?.baselineKey!==o)continue;return await yY(K1(M,J0.replace(/\.meta\.json$/,".body.json")),F8)}catch(T0){if(T0 instanceof z9&&(F8||T0.code==="ERR_PRIVATE_FILES_SECURITY"))throw T0}return}function D(M,y){if(!U.has(M))while(U.size>=wz){let n=U.keys().next().value;if(n===void 0)break;U.delete(n)}U.set(M,y)}async function E(M){if(!X)return;let y=++mz,n=M.session?.trim()||vY,o=Z(),V0=new Date(Q()).toISOString(),u=[V0.replace(/[:.]/g,"-"),String(J),String(y).padStart(6,"0"),W9(n,vY),W9(M.channel,"channel"),...M.phase?[W9(M.phase,"phase")]:[]].join("-"),G0=K1(o,u),J0={body:`${G0}.body.json`,metadata:`${G0}.meta.json`,request:`${G0}.request.json`},T0=w3(`${M.channel}\x00${n}`);try{if(F8)await b3(o);else await Az(o,{recursive:!0,mode:448}),await Mz(o,448);let v=U.get(T0),x0=v===void 0?void 0:"memory";if(v===void 0){if(v=await V(o,n,M.channel,T0),v!==void 0)x0="disk"}let R0=N(M.bodyText),H0={id:u,createdAt:V0,pid:J,session:hY(n),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:T0,bodyBytes:Buffer.byteLength(M.bodyText,"utf8"),bodyHash:w3(M.bodyText),diff:fz(v,R0.text),baselineSource:x0,body:R0.parsed?{parseable:!0,...Y.summarize?.(R0.parsed)}:{parseable:!1},...M.meta?{extra:O(M.meta)}:{},files:J0},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())}),_0=(d,g)=>F8?k3(d,g):Cz(d,g,{encoding:"utf8",mode:384,flag:"wx"}),l=[[J0.body,R0.text],[J0.metadata,`${JSON.stringify(H0,null,2)}
|
|
8
|
-
`],[J0.request,`${JSON.stringify(r,null,2)}
|
|
9
|
-
`]],I=await Promise.allSettled(l.map(([d,g])=>_0(d,g))),p=I.find((d)=>d.status==="rejected");if(p){if(Y.cleanupFailedDumps)await P(l,I);throw p.reason}return D(T0,R0.text),G?.debug("dumped request",{id:u,session:hY(n),body:J0.body}),S(o,Object.values(J0)),{id:u,files:J0,responseFile:`${G0}.response.json`}}catch(v){if(v instanceof z9&&(F8||v.code==="ERR_PRIVATE_FILES_SECURITY"))throw v;G?.warn("request dump failed",{session:hY(n),error:v instanceof Error?v.message:String(v)});return}}async function P(M,y){await Promise.all(M.map(async([n],o)=>{let V0=y[o];if(V0?.status==="rejected"&&V0.reason?.code==="EEXIST")return;await gY(n).catch(()=>{})}))}let T=Y.maxBytes??0,w=Y.sweepIntervalMs??Sz,x=0;function j(M,y){return{dir:M,maxBytes:T,protectedPaths:y,now:Q(),minAgeMs:Y.sweepMinAgeMs,partialStaleMs:Y.partialStaleMs,logger:G}}function S(M,y){if(!(T>0))return;let n=Q();if(n-x<w)return;x=n,C3(j(M,y))}async function h(M,y){if(!M)return;let n=O({status:y.status,requestId:y.requestId,usage:y.usage,...y.fields,complete:y.complete??!0});try{return await yz(M.responseFile,`${JSON.stringify(n,null,2)}
|
|
10
|
-
`,Y.stageName),M.responseFile}catch(o){if(o instanceof z9&&(F8||o.code==="ERR_PRIVATE_FILES_SECURITY"))throw o;G?.warn("response dump failed",{id:M.id,error:o instanceof Error?o.message:String(o)});return}}return{isEnabled:()=>X,setEnabled:(M)=>{X=M},dump:E,dumpResponse:h,sweep:(M)=>C3(j(Z(),M))}}var m3=B0("dump"),y8="x-cortexkit-openai-auth-dump-session",uz=["chatgpt-account-id","email","org_name","organization_name"],pz=["tools"];function fY(Y){return cz("sha256").update(JSON.stringify(Y)).digest("hex")}function lz(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function dz(Y){let X=Array.isArray(Y.input)?Y.input:[],J=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:X.length,inputHash:fY(X),inputBytes:JSON.stringify(X).length,firstInputHash:X[0]===void 0?null:fY(X[0]),toolsCount:J.length,toolTypes:J.map(lz),toolsHash:fY(J),clientMetadataKeys:Q?Object.keys(Q).sort():[]}}function iz(){return g3({dir:()=>r0().dumpDir,logger:m3,secretKeys:uz,schemaKeys:pz,summarize:dz})}var f3=iz();async function w6(Y){let X=r0().dump===!0;if(f3.setEnabled(X),!X)return;let J=typeof Y.bodyText==="function"?Y.bodyText():Y.bodyText;await f3.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 G6(Y){if(!r0().dump)return;m3.debug("diagnostic",Y)}import{readFile as nz}from"node:fs/promises";import{homedir as oz}from"node:os";import{join as c3}from"node:path";var rz="https://models.dev/api.json",sz="OPENCODE_OPENAI_AUTH_MODELS_CACHE",az="OPENCODE_MODELS_PATH",tz="OPENCODE_DISABLE_MODELS_FETCH",ez=1e4,YK=300000;function g8(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function u3(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function mY(Y){let{input:X,output:J}=Y;if(typeof X!=="number"||!Number.isFinite(X)||X<0)return null;if(typeof J!=="number"||!Number.isFinite(J)||J<0)return null;let Q=u3(Y.cache_read),G=u3(Y.cache_write);if(Q===null||G===null)return null;return{input:X,output:J,cache:{read:Q,write:G}}}function XK(Y){let X=g8(Y);if(!X)return null;let J=mY(X);if(!J)return null;let Q=J;if(Array.isArray(X.tiers)){let W=[];for(let K of X.tiers){let U=g8(K);if(!U)continue;let Z=g8(U.tier),B=Z?.size;if(Z?.type!=="context")continue;if(typeof B!=="number"||!Number.isFinite(B)||B<=0)continue;let O=mY(U);if(!O)continue;W.push({...O,tier:{type:"context",size:B}})}if(W.length>0)Q.tiers=W}let G=g8(X.context_over_200k),$=G?mY(G):null;if($)Q.experimentalOver200K=$;return Q}function p3(Y){let X=g8(Y),J=g8(X?.openai),Q=g8(J?.models);if(!Q)return null;let G={};for(let[$,W]of Object.entries(Q)){let K=g8(W),U=XK(K?.cost);if(U)G[$]=U}return Object.keys(G).length>0?G:null}function JK(){let Y=process.env[sz]?.trim();if(Y)return Y;let X=process.env[az]?.trim();if(X)return X;let J=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||c3(oz(),".cache");return c3(J,"opencode","models.json")}function QK(){let Y=process.env[tz]?.toLowerCase();return Y==="true"||Y==="1"}async function GK(){try{let Y=p3(JSON.parse(await nz(JK(),"utf8")));if(Y)return Y}catch{}if(QK())return null;try{let Y=await fetch(rz,{signal:AbortSignal.timeout(ez)});if(!Y.ok)return null;return p3(await Y.json())}catch{return null}}var S6;function l3(){let Y=Date.now();if(S6&&S6.expiresAt>Y)return S6.promise;let X={expiresAt:Y+YK,promise:GK()};return S6=X,X.promise.then((J)=>{if(J===null&&S6===X)S6=void 0}),X.promise}function I6(Y){return typeof Y==="object"&&Y!==null}function $K(Y){if(Array.isArray(Y))return Y;if(I6(Y)&&Array.isArray(Y.data))return Y.data;return[]}function WK(Y){if(!I6(Y)||!I6(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function d3(Y){if(!I6(Y)||!I6(Y.info))return null;let X=Y.info,J=I6(X.model)?X.model:void 0,Q=typeof X.agent==="string"?X.agent:void 0,G=typeof J?.providerID==="string"?J.providerID:typeof X.providerID==="string"?X.providerID:void 0,$=typeof J?.modelID==="string"?J.modelID:typeof X.modelID==="string"?X.modelID:void 0,W=typeof J?.variant==="string"?J.variant:typeof X.variant==="string"?X.variant:void 0;if(!Q&&(!G||!$)&&!W)return null;let K={};if(Q)K.agent=Q;if(G&&$)K.model={providerID:G,modelID:$};if(W)K.variant=W;return K}function i3(Y,X){return{agent:Y.agent??X.agent,model:Y.model??X.model,variant:Y.variant??X.variant}}function n3(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function o3(Y,X){if(!Y||!X)return null;let J=Y;if(typeof J.session?.messages!=="function")return null;let Q=[];try{Q=$K(await Promise.resolve(J.session.messages({path:{id:X},query:{limit:100}})))}catch{return null}if(Q.length===0)return null;let G={};for(let $=Q.length-1;$>=0;$--){if(WK(Q[$])!=="assistant")continue;let W=d3(Q[$]);if(!W)continue;if(G=i3(G,W),n3(G))return G}for(let $=Q.length-1;$>=0;$--){let W=d3(Q[$]);if(!W)continue;if(G=i3(G,W),n3(G))return G}if(!G.agent&&!G.model&&!G.variant)return null;return G}var zK=B0("rpc"),s3="__openaiAuthRpcServers";function a3(Y){return r3({...Y,isManagedDir:u9,log:zK,drain:(X,J)=>Y.drain(X,J),apply:async(X)=>await Y.apply(X)})}function b6(Y){return JSON.stringify(cY(Y))??"undefined"}function cY(Y){if(Array.isArray(Y))return Y.map(cY);if(!s(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((X)=>[X,cY(Y[X])]))}var KK=512,UK=2097152;function uY(Y,X){if(typeof Y==="function"||typeof X==="function")return!1;if(X!==null&&typeof X==="object"&&Object.hasOwn(X,"toJSON")&&typeof X.toJSON==="function")return!1;if(Y===X)return!0;if(Array.isArray(Y))return Array.isArray(X)&&Y.length===X.length&&Y.every(($,W)=>uY($,X[W]));if(Y===null||X===null||typeof Y!=="object"||typeof X!=="object"||Array.isArray(X))return!1;let J=Y,Q=X,G=Object.keys(J);return G.length===Object.keys(Q).length&&G.every(($)=>Object.prototype.propertyIsEnumerable.call(Q,$)&&uY(J[$],Q[$]))}function $6(Y,X){let J=[],Q=[],G=0;for(let $=0;$<Y.length;$++){let W=X?.texts[$],K=W!==void 0&&uY(X?.snapshots[$],Y[$]),U=K?W:b6(Y[$]);J.push(U),Q.push(K?X?.snapshots[$]:U==="undefined"?void 0:JSON.parse(U)),G+=U.length}return{texts:J,snapshots:Q,retainable:Y.length<=KK&&G<=UK}}function K9(Y){return Y.retainable?Y:void 0}function U9(Y,X){if(Y.texts.length>X.texts.length)return;for(let J=0;J<Y.texts.length;J++)if(Y.texts[J]!==X.texts[J])return;return Y.texts.length}function W6(){let Y=crypto.getRandomValues(new Uint8Array(16)),X=Date.now();Y[0]=X/1099511627776&255,Y[1]=X/4294967296&255,Y[2]=X/16777216&255,Y[3]=X/65536&255,Y[4]=X/256&255,Y[5]=X&255,Y[6]=(Y[6]??0)&15|112,Y[8]=(Y[8]??0)&63|128;let J=Array.from(Y,(Q)=>Q.toString(16).padStart(2,"0")).join("");return`${J.slice(0,8)}-${J.slice(8,12)}-${J.slice(12,16)}-${J.slice(16,20)}-${J.slice(20)}`}var b8={};dY(b8,{withoutInternalHeaders:()=>nG,sanitizeHttpFallbackBody:()=>BY,orderCodexBody:()=>T9,hasWebSocketResponsesLiteMetadata:()=>VY,createWebSocketFetch:()=>oV,applyTurnId:()=>cG,advanceTurn:()=>m4,TITLE_HEADER:()=>f4,QUOTA_ACCOUNT_HEADER:()=>k1,OpenAIWebSocketPool:()=>b8,CODEX_BODY_KEY_ORDER:()=>fG});import{createHash as pV}from"node:crypto";var HK=Symbol.for("vercel.ai.error"),R8=class Y extends Error{constructor({name:X,message:J,cause:Q}){super(J);this[HK]=!0,this.name=X,this.cause=Q}static isInstance(X){return Y.hasMarker(X,"vercel.ai.error")}static hasMarker(X,J){let Q=Symbol.for(J);return X!=null&&typeof X==="object"&&Q in X&&typeof X[Q]==="boolean"&&X[Q]===!0}},ZK="AI_DecisionUnsupportedQuestionTypeError",JF=`vercel.ai.error.${ZK}`;var t3="AI_APICallError",e3=`vercel.ai.error.${t3}`,VK=Symbol.for(e3),z6=class extends R8{constructor({message:Y,url:X,requestBodyValues:J,statusCode:Q,responseHeaders:G,responseBody:$,cause:W,isRetryable:K=Q!=null&&(Q===408||Q===409||Q===429||Q>=500),data:U}){super({name:t3,message:Y,cause:W});this[VK]=!0,this.url=X,this.requestBodyValues=J,this.statusCode=Q,this.responseHeaders=G,this.responseBody=$,this.isRetryable=K,this.data=U}static isInstance(Y){return R8.hasMarker(Y,e3)}},BK="AI_EmptyResponseBodyError",QF=`vercel.ai.error.${BK}`;var LK="AI_DecisionRefusalError",GF=`vercel.ai.error.${LK}`;var Y2="AI_InvalidArgumentError",X2=`vercel.ai.error.${Y2}`,NK=Symbol.for(X2),pY=class extends R8{constructor({message:Y,cause:X,argument:J}){super({name:Y2,message:Y,cause:X});this[NK]=!0,this.argument=J}static isInstance(Y){return R8.hasMarker(Y,X2)}},jK="AI_InvalidPromptError",$F=`vercel.ai.error.${jK}`;var FK="AI_InvalidResponseDataError",WF=`vercel.ai.error.${FK}`;var DK="AI_JSONParseError",zF=`vercel.ai.error.${DK}`;var OK="AI_LoadAPIKeyError",KF=`vercel.ai.error.${OK}`;var _K="AI_LoadSettingError",UF=`vercel.ai.error.${_K}`;var PK="AI_NoContentGeneratedError",HF=`vercel.ai.error.${PK}`;var qK="AI_NoSuchModelError",ZF=`vercel.ai.error.${qK}`;var EK="AI_NoSuchProviderReferenceError",VF=`vercel.ai.error.${EK}`;var MK="AI_TooManyEmbeddingValuesForCallError",BF=`vercel.ai.error.${MK}`;var AK="AI_TypeValidationError",LF=`vercel.ai.error.${AK}`;var TK="AI_UnsupportedFunctionalityError",NF=`vercel.ai.error.${TK}`;var OF=Object.freeze({status:"aborted"});function _(Y,X,J){function Q(K,U){var Z;Object.defineProperty(K,"_zod",{value:K._zod??{},enumerable:!1}),(Z=K._zod).traits??(Z.traits=new Set),K._zod.traits.add(Y),X(K,U);for(let B in W.prototype)if(!(B in K))Object.defineProperty(K,B,{value:W.prototype[B].bind(K)});K._zod.constr=W,K._zod.def=U}let G=J?.Parent??Object;class $ extends G{}Object.defineProperty($,"name",{value:Y});function W(K){var U;let Z=J?.Parent?new $:this;Q(Z,K),(U=Z._zod).deferred??(U.deferred=[]);for(let B of Z._zod.deferred)B();return Z}return Object.defineProperty(W,"init",{value:Q}),Object.defineProperty(W,Symbol.hasInstance,{value:(K)=>{if(J?.Parent&&K instanceof J.Parent)return!0;return K?._zod?.traits?.has(Y)}}),Object.defineProperty(W,"name",{value:Y}),W}var _F=Symbol("zod_brand");class C8 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class H9 extends Error{constructor(Y){super(`Encountered unidirectional transform during encode: ${Y}`);this.name="ZodEncodeError"}}var U1={};function D8(Y){if(Y)Object.assign(U1,Y);return U1}var Q0={};dY(Q0,{unwrapMessage:()=>Z9,uint8ArrayToHex:()=>tK,uint8ArrayToBase64url:()=>sK,uint8ArrayToBase64:()=>U2,stringifyPrimitive:()=>$2,shallowClone:()=>Q2,safeExtend:()=>lK,required:()=>nK,randomString:()=>yK,propertyKeyTypes:()=>oY,promiseAllObject:()=>hK,primitiveTypes:()=>G2,prefixIssues:()=>S8,pick:()=>cK,partial:()=>iK,optionalKeys:()=>rY,omit:()=>uK,objectClone:()=>kK,numKeys:()=>gK,nullish:()=>B9,normalizeParams:()=>i,mergeDefs:()=>m8,merge:()=>dK,jsonStringifyReplacer:()=>k6,joinValues:()=>bK,issue:()=>v6,isPlainObject:()=>c8,isObject:()=>K6,hexToUint8Array:()=>aK,getSizableOrigin:()=>z2,getParsedType:()=>fK,getLengthableOrigin:()=>N9,getEnumValues:()=>V9,getElementAtPath:()=>vK,floatSafeRemainder:()=>iY,finalizeIssue:()=>$8,extend:()=>pK,escapeRegex:()=>w8,esc:()=>H1,defineLazy:()=>$0,createTransparentProxy:()=>mK,cloneDef:()=>xK,clone:()=>G8,cleanRegex:()=>L9,cleanEnum:()=>oK,captureStackTrace:()=>Z1,cached:()=>x6,base64urlToUint8Array:()=>rK,base64ToUint8Array:()=>K2,assignProp:()=>f8,assertNotEqual:()=>CK,assertNever:()=>SK,assertIs:()=>wK,assertEqual:()=>RK,assert:()=>IK,allowsEval:()=>nY,aborted:()=>u8,NUMBER_FORMAT_RANGES:()=>sY,Class:()=>H2,BIGINT_FORMAT_RANGES:()=>W2});function RK(Y){return Y}function CK(Y){return Y}function wK(Y){}function SK(Y){throw Error()}function IK(Y){}function V9(Y){let X=Object.values(Y).filter((Q)=>typeof Q==="number");return Object.entries(Y).filter(([Q,G])=>X.indexOf(+Q)===-1).map(([Q,G])=>G)}function bK(Y,X="|"){return Y.map((J)=>$2(J)).join(X)}function k6(Y,X){if(typeof X==="bigint")return X.toString();return X}function x6(Y){return{get value(){{let J=Y();return Object.defineProperty(this,"value",{value:J}),J}throw Error("cached value already set")}}}function B9(Y){return Y===null||Y===void 0}function L9(Y){let X=Y.startsWith("^")?1:0,J=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(X,J)}function iY(Y,X){let J=(Y.toString().split(".")[1]||"").length,Q=X.toString(),G=(Q.split(".")[1]||"").length;if(G===0&&/\d?e-\d?/.test(Q)){let U=Q.match(/\d?e-(\d?)/);if(U?.[1])G=Number.parseInt(U[1])}let $=J>G?J:G,W=Number.parseInt(Y.toFixed($).replace(".","")),K=Number.parseInt(X.toFixed($).replace(".",""));return W%K/10**$}var J2=Symbol("evaluating");function $0(Y,X,J){let Q=void 0;Object.defineProperty(Y,X,{get(){if(Q===J2)return;if(Q===void 0)Q=J2,Q=J();return Q},set(G){Object.defineProperty(Y,X,{value:G})},configurable:!0})}function kK(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function f8(Y,X,J){Object.defineProperty(Y,X,{value:J,writable:!0,enumerable:!0,configurable:!0})}function m8(...Y){let X={};for(let J of Y){let Q=Object.getOwnPropertyDescriptors(J);Object.assign(X,Q)}return Object.defineProperties({},X)}function xK(Y){return m8(Y._zod.def)}function vK(Y,X){if(!X)return Y;return X.reduce((J,Q)=>J?.[Q],Y)}function hK(Y){let X=Object.keys(Y),J=X.map((Q)=>Y[Q]);return Promise.all(J).then((Q)=>{let G={};for(let $=0;$<X.length;$++)G[X[$]]=Q[$];return G})}function yK(Y=10){let J="";for(let Q=0;Q<Y;Q++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function H1(Y){return JSON.stringify(Y)}var Z1="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function K6(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var nY=x6(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function c8(Y){if(K6(Y)===!1)return!1;let X=Y.constructor;if(X===void 0)return!0;let J=X.prototype;if(K6(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function Q2(Y){if(c8(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function gK(Y){let X=0;for(let J in Y)if(Object.prototype.hasOwnProperty.call(Y,J))X++;return X}var fK=(Y)=>{let X=typeof Y;switch(X){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: ${X}`)}},oY=new Set(["string","number","symbol"]),G2=new Set(["string","number","bigint","boolean","symbol","undefined"]);function w8(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function G8(Y,X,J){let Q=new Y._zod.constr(X??Y._zod.def);if(!X||J?.parent)Q._zod.parent=Y;return Q}function i(Y){let X=Y;if(!X)return{};if(typeof X==="string")return{error:()=>X};if(X?.message!==void 0){if(X?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");X.error=X.message}if(delete X.message,typeof X.error==="string")return{...X,error:()=>X.error};return X}function mK(Y){let X;return new Proxy({},{get(J,Q,G){return X??(X=Y()),Reflect.get(X,Q,G)},set(J,Q,G,$){return X??(X=Y()),Reflect.set(X,Q,G,$)},has(J,Q){return X??(X=Y()),Reflect.has(X,Q)},deleteProperty(J,Q){return X??(X=Y()),Reflect.deleteProperty(X,Q)},ownKeys(J){return X??(X=Y()),Reflect.ownKeys(X)},getOwnPropertyDescriptor(J,Q){return X??(X=Y()),Reflect.getOwnPropertyDescriptor(X,Q)},defineProperty(J,Q,G){return X??(X=Y()),Reflect.defineProperty(X,Q,G)}})}function $2(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function rY(Y){return Object.keys(Y).filter((X)=>{return Y[X]._zod.optin==="optional"&&Y[X]._zod.optout==="optional"})}var sY={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]},W2={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function cK(Y,X){let J=Y._zod.def,Q=m8(Y._zod.def,{get shape(){let G={};for(let $ in X){if(!($ in J.shape))throw Error(`Unrecognized key: "${$}"`);if(!X[$])continue;G[$]=J.shape[$]}return f8(this,"shape",G),G},checks:[]});return G8(Y,Q)}function uK(Y,X){let J=Y._zod.def,Q=m8(Y._zod.def,{get shape(){let G={...Y._zod.def.shape};for(let $ in X){if(!($ in J.shape))throw Error(`Unrecognized key: "${$}"`);if(!X[$])continue;delete G[$]}return f8(this,"shape",G),G},checks:[]});return G8(Y,Q)}function pK(Y,X){if(!c8(X))throw Error("Invalid input to extend: expected a plain object");let J=Y._zod.def.checks;if(J&&J.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let G=m8(Y._zod.def,{get shape(){let $={...Y._zod.def.shape,...X};return f8(this,"shape",$),$},checks:[]});return G8(Y,G)}function lK(Y,X){if(!c8(X))throw Error("Invalid input to safeExtend: expected a plain object");let J={...Y._zod.def,get shape(){let Q={...Y._zod.def.shape,...X};return f8(this,"shape",Q),Q},checks:Y._zod.def.checks};return G8(Y,J)}function dK(Y,X){let J=m8(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape,...X._zod.def.shape};return f8(this,"shape",Q),Q},get catchall(){return X._zod.def.catchall},checks:[]});return G8(Y,J)}function iK(Y,X,J){let Q=m8(X._zod.def,{get shape(){let G=X._zod.def.shape,$={...G};if(J)for(let W in J){if(!(W in G))throw Error(`Unrecognized key: "${W}"`);if(!J[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 f8(this,"shape",$),$},checks:[]});return G8(X,Q)}function nK(Y,X,J){let Q=m8(X._zod.def,{get shape(){let G=X._zod.def.shape,$={...G};if(J)for(let W in J){if(!(W in $))throw Error(`Unrecognized key: "${W}"`);if(!J[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 f8(this,"shape",$),$},checks:[]});return G8(X,Q)}function u8(Y,X=0){if(Y.aborted===!0)return!0;for(let J=X;J<Y.issues.length;J++)if(Y.issues[J]?.continue!==!0)return!0;return!1}function S8(Y,X){return X.map((J)=>{var Q;return(Q=J).path??(Q.path=[]),J.path.unshift(Y),J})}function Z9(Y){return typeof Y==="string"?Y:Y?.message}function $8(Y,X,J){let Q={...Y,path:Y.path??[]};if(!Y.message){let G=Z9(Y.inst?._zod.def?.error?.(Y))??Z9(X?.error?.(Y))??Z9(J.customError?.(Y))??Z9(J.localeError?.(Y))??"Invalid input";Q.message=G}if(delete Q.inst,delete Q.continue,!X?.reportInput)delete Q.input;return Q}function z2(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function N9(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function v6(...Y){let[X,J,Q]=Y;if(typeof X==="string")return{message:X,code:"custom",input:J,inst:Q};return{...X}}function oK(Y){return Object.entries(Y).filter(([X,J])=>{return Number.isNaN(Number.parseInt(X,10))}).map((X)=>X[1])}function K2(Y){let X=atob(Y),J=new Uint8Array(X.length);for(let Q=0;Q<X.length;Q++)J[Q]=X.charCodeAt(Q);return J}function U2(Y){let X="";for(let J=0;J<Y.length;J++)X+=String.fromCharCode(Y[J]);return btoa(X)}function rK(Y){let X=Y.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-X.length%4)%4);return K2(X+J)}function sK(Y){return U2(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function aK(Y){let X=Y.replace(/^0x/,"");if(X.length%2!==0)throw Error("Invalid hex string length");let J=new Uint8Array(X.length/2);for(let Q=0;Q<X.length;Q+=2)J[Q/2]=Number.parseInt(X.slice(Q,Q+2),16);return J}function tK(Y){return Array.from(Y).map((X)=>X.toString(16).padStart(2,"0")).join("")}class H2{constructor(...Y){}}var Z2=(Y,X)=>{Y.name="$ZodError",Object.defineProperty(Y,"_zod",{value:Y._zod,enumerable:!1}),Object.defineProperty(Y,"issues",{value:X,enumerable:!1}),Y.message=JSON.stringify(X,k6,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},V1=_("$ZodError",Z2),aY=_("$ZodError",Z2,{Parent:Error});function V2(Y,X=(J)=>J.message){let J={},Q=[];for(let G of Y.issues)if(G.path.length>0)J[G.path[0]]=J[G.path[0]]||[],J[G.path[0]].push(X(G));else Q.push(X(G));return{formErrors:Q,fieldErrors:J}}function B2(Y,X){let J=X||function($){return $.message},Q={_errors:[]},G=($)=>{for(let W of $.issues)if(W.code==="invalid_union"&&W.errors.length)W.errors.map((K)=>G({issues:K}));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(J(W));else{let K=Q,U=0;while(U<W.path.length){let Z=W.path[U];if(U!==W.path.length-1)K[Z]=K[Z]||{_errors:[]};else K[Z]=K[Z]||{_errors:[]},K[Z]._errors.push(J(W));K=K[Z],U++}}};return G(Y),Q}var B1=(Y)=>(X,J,Q,G)=>{let $=Q?Object.assign(Q,{async:!1}):{async:!1},W=X._zod.run({value:J,issues:[]},$);if(W instanceof Promise)throw new C8;if(W.issues.length){let K=new(G?.Err??Y)(W.issues.map((U)=>$8(U,$,D8())));throw Z1(K,G?.callee),K}return W.value};var L1=(Y)=>async(X,J,Q,G)=>{let $=Q?Object.assign(Q,{async:!0}):{async:!0},W=X._zod.run({value:J,issues:[]},$);if(W instanceof Promise)W=await W;if(W.issues.length){let K=new(G?.Err??Y)(W.issues.map((U)=>$8(U,$,D8())));throw Z1(K,G?.callee),K}return W.value};var j9=(Y)=>(X,J,Q)=>{let G=Q?{...Q,async:!1}:{async:!1},$=X._zod.run({value:J,issues:[]},G);if($ instanceof Promise)throw new C8;return $.issues.length?{success:!1,error:new(Y??V1)($.issues.map((W)=>$8(W,G,D8())))}:{success:!0,data:$.value}},L2=j9(aY),F9=(Y)=>async(X,J,Q)=>{let G=Q?Object.assign(Q,{async:!0}):{async:!0},$=X._zod.run({value:J,issues:[]},G);if($ instanceof Promise)$=await $;return $.issues.length?{success:!1,error:new Y($.issues.map((W)=>$8(W,G,D8())))}:{success:!0,data:$.value}},N2=F9(aY),j2=(Y)=>(X,J,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return B1(Y)(X,J,G)};var F2=(Y)=>(X,J,Q)=>{return B1(Y)(X,J,Q)};var D2=(Y)=>async(X,J,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return L1(Y)(X,J,G)};var O2=(Y)=>async(X,J,Q)=>{return L1(Y)(X,J,Q)};var _2=(Y)=>(X,J,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return j9(Y)(X,J,G)};var P2=(Y)=>(X,J,Q)=>{return j9(Y)(X,J,Q)};var q2=(Y)=>async(X,J,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return F9(Y)(X,J,G)};var E2=(Y)=>async(X,J,Q)=>{return F9(Y)(X,J,Q)};var M2=/^[cC][^\s-]{8,}$/,A2=/^[0-9a-z]+$/,T2=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,R2=/^[0-9a-vA-V]{20}$/,C2=/^[A-Za-z0-9]{27}$/,w2=/^[a-zA-Z0-9_-]{21}$/,S2=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var I2=/^([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})$/,tY=(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 b2=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function k2(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var x2=/^(?:(?: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])$/,v2=/^(([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}|:))$/,h2=/^((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])$/,y2=/^(([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])$/,g2=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,eY=/^[A-Za-z0-9_-]*$/,f2=/^(?=.{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 m2=/^\+(?:[0-9]){6,14}[0-9]$/,c2="(?:(?:\\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])))",u2=new RegExp(`^${c2}$`);function p2(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 l2(Y){return new RegExp(`^${p2(Y)}$`)}function d2(Y){let X=p2({precision:Y.precision}),J=["Z"];if(Y.local)J.push("");if(Y.offset)J.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let Q=`${X}(?:${J.join("|")})`;return new RegExp(`^${c2}T(?:${Q})$`)}var i2=(Y)=>{let X=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${X}$`)};var n2=/^-?\d+$/,o2=/^-?\d+(?:\.\d+)?/,r2=/^(?:true|false)$/i,s2=/^null$/i;var a2=/^[^A-Z]*$/,t2=/^[^a-z]*$/;var k0=_("$ZodCheck",(Y,X)=>{var J;Y._zod??(Y._zod={}),Y._zod.def=X,(J=Y._zod).onattach??(J.onattach=[])}),e2={number:"number",bigint:"bigint",object:"date"},Y4=_("$ZodCheckLessThan",(Y,X)=>{k0.init(Y,X);let J=e2[typeof X.value];Y._zod.onattach.push((Q)=>{let G=Q._zod.bag,$=(X.inclusive?G.maximum:G.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(X.value<$)if(X.inclusive)G.maximum=X.value;else G.exclusiveMaximum=X.value}),Y._zod.check=(Q)=>{if(X.inclusive?Q.value<=X.value:Q.value<X.value)return;Q.issues.push({origin:J,code:"too_big",maximum:X.value,input:Q.value,inclusive:X.inclusive,inst:Y,continue:!X.abort})}}),X4=_("$ZodCheckGreaterThan",(Y,X)=>{k0.init(Y,X);let J=e2[typeof X.value];Y._zod.onattach.push((Q)=>{let G=Q._zod.bag,$=(X.inclusive?G.minimum:G.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(X.value>$)if(X.inclusive)G.minimum=X.value;else G.exclusiveMinimum=X.value}),Y._zod.check=(Q)=>{if(X.inclusive?Q.value>=X.value:Q.value>X.value)return;Q.issues.push({origin:J,code:"too_small",minimum:X.value,input:Q.value,inclusive:X.inclusive,inst:Y,continue:!X.abort})}}),Y7=_("$ZodCheckMultipleOf",(Y,X)=>{k0.init(Y,X),Y._zod.onattach.push((J)=>{var Q;(Q=J._zod.bag).multipleOf??(Q.multipleOf=X.value)}),Y._zod.check=(J)=>{if(typeof J.value!==typeof X.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof J.value==="bigint"?J.value%X.value===BigInt(0):iY(J.value,X.value)===0)return;J.issues.push({origin:typeof J.value,code:"not_multiple_of",divisor:X.value,input:J.value,inst:Y,continue:!X.abort})}}),X7=_("$ZodCheckNumberFormat",(Y,X)=>{k0.init(Y,X),X.format=X.format||"float64";let J=X.format?.includes("int"),Q=J?"int":"number",[G,$]=sY[X.format];Y._zod.onattach.push((W)=>{let K=W._zod.bag;if(K.format=X.format,K.minimum=G,K.maximum=$,J)K.pattern=n2}),Y._zod.check=(W)=>{let K=W.value;if(J){if(!Number.isInteger(K)){W.issues.push({expected:Q,format:X.format,code:"invalid_type",continue:!1,input:K,inst:Y});return}if(!Number.isSafeInteger(K)){if(K>0)W.issues.push({input:K,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:Q,continue:!X.abort});else W.issues.push({input:K,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:Q,continue:!X.abort});return}}if(K<G)W.issues.push({origin:"number",input:K,code:"too_small",minimum:G,inclusive:!0,inst:Y,continue:!X.abort});if(K>$)W.issues.push({origin:"number",input:K,code:"too_big",maximum:$,inst:Y})}});var J7=_("$ZodCheckMaxLength",(Y,X)=>{var J;k0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let G=Q.value;return!B9(G)&&G.length!==void 0}),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(X.maximum<G)Q._zod.bag.maximum=X.maximum}),Y._zod.check=(Q)=>{let G=Q.value;if(G.length<=X.maximum)return;let W=N9(G);Q.issues.push({origin:W,code:"too_big",maximum:X.maximum,inclusive:!0,input:G,inst:Y,continue:!X.abort})}}),Q7=_("$ZodCheckMinLength",(Y,X)=>{var J;k0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let G=Q.value;return!B9(G)&&G.length!==void 0}),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(X.minimum>G)Q._zod.bag.minimum=X.minimum}),Y._zod.check=(Q)=>{let G=Q.value;if(G.length>=X.minimum)return;let W=N9(G);Q.issues.push({origin:W,code:"too_small",minimum:X.minimum,inclusive:!0,input:G,inst:Y,continue:!X.abort})}}),G7=_("$ZodCheckLengthEquals",(Y,X)=>{var J;k0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let G=Q.value;return!B9(G)&&G.length!==void 0}),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.minimum=X.length,G.maximum=X.length,G.length=X.length}),Y._zod.check=(Q)=>{let G=Q.value,$=G.length;if($===X.length)return;let W=N9(G),K=$>X.length;Q.issues.push({origin:W,...K?{code:"too_big",maximum:X.length}:{code:"too_small",minimum:X.length},inclusive:!0,exact:!0,input:Q.value,inst:Y,continue:!X.abort})}}),D9=_("$ZodCheckStringFormat",(Y,X)=>{var J,Q;if(k0.init(Y,X),Y._zod.onattach.push((G)=>{let $=G._zod.bag;if($.format=X.format,X.pattern)$.patterns??($.patterns=new Set),$.patterns.add(X.pattern)}),X.pattern)(J=Y._zod).check??(J.check=(G)=>{if(X.pattern.lastIndex=0,X.pattern.test(G.value))return;G.issues.push({origin:"string",code:"invalid_format",format:X.format,input:G.value,...X.pattern?{pattern:X.pattern.toString()}:{},inst:Y,continue:!X.abort})});else(Q=Y._zod).check??(Q.check=()=>{})}),$7=_("$ZodCheckRegex",(Y,X)=>{D9.init(Y,X),Y._zod.check=(J)=>{if(X.pattern.lastIndex=0,X.pattern.test(J.value))return;J.issues.push({origin:"string",code:"invalid_format",format:"regex",input:J.value,pattern:X.pattern.toString(),inst:Y,continue:!X.abort})}}),W7=_("$ZodCheckLowerCase",(Y,X)=>{X.pattern??(X.pattern=a2),D9.init(Y,X)}),z7=_("$ZodCheckUpperCase",(Y,X)=>{X.pattern??(X.pattern=t2),D9.init(Y,X)}),K7=_("$ZodCheckIncludes",(Y,X)=>{k0.init(Y,X);let J=w8(X.includes),Q=new RegExp(typeof X.position==="number"?`^.{${X.position}}${J}`:J);X.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(X.includes,X.position))return;G.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:X.includes,input:G.value,inst:Y,continue:!X.abort})}}),U7=_("$ZodCheckStartsWith",(Y,X)=>{k0.init(Y,X);let J=new RegExp(`^${w8(X.prefix)}.*`);X.pattern??(X.pattern=J),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(J)}),Y._zod.check=(Q)=>{if(Q.value.startsWith(X.prefix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:X.prefix,input:Q.value,inst:Y,continue:!X.abort})}}),H7=_("$ZodCheckEndsWith",(Y,X)=>{k0.init(Y,X);let J=new RegExp(`.*${w8(X.suffix)}$`);X.pattern??(X.pattern=J),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(J)}),Y._zod.check=(Q)=>{if(Q.value.endsWith(X.suffix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:X.suffix,input:Q.value,inst:Y,continue:!X.abort})}});var Z7=_("$ZodCheckOverwrite",(Y,X)=>{k0.init(Y,X),Y._zod.check=(J)=>{J.value=X.tx(J.value)}});class J4{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 J=Y.split(`
|
|
11
|
-
`).filter(($)=>$),Q=Math.min(...J.map(($)=>$.length-$.trimStart().length)),G=J.map(($)=>$.slice(Q)).map(($)=>" ".repeat(this.indent*2)+$);for(let $ of G)this.content.push($)}compile(){let Y=Function,X=this?.args,Q=[...(this?.content??[""]).map((G)=>` ${G}`)];return new Y(...X,Q.join(`
|
|
12
|
-
`))}}var B7={major:4,minor:1,patch:8};var j0=_("$ZodType",(Y,X)=>{var J;Y??(Y={}),Y._zod.def=X,Y._zod.bag=Y._zod.bag||{},Y._zod.version=B7;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)(J=Y._zod).deferred??(J.deferred=[]),Y._zod.deferred?.push(()=>{Y._zod.run=Y._zod.parse});else{let G=(W,K,U)=>{let Z=u8(W),B;for(let O of K){if(O._zod.def.when){if(!O._zod.def.when(W))continue}else if(Z)continue;let N=W.issues.length,V=O._zod.check(W);if(V instanceof Promise&&U?.async===!1)throw new C8;if(B||V instanceof Promise)B=(B??Promise.resolve()).then(async()=>{if(await V,W.issues.length===N)return;if(!Z)Z=u8(W,N)});else{if(W.issues.length===N)continue;if(!Z)Z=u8(W,N)}}if(B)return B.then(()=>{return W});return W},$=(W,K,U)=>{if(u8(W))return W.aborted=!0,W;let Z=G(K,Q,U);if(Z instanceof Promise){if(U.async===!1)throw new C8;return Z.then((B)=>Y._zod.parse(B,U))}return Y._zod.parse(Z,U)};Y._zod.run=(W,K)=>{if(K.skipChecks)return Y._zod.parse(W,K);if(K.direction==="backward"){let Z=Y._zod.parse({value:W.value,issues:[]},{...K,skipChecks:!0});if(Z instanceof Promise)return Z.then((B)=>{return $(B,W,K)});return $(Z,W,K)}let U=Y._zod.parse(W,K);if(U instanceof Promise){if(K.async===!1)throw new C8;return U.then((Z)=>G(Z,Q,K))}return G(U,Q,K)}}Y["~standard"]={validate:(G)=>{try{let $=L2(Y,G);return $.success?{value:$.data}:{issues:$.error?.issues}}catch($){return N2(Y,G).then((W)=>W.success?{value:W.data}:{issues:W.error?.issues})}},vendor:"zod",version:1}}),D1=_("$ZodString",(Y,X)=>{j0.init(Y,X),Y._zod.pattern=[...Y?._zod.bag?.patterns??[]].pop()??i2(Y._zod.bag),Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=String(J.value)}catch(G){}if(typeof J.value==="string")return J;return J.issues.push({expected:"string",code:"invalid_type",input:J.value,inst:Y}),J}}),F0=_("$ZodStringFormat",(Y,X)=>{D9.init(Y,X),D1.init(Y,X)}),q7=_("$ZodGUID",(Y,X)=>{X.pattern??(X.pattern=I2),F0.init(Y,X)}),E7=_("$ZodUUID",(Y,X)=>{if(X.version){let Q={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[X.version];if(Q===void 0)throw Error(`Invalid UUID version: "${X.version}"`);X.pattern??(X.pattern=tY(Q))}else X.pattern??(X.pattern=tY());F0.init(Y,X)}),M7=_("$ZodEmail",(Y,X)=>{X.pattern??(X.pattern=b2),F0.init(Y,X)}),A7=_("$ZodURL",(Y,X)=>{F0.init(Y,X),Y._zod.check=(J)=>{try{let Q=J.value.trim(),G=new URL(Q);if(X.hostname){if(X.hostname.lastIndex=0,!X.hostname.test(G.hostname))J.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:f2.source,input:J.value,inst:Y,continue:!X.abort})}if(X.protocol){if(X.protocol.lastIndex=0,!X.protocol.test(G.protocol.endsWith(":")?G.protocol.slice(0,-1):G.protocol))J.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:X.protocol.source,input:J.value,inst:Y,continue:!X.abort})}if(X.normalize)J.value=G.href;else J.value=Q;return}catch(Q){J.issues.push({code:"invalid_format",format:"url",input:J.value,inst:Y,continue:!X.abort})}}}),T7=_("$ZodEmoji",(Y,X)=>{X.pattern??(X.pattern=k2()),F0.init(Y,X)}),R7=_("$ZodNanoID",(Y,X)=>{X.pattern??(X.pattern=w2),F0.init(Y,X)}),C7=_("$ZodCUID",(Y,X)=>{X.pattern??(X.pattern=M2),F0.init(Y,X)}),w7=_("$ZodCUID2",(Y,X)=>{X.pattern??(X.pattern=A2),F0.init(Y,X)}),S7=_("$ZodULID",(Y,X)=>{X.pattern??(X.pattern=T2),F0.init(Y,X)}),I7=_("$ZodXID",(Y,X)=>{X.pattern??(X.pattern=R2),F0.init(Y,X)}),b7=_("$ZodKSUID",(Y,X)=>{X.pattern??(X.pattern=C2),F0.init(Y,X)}),k7=_("$ZodISODateTime",(Y,X)=>{X.pattern??(X.pattern=d2(X)),F0.init(Y,X)}),x7=_("$ZodISODate",(Y,X)=>{X.pattern??(X.pattern=u2),F0.init(Y,X)}),v7=_("$ZodISOTime",(Y,X)=>{X.pattern??(X.pattern=l2(X)),F0.init(Y,X)}),h7=_("$ZodISODuration",(Y,X)=>{X.pattern??(X.pattern=S2),F0.init(Y,X)}),y7=_("$ZodIPv4",(Y,X)=>{X.pattern??(X.pattern=x2),F0.init(Y,X),Y._zod.onattach.push((J)=>{let Q=J._zod.bag;Q.format="ipv4"})}),g7=_("$ZodIPv6",(Y,X)=>{X.pattern??(X.pattern=v2),F0.init(Y,X),Y._zod.onattach.push((J)=>{let Q=J._zod.bag;Q.format="ipv6"}),Y._zod.check=(J)=>{try{new URL(`http://[${J.value}]`)}catch{J.issues.push({code:"invalid_format",format:"ipv6",input:J.value,inst:Y,continue:!X.abort})}}}),f7=_("$ZodCIDRv4",(Y,X)=>{X.pattern??(X.pattern=h2),F0.init(Y,X)}),m7=_("$ZodCIDRv6",(Y,X)=>{X.pattern??(X.pattern=y2),F0.init(Y,X),Y._zod.check=(J)=>{let Q=J.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{J.issues.push({code:"invalid_format",format:"cidrv6",input:J.value,inst:Y,continue:!X.abort})}}});function c7(Y){if(Y==="")return!0;if(Y.length%4!==0)return!1;try{return atob(Y),!0}catch{return!1}}var u7=_("$ZodBase64",(Y,X)=>{X.pattern??(X.pattern=g2),F0.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64"}),Y._zod.check=(J)=>{if(c7(J.value))return;J.issues.push({code:"invalid_format",format:"base64",input:J.value,inst:Y,continue:!X.abort})}});function YU(Y){if(!eY.test(Y))return!1;let X=Y.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),J=X.padEnd(Math.ceil(X.length/4)*4,"=");return c7(J)}var p7=_("$ZodBase64URL",(Y,X)=>{X.pattern??(X.pattern=eY),F0.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64url"}),Y._zod.check=(J)=>{if(YU(J.value))return;J.issues.push({code:"invalid_format",format:"base64url",input:J.value,inst:Y,continue:!X.abort})}}),l7=_("$ZodE164",(Y,X)=>{X.pattern??(X.pattern=m2),F0.init(Y,X)});function XU(Y,X=null){try{let J=Y.split(".");if(J.length!==3)return!1;let[Q]=J;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(X&&(!("alg"in G)||G.alg!==X))return!1;return!0}catch{return!1}}var d7=_("$ZodJWT",(Y,X)=>{F0.init(Y,X),Y._zod.check=(J)=>{if(XU(J.value,X.alg))return;J.issues.push({code:"invalid_format",format:"jwt",input:J.value,inst:Y,continue:!X.abort})}});var G4=_("$ZodNumber",(Y,X)=>{j0.init(Y,X),Y._zod.pattern=Y._zod.bag.pattern??o2,Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=Number(J.value)}catch(W){}let G=J.value;if(typeof G==="number"&&!Number.isNaN(G)&&Number.isFinite(G))return J;let $=typeof G==="number"?Number.isNaN(G)?"NaN":!Number.isFinite(G)?"Infinity":void 0:void 0;return J.issues.push({expected:"number",code:"invalid_type",input:G,inst:Y,...$?{received:$}:{}}),J}}),i7=_("$ZodNumber",(Y,X)=>{X7.init(Y,X),G4.init(Y,X)}),n7=_("$ZodBoolean",(Y,X)=>{j0.init(Y,X),Y._zod.pattern=r2,Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=Boolean(J.value)}catch($){}let G=J.value;if(typeof G==="boolean")return J;return J.issues.push({expected:"boolean",code:"invalid_type",input:G,inst:Y}),J}});var o7=_("$ZodNull",(Y,X)=>{j0.init(Y,X),Y._zod.pattern=s2,Y._zod.values=new Set([null]),Y._zod.parse=(J,Q)=>{let G=J.value;if(G===null)return J;return J.issues.push({expected:"null",code:"invalid_type",input:G,inst:Y}),J}});var r7=_("$ZodUnknown",(Y,X)=>{j0.init(Y,X),Y._zod.parse=(J)=>J}),s7=_("$ZodNever",(Y,X)=>{j0.init(Y,X),Y._zod.parse=(J,Q)=>{return J.issues.push({expected:"never",code:"invalid_type",input:J.value,inst:Y}),J}});function L7(Y,X,J){if(Y.issues.length)X.issues.push(...S8(J,Y.issues));X.value[J]=Y.value}var a7=_("$ZodArray",(Y,X)=>{j0.init(Y,X),Y._zod.parse=(J,Q)=>{let G=J.value;if(!Array.isArray(G))return J.issues.push({expected:"array",code:"invalid_type",input:G,inst:Y}),J;J.value=Array(G.length);let $=[];for(let W=0;W<G.length;W++){let K=G[W],U=X.element._zod.run({value:K,issues:[]},Q);if(U instanceof Promise)$.push(U.then((Z)=>L7(Z,J,W)));else L7(U,J,W)}if($.length)return Promise.all($).then(()=>J);return J}});function F1(Y,X,J,Q){if(Y.issues.length)X.issues.push(...S8(J,Y.issues));if(Y.value===void 0){if(J in Q)X.value[J]=void 0}else X.value[J]=Y.value}function t7(Y){let X=Object.keys(Y.shape);for(let Q of X)if(!Y.shape?.[Q]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${Q}": expected a Zod schema`);let J=rY(Y.shape);return{...Y,keys:X,keySet:new Set(X),numKeys:X.length,optionalKeys:new Set(J)}}function e7(Y,X,J,Q,G,$){let W=[],K=G.keySet,U=G.catchall._zod,Z=U.def.type;for(let B of Object.keys(X)){if(K.has(B))continue;if(Z==="never"){W.push(B);continue}let O=U.run({value:X[B],issues:[]},Q);if(O instanceof Promise)Y.push(O.then((N)=>F1(N,J,B,X)));else F1(O,J,B,X)}if(W.length)J.issues.push({code:"unrecognized_keys",keys:W,input:X,inst:$});if(!Y.length)return J;return Promise.all(Y).then(()=>{return J})}var JU=_("$ZodObject",(Y,X)=>{j0.init(Y,X);let J=x6(()=>t7(X));$0(Y._zod,"propValues",()=>{let W=X.shape,K={};for(let U in W){let Z=W[U]._zod;if(Z.values){K[U]??(K[U]=new Set);for(let B of Z.values)K[U].add(B)}}return K});let Q=K6,G=X.catchall,$;Y._zod.parse=(W,K)=>{$??($=J.value);let U=W.value;if(!Q(U))return W.issues.push({expected:"object",code:"invalid_type",input:U,inst:Y}),W;W.value={};let Z=[],B=$.shape;for(let O of $.keys){let V=B[O]._zod.run({value:U[O],issues:[]},K);if(V instanceof Promise)Z.push(V.then((D)=>F1(D,W,O,U)));else F1(V,W,O,U)}if(!G)return Z.length?Promise.all(Z).then(()=>W):W;return e7(Z,U,W,K,J.value,Y)}}),Y5=_("$ZodObjectJIT",(Y,X)=>{JU.init(Y,X);let J=Y._zod.parse,Q=x6(()=>t7(X)),G=(N)=>{let V=new J4(["shape","payload","ctx"]),D=Q.value,E=(x)=>{let j=H1(x);return`shape[${j}]._zod.run({ value: input[${j}], issues: [] }, ctx)`};V.write("const input = payload.value;");let P=Object.create(null),T=0;for(let x of D.keys)P[x]=`key_${T++}`;V.write("const newResult = {};");for(let x of D.keys){let j=P[x],S=H1(x);V.write(`const ${j} = ${E(x)};`),V.write(`
|
|
13
|
-
if (${j}.issues.length) {
|
|
14
|
-
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
|
|
15
|
-
...iss,
|
|
16
|
-
path: iss.path ? [${S}, ...iss.path] : [${S}]
|
|
17
|
-
})));
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
if (${j}.value === undefined) {
|
|
22
|
-
if (${S} in input) {
|
|
23
|
-
newResult[${S}] = undefined;
|
|
24
|
-
}
|
|
25
|
-
} else {
|
|
26
|
-
newResult[${S}] = ${j}.value;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
`)}V.write("payload.value = newResult;"),V.write("return payload;");let w=V.compile();return(x,j)=>w(N,x,j)},$,W=K6,K=!U1.jitless,Z=K&&nY.value,B=X.catchall,O;Y._zod.parse=(N,V)=>{O??(O=Q.value);let D=N.value;if(!W(D))return N.issues.push({expected:"object",code:"invalid_type",input:D,inst:Y}),N;if(K&&Z&&V?.async===!1&&V.jitless!==!0){if(!$)$=G(X.shape);if(N=$(N,V),!B)return N;return e7([],D,N,V,O,Y)}return J(N,V)}});function N7(Y,X,J,Q){for(let $ of Y)if($.issues.length===0)return X.value=$.value,X;let G=Y.filter(($)=>!u8($));if(G.length===1)return X.value=G[0].value,G[0];return X.issues.push({code:"invalid_union",input:X.value,inst:J,errors:Y.map(($)=>$.issues.map((W)=>$8(W,Q,D8())))}),X}var $4=_("$ZodUnion",(Y,X)=>{j0.init(Y,X),$0(Y._zod,"optin",()=>X.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),$0(Y._zod,"optout",()=>X.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),$0(Y._zod,"values",()=>{if(X.options.every((G)=>G._zod.values))return new Set(X.options.flatMap((G)=>Array.from(G._zod.values)));return}),$0(Y._zod,"pattern",()=>{if(X.options.every((G)=>G._zod.pattern)){let G=X.options.map(($)=>$._zod.pattern);return new RegExp(`^(${G.map(($)=>L9($.source)).join("|")})$`)}return});let J=X.options.length===1,Q=X.options[0]._zod.run;Y._zod.parse=(G,$)=>{if(J)return Q(G,$);let W=!1,K=[];for(let U of X.options){let Z=U._zod.run({value:G.value,issues:[]},$);if(Z instanceof Promise)K.push(Z),W=!0;else{if(Z.issues.length===0)return Z;K.push(Z)}}if(!W)return N7(K,G,Y,$);return Promise.all(K).then((U)=>{return N7(U,G,Y,$)})}}),X5=_("$ZodDiscriminatedUnion",(Y,X)=>{$4.init(Y,X);let J=Y._zod.parse;$0(Y._zod,"propValues",()=>{let G={};for(let $ of X.options){let W=$._zod.propValues;if(!W||Object.keys(W).length===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf($)}"`);for(let[K,U]of Object.entries(W)){if(!G[K])G[K]=new Set;for(let Z of U)G[K].add(Z)}}return G});let Q=x6(()=>{let G=X.options,$=new Map;for(let W of G){let K=W._zod.propValues?.[X.discriminator];if(!K||K.size===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf(W)}"`);for(let U of K){if($.has(U))throw Error(`Duplicate discriminator value "${String(U)}"`);$.set(U,W)}}return $});Y._zod.parse=(G,$)=>{let W=G.value;if(!K6(W))return G.issues.push({code:"invalid_type",expected:"object",input:W,inst:Y}),G;let K=Q.value.get(W?.[X.discriminator]);if(K)return K._zod.run(G,$);if(X.unionFallback)return J(G,$);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:X.discriminator,input:W,path:[X.discriminator],inst:Y}),G}}),J5=_("$ZodIntersection",(Y,X)=>{j0.init(Y,X),Y._zod.parse=(J,Q)=>{let G=J.value,$=X.left._zod.run({value:G,issues:[]},Q),W=X.right._zod.run({value:G,issues:[]},Q);if($ instanceof Promise||W instanceof Promise)return Promise.all([$,W]).then(([U,Z])=>{return j7(J,U,Z)});return j7(J,$,W)}});function Q4(Y,X){if(Y===X)return{valid:!0,data:Y};if(Y instanceof Date&&X instanceof Date&&+Y===+X)return{valid:!0,data:Y};if(c8(Y)&&c8(X)){let J=Object.keys(X),Q=Object.keys(Y).filter(($)=>J.indexOf($)!==-1),G={...Y,...X};for(let $ of Q){let W=Q4(Y[$],X[$]);if(!W.valid)return{valid:!1,mergeErrorPath:[$,...W.mergeErrorPath]};G[$]=W.data}return{valid:!0,data:G}}if(Array.isArray(Y)&&Array.isArray(X)){if(Y.length!==X.length)return{valid:!1,mergeErrorPath:[]};let J=[];for(let Q=0;Q<Y.length;Q++){let G=Y[Q],$=X[Q],W=Q4(G,$);if(!W.valid)return{valid:!1,mergeErrorPath:[Q,...W.mergeErrorPath]};J.push(W.data)}return{valid:!0,data:J}}return{valid:!1,mergeErrorPath:[]}}function j7(Y,X,J){if(X.issues.length)Y.issues.push(...X.issues);if(J.issues.length)Y.issues.push(...J.issues);if(u8(Y))return Y;let Q=Q4(X.value,J.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return Y.value=Q.data,Y}var Q5=_("$ZodRecord",(Y,X)=>{j0.init(Y,X),Y._zod.parse=(J,Q)=>{let G=J.value;if(!c8(G))return J.issues.push({expected:"record",code:"invalid_type",input:G,inst:Y}),J;let $=[];if(X.keyType._zod.values){let W=X.keyType._zod.values;J.value={};for(let U of W)if(typeof U==="string"||typeof U==="number"||typeof U==="symbol"){let Z=X.valueType._zod.run({value:G[U],issues:[]},Q);if(Z instanceof Promise)$.push(Z.then((B)=>{if(B.issues.length)J.issues.push(...S8(U,B.issues));J.value[U]=B.value}));else{if(Z.issues.length)J.issues.push(...S8(U,Z.issues));J.value[U]=Z.value}}let K;for(let U in G)if(!W.has(U))K=K??[],K.push(U);if(K&&K.length>0)J.issues.push({code:"unrecognized_keys",input:G,inst:Y,keys:K})}else{J.value={};for(let W of Reflect.ownKeys(G)){if(W==="__proto__")continue;let K=X.keyType._zod.run({value:W,issues:[]},Q);if(K instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(K.issues.length){J.issues.push({code:"invalid_key",origin:"record",issues:K.issues.map((Z)=>$8(Z,Q,D8())),input:W,path:[W],inst:Y}),J.value[K.value]=K.value;continue}let U=X.valueType._zod.run({value:G[W],issues:[]},Q);if(U instanceof Promise)$.push(U.then((Z)=>{if(Z.issues.length)J.issues.push(...S8(W,Z.issues));J.value[K.value]=Z.value}));else{if(U.issues.length)J.issues.push(...S8(W,U.issues));J.value[K.value]=U.value}}}if($.length)return Promise.all($).then(()=>J);return J}});var G5=_("$ZodEnum",(Y,X)=>{j0.init(Y,X);let J=V9(X.entries),Q=new Set(J);Y._zod.values=Q,Y._zod.pattern=new RegExp(`^(${J.filter((G)=>oY.has(typeof G)).map((G)=>typeof G==="string"?w8(G):G.toString()).join("|")})$`),Y._zod.parse=(G,$)=>{let W=G.value;if(Q.has(W))return G;return G.issues.push({code:"invalid_value",values:J,input:W,inst:Y}),G}}),$5=_("$ZodLiteral",(Y,X)=>{if(j0.init(Y,X),X.values.length===0)throw Error("Cannot create literal schema with no valid values");Y._zod.values=new Set(X.values),Y._zod.pattern=new RegExp(`^(${X.values.map((J)=>typeof J==="string"?w8(J):J?w8(J.toString()):String(J)).join("|")})$`),Y._zod.parse=(J,Q)=>{let G=J.value;if(Y._zod.values.has(G))return J;return J.issues.push({code:"invalid_value",values:X.values,input:G,inst:Y}),J}});var W5=_("$ZodTransform",(Y,X)=>{j0.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new H9(Y.constructor.name);let G=X.transform(J.value,J);if(Q.async)return(G instanceof Promise?G:Promise.resolve(G)).then((W)=>{return J.value=W,J});if(G instanceof Promise)throw new C8;return J.value=G,J}});function F7(Y,X){if(Y.issues.length&&X===void 0)return{issues:[],value:void 0};return Y}var z5=_("$ZodOptional",(Y,X)=>{j0.init(Y,X),Y._zod.optin="optional",Y._zod.optout="optional",$0(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,void 0]):void 0}),$0(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${L9(J.source)})?$`):void 0}),Y._zod.parse=(J,Q)=>{if(X.innerType._zod.optin==="optional"){let G=X.innerType._zod.run(J,Q);if(G instanceof Promise)return G.then(($)=>F7($,J.value));return F7(G,J.value)}if(J.value===void 0)return J;return X.innerType._zod.run(J,Q)}}),K5=_("$ZodNullable",(Y,X)=>{j0.init(Y,X),$0(Y._zod,"optin",()=>X.innerType._zod.optin),$0(Y._zod,"optout",()=>X.innerType._zod.optout),$0(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${L9(J.source)}|null)$`):void 0}),$0(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,null]):void 0}),Y._zod.parse=(J,Q)=>{if(J.value===null)return J;return X.innerType._zod.run(J,Q)}}),U5=_("$ZodDefault",(Y,X)=>{j0.init(Y,X),Y._zod.optin="optional",$0(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);if(J.value===void 0)return J.value=X.defaultValue,J;let G=X.innerType._zod.run(J,Q);if(G instanceof Promise)return G.then(($)=>D7($,X));return D7(G,X)}});function D7(Y,X){if(Y.value===void 0)Y.value=X.defaultValue;return Y}var H5=_("$ZodPrefault",(Y,X)=>{j0.init(Y,X),Y._zod.optin="optional",$0(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);if(J.value===void 0)J.value=X.defaultValue;return X.innerType._zod.run(J,Q)}}),Z5=_("$ZodNonOptional",(Y,X)=>{j0.init(Y,X),$0(Y._zod,"values",()=>{let J=X.innerType._zod.values;return J?new Set([...J].filter((Q)=>Q!==void 0)):void 0}),Y._zod.parse=(J,Q)=>{let G=X.innerType._zod.run(J,Q);if(G instanceof Promise)return G.then(($)=>O7($,Y));return O7(G,Y)}});function O7(Y,X){if(!Y.issues.length&&Y.value===void 0)Y.issues.push({code:"invalid_type",expected:"nonoptional",input:Y.value,inst:X});return Y}var V5=_("$ZodCatch",(Y,X)=>{j0.init(Y,X),$0(Y._zod,"optin",()=>X.innerType._zod.optin),$0(Y._zod,"optout",()=>X.innerType._zod.optout),$0(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);let G=X.innerType._zod.run(J,Q);if(G instanceof Promise)return G.then(($)=>{if(J.value=$.value,$.issues.length)J.value=X.catchValue({...J,error:{issues:$.issues.map((W)=>$8(W,Q,D8()))},input:J.value}),J.issues=[];return J});if(J.value=G.value,G.issues.length)J.value=X.catchValue({...J,error:{issues:G.issues.map(($)=>$8($,Q,D8()))},input:J.value}),J.issues=[];return J}});var B5=_("$ZodPipe",(Y,X)=>{j0.init(Y,X),$0(Y._zod,"values",()=>X.in._zod.values),$0(Y._zod,"optin",()=>X.in._zod.optin),$0(Y._zod,"optout",()=>X.out._zod.optout),$0(Y._zod,"propValues",()=>X.in._zod.propValues),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward"){let $=X.out._zod.run(J,Q);if($ instanceof Promise)return $.then((W)=>j1(W,X.in,Q));return j1($,X.in,Q)}let G=X.in._zod.run(J,Q);if(G instanceof Promise)return G.then(($)=>j1($,X.out,Q));return j1(G,X.out,Q)}});function j1(Y,X,J){if(Y.issues.length)return Y.aborted=!0,Y;return X._zod.run({value:Y.value,issues:Y.issues},J)}var L5=_("$ZodReadonly",(Y,X)=>{j0.init(Y,X),$0(Y._zod,"propValues",()=>X.innerType._zod.propValues),$0(Y._zod,"values",()=>X.innerType._zod.values),$0(Y._zod,"optin",()=>X.innerType._zod.optin),$0(Y._zod,"optout",()=>X.innerType._zod.optout),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);let G=X.innerType._zod.run(J,Q);if(G instanceof Promise)return G.then(_7);return _7(G)}});function _7(Y){return Y.value=Object.freeze(Y.value),Y}var N5=_("$ZodLazy",(Y,X)=>{j0.init(Y,X),$0(Y._zod,"innerType",()=>X.getter()),$0(Y._zod,"pattern",()=>Y._zod.innerType._zod.pattern),$0(Y._zod,"propValues",()=>Y._zod.innerType._zod.propValues),$0(Y._zod,"optin",()=>Y._zod.innerType._zod.optin??void 0),$0(Y._zod,"optout",()=>Y._zod.innerType._zod.optout??void 0),Y._zod.parse=(J,Q)=>{return Y._zod.innerType._zod.run(J,Q)}}),j5=_("$ZodCustom",(Y,X)=>{k0.init(Y,X),j0.init(Y,X),Y._zod.parse=(J,Q)=>{return J},Y._zod.check=(J)=>{let Q=J.value,G=X.fn(Q);if(G instanceof Promise)return G.then(($)=>P7($,J,Q,Y));P7(G,J,Q,Y);return}});function P7(Y,X,J,Q){if(!Y){let G={code:"custom",input:J,inst:Q,path:[...Q._zod.def.path??[]],continue:!Q._zod.def.abort};if(Q._zod.def.params)G.params=Q._zod.def.params;X.issues.push(v6(G))}}var vF=Symbol("ZodOutput"),hF=Symbol("ZodInput");class O1{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Y,...X){let J=X[0];if(this._map.set(Y,J),J&&typeof J==="object"&&"id"in J){if(this._idmap.has(J.id))throw Error(`ID ${J.id} already exists in the registry`);this._idmap.set(J.id,Y)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Y){let X=this._map.get(Y);if(X&&typeof X==="object"&&"id"in X)this._idmap.delete(X.id);return this._map.delete(Y),this}get(Y){let X=Y._zod.parent;if(X){let J={...this.get(X)??{}};delete J.id;let Q={...J,...this._map.get(Y)};return Object.keys(Q).length?Q:void 0}return this._map.get(Y)}has(Y){return this._map.has(Y)}}function QU(){return new O1}var U6=QU();function F5(Y,X){return new Y({type:"string",...i(X)})}function D5(Y,X){return new Y({type:"string",format:"email",check:"string_format",abort:!1,...i(X)})}function W4(Y,X){return new Y({type:"string",format:"guid",check:"string_format",abort:!1,...i(X)})}function O5(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...i(X)})}function _5(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...i(X)})}function P5(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...i(X)})}function q5(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...i(X)})}function E5(Y,X){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...i(X)})}function M5(Y,X){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...i(X)})}function A5(Y,X){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...i(X)})}function T5(Y,X){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...i(X)})}function R5(Y,X){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...i(X)})}function C5(Y,X){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...i(X)})}function w5(Y,X){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...i(X)})}function S5(Y,X){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...i(X)})}function I5(Y,X){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...i(X)})}function b5(Y,X){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...i(X)})}function k5(Y,X){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...i(X)})}function x5(Y,X){return new Y({type:"string",format:"cidrv6",check:"string_format",abort:!1,...i(X)})}function v5(Y,X){return new Y({type:"string",format:"base64",check:"string_format",abort:!1,...i(X)})}function h5(Y,X){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...i(X)})}function y5(Y,X){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...i(X)})}function g5(Y,X){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...i(X)})}function f5(Y,X){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...i(X)})}function m5(Y,X){return new Y({type:"string",format:"date",check:"string_format",...i(X)})}function c5(Y,X){return new Y({type:"string",format:"time",check:"string_format",precision:null,...i(X)})}function u5(Y,X){return new Y({type:"string",format:"duration",check:"string_format",...i(X)})}function p5(Y,X){return new Y({type:"number",checks:[],...i(X)})}function l5(Y,X){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...i(X)})}function d5(Y,X){return new Y({type:"boolean",...i(X)})}function i5(Y,X){return new Y({type:"null",...i(X)})}function n5(Y){return new Y({type:"unknown"})}function o5(Y,X){return new Y({type:"never",...i(X)})}function _1(Y,X){return new Y4({check:"less_than",...i(X),value:Y,inclusive:!1})}function O9(Y,X){return new Y4({check:"less_than",...i(X),value:Y,inclusive:!0})}function P1(Y,X){return new X4({check:"greater_than",...i(X),value:Y,inclusive:!1})}function _9(Y,X){return new X4({check:"greater_than",...i(X),value:Y,inclusive:!0})}function q1(Y,X){return new Y7({check:"multiple_of",...i(X),value:Y})}function E1(Y,X){return new J7({check:"max_length",...i(X),maximum:Y})}function h6(Y,X){return new Q7({check:"min_length",...i(X),minimum:Y})}function M1(Y,X){return new G7({check:"length_equals",...i(X),length:Y})}function z4(Y,X){return new $7({check:"string_format",format:"regex",...i(X),pattern:Y})}function K4(Y){return new W7({check:"string_format",format:"lowercase",...i(Y)})}function U4(Y){return new z7({check:"string_format",format:"uppercase",...i(Y)})}function H4(Y,X){return new K7({check:"string_format",format:"includes",...i(X),includes:Y})}function Z4(Y,X){return new U7({check:"string_format",format:"starts_with",...i(X),prefix:Y})}function V4(Y,X){return new H7({check:"string_format",format:"ends_with",...i(X),suffix:Y})}function H6(Y){return new Z7({check:"overwrite",tx:Y})}function B4(Y){return H6((X)=>X.normalize(Y))}function L4(){return H6((Y)=>Y.trim())}function N4(){return H6((Y)=>Y.toLowerCase())}function j4(){return H6((Y)=>Y.toUpperCase())}function r5(Y,X,J){return new Y({type:"array",element:X,...i(J)})}function s5(Y,X,J){let Q=i(J);return Q.abort??(Q.abort=!0),new Y({type:"custom",check:"custom",fn:X,...Q})}function a5(Y,X,J){return new Y({type:"custom",check:"custom",fn:X,...i(J)})}function t5(Y){let X=GU((J)=>{return J.addIssue=(Q)=>{if(typeof Q==="string")J.issues.push(v6(Q,J.value,X._zod.def));else{let G=Q;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=J.value),G.inst??(G.inst=X),G.continue??(G.continue=!X._zod.def.abort),J.issues.push(v6(G))}},Y(J.value,J)});return X}function GU(Y,X){let J=new k0({check:"custom",...i(X)});return J._zod.check=Y,J}class F4{constructor(Y){this.counter=0,this.metadataRegistry=Y?.metadata??U6,this.target=Y?.target??"draft-2020-12",this.unrepresentable=Y?.unrepresentable??"throw",this.override=Y?.override??(()=>{}),this.io=Y?.io??"output",this.seen=new Map}process(Y,X={path:[],schemaPath:[]}){var J;let Q=Y._zod.def,G={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},$=this.seen.get(Y);if($){if($.count++,X.schemaPath.includes(Y))$.cycle=X.path;return $.schema}let W={schema:{},count:1,cycle:void 0,path:X.path};this.seen.set(Y,W);let K=Y._zod.toJSONSchema?.();if(K)W.schema=K;else{let B={...X,schemaPath:[...X.schemaPath,Y],path:X.path},O=Y._zod.parent;if(O)W.ref=O,this.process(O,B),this.seen.get(O).isParent=!0;else{let N=W.schema;switch(Q.type){case"string":{let V=N;V.type="string";let{minimum:D,maximum:E,format:P,patterns:T,contentEncoding:w}=Y._zod.bag;if(typeof D==="number")V.minLength=D;if(typeof E==="number")V.maxLength=E;if(P){if(V.format=G[P]??P,V.format==="")delete V.format}if(w)V.contentEncoding=w;if(T&&T.size>0){let x=[...T];if(x.length===1)V.pattern=x[0].source;else if(x.length>1)W.schema.allOf=[...x.map((j)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:j.source}))]}break}case"number":{let V=N,{minimum:D,maximum:E,format:P,multipleOf:T,exclusiveMaximum:w,exclusiveMinimum:x}=Y._zod.bag;if(typeof P==="string"&&P.includes("int"))V.type="integer";else V.type="number";if(typeof x==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")V.minimum=x,V.exclusiveMinimum=!0;else V.exclusiveMinimum=x;if(typeof D==="number"){if(V.minimum=D,typeof x==="number"&&this.target!=="draft-4")if(x>=D)delete V.minimum;else delete V.exclusiveMinimum}if(typeof w==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")V.maximum=w,V.exclusiveMaximum=!0;else V.exclusiveMaximum=w;if(typeof E==="number"){if(V.maximum=E,typeof w==="number"&&this.target!=="draft-4")if(w<=E)delete V.maximum;else delete V.exclusiveMaximum}if(typeof T==="number")V.multipleOf=T;break}case"boolean":{let V=N;V.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema");break}case"null":{if(this.target==="openapi-3.0")N.type="string",N.nullable=!0,N.enum=[null];else N.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema");break}case"never":{N.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let V=N,{minimum:D,maximum:E}=Y._zod.bag;if(typeof D==="number")V.minItems=D;if(typeof E==="number")V.maxItems=E;V.type="array",V.items=this.process(Q.element,{...B,path:[...B.path,"items"]});break}case"object":{let V=N;V.type="object",V.properties={};let D=Q.shape;for(let T in D)V.properties[T]=this.process(D[T],{...B,path:[...B.path,"properties",T]});let E=new Set(Object.keys(D)),P=new Set([...E].filter((T)=>{let w=Q.shape[T]._zod;if(this.io==="input")return w.optin===void 0;else return w.optout===void 0}));if(P.size>0)V.required=Array.from(P);if(Q.catchall?._zod.def.type==="never")V.additionalProperties=!1;else if(!Q.catchall){if(this.io==="output")V.additionalProperties=!1}else if(Q.catchall)V.additionalProperties=this.process(Q.catchall,{...B,path:[...B.path,"additionalProperties"]});break}case"union":{let V=N,D=Q.options.map((E,P)=>this.process(E,{...B,path:[...B.path,"anyOf",P]}));V.anyOf=D;break}case"intersection":{let V=N,D=this.process(Q.left,{...B,path:[...B.path,"allOf",0]}),E=this.process(Q.right,{...B,path:[...B.path,"allOf",1]}),P=(w)=>("allOf"in w)&&Object.keys(w).length===1,T=[...P(D)?D.allOf:[D],...P(E)?E.allOf:[E]];V.allOf=T;break}case"tuple":{let V=N;V.type="array";let D=this.target==="draft-2020-12"?"prefixItems":"items",E=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",P=Q.items.map((j,S)=>this.process(j,{...B,path:[...B.path,D,S]})),T=Q.rest?this.process(Q.rest,{...B,path:[...B.path,E,...this.target==="openapi-3.0"?[Q.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(V.prefixItems=P,T)V.items=T}else if(this.target==="openapi-3.0"){if(V.items={anyOf:P},T)V.items.anyOf.push(T);if(V.minItems=P.length,!T)V.maxItems=P.length}else if(V.items=P,T)V.additionalItems=T;let{minimum:w,maximum:x}=Y._zod.bag;if(typeof w==="number")V.minItems=w;if(typeof x==="number")V.maxItems=x;break}case"record":{let V=N;if(V.type="object",this.target==="draft-7"||this.target==="draft-2020-12")V.propertyNames=this.process(Q.keyType,{...B,path:[...B.path,"propertyNames"]});V.additionalProperties=this.process(Q.valueType,{...B,path:[...B.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let V=N,D=V9(Q.entries);if(D.every((E)=>typeof E==="number"))V.type="number";if(D.every((E)=>typeof E==="string"))V.type="string";V.enum=D;break}case"literal":{let V=N,D=[];for(let E of Q.values)if(E===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof E==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else D.push(Number(E));else D.push(E);if(D.length===0);else if(D.length===1){let E=D[0];if(V.type=E===null?"null":typeof E,this.target==="draft-4"||this.target==="openapi-3.0")V.enum=[E];else V.const=E}else{if(D.every((E)=>typeof E==="number"))V.type="number";if(D.every((E)=>typeof E==="string"))V.type="string";if(D.every((E)=>typeof E==="boolean"))V.type="string";if(D.every((E)=>E===null))V.type="null";V.enum=D}break}case"file":{let V=N,D={type:"string",format:"binary",contentEncoding:"binary"},{minimum:E,maximum:P,mime:T}=Y._zod.bag;if(E!==void 0)D.minLength=E;if(P!==void 0)D.maxLength=P;if(T)if(T.length===1)D.contentMediaType=T[0],Object.assign(V,D);else V.anyOf=T.map((w)=>{return{...D,contentMediaType:w}});else Object.assign(V,D);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let V=this.process(Q.innerType,B);if(this.target==="openapi-3.0")W.ref=Q.innerType,N.nullable=!0;else N.anyOf=[V,{type:"null"}];break}case"nonoptional":{this.process(Q.innerType,B),W.ref=Q.innerType;break}case"success":{let V=N;V.type="boolean";break}case"default":{this.process(Q.innerType,B),W.ref=Q.innerType,N.default=JSON.parse(JSON.stringify(Q.defaultValue));break}case"prefault":{if(this.process(Q.innerType,B),W.ref=Q.innerType,this.io==="input")N._prefault=JSON.parse(JSON.stringify(Q.defaultValue));break}case"catch":{this.process(Q.innerType,B),W.ref=Q.innerType;let V;try{V=Q.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}N.default=V;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let V=N,D=Y._zod.pattern;if(!D)throw Error("Pattern not found in template literal");V.type="string",V.pattern=D.source;break}case"pipe":{let V=this.io==="input"?Q.in._zod.def.type==="transform"?Q.out:Q.in:Q.out;this.process(V,B),W.ref=V;break}case"readonly":{this.process(Q.innerType,B),W.ref=Q.innerType,N.readOnly=!0;break}case"promise":{this.process(Q.innerType,B),W.ref=Q.innerType;break}case"optional":{this.process(Q.innerType,B),W.ref=Q.innerType;break}case"lazy":{let V=Y._zod.innerType;this.process(V,B),W.ref=V;break}case"custom":{if(this.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema");break}case"function":{if(this.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema");break}default:}}}let U=this.metadataRegistry.get(Y);if(U)Object.assign(W.schema,U);if(this.io==="input"&&w0(Y))delete W.schema.examples,delete W.schema.default;if(this.io==="input"&&W.schema._prefault)(J=W.schema).default??(J.default=W.schema._prefault);return delete W.schema._prefault,this.seen.get(Y).schema}emit(Y,X){let J={cycles:X?.cycles??"ref",reused:X?.reused??"inline",external:X?.external??void 0},Q=this.seen.get(Y);if(!Q)throw Error("Unprocessed schema. This is a bug in Zod.");let G=(Z)=>{let B=this.target==="draft-2020-12"?"$defs":"definitions";if(J.external){let D=J.external.registry.get(Z[0])?.id,E=J.external.uri??((T)=>T);if(D)return{ref:E(D)};let P=Z[1].defId??Z[1].schema.id??`schema${this.counter++}`;return Z[1].defId=P,{defId:P,ref:`${E("__shared")}#/${B}/${P}`}}if(Z[1]===Q)return{ref:"#"};let N=`${"#"}/${B}/`,V=Z[1].schema.id??`__schema${this.counter++}`;return{defId:V,ref:N+V}},$=(Z)=>{if(Z[1].schema.$ref)return;let B=Z[1],{ref:O,defId:N}=G(Z);if(B.def={...B.schema},N)B.defId=N;let V=B.schema;for(let D in V)delete V[D];V.$ref=O};if(J.cycles==="throw")for(let Z of this.seen.entries()){let B=Z[1];if(B.cycle)throw Error(`Cycle detected: #/${B.cycle?.join("/")}/<root>
|
|
30
|
-
|
|
31
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let Z of this.seen.entries()){let B=Z[1];if(Y===Z[0]){$(Z);continue}if(J.external){let N=J.external.registry.get(Z[0])?.id;if(Y!==Z[0]&&N){$(Z);continue}}if(this.metadataRegistry.get(Z[0])?.id){$(Z);continue}if(B.cycle){$(Z);continue}if(B.count>1){if(J.reused==="ref"){$(Z);continue}}}let W=(Z,B)=>{let O=this.seen.get(Z),N=O.def??O.schema,V={...N};if(O.ref===null)return;let D=O.ref;if(O.ref=null,D){W(D,B);let E=this.seen.get(D).schema;if(E.$ref&&(B.target==="draft-7"||B.target==="draft-4"||B.target==="openapi-3.0"))N.allOf=N.allOf??[],N.allOf.push(E);else Object.assign(N,E),Object.assign(N,V)}if(!O.isParent)this.override({zodSchema:Z,jsonSchema:N,path:O.path??[]})};for(let Z of[...this.seen.entries()].reverse())W(Z[0],{target:this.target});let K={};if(this.target==="draft-2020-12")K.$schema="https://json-schema.org/draft/2020-12/schema";else if(this.target==="draft-7")K.$schema="http://json-schema.org/draft-07/schema#";else if(this.target==="draft-4")K.$schema="http://json-schema.org/draft-04/schema#";else if(this.target==="openapi-3.0");else console.warn(`Invalid target: ${this.target}`);if(J.external?.uri){let Z=J.external.registry.get(Y)?.id;if(!Z)throw Error("Schema is missing an `id` property");K.$id=J.external.uri(Z)}Object.assign(K,Q.def);let U=J.external?.defs??{};for(let Z of this.seen.entries()){let B=Z[1];if(B.def&&B.defId)U[B.defId]=B.def}if(J.external);else if(Object.keys(U).length>0)if(this.target==="draft-2020-12")K.$defs=U;else K.definitions=U;try{return JSON.parse(JSON.stringify(K))}catch(Z){throw Error("Error converting schema to JSON.")}}}function e5(Y,X){if(Y instanceof O1){let Q=new F4(X),G={};for(let K of Y._idmap.entries()){let[U,Z]=K;Q.process(Z)}let $={},W={registry:Y,uri:X?.uri,defs:G};for(let K of Y._idmap.entries()){let[U,Z]=K;$[U]=Q.emit(Z,{...X,external:W})}if(Object.keys(G).length>0){let K=Q.target==="draft-2020-12"?"$defs":"definitions";$.__shared={[K]:G}}return{schemas:$}}let J=new F4(X);return J.process(Y),J.emit(Y,X)}function w0(Y,X){let J=X??{seen:new Set};if(J.seen.has(Y))return!1;J.seen.add(Y);let G=Y._zod.def;switch(G.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return w0(G.element,J);case"object":{for(let $ in G.shape)if(w0(G.shape[$],J))return!0;return!1}case"union":{for(let $ of G.options)if(w0($,J))return!0;return!1}case"intersection":return w0(G.left,J)||w0(G.right,J);case"tuple":{for(let $ of G.items)if(w0($,J))return!0;if(G.rest&&w0(G.rest,J))return!0;return!1}case"record":return w0(G.keyType,J)||w0(G.valueType,J);case"map":return w0(G.keyType,J)||w0(G.valueType,J);case"set":return w0(G.valueType,J);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return w0(G.innerType,J);case"lazy":return w0(G.getter(),J);case"default":return w0(G.innerType,J);case"prefault":return w0(G.innerType,J);case"custom":return!1;case"transform":return!0;case"pipe":return w0(G.in,J)||w0(G.out,J);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${G.type}`)}var HU=_("ZodISODateTime",(Y,X)=>{k7.init(Y,X),D0.init(Y,X)});function YQ(Y){return f5(HU,Y)}var ZU=_("ZodISODate",(Y,X)=>{x7.init(Y,X),D0.init(Y,X)});function XQ(Y){return m5(ZU,Y)}var VU=_("ZodISOTime",(Y,X)=>{v7.init(Y,X),D0.init(Y,X)});function JQ(Y){return c5(VU,Y)}var BU=_("ZodISODuration",(Y,X)=>{h7.init(Y,X),D0.init(Y,X)});function QQ(Y){return u5(BU,Y)}var GQ=(Y,X)=>{V1.init(Y,X),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(J)=>B2(Y,J)},flatten:{value:(J)=>V2(Y,J)},addIssue:{value:(J)=>{Y.issues.push(J),Y.message=JSON.stringify(Y.issues,k6,2)}},addIssues:{value:(J)=>{Y.issues.push(...J),Y.message=JSON.stringify(Y.issues,k6,2)}},isEmpty:{get(){return Y.issues.length===0}}})},VD=_("ZodError",GQ),t0=_("ZodError",GQ,{Parent:Error});var $Q=B1(t0),WQ=L1(t0),zQ=j9(t0),T1=F9(t0),KQ=j2(t0),UQ=F2(t0),HQ=D2(t0),ZQ=O2(t0),VQ=_2(t0),BQ=P2(t0),LQ=q2(t0),NQ=E2(t0);var O0=_("ZodType",(Y,X)=>{return j0.init(Y,X),Y.def=X,Y.type=X.type,Object.defineProperty(Y,"_def",{value:X}),Y.check=(...J)=>{return Y.clone({...X,checks:[...X.checks??[],...J.map((Q)=>typeof Q==="function"?{_zod:{check:Q,def:{check:"custom"},onattach:[]}}:Q)]})},Y.clone=(J,Q)=>G8(Y,J,Q),Y.brand=()=>Y,Y.register=(J,Q)=>{return J.add(Y,Q),Y},Y.parse=(J,Q)=>$Q(Y,J,Q,{callee:Y.parse}),Y.safeParse=(J,Q)=>zQ(Y,J,Q),Y.parseAsync=async(J,Q)=>WQ(Y,J,Q,{callee:Y.parseAsync}),Y.safeParseAsync=async(J,Q)=>T1(Y,J,Q),Y.spa=Y.safeParseAsync,Y.encode=(J,Q)=>KQ(Y,J,Q),Y.decode=(J,Q)=>UQ(Y,J,Q),Y.encodeAsync=async(J,Q)=>HQ(Y,J,Q),Y.decodeAsync=async(J,Q)=>ZQ(Y,J,Q),Y.safeEncode=(J,Q)=>VQ(Y,J,Q),Y.safeDecode=(J,Q)=>BQ(Y,J,Q),Y.safeEncodeAsync=async(J,Q)=>LQ(Y,J,Q),Y.safeDecodeAsync=async(J,Q)=>NQ(Y,J,Q),Y.refine=(J,Q)=>Y.check(WH(J,Q)),Y.superRefine=(J)=>Y.check(zH(J)),Y.overwrite=(J)=>Y.check(H6(J)),Y.optional=()=>DQ(Y),Y.nullable=()=>OQ(Y),Y.nullish=()=>DQ(OQ(Y)),Y.nonoptional=(J)=>eU(Y,J),Y.array=()=>_4(Y),Y.or=(J)=>P4([Y,J]),Y.and=(J)=>pU(Y,J),Y.transform=(J)=>_Q(Y,nU(J)),Y.default=(J)=>sU(Y,J),Y.prefault=(J)=>tU(Y,J),Y.catch=(J)=>XH(Y,J),Y.pipe=(J)=>_Q(Y,J),Y.readonly=()=>GH(Y),Y.describe=(J)=>{let Q=Y.clone();return U6.add(Q,{description:J}),Q},Object.defineProperty(Y,"description",{get(){return U6.get(Y)?.description},configurable:!0}),Y.meta=(...J)=>{if(J.length===0)return U6.get(Y);let Q=Y.clone();return U6.add(Q,J[0]),Q},Y.isOptional=()=>Y.safeParse(void 0).success,Y.isNullable=()=>Y.safeParse(null).success,Y}),PQ=_("_ZodString",(Y,X)=>{D1.init(Y,X),O0.init(Y,X);let J=Y._zod.bag;Y.format=J.format??null,Y.minLength=J.minimum??null,Y.maxLength=J.maximum??null,Y.regex=(...Q)=>Y.check(z4(...Q)),Y.includes=(...Q)=>Y.check(H4(...Q)),Y.startsWith=(...Q)=>Y.check(Z4(...Q)),Y.endsWith=(...Q)=>Y.check(V4(...Q)),Y.min=(...Q)=>Y.check(h6(...Q)),Y.max=(...Q)=>Y.check(E1(...Q)),Y.length=(...Q)=>Y.check(M1(...Q)),Y.nonempty=(...Q)=>Y.check(h6(1,...Q)),Y.lowercase=(Q)=>Y.check(K4(Q)),Y.uppercase=(Q)=>Y.check(U4(Q)),Y.trim=()=>Y.check(L4()),Y.normalize=(...Q)=>Y.check(B4(...Q)),Y.toLowerCase=()=>Y.check(N4()),Y.toUpperCase=()=>Y.check(j4())}),FU=_("ZodString",(Y,X)=>{D1.init(Y,X),PQ.init(Y,X),Y.email=(J)=>Y.check(D5(DU,J)),Y.url=(J)=>Y.check(E5(OU,J)),Y.jwt=(J)=>Y.check(g5(xU,J)),Y.emoji=(J)=>Y.check(M5(_U,J)),Y.guid=(J)=>Y.check(W4(jQ,J)),Y.uuid=(J)=>Y.check(O5(R1,J)),Y.uuidv4=(J)=>Y.check(_5(R1,J)),Y.uuidv6=(J)=>Y.check(P5(R1,J)),Y.uuidv7=(J)=>Y.check(q5(R1,J)),Y.nanoid=(J)=>Y.check(A5(PU,J)),Y.guid=(J)=>Y.check(W4(jQ,J)),Y.cuid=(J)=>Y.check(T5(qU,J)),Y.cuid2=(J)=>Y.check(R5(EU,J)),Y.ulid=(J)=>Y.check(C5(MU,J)),Y.base64=(J)=>Y.check(v5(IU,J)),Y.base64url=(J)=>Y.check(h5(bU,J)),Y.xid=(J)=>Y.check(w5(AU,J)),Y.ksuid=(J)=>Y.check(S5(TU,J)),Y.ipv4=(J)=>Y.check(I5(RU,J)),Y.ipv6=(J)=>Y.check(b5(CU,J)),Y.cidrv4=(J)=>Y.check(k5(wU,J)),Y.cidrv6=(J)=>Y.check(x5(SU,J)),Y.e164=(J)=>Y.check(y5(kU,J)),Y.datetime=(J)=>Y.check(YQ(J)),Y.date=(J)=>Y.check(XQ(J)),Y.time=(J)=>Y.check(JQ(J)),Y.duration=(J)=>Y.check(QQ(J))});function qQ(Y){return F5(FU,Y)}var D0=_("ZodStringFormat",(Y,X)=>{F0.init(Y,X),PQ.init(Y,X)}),DU=_("ZodEmail",(Y,X)=>{M7.init(Y,X),D0.init(Y,X)});var jQ=_("ZodGUID",(Y,X)=>{q7.init(Y,X),D0.init(Y,X)});var R1=_("ZodUUID",(Y,X)=>{E7.init(Y,X),D0.init(Y,X)});var OU=_("ZodURL",(Y,X)=>{A7.init(Y,X),D0.init(Y,X)});var _U=_("ZodEmoji",(Y,X)=>{T7.init(Y,X),D0.init(Y,X)});var PU=_("ZodNanoID",(Y,X)=>{R7.init(Y,X),D0.init(Y,X)});var qU=_("ZodCUID",(Y,X)=>{C7.init(Y,X),D0.init(Y,X)});var EU=_("ZodCUID2",(Y,X)=>{w7.init(Y,X),D0.init(Y,X)});var MU=_("ZodULID",(Y,X)=>{S7.init(Y,X),D0.init(Y,X)});var AU=_("ZodXID",(Y,X)=>{I7.init(Y,X),D0.init(Y,X)});var TU=_("ZodKSUID",(Y,X)=>{b7.init(Y,X),D0.init(Y,X)});var RU=_("ZodIPv4",(Y,X)=>{y7.init(Y,X),D0.init(Y,X)});var CU=_("ZodIPv6",(Y,X)=>{g7.init(Y,X),D0.init(Y,X)});var wU=_("ZodCIDRv4",(Y,X)=>{f7.init(Y,X),D0.init(Y,X)});var SU=_("ZodCIDRv6",(Y,X)=>{m7.init(Y,X),D0.init(Y,X)});var IU=_("ZodBase64",(Y,X)=>{u7.init(Y,X),D0.init(Y,X)});var bU=_("ZodBase64URL",(Y,X)=>{p7.init(Y,X),D0.init(Y,X)});var kU=_("ZodE164",(Y,X)=>{l7.init(Y,X),D0.init(Y,X)});var xU=_("ZodJWT",(Y,X)=>{d7.init(Y,X),D0.init(Y,X)});var EQ=_("ZodNumber",(Y,X)=>{G4.init(Y,X),O0.init(Y,X),Y.gt=(Q,G)=>Y.check(P1(Q,G)),Y.gte=(Q,G)=>Y.check(_9(Q,G)),Y.min=(Q,G)=>Y.check(_9(Q,G)),Y.lt=(Q,G)=>Y.check(_1(Q,G)),Y.lte=(Q,G)=>Y.check(O9(Q,G)),Y.max=(Q,G)=>Y.check(O9(Q,G)),Y.int=(Q)=>Y.check(FQ(Q)),Y.safe=(Q)=>Y.check(FQ(Q)),Y.positive=(Q)=>Y.check(P1(0,Q)),Y.nonnegative=(Q)=>Y.check(_9(0,Q)),Y.negative=(Q)=>Y.check(_1(0,Q)),Y.nonpositive=(Q)=>Y.check(O9(0,Q)),Y.multipleOf=(Q,G)=>Y.check(q1(Q,G)),Y.step=(Q,G)=>Y.check(q1(Q,G)),Y.finite=()=>Y;let J=Y._zod.bag;Y.minValue=Math.max(J.minimum??Number.NEGATIVE_INFINITY,J.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Y.maxValue=Math.min(J.maximum??Number.POSITIVE_INFINITY,J.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Y.isInt=(J.format??"").includes("int")||Number.isSafeInteger(J.multipleOf??0.5),Y.isFinite=!0,Y.format=J.format??null});function MQ(Y){return p5(EQ,Y)}var vU=_("ZodNumberFormat",(Y,X)=>{i7.init(Y,X),EQ.init(Y,X)});function FQ(Y){return l5(vU,Y)}var hU=_("ZodBoolean",(Y,X)=>{n7.init(Y,X),O0.init(Y,X)});function AQ(Y){return d5(hU,Y)}var yU=_("ZodNull",(Y,X)=>{o7.init(Y,X),O0.init(Y,X)});function TQ(Y){return i5(yU,Y)}var gU=_("ZodUnknown",(Y,X)=>{r7.init(Y,X),O0.init(Y,X)});function P9(){return n5(gU)}var fU=_("ZodNever",(Y,X)=>{s7.init(Y,X),O0.init(Y,X)});function O4(Y){return o5(fU,Y)}var mU=_("ZodArray",(Y,X)=>{a7.init(Y,X),O0.init(Y,X),Y.element=X.element,Y.min=(J,Q)=>Y.check(h6(J,Q)),Y.nonempty=(J)=>Y.check(h6(1,J)),Y.max=(J,Q)=>Y.check(E1(J,Q)),Y.length=(J,Q)=>Y.check(M1(J,Q)),Y.unwrap=()=>Y.element});function _4(Y,X){return r5(mU,Y,X)}var RQ=_("ZodObject",(Y,X)=>{Y5.init(Y,X),O0.init(Y,X),Q0.defineLazy(Y,"shape",()=>X.shape),Y.keyof=()=>q4(Object.keys(Y._zod.def.shape)),Y.catchall=(J)=>Y.clone({...Y._zod.def,catchall:J}),Y.passthrough=()=>Y.clone({...Y._zod.def,catchall:P9()}),Y.loose=()=>Y.clone({...Y._zod.def,catchall:P9()}),Y.strict=()=>Y.clone({...Y._zod.def,catchall:O4()}),Y.strip=()=>Y.clone({...Y._zod.def,catchall:void 0}),Y.extend=(J)=>{return Q0.extend(Y,J)},Y.safeExtend=(J)=>{return Q0.safeExtend(Y,J)},Y.merge=(J)=>Q0.merge(Y,J),Y.pick=(J)=>Q0.pick(Y,J),Y.omit=(J)=>Q0.omit(Y,J),Y.partial=(...J)=>Q0.partial(xQ,Y,J[0]),Y.required=(...J)=>Q0.required(vQ,Y,J[0])});function CQ(Y,X){let J={type:"object",get shape(){return Q0.assignProp(this,"shape",Y?Q0.objectClone(Y):{}),this.shape},...Q0.normalizeParams(X)};return new RQ(J)}function wQ(Y,X){return new RQ({type:"object",get shape(){return Q0.assignProp(this,"shape",Q0.objectClone(Y)),this.shape},catchall:P9(),...Q0.normalizeParams(X)})}var SQ=_("ZodUnion",(Y,X)=>{$4.init(Y,X),O0.init(Y,X),Y.options=X.options});function P4(Y,X){return new SQ({type:"union",options:Y,...Q0.normalizeParams(X)})}var cU=_("ZodDiscriminatedUnion",(Y,X)=>{SQ.init(Y,X),X5.init(Y,X)});function IQ(Y,X,J){return new cU({type:"union",options:X,discriminator:Y,...Q0.normalizeParams(J)})}var uU=_("ZodIntersection",(Y,X)=>{J5.init(Y,X),O0.init(Y,X)});function pU(Y,X){return new uU({type:"intersection",left:Y,right:X})}var lU=_("ZodRecord",(Y,X)=>{Q5.init(Y,X),O0.init(Y,X),Y.keyType=X.keyType,Y.valueType=X.valueType});function bQ(Y,X,J){return new lU({type:"record",keyType:Y,valueType:X,...Q0.normalizeParams(J)})}var D4=_("ZodEnum",(Y,X)=>{G5.init(Y,X),O0.init(Y,X),Y.enum=X.entries,Y.options=Object.values(X.entries);let J=new Set(Object.keys(X.entries));Y.extract=(Q,G)=>{let $={};for(let W of Q)if(J.has(W))$[W]=X.entries[W];else throw Error(`Key ${W} not found in enum`);return new D4({...X,checks:[],...Q0.normalizeParams(G),entries:$})},Y.exclude=(Q,G)=>{let $={...X.entries};for(let W of Q)if(J.has(W))delete $[W];else throw Error(`Key ${W} not found in enum`);return new D4({...X,checks:[],...Q0.normalizeParams(G),entries:$})}});function q4(Y,X){let J=Array.isArray(Y)?Object.fromEntries(Y.map((Q)=>[Q,Q])):Y;return new D4({type:"enum",entries:J,...Q0.normalizeParams(X)})}var dU=_("ZodLiteral",(Y,X)=>{$5.init(Y,X),O0.init(Y,X),Y.values=new Set(X.values),Object.defineProperty(Y,"value",{get(){if(X.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return X.values[0]}})});function kQ(Y,X){return new dU({type:"literal",values:Array.isArray(Y)?Y:[Y],...Q0.normalizeParams(X)})}var iU=_("ZodTransform",(Y,X)=>{W5.init(Y,X),O0.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new H9(Y.constructor.name);J.addIssue=($)=>{if(typeof $==="string")J.issues.push(Q0.issue($,J.value,X));else{let W=$;if(W.fatal)W.continue=!1;W.code??(W.code="custom"),W.input??(W.input=J.value),W.inst??(W.inst=Y),J.issues.push(Q0.issue(W))}};let G=X.transform(J.value,J);if(G instanceof Promise)return G.then(($)=>{return J.value=$,J});return J.value=G,J}});function nU(Y){return new iU({type:"transform",transform:Y})}var xQ=_("ZodOptional",(Y,X)=>{z5.init(Y,X),O0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function DQ(Y){return new xQ({type:"optional",innerType:Y})}var oU=_("ZodNullable",(Y,X)=>{K5.init(Y,X),O0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function OQ(Y){return new oU({type:"nullable",innerType:Y})}var rU=_("ZodDefault",(Y,X)=>{U5.init(Y,X),O0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function sU(Y,X){return new rU({type:"default",innerType:Y,get defaultValue(){return typeof X==="function"?X():Q0.shallowClone(X)}})}var aU=_("ZodPrefault",(Y,X)=>{H5.init(Y,X),O0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function tU(Y,X){return new aU({type:"prefault",innerType:Y,get defaultValue(){return typeof X==="function"?X():Q0.shallowClone(X)}})}var vQ=_("ZodNonOptional",(Y,X)=>{Z5.init(Y,X),O0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function eU(Y,X){return new vQ({type:"nonoptional",innerType:Y,...Q0.normalizeParams(X)})}var YH=_("ZodCatch",(Y,X)=>{V5.init(Y,X),O0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function XH(Y,X){return new YH({type:"catch",innerType:Y,catchValue:typeof X==="function"?X:()=>X})}var JH=_("ZodPipe",(Y,X)=>{B5.init(Y,X),O0.init(Y,X),Y.in=X.in,Y.out=X.out});function _Q(Y,X){return new JH({type:"pipe",in:Y,out:X})}var QH=_("ZodReadonly",(Y,X)=>{L5.init(Y,X),O0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function GH(Y){return new QH({type:"readonly",innerType:Y})}var $H=_("ZodLazy",(Y,X)=>{N5.init(Y,X),O0.init(Y,X),Y.unwrap=()=>Y._zod.def.getter()});function hQ(Y){return new $H({type:"lazy",getter:Y})}var E4=_("ZodCustom",(Y,X)=>{j5.init(Y,X),O0.init(Y,X)});function yQ(Y,X){return s5(E4,Y??(()=>!0),X)}function WH(Y,X={}){return a5(E4,Y,X)}function zH(Y){return t5(Y)}function gQ(Y,X={error:`Input not instance of ${Y.name}`}){let J=new E4({type:"custom",check:"custom",fn:(Q)=>Q instanceof Y,abort:!0,...Q0.normalizeParams(X)});return J._zod.bag.Class=Y,J}function oQ(Y=globalThis){if(Y.navigator?.userAgent)return Y.navigator.userAgent.toLowerCase();if(Y.process?.versions?.node)return`node.js/${Y.process.version}`;if(Y.EdgeRuntime)return"vercel-edge";return""}function rQ(Y){if(Y==null)return{};let X={};if(Y instanceof Headers)Y.forEach((J,Q)=>{X[Q.toLowerCase()]=J});else{if(!Array.isArray(Y))Y=Object.entries(Y);for(let[J,Q]of Y)if(Q!=null)X[J.toLowerCase()]=Q}return X}function sQ(Y,...X){let J=new Headers(rQ(Y)),Q=J.get("user-agent")||"";return J.set("user-agent",[Q,...X].filter(Boolean).join(" ")),Object.fromEntries(J.entries())}var ZH=[{mediaType:"audio/aac",bytesPrefix:[255,240]},{mediaType:"audio/aac",bytesPrefix:[255,241]},{mediaType:"audio/aac",bytesPrefix:[255,248]},{mediaType:"audio/aac",bytesPrefix:[255,249]},{mediaType:"audio/mpeg",bytesPrefix:[255,251]},{mediaType:"audio/mpeg",bytesPrefix:[255,250]},{mediaType:"audio/mpeg",bytesPrefix:[255,243]},{mediaType:"audio/mpeg",bytesPrefix:[255,242]},{mediaType:"audio/mpeg",bytesPrefix:[255,227]},{mediaType:"audio/mpeg",bytesPrefix:[255,226]},{mediaType:"audio/wav",bytesPrefix:[82,73,70,70,null,null,null,null,87,65,86,69]},{mediaType:"audio/ogg",bytesPrefix:[79,103,103,83]},{mediaType:"audio/flac",bytesPrefix:[102,76,97,67]},{mediaType:"audio/aac",bytesPrefix:[64,21,0,0]},{mediaType:"audio/webm",bytesPrefix:[26,69,223,163]}],QO=[...ZH,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];async function C1(Y){try{await Y.body?.cancel()}catch{}}var aQ="AI_DownloadError",tQ=`vercel.ai.error.${aQ}`,VH=Symbol.for(tQ),h0=class extends R8{constructor({url:Y,statusCode:X,statusText:J,cause:Q,message:G=Q==null?`Failed to download ${Y}: ${X} ${J}`:`Failed to download ${Y}: ${Q}`}){super({name:aQ,message:G,cause:Q});this[VH]=!0,this.url=Y,this.statusCode=X,this.statusText=J}static isInstance(Y){return R8.hasMarker(Y,tQ)}};function BH(Y=globalThis){return Y.window!=null}function T4(Y,X){try{return new URL(Y).origin===new URL(X).origin}catch{return!1}}function LH(Y){let X;try{X=new URL(Y)}catch{throw new h0({url:Y,message:`Invalid URL: ${Y}`})}if(X.protocol==="data:")return;if(X.protocol!=="http:"&&X.protocol!=="https:")throw new h0({url:Y,message:`URL scheme must be http, https, or data, got ${X.protocol}`});let J=X.hostname.toLowerCase().replace(/\.+$/,"");if(!J)throw new h0({url:Y,message:"URL must have a hostname"});if(J==="localhost"||J.endsWith(".local")||J.endsWith(".localhost"))throw new h0({url:Y,message:`URL with hostname ${J} is not allowed`});if(J.startsWith("[")&&J.endsWith("]")){if(eQ(J.slice(1,-1)))throw new h0({url:Y,message:`URL with IPv6 address ${J} is not allowed`});return}if(C4(J)){if(w4(J))throw new h0({url:Y,message:`URL with IP address ${J} is not allowed`})}}function NH({address:Y,family:X,hostname:J}){if(X===4?!C4(Y)||w4(Y):X===6?eQ(Y):!0)throw new h0({url:J,message:`Hostname ${J} resolved to disallowed IP address ${Y}`})}function C4(Y){let X=Y.split(".");if(X.length!==4)return!1;return X.every((J)=>{let Q=Number(J);return Number.isInteger(Q)&&Q>=0&&Q<=255&&String(Q)===J})}function w4(Y){let[X,J,Q]=Y.split(".").map(Number);if(X===0)return!0;if(X===10)return!0;if(X===100&&J>=64&&J<=127)return!0;if(X===127)return!0;if(X===169&&J===254)return!0;if(X===172&&J>=16&&J<=31)return!0;if(X===192&&J===0&&Q===0)return!0;if(X===192&&J===0&&Q===2)return!0;if(X===192&&J===168)return!0;if(X===198&&(J===18||J===19))return!0;if(X===198&&J===51&&Q===100)return!0;if(X===203&&J===0&&Q===113)return!0;if(X>=224)return!0;return!1}function jH(Y){let X=Y.toLowerCase(),J=X.indexOf("%");if(J!==-1)X=X.slice(0,J);let Q=X.split("::");if(Q.length>2)return null;let G=(W)=>{if(W==="")return[];let K=[],U=W.split(":");for(let Z=0;Z<U.length;Z++){let B=U[Z];if(B.includes(".")){if(Z!==U.length-1||!C4(B))return null;let[O,N,V,D]=B.split(".").map(Number);K.push(O<<8|N,V<<8|D);continue}if(!/^[0-9a-f]{1,4}$/.test(B))return null;K.push(parseInt(B,16))}return K},$=G(Q[0]);if($===null)return null;if(Q.length===2){let W=G(Q[1]);if(W===null)return null;let K=8-$.length-W.length;if(K<0)return null;return[...$,...Array(K).fill(0),...W]}return $.length===8?$:null}function eQ(Y){let X=jH(Y);if(X===null)return!0;let J=(Q)=>X.slice(0,Q).every((G)=>G===0);if(J(7)&&(X[7]===0||X[7]===1))return!0;if((X[0]&65024)===64512)return!0;if((X[0]&65472)===65152)return!0;if((X[0]&65472)===65216)return!0;if((X[0]&65280)===65280)return!0;if(X[0]===8193&&X[1]===3512)return!0;if(X[0]===16383&&(X[1]&61440)===0)return!0;if(J(6)||J(5)&&X[5]===65535||J(4)&&X[4]===65535&&X[5]===0||X[0]===100&&X[1]===65435&&X[2]===0&&X[3]===0&&X[4]===0&&X[5]===0||X[0]===100&&X[1]===65435&&X[2]===1)return w4(`${X[6]>>8&255}.${X[6]&255}.${X[7]>>8&255}.${X[7]&255}`);return!1}function FH(Y){return(X,J,Q)=>{Y(X,{...J,all:!0},(G,$)=>{if(G){Q(G);return}try{let[W]=$;if(W==null)throw Error(`Hostname ${X} did not resolve to an address`);for(let{address:K,family:U}of $)NH({address:K,family:U,hostname:X});if(J.all===!0)Q(null,$);else Q(null,W.address,W.family)}catch(W){Q(W instanceof Error?W:Error(String(W)))}})}}var DH;function OH(){let Y=globalThis.process;return Y?.release?.name==="node"&&Y.versions?.bun==null&&Y.versions?.deno==null&&Y.title!=="workerd"&&globalThis.EdgeRuntime==null}async function _H(){if(!OH())return globalThis.fetch;return DH??=Promise.resolve().then(PH)}function PH(){let Y=fQ("node:module"),{lookup:X}=fQ("node:dns"),{Agent:J,fetch:Q}=Y.createRequire(YG())("undici"),G=new J({connect:{lookup:FH(X)}});return($,W)=>Q($,{...W,dispatcher:G})}function fQ(Y){let X=globalThis.process?.getBuiltinModule?.(Y);if(X==null)throw Error(`Node.js built-in module ${Y} is unavailable`);return X}function YG(){let Y=Error.prepareStackTrace;try{Error.prepareStackTrace=(G,$)=>$;let X=Error("Capture current module path");Error.captureStackTrace(X,YG);let[J]=X.stack,Q=J?.getFileName();if(Q==null)throw Error("Unable to determine the current module path");return Q}finally{Error.prepareStackTrace=Y}}var qH=["connection","keep-alive","te","trailer","transfer-encoding","upgrade","host","forwarded","proxy-authorization","via","x-forwarded-for","x-forwarded-host","x-forwarded-proto","x-real-ip","metadata","metadata-flavor","x-aws-ec2-metadata-token","x-metadata-token","cookie","set-cookie"];function XG(Y){let X=new Headers(Y);for(let J of qH)X.delete(J);return X}var EH=10,MH=new Set([301,302,303,307,308]);async function AH(Y){return Y==null||Y===globalThis.fetch?await _H():Y}async function TH({url:Y,headers:X,abortSignal:J,maxRedirects:Q=EH,fetch:G,trustedOrigin:$}){let W=X===void 0?void 0:XG(X),K=(Z)=>{let B={signal:J,redirect:Z};if(W!==void 0)B.headers=new Headers(W);return B},U=Y;for(let Z=0;Z<=Q;Z++){let B=$!==void 0&&T4(U,$);if(!B)LH(U);let O=B&&G!=null?G:B?globalThis.fetch:await AH(G),N=await O(U,K("manual"));if(N.type==="opaqueredirect"){if(!BH())throw new h0({url:Y,message:`Redirect from ${U} could not be validated and was blocked`});return await O(U,K("follow"))}let V=N.headers?.get("location");if(MH.has(N.status)&&V){C1(N);let D=new URL(V,U).toString();if(W!==void 0&&!T4(D,U)){let E=W.get("user-agent");W=new Headers(E==null?void 0:{"user-agent":E})}U=D;continue}return N}throw new h0({url:Y,message:`Too many redirects (max ${Q})`})}var RH=new Set(["accept","accept-language","baggage","cache-control","idempotency-key","if-match","if-modified-since","if-none-match","if-range","if-unmodified-since","pragma","range","traceparent","tracestate","user-agent","x-correlation-id","x-request-id"]);async function JG({headers:Y,credentialedOrigin:X,untrustedFirstHopHeaders:J,...Q}){let G;if(Y!==void 0){G=XG(Y);let $=X??Q.trustedOrigin;if($===void 0||!T4(Q.url,$)){let W=new Set([...RH,...(J??[]).map((K)=>K.toLowerCase())]);G=new Headers([...G].filter(([K])=>W.has(K)))}}return TH({...Q,headers:G})}var S4=2147483648;async function QG({response:Y,url:X,maxBytes:J=S4}){let Q=Y.headers.get("content-length");if(Q!=null){let B=parseInt(Q,10);if(!isNaN(B)&&B>J)throw await C1(Y),new h0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes (Content-Length: ${B}).`})}let G=Y.body;if(G==null)return new Uint8Array(0);let $=G.getReader(),W=[],K=0;try{while(!0){let{done:B,value:O}=await $.read();if(B)break;if(K+=O.length,K>J)throw new h0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes.`});W.push(O)}}finally{try{await $.cancel()}catch{}finally{$.releaseLock()}}let U=new Uint8Array(K),Z=0;for(let B of W)U.set(B,Z),Z+=B.length;return U}var I0=({prefix:Y,size:X=16,alphabet:J="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:Q="-"}={})=>{let G=()=>{let $=J.length,W=Array(X);for(let K=0;K<X;K++)W[K]=J[Math.random()*$|0];return W.join("")};if(Y==null)return G;if(J.includes(Q))throw new pY({argument:"separator",message:`The separator "${Q}" must not be part of the alphabet "${J}".`});return()=>`${Y}${Q}${G()}`},GG=I0();function $G(Y){return globalThis.Buffer?.isBuffer(Y)??!1}function WG(Y){if(Y.type==="object"||Array.isArray(Y.type)&&Y.type.includes("object")){let{additionalProperties:J}=Y;Y.additionalProperties=J!=null&&typeof J!=="boolean"?p8(J):!1;let{properties:Q}=Y;if(Q!=null)for(let G of Object.keys(Q))Q[G]=p8(Q[G])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(p8):p8(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(p8);if(Y.allOf!=null)Y.allOf=Y.allOf.map(p8);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(p8);let{definitions:X}=Y;if(X!=null)for(let J of Object.keys(X))X[J]=p8(X[J]);return Y}function p8(Y){if(typeof Y==="boolean")return Y;return WG(Y)}var CH=Symbol("Let zodToJsonSchema decide on which parser to use"),mQ={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},wH=(Y)=>typeof Y==="string"?{...mQ,name:Y}:{...mQ,...Y};function e0(){return{}}function SH(Y,X){let J={type:"array"};if(Y.type?._def&&Y.type?._def?.typeName!=="ZodAny")J.items=Z0(Y.type._def,{...X,currentPath:[...X.currentPath,"items"]});if(Y.minLength)J.minItems=Y.minLength.value;if(Y.maxLength)J.maxItems=Y.maxLength.value;if(Y.exactLength)J.minItems=Y.exactLength.value,J.maxItems=Y.exactLength.value;return J}function IH(Y){let X={type:"integer",format:"int64"};if(!Y.checks)return X;for(let J of Y.checks)switch(J.kind){case"min":if(J.inclusive)X.minimum=J.value;else X.exclusiveMinimum=J.value;break;case"max":if(J.inclusive)X.maximum=J.value;else X.exclusiveMaximum=J.value;break;case"multipleOf":X.multipleOf=J.value}return X}function bH(){return{type:"boolean"}}function zG(Y,X){return Z0(Y.type._def,X)}var kH=(Y,X)=>{return Z0(Y.innerType._def,X)};function KG(Y,X,J){let Q=J??X.dateStrategy;if(Array.isArray(Q))return{anyOf:Q.map((G)=>KG(Y,X,G))};switch(Q){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return xH(Y)}}var xH=(Y)=>{let X={type:"integer",format:"unix-time"};for(let J of Y.checks)switch(J.kind){case"min":X.minimum=J.value;break;case"max":X.maximum=J.value}return X};function vH(Y,X){return{...Z0(Y.innerType._def,X),default:Y.defaultValue()}}function hH(Y,X){return X.effectStrategy==="input"?Z0(Y.schema._def,X):e0()}function yH(Y){return{type:"string",enum:Array.from(Y.values)}}var gH=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function fH(Y,X){let J=[Z0(Y.left._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),Z0(Y.right._def,{...X,currentPath:[...X.currentPath,"allOf","1"]})].filter((G)=>!!G),Q=[];return J.forEach((G)=>{if(gH(G))Q.push(...G.allOf);else{let $=G;if("additionalProperties"in G&&G.additionalProperties===!1){let{additionalProperties:W,...K}=G;$=K}Q.push($)}}),Q.length?{allOf:Q}:void 0}function mH(Y){let X=typeof Y.value;if(X!=="bigint"&&X!=="number"&&X!=="boolean"&&X!=="string")return{type:Array.isArray(Y.value)?"array":"object"};return{type:X==="bigint"?"integer":X,const:Y.value}}var M4=void 0,W8={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(M4===void 0)M4=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return M4},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function UG(Y,X){let J={type:"string"};if(Y.checks)for(let Q of Y.checks)switch(Q.kind){case"min":J.minLength=typeof J.minLength==="number"?Math.max(J.minLength,Q.value):Q.value;break;case"max":J.maxLength=typeof J.maxLength==="number"?Math.min(J.maxLength,Q.value):Q.value;break;case"email":switch(X.emailStrategy){case"format:email":z8(J,"email",Q.message,X);break;case"format:idn-email":z8(J,"idn-email",Q.message,X);break;case"pattern:zod":p0(J,W8.email,Q.message,X)}break;case"url":z8(J,"uri",Q.message,X);break;case"uuid":z8(J,"uuid",Q.message,X);break;case"regex":p0(J,Q.regex,Q.message,X);break;case"cuid":p0(J,W8.cuid,Q.message,X);break;case"cuid2":p0(J,W8.cuid2,Q.message,X);break;case"startsWith":p0(J,RegExp(`^${A4(Q.value,X)}`),Q.message,X);break;case"endsWith":p0(J,RegExp(`${A4(Q.value,X)}$`),Q.message,X);break;case"datetime":z8(J,"date-time",Q.message,X);break;case"date":z8(J,"date",Q.message,X);break;case"time":z8(J,"time",Q.message,X);break;case"duration":z8(J,"duration",Q.message,X);break;case"length":J.minLength=typeof J.minLength==="number"?Math.max(J.minLength,Q.value):Q.value,J.maxLength=typeof J.maxLength==="number"?Math.min(J.maxLength,Q.value):Q.value;break;case"includes":p0(J,RegExp(A4(Q.value,X)),Q.message,X);break;case"ip":if(Q.version!=="v6")z8(J,"ipv4",Q.message,X);if(Q.version!=="v4")z8(J,"ipv6",Q.message,X);break;case"base64url":p0(J,W8.base64url,Q.message,X);break;case"jwt":p0(J,W8.jwt,Q.message,X);break;case"cidr":if(Q.version!=="v6")p0(J,W8.ipv4Cidr,Q.message,X);if(Q.version!=="v4")p0(J,W8.ipv6Cidr,Q.message,X);break;case"emoji":p0(J,W8.emoji(),Q.message,X);break;case"ulid":p0(J,W8.ulid,Q.message,X);break;case"base64":switch(X.base64Strategy){case"format:binary":z8(J,"binary",Q.message,X);break;case"contentEncoding:base64":J.contentEncoding="base64";break;case"pattern:zod":p0(J,W8.base64,Q.message,X)}break;case"nanoid":p0(J,W8.nanoid,Q.message,X)}return J}function A4(Y,X){return X.patternStrategy==="escape"?uH(Y):Y}var cH=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function uH(Y){let X="";for(let J=0;J<Y.length;J++){if(!cH.has(Y[J]))X+="\\";X+=Y[J]}return X}function z8(Y,X,J,Q){if(Y.format||Y.anyOf?.some((G)=>G.format)){if(!Y.anyOf)Y.anyOf=[];if(Y.format)Y.anyOf.push({format:Y.format}),delete Y.format;Y.anyOf.push({format:X,...J&&Q.errorMessages&&{errorMessage:{format:J}}})}else Y.format=X}function p0(Y,X,J,Q){if(Y.pattern||Y.allOf?.some((G)=>G.pattern)){if(!Y.allOf)Y.allOf=[];if(Y.pattern)Y.allOf.push({pattern:Y.pattern}),delete Y.pattern;Y.allOf.push({pattern:cQ(X,Q),...J&&Q.errorMessages&&{errorMessage:{pattern:J}}})}else Y.pattern=cQ(X,Q)}function cQ(Y,X){if(!X.applyRegexFlags||!Y.flags)return Y.source;let J={i:Y.flags.includes("i"),m:Y.flags.includes("m"),s:Y.flags.includes("s")},Q=J.i?Y.source.toLowerCase():Y.source,G="",$=!1,W=!1,K=!1;for(let U=0;U<Q.length;U++){if($){G+=Q[U],$=!1;continue}if(J.i){if(W){if(Q[U].match(/[a-z]/)){if(K)G+=Q[U],G+=`${Q[U-2]}-${Q[U]}`.toUpperCase(),K=!1;else if(Q[U+1]==="-"&&Q[U+2]?.match(/[a-z]/))G+=Q[U],K=!0;else G+=`${Q[U]}${Q[U].toUpperCase()}`;continue}}else if(Q[U].match(/[a-z]/)){G+=`[${Q[U]}${Q[U].toUpperCase()}]`;continue}}if(J.m){if(Q[U]==="^"){G+=`(^|(?<=[\r
|
|
32
|
-
]))`;continue}else if(Q[U]==="$"){G+=`($|(?=[\r
|
|
33
|
-
]))`;continue}}if(J.s&&Q[U]==="."){G+=W?`${Q[U]}\r
|
|
34
|
-
`:`[${Q[U]}\r
|
|
35
|
-
]`;continue}if(G+=Q[U],Q[U]==="\\")$=!0;else if(W&&Q[U]==="]")W=!1;else if(!W&&Q[U]==="[")W=!0}try{new RegExp(G)}catch{return console.warn(`Could not convert regex pattern at ${X.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Y.source}return G}function HG(Y,X){let J={type:"object",additionalProperties:Z0(Y.valueType._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]})??X.allowedAdditionalProperties};if(Y.keyType?._def.typeName==="ZodString"&&Y.keyType._def.checks?.length){let{type:Q,...G}=UG(Y.keyType._def,X);return{...J,propertyNames:G}}else if(Y.keyType?._def.typeName==="ZodEnum")return{...J,propertyNames:{enum:Y.keyType._def.values}};else if(Y.keyType?._def.typeName==="ZodBranded"&&Y.keyType._def.type._def.typeName==="ZodString"&&Y.keyType._def.type._def.checks?.length){let{type:Q,...G}=zG(Y.keyType._def,X);return{...J,propertyNames:G}}return J}function pH(Y,X){if(X.mapStrategy==="record")return HG(Y,X);return{type:"array",maxItems:125,items:{type:"array",items:[Z0(Y.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||e0(),Z0(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||e0()],minItems:2,maxItems:2}}}function lH(Y){let X=Y.values,J=Object.keys(Y.values).filter((G)=>{return typeof X[X[G]]!=="number"}).map((G)=>X[G]),Q=Array.from(new Set(J.map((G)=>typeof G)));return{type:Q.length===1?Q[0]==="string"?"string":"number":["string","number"],enum:J}}function dH(){return{not:e0()}}function iH(){return{type:"null"}}var R4={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function nH(Y,X){let J=Y.options instanceof Map?Array.from(Y.options.values()):Y.options;if(J.every((Q)=>(Q._def.typeName in R4)&&(!Q._def.checks||!Q._def.checks.length))){let Q=J.reduce((G,$)=>{let W=R4[$._def.typeName];return W&&!G.includes(W)?[...G,W]:G},[]);return{type:Q.length>1?Q:Q[0]}}else if(J.every((Q)=>Q._def.typeName==="ZodLiteral"&&!Q.description)){let Q=J.reduce((G,$)=>{let W=typeof $._def.value;switch(W){case"string":case"number":case"boolean":return[...G,W];case"bigint":return[...G,"integer"];case"object":if($._def.value===null)return[...G,"null"];default:return G}},[]);if(Q.length===J.length){let G=Q.filter(($,W,K)=>K.indexOf($)===W);return{type:G.length>1?G:G[0],enum:J.reduce(($,W)=>{return $.includes(W._def.value)?$:[...$,W._def.value]},[])}}}else if(J.every((Q)=>Q._def.typeName==="ZodEnum"))return{type:"string",enum:J.reduce((Q,G)=>[...Q,...G._def.values.filter(($)=>!Q.includes($))],[])};return oH(Y,X)}var oH=(Y,X)=>{let J=(Y.options instanceof Map?Array.from(Y.options.values()):Y.options).map((Q,G)=>Z0(Q._def,{...X,currentPath:[...X.currentPath,"anyOf",`${G}`]})).filter((Q)=>!!Q&&(!X.strictUnions||typeof Q==="object"&&Object.keys(Q).length>0));return J.length?{anyOf:J}:void 0};function rH(Y,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Y.innerType._def.typeName)&&(!Y.innerType._def.checks||!Y.innerType._def.checks.length))return{type:[R4[Y.innerType._def.typeName],"null"]};let J=Z0(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return J&&{anyOf:[J,{type:"null"}]}}function sH(Y){let X={type:"number"};if(!Y.checks)return X;for(let J of Y.checks)switch(J.kind){case"int":X.type="integer";break;case"min":if(J.inclusive)X.minimum=J.value;else X.exclusiveMinimum=J.value;break;case"max":if(J.inclusive)X.maximum=J.value;else X.exclusiveMaximum=J.value;break;case"multipleOf":X.multipleOf=J.value}return X}function aH(Y,X){let J={type:"object",properties:{}},Q=[],G=Y.shape();for(let W in G){let K=G[W];if(K===void 0||K._def===void 0)continue;let U=eH(K),Z=Z0(K._def,{...X,currentPath:[...X.currentPath,"properties",W],propertyPath:[...X.currentPath,"properties",W]});if(Z===void 0)continue;if(J.properties[W]=Z,!U)Q.push(W)}if(Q.length)J.required=Q;let $=tH(Y,X);if($!==void 0)J.additionalProperties=$;return J}function tH(Y,X){if(Y.catchall._def.typeName!=="ZodNever")return Z0(Y.catchall._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]});switch(Y.unknownKeys){case"passthrough":return X.allowedAdditionalProperties;case"strict":return X.rejectedAdditionalProperties;case"strip":return X.removeAdditionalStrategy==="strict"?X.allowedAdditionalProperties:X.rejectedAdditionalProperties}}function eH(Y){try{return Y.isOptional()}catch{return!0}}var YZ=(Y,X)=>{if(X.currentPath.toString()===X.propertyPath?.toString())return Z0(Y.innerType._def,X);let J=Z0(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return J?{anyOf:[{not:e0()},J]}:e0()},XZ=(Y,X)=>{if(X.pipeStrategy==="input")return Z0(Y.in._def,X);else if(X.pipeStrategy==="output")return Z0(Y.out._def,X);let J=Z0(Y.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]});return{allOf:[J,Z0(Y.out._def,{...X,currentPath:[...X.currentPath,"allOf",J?"1":"0"]})].filter((Q)=>Q!==void 0)}};function JZ(Y,X){return Z0(Y.type._def,X)}function QZ(Y,X){let J={type:"array",uniqueItems:!0,items:Z0(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items"]})};if(Y.minSize)J.minItems=Y.minSize.value;if(Y.maxSize)J.maxItems=Y.maxSize.value;return J}function GZ(Y,X){if(Y.rest)return{type:"array",minItems:Y.items.length,items:Y.items.map((J,Q)=>Z0(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[]),additionalItems:Z0(Y.rest._def,{...X,currentPath:[...X.currentPath,"additionalItems"]})};else return{type:"array",minItems:Y.items.length,maxItems:Y.items.length,items:Y.items.map((J,Q)=>Z0(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[])}}function $Z(){return{not:e0()}}function WZ(){return e0()}var zZ=(Y,X)=>{return Z0(Y.innerType._def,X)},KZ=(Y,X,J)=>{switch(X){case"ZodString":return UG(Y,J);case"ZodNumber":return sH(Y);case"ZodObject":return aH(Y,J);case"ZodBigInt":return IH(Y);case"ZodBoolean":return bH();case"ZodDate":return KG(Y,J);case"ZodUndefined":return $Z();case"ZodNull":return iH();case"ZodArray":return SH(Y,J);case"ZodUnion":case"ZodDiscriminatedUnion":return nH(Y,J);case"ZodIntersection":return fH(Y,J);case"ZodTuple":return GZ(Y,J);case"ZodRecord":return HG(Y,J);case"ZodLiteral":return mH(Y);case"ZodEnum":return yH(Y);case"ZodNativeEnum":return lH(Y);case"ZodNullable":return rH(Y,J);case"ZodOptional":return YZ(Y,J);case"ZodMap":return pH(Y,J);case"ZodSet":return QZ(Y,J);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return JZ(Y,J);case"ZodNaN":case"ZodNever":return dH();case"ZodEffects":return hH(Y,J);case"ZodAny":return e0();case"ZodUnknown":return WZ();case"ZodDefault":return vH(Y,J);case"ZodBranded":return zG(Y,J);case"ZodReadonly":return zZ(Y,J);case"ZodCatch":return kH(Y,J);case"ZodPipeline":return XZ(Y,J);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Q)=>{return})(X)}},UZ=(Y,X)=>{let J=0;for(;J<Y.length&&J<X.length;J++)if(Y[J]!==X[J])break;return[(Y.length-J).toString(),...X.slice(J)].join("/")};function Z0(Y,X,J=!1){let Q=X.seen.get(Y);if(X.override){let K=X.override?.(Y,X,Q,J);if(K!==CH)return K}if(Q&&!J){let K=HZ(Q,X);if(K!==void 0)return K}let G={def:Y,path:X.currentPath,jsonSchema:void 0};X.seen.set(Y,G);let $=KZ(Y,Y.typeName,X),W=typeof $==="function"?Z0($(),X):$;if(W)ZZ(Y,X,W);if(X.postProcess){let K=X.postProcess(W,Y,X);return G.jsonSchema=W,K}return G.jsonSchema=W,W}var HZ=(Y,X)=>{switch(X.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:UZ(X.currentPath,Y.path)};case"none":case"seen":if(Y.path.length<X.currentPath.length&&Y.path.every((J,Q)=>X.currentPath[Q]===J))return console.warn(`Recursive reference detected at ${X.currentPath.join("/")}! Defaulting to any`),e0();return X.$refStrategy==="seen"?e0():void 0}},ZZ=(Y,X,J)=>{if(Y.description)J.description=Y.description;return J},VZ=(Y)=>{let X=wH(Y),J=X.name!==void 0?[...X.basePath,X.definitionPath,X.name]:X.basePath;return{...X,currentPath:J,propertyPath:void 0,seen:new Map(Object.entries(X.definitions).map(([Q,G])=>[G._def,{def:G._def,path:[...X.basePath,X.definitionPath,Q],jsonSchema:void 0}]))}},BZ=(Y,X)=>{let J=VZ(X),Q=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((U,[Z,B])=>({...U,[Z]:Z0(B._def,{...J,currentPath:[...J.basePath,J.definitionPath,Z]},!0)??e0()}),{}):void 0,G=typeof X==="string"?X:X?.nameStrategy==="title"?void 0:X?.name,$=Z0(Y._def,G===void 0?J:{...J,currentPath:[...J.basePath,J.definitionPath,G]},!1)??e0(),W=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if(W!==void 0)$.title=W;let K=G===void 0?Q?{...$,[J.definitionPath]:Q}:$:{$ref:[...J.$refStrategy==="relative"?[]:J.basePath,J.definitionPath,G].join("/"),[J.definitionPath]:{...Q,[G]:$}};return K.$schema="http://json-schema.org/draft-07/schema#",K},LZ=Symbol.for("vercel.ai.schema");function I4(Y){let X;return()=>{if(X==null)X=Y();return X}}function w1(Y,{validate:X}={}){return{[LZ]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:X}}function NZ(Y,X){let J=X?.useReferences??!1;return w1(()=>BZ(Y,{$refStrategy:J?"root":"none"}),{validate:async(Q)=>{let G=await Y.safeParseAsync(Q);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function jZ(Y,X){let J=X?.useReferences??!1;return w1(()=>WG(e5(Y,{target:"draft-7",io:"input",reused:J?"ref":"inline"})),{validate:async(Q)=>{let G=await T1(Y,Q);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function FZ(Y){return"_zod"in Y}function S1(Y,X){if(FZ(Y))return jZ(Y,X);else return NZ(Y,X)}var DZ="AI_SerializationError",GO=`vercel.ai.error.${DZ}`;var TZ="AI_InvalidArgumentError",pO=`vercel.ai.error.${TZ}`;var RZ="AI_InvalidStreamPartError",lO=`vercel.ai.error.${RZ}`;var CZ="AI_InvalidToolApprovalError",dO=`vercel.ai.error.${CZ}`;var wZ="AI_InvalidToolApprovalSignatureError",iO=`vercel.ai.error.${wZ}`;var SZ="AI_InvalidToolInputError",nO=`vercel.ai.error.${SZ}`;var IZ="AI_ToolCallNotFoundForApprovalError",oO=`vercel.ai.error.${IZ}`;var bZ="AI_MissingToolResultsError",rO=`vercel.ai.error.${bZ}`;var kZ="AI_NoImageGeneratedError",sO=`vercel.ai.error.${kZ}`;var xZ="AI_NoObjectGeneratedError",aO=`vercel.ai.error.${xZ}`;var vZ="AI_NoOutputGeneratedError",tO=`vercel.ai.error.${vZ}`;var hZ="AI_NoSpeechGeneratedError",eO=`vercel.ai.error.${hZ}`;var yZ="AI_NoTranscriptGeneratedError",Y_=`vercel.ai.error.${yZ}`;var gZ="AI_NoTranslationGeneratedError",X_=`vercel.ai.error.${gZ}`;var fZ="AI_NoVideoGeneratedError",J_=`vercel.ai.error.${fZ}`;var mZ="AI_NoSuchToolError",Q_=`vercel.ai.error.${mZ}`;var cZ="AI_StreamProviderError",G_=`vercel.ai.error.${cZ}`;var uZ="AI_ToolCallRepairError",$_=`vercel.ai.error.${uZ}`;var pZ="AI_ToolChoiceViolationError",W_=`vercel.ai.error.${pZ}`;var lZ="AI_UIMessageStreamError",z_=`vercel.ai.error.${lZ}`;var dZ="AI_InvalidDataContentError",K_=`vercel.ai.error.${dZ}`;var iZ="AI_InvalidMessageRoleError",U_=`vercel.ai.error.${iZ}`;var nZ="AI_MessageConversionError",H_=`vercel.ai.error.${nZ}`;var oZ="AI_RetryError",Z_=`vercel.ai.error.${oZ}`;var rZ="7.0.140",sZ=async({url:Y,maxBytes:X,abortSignal:J})=>{let Q=Y.toString();try{let G=sQ({},`ai-sdk/${rZ}`,oQ()),$=await JG({url:Q,headers:G,abortSignal:J});if(!$.ok)throw await C1($),new h0({url:Q,statusCode:$.status,statusText:$.statusText});return{data:await QG({response:$,url:Q,maxBytes:X??S4}),mediaType:$.headers.get("content-type")??void 0}}catch(G){if(h0.isInstance(G))throw G;throw new h0({url:Q,cause:G})}};var z={array:_4,boolean:AQ,custom:yQ,discriminatedUnion:IQ,enum:q4,instanceof:gQ,lazy:hQ,literal:kQ,looseObject:wQ,never:O4,null:TQ,number:MQ,object:CQ,record:bQ,string:qQ,union:P4,unknown:P9},Z6=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),Z6.optional()),z.array(Z6)])),k=z.record(z.string(),z.record(z.string(),Z6.optional())),E9=z.union([z.string(),z.instanceof(Uint8Array),z.instanceof(ArrayBuffer),z.custom($G,{message:"Must be a Buffer"})]),b4=z.record(z.string(),z.string()),ZG=z.object({type:z.literal("text"),text:z.string(),providerOptions:k.optional()}),aZ=z.object({type:z.literal("image"),image:z.union([E9,z.instanceof(URL),b4]),mediaType:z.string().optional(),providerOptions:k.optional()}),VG=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:E9}),z.object({type:z.literal("url"),url:z.instanceof(URL)}),z.object({type:z.literal("reference"),reference:b4}),z.object({type:z.literal("text"),text:z.string()})]),tZ=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:E9}),z.object({type:z.literal("url"),url:z.instanceof(URL)})]),BG=z.object({type:z.literal("file"),data:z.union([VG,E9,z.instanceof(URL),b4]),filename:z.string().optional(),mediaType:z.string(),providerOptions:k.optional()}),eZ=z.object({type:z.literal("reasoning"),text:z.string(),providerOptions:k.optional()}),YV=z.object({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerOptions:k.optional()}),XV=z.object({type:z.literal("reasoning-file"),data:z.union([tZ,E9,z.instanceof(URL)]),mediaType:z.string(),providerOptions:k.optional()}),JV=z.object({type:z.literal("tool-call"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerOptions:k.optional(),providerExecuted:z.boolean().optional()}),QV=z.discriminatedUnion("type",[z.object({type:z.literal("text"),value:z.string(),providerOptions:k.optional()}),z.object({type:z.literal("json"),value:Z6,providerOptions:k.optional()}),z.object({type:z.literal("execution-denied"),reason:z.string().optional(),providerOptions:k.optional()}),z.object({type:z.literal("error-text"),value:z.string(),providerOptions:k.optional()}),z.object({type:z.literal("error-json"),value:Z6,providerOptions:k.optional()}),z.object({type:z.literal("content"),value:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),providerOptions:k.optional()}),z.object({type:z.literal("file"),data:VG,mediaType:z.string(),filename:z.string().optional(),providerOptions:k.optional()}),z.object({type:z.literal("file-data"),data:z.string(),mediaType:z.string(),filename:z.string().optional(),providerOptions:k.optional()}),z.object({type:z.literal("file-url"),url:z.string(),mediaType:z.string().optional(),providerOptions:k.optional()}),z.object({type:z.literal("file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:k.optional()}),z.object({type:z.literal("file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:k.optional()}),z.object({type:z.literal("image-data"),data:z.string(),mediaType:z.string(),providerOptions:k.optional()}),z.object({type:z.literal("image-url"),url:z.string(),providerOptions:k.optional()}),z.object({type:z.literal("image-file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:k.optional()}),z.object({type:z.literal("image-file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:k.optional()}),z.object({type:z.literal("custom"),providerOptions:k.optional()})]))})]),LG=z.object({type:z.literal("tool-result"),toolCallId:z.string(),toolName:z.string(),output:QV,providerOptions:k.optional()}),GV=z.object({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional(),inputSchemaInput:z.unknown().optional()}),$V=z.object({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional()}),WV=z.object({role:z.literal("system"),content:z.string(),providerOptions:k.optional()}),zV=z.object({role:z.literal("user"),content:z.union([z.string(),z.array(z.union([ZG,aZ,BG]))]),providerOptions:k.optional()}),KV=z.object({role:z.literal("assistant"),content:z.union([z.string(),z.array(z.union([ZG,YV,BG,eZ,XV,JV,LG,GV]))]),providerOptions:k.optional()}),UV=z.object({role:z.literal("tool"),content:z.array(z.union([LG,$V])),providerOptions:k.optional()}),V_=z.union([WV,zV,KV,UV]);var B_=Symbol("ai-sdk-tool-call-input-schema-input");var L_=I0({prefix:"aitxt",size:24}),N_=I0({prefix:"call",size:24});var j_=class extends TransformStream{constructor(){super({transform(Y,X){X.enqueue(`data: ${JSON.stringify(Y)}
|
|
36
|
-
|
|
37
|
-
`)},flush(Y){Y.enqueue(`data: [DONE]
|
|
38
|
-
|
|
39
|
-
`)}})}};var NG=z.object({source:z.discriminatedUnion("sourceType",[z.object({type:z.literal("source"),sourceType:z.literal("url"),id:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:k.optional()}),z.object({type:z.literal("source"),sourceType:z.literal("document"),id:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:k.optional()})]),startIndex:z.number().int().nonnegative().optional(),endIndex:z.number().int().nonnegative().optional(),citedText:z.string().optional()}),q9=z.record(z.string(),Z6.optional()),F_=I4(()=>S1(z.union([z.looseObject({type:z.literal("text-start"),id:z.string(),providerMetadata:k.optional()}),z.looseObject({type:z.literal("text-delta"),id:z.string(),delta:z.string(),providerMetadata:k.optional()}),z.looseObject({type:z.literal("text-end"),id:z.string(),citations:z.array(NG).optional(),providerMetadata:k.optional()}),z.looseObject({type:z.literal("error"),errorText:z.string()}),z.looseObject({type:z.literal("tool-input-start"),toolCallId:z.string(),toolName:z.string(),providerExecuted:z.boolean().optional(),providerMetadata:k.optional(),toolMetadata:q9.optional(),dynamic:z.boolean().optional(),title:z.string().optional()}),z.looseObject({type:z.literal("tool-input-delta"),toolCallId:z.string(),inputTextDelta:z.string()}),z.looseObject({type:z.literal("tool-input-available"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:k.optional(),toolMetadata:q9.optional(),dynamic:z.boolean().optional(),title:z.string().optional()}),z.looseObject({type:z.literal("tool-input-error"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:k.optional(),toolMetadata:q9.optional(),dynamic:z.boolean().optional(),errorText:z.string(),title:z.string().optional()}),z.looseObject({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string(),approvalDescriptor:z.unknown().optional(),inputSchemaInput:z.unknown().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}),z.looseObject({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional(),providerExecuted:z.boolean().optional(),providerMetadata:k.optional()}),z.looseObject({type:z.literal("tool-output-available"),toolCallId:z.string(),output:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:k.optional(),toolMetadata:q9.optional(),dynamic:z.boolean().optional(),preliminary:z.boolean().optional()}),z.looseObject({type:z.literal("tool-output-error"),toolCallId:z.string(),errorText:z.string(),providerExecuted:z.boolean().optional(),providerMetadata:k.optional(),toolMetadata:q9.optional(),dynamic:z.boolean().optional()}),z.looseObject({type:z.literal("tool-output-denied"),toolCallId:z.string()}),z.looseObject({type:z.literal("reasoning-start"),id:z.string(),providerMetadata:k.optional()}),z.looseObject({type:z.literal("reasoning-delta"),id:z.string(),delta:z.string(),providerMetadata:k.optional()}),z.looseObject({type:z.literal("reasoning-end"),id:z.string(),providerMetadata:k.optional()}),z.looseObject({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerMetadata:k.optional()}),z.looseObject({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:k.optional()}),z.looseObject({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:k.optional()}),z.looseObject({type:z.literal("file"),url:z.string(),mediaType:z.string(),providerMetadata:k.optional()}),z.looseObject({type:z.literal("reasoning-file"),url:z.string(),mediaType:z.string(),providerMetadata:k.optional()}),z.looseObject({type:z.custom((Y)=>typeof Y==="string"&&Y.startsWith("data-"),{message:'Type must start with "data-"'}),id:z.string().optional(),data:z.unknown(),transient:z.boolean().optional()}),z.looseObject({type:z.literal("start-step")}),z.looseObject({type:z.literal("finish-step")}),z.looseObject({type:z.literal("reset-step")}),z.looseObject({type:z.literal("start"),messageId:z.string().optional(),messageMetadata:z.unknown().optional()}),z.looseObject({type:z.literal("finish"),finishReason:z.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:z.unknown().optional()}),z.looseObject({type:z.literal("abort"),reason:z.string().optional()}),z.looseObject({type:z.literal("message-metadata"),messageMetadata:z.unknown()})])));var D_=Symbol("streamRetryAttemptBoundary");var O_=I0({prefix:"aitxt",size:24}),__=I0({prefix:"call",size:24});var P_=I0({prefix:"aitxt",size:24}),q_=I0({prefix:"call",size:24});var E_=Symbol("streamRetryBoundary");var d0=z.record(z.string(),Z6.optional()),HV=z.record(z.string(),z.string());var M_=I4(()=>{let Y=z.object({id:z.string(),approved:z.never().optional(),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.never().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional(),inputSchemaInput:z.unknown().optional()}),X=Y.extend({approved:z.boolean(),reason:z.string().optional()}),J=X.extend({approved:z.literal(!0)}),Q=X.extend({approved:z.literal(!1)});return S1(z.array(z.object({id:z.string(),role:z.enum(["system","user","assistant"]),metadata:z.unknown().optional(),parts:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),citations:z.array(NG).optional(),state:z.enum(["streaming","done"]).optional(),providerMetadata:k.optional()}),z.object({type:z.literal("reasoning"),id:z.string().optional(),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:k.optional()}),z.object({type:z.literal("custom"),kind:z.string(),providerMetadata:k.optional()}),z.object({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:k.optional()}),z.object({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:k.optional()}),z.object({type:z.literal("file"),mediaType:z.string(),filename:z.string().optional(),url:z.string(),providerReference:HV.optional(),providerMetadata:k.optional()}),z.object({type:z.literal("reasoning-file"),mediaType:z.string(),url:z.string(),providerMetadata:k.optional()}),z.object({type:z.literal("step-start")}),z.object({type:z.string().startsWith("data-"),id:z.string().optional(),data:z.unknown()}),z.object({type:z.literal("dynamic-tool"),dynamic:z.literal(!1).optional(),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:d0.optional(),state:z.literal("input-streaming"),input:z.unknown().optional(),rawInput:z.string().optional(),providerExecuted:z.boolean().optional(),callProviderMetadata:k.optional(),output:z.never().optional(),errorText:z.never().optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),dynamic:z.literal(!1).optional(),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:d0.optional(),state:z.literal("input-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:k.optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),dynamic:z.literal(!1).optional(),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:d0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:k.optional(),approval:Y}),z.object({type:z.literal("dynamic-tool"),dynamic:z.literal(!1).optional(),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:d0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:k.optional(),approval:X}),z.object({type:z.literal("dynamic-tool"),dynamic:z.literal(!1).optional(),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:d0.optional(),state:z.literal("output-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:k.optional(),resultProviderMetadata:k.optional(),preliminary:z.boolean().optional(),approval:J.optional()}),z.object({type:z.literal("dynamic-tool"),dynamic:z.literal(!1).optional(),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:d0.optional(),state:z.literal("output-error"),input:z.unknown().optional(),rawInput:z.unknown().optional(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.string(),callProviderMetadata:k.optional(),resultProviderMetadata:k.optional(),approval:J.optional()}),z.object({type:z.literal("dynamic-tool"),dynamic:z.literal(!1).optional(),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:d0.optional(),state:z.literal("output-denied"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:k.optional(),approval:Q}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:d0.optional(),state:z.literal("input-streaming"),providerExecuted:z.boolean().optional(),callProviderMetadata:k.optional(),input:z.unknown().optional(),rawInput:z.string().optional(),output:z.never().optional(),errorText:z.never().optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:d0.optional(),state:z.literal("input-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:k.optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:d0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:k.optional(),approval:Y}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:d0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:k.optional(),approval:X}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:d0.optional(),state:z.literal("output-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:k.optional(),resultProviderMetadata:k.optional(),preliminary:z.boolean().optional(),approval:J.optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:d0.optional(),state:z.literal("output-error"),providerExecuted:z.boolean().optional(),input:z.unknown().optional(),rawInput:z.unknown().optional(),output:z.never().optional(),errorText:z.string(),callProviderMetadata:k.optional(),resultProviderMetadata:k.optional(),approval:J.optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:d0.optional(),state:z.literal("output-denied"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:k.optional(),approval:Q})]))}).superRefine((G,$)=>{if(G.role!=="assistant"&&G.parts.length===0)$.addIssue({origin:"array",code:"too_small",minimum:1,inclusive:!0,input:G.parts,path:["parts"],message:"Message must contain at least one part"})})).nonempty("Messages array must not be empty"))});var A_=I0({prefix:"call",size:24});var T_=I0({prefix:"call",size:24});var R_=I0({prefix:"call",size:24});var C_=I0({prefix:"aiobj",size:24});function jG(Y){return({url:X,abortSignal:J})=>sZ({url:X,maxBytes:Y?.maxBytes,abortSignal:J})}var w_=I0({prefix:"aiobj",size:24});var S_=I0({prefix:"call",size:24});var I_=jG();var b_=z.object({token:z.string().refine((Y)=>Y.trim().length>0),url:z.string().refine((Y)=>{try{let X=new URL(Y);return(X.protocol==="ws:"||X.protocol==="wss:")&&X.hostname!==""}catch{return!1}}),expiresAt:z.number().positive().max(Number.MAX_SAFE_INTEGER).optional(),tools:z.array(z.object({type:z.literal("function"),name:z.string().min(1),description:z.string().optional(),parameters:z.record(z.string(),z.unknown())})).optional()});var ZV="AI_NoSuchProviderError",k_=`vercel.ai.error.${ZV}`;var x_=I0({prefix:"call",size:24});var v_=I0({prefix:"call",size:24}),h_=jG();var y_=I0({prefix:"call",size:24});class i0 extends z6{name="ProviderResponseStreamError";constructor(Y,X){super({message:Y,url:"",requestBodyValues:void 0,cause:X?.cause,isRetryable:X?.retryable??!0})}}var y0={};dY(y0,{toWebSocketUrl:()=>wV,streamResponsesWebSocket:()=>xV,parseRateLimitSignal:()=>A9,normalizeHeaders:()=>SV,markOversizedFrame:()=>CG,isUpgradeFailure:()=>IV,isOversizedFrame:()=>bV,isNonEmittingFrame:()=>SG,isAbortError:()=>y4,connectResponsesWebSocket:()=>kV,TERMINAL_AFTER_OUTPUT_MESSAGE:()=>h4,PROTOCOL_HEADER:()=>AG,OpenAIWebSocket:()=>y0,OVERSIZED_FRAME_MESSAGE:()=>IG});function M9(Y){let X=Number(Y.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(X)?X:void 0}function I1(Y,X,J=!1){let G=Buffer.from(Y.slice(0,X)).toString("latin1").split(`\r
|
|
40
|
-
`),$=G[0]??"",W=M9($);if(W===void 0||W===101)return;let K=Object.fromEntries(G.slice(1).flatMap((V)=>{let D=V.indexOf(":");return D===-1?[]:[[V.slice(0,D).trim().toLowerCase(),V.slice(D+1).trim()]]})),U=Y.slice(X+4),Z=K["content-length"],B=Number(Z);if(!J&&(Z===void 0||Number.isFinite(B)&&U.length<B))return;let O=Buffer.from(U).toString("utf8"),N=(()=>{try{let V=JSON.parse(O);return s(V)?V:void 0}catch{return}})();return{message:`WS upgrade failed: ${$}`,status:W,status_code:W,headers:K,body:O,...s(N?.error)?{error:N.error}:{}}}var VV="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",FG=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class k4{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];writeQueue=[];constructor(Y,X,J){this.url=Y,this.sessionID=J?.sessionID,this.connect(Y,X)}addEventListener(Y,X,J){this.listeners[Y]?.add(X)}removeEventListener(Y,X){this.listeners[Y]?.delete(X)}peerClose;closeEmitted=!1;emitClose(Y,X){if(this.closeEmitted)return;this.closeEmitted=!0,this.emit("close",{code:Y,reason:X})}emit(Y,X){for(let J of[...this.listeners[Y]??[]])try{J(X)}catch{}}async connect(Y,X){let J=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),Q=J.hostname,G=J.port?Number(J.port):J.protocol==="https:"?443:80,$=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),K=Buffer.from(W).toString("base64"),U=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(K+VV));this.expectedAccept=Buffer.from(new Uint8Array(U)).toString("base64");let Z={};for(let[N,V]of Object.entries(X))Z[N.toLowerCase()]=V;let B=[`GET ${$} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${K}`];for(let N of FG)if(Z[N]!==void 0)B.push(`${BV(N)}: ${Z[N]}`);for(let[N,V]of Object.entries(X))if(!FG.includes(N.toLowerCase())&&N.toLowerCase()!=="content-length")B.push(`${N}: ${V}`);let O=`${B.join(`\r
|
|
41
|
-
`)}\r
|
|
42
|
-
\r
|
|
43
|
-
`;try{this.log("connect_start",{host:Q,port:G,tls:J.protocol==="https:"});let N=globalThis.Bun?.connect;if(!N)throw Error("Bun.connect is not available");this.socket=await N({hostname:Q,port:G,tls:J.protocol==="https:"?{serverName:Q}:void 0,socket:{open:(V)=>{this.socket=V,this.enqueueWrite(new TextEncoder().encode(O))},data:(V,D)=>this.onData(D),drain:()=>this.flushWrites(),error:(V,D)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let E=D instanceof Error?D.message:String(D);this.log("socket_error",{message:E}),this.emit("error",{message:E})},close:()=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close"),this.emitClose(this.peerClose?.code??1006,this.peerClose?.reason??"socket closed")}}})}catch(N){this.readyState=3;let V=N instanceof Error?N.message:String(N);this.log("connect_exception",{message:V}),this.emit("error",{message:V})}}onData(Y){if(this.rxBuffer=LV(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
|
|
44
|
-
\r
|
|
45
|
-
`);if(J===-1)return;let Q=X.slice(0,J),G=Q.split(`\r
|
|
46
|
-
`)[0]??"",$=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=M9(G);if(W!==101){if(W===void 0){this.readyState=3;try{this.socket?.end()}catch{}this.log("upgrade_failed",{statusLine:G}),this.emit("error",{message:`WS upgrade failed: ${G}`});return}if(!this.emitRejectedUpgrade())return;try{this.socket?.end()}catch{}return}if(!$||$[1]!==this.expectedAccept){this.readyState=3;try{this.socket?.end()}catch{}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(J+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 X=Buffer.from(this.rxBuffer).indexOf(`\r
|
|
47
|
-
\r
|
|
48
|
-
`);if(X===-1)return!1;let J=I1(this.rxBuffer,X,Y);if(!J)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:J.status,partial:Y}),this.emit("error",J),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let X=Y[0],J=Y[1],Q=(X&128)!==0,G=X&15,$=(J&128)!==0,W=J&127,K=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],K=4}else if(W===127){if(Y.length<10)return;W=0;for(let Z=0;Z<8;Z++)W=W*256+Y[2+Z];K=10}if($)K+=4;if(Y.length<K+W)return;let U=Y.slice(K,K+W);this.rxBuffer=Y.slice(K+W),this.handleFrame(Q,G,U)}}handleFrame(Y,X,J){if(X===9){this.writeFrame(10,J);return}if(X===10)return;if(X===8){let G=1005,$="";if(J.length>=2)G=J[0]<<8|J[1],$=Buffer.from(J.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(X===1||X===2)this.fragOpcode=X,this.fragChunks=[J];else if(X===0)this.fragChunks.push(J);if(!Y)return;let Q=NV(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,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),G;if(J<126)G=[128|Y,128|J];else if(J<65536)G=[128|Y,254,J>>8&255,J&255];else{G=[128|Y,255];for(let K=7;K>=0;K--)G.push(J/2**(8*K)&255)}let $=new Uint8Array(J);for(let K=0;K<J;K++)$[K]=X[K]^Q[K%4];let W=new Uint8Array(G.length+4+J);W.set(G,0),W.set(Q,G.length),W.set($,G.length+4);try{this.enqueueWrite(W)}catch{}}enqueueWrite(Y){this.writeQueue.push(Y),this.flushWrites()}flushWrites(){let Y=this.socket;if(!Y)return;while(this.writeQueue.length>0){let X=this.writeQueue[0],J=Y.write(X);if(J<X.length){this.writeQueue[0]=X.slice(J),this.log("write_backpressure",{written:J,remaining:X.length-J});return}this.writeQueue.shift()}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return G6({component:"raw-ws-bun",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function BV(Y){return Y}function LV(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function NV(Y){let X=0;for(let G of Y)X+=G.length;let J=new Uint8Array(X),Q=0;for(let G of Y)J.set(G,Q),Q+=G.length;return J}import{connect as jV}from"node:net";import{connect as FV}from"node:tls";var DV="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",DG=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class x4{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];constructor(Y,X,J){this.url=Y,this.sessionID=J?.sessionID,this.connect(Y,X)}addEventListener(Y,X,J){this.listeners[Y]?.add(X)}removeEventListener(Y,X){this.listeners[Y]?.delete(X)}peerClose;closeEmitted=!1;emitClose(Y,X){if(this.closeEmitted)return;this.closeEmitted=!0,this.emit("close",{code:Y,reason:X})}emit(Y,X){for(let J of[...this.listeners[Y]??[]])try{J(X)}catch{}}async connect(Y,X){let J=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),Q=J.hostname,G=J.port?Number(J.port):J.protocol==="https:"?443:80,$=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),K=Buffer.from(W).toString("base64"),U=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(K+DV));this.expectedAccept=Buffer.from(new Uint8Array(U)).toString("base64");let Z={};for(let[N,V]of Object.entries(X))Z[N.toLowerCase()]=V;let B=[`GET ${$} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${K}`];for(let N of DG)if(Z[N]!==void 0)B.push(`${OV(N)}: ${Z[N]}`);for(let[N,V]of Object.entries(X))if(!DG.includes(N.toLowerCase())&&N.toLowerCase()!=="content-length")B.push(`${N}: ${V}`);let O=`${B.join(`\r
|
|
49
|
-
`)}\r
|
|
50
|
-
\r
|
|
51
|
-
`;try{this.log("connect_start",{host:Q,port:G,tls:J.protocol==="https:"});let N=()=>{this.socket?.write(O)},V=J.protocol==="https:"?FV({host:Q,port:G,servername:Q},N):jV({host:Q,port:G},N);this.socket=V,V.on("data",(D)=>{this.onData(typeof D==="string"?Buffer.from(D,"binary"):D)}),V.on("error",(D)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let E=D instanceof Error?D.message:String(D);this.log("socket_error",{message:E}),this.emit("error",{message:E})}),V.on("close",(D)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close",{hadError:D}),this.emitClose(this.peerClose?.code??1006,this.peerClose?.reason??"socket closed")})}catch(N){this.readyState=3,this.log("connect_exception",{message:N instanceof Error?N.message:String(N)}),this.emit("error",{message:N instanceof Error?N.message:String(N)})}}onData(Y){if(this.rxBuffer=_V(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
|
|
52
|
-
\r
|
|
53
|
-
`);if(J===-1)return;let Q=X.slice(0,J),G=Q.split(`\r
|
|
54
|
-
`)[0]??"",$=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=M9(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(J+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 X=Buffer.from(this.rxBuffer).indexOf(`\r
|
|
55
|
-
\r
|
|
56
|
-
`);if(X===-1)return!1;let J=I1(this.rxBuffer,X,Y);if(!J)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:J.status,partial:Y}),this.emit("error",J),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let X=Y[0],J=Y[1],Q=(X&128)!==0,G=X&15,$=(J&128)!==0,W=J&127,K=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],K=4}else if(W===127){if(Y.length<10)return;W=0;for(let Z=0;Z<8;Z++)W=W*256+Y[2+Z];K=10}if($)K+=4;if(Y.length<K+W)return;let U=Y.slice(K,K+W);this.rxBuffer=Y.slice(K+W),this.handleFrame(Q,G,U)}}handleFrame(Y,X,J){if(X===9){this.writeFrame(10,J);return}if(X===10)return;if(X===8){let G=1005,$="";if(J.length>=2)G=J[0]<<8|J[1],$=Buffer.from(J.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(X===1||X===2)this.fragOpcode=X,this.fragChunks=[J];else if(X===0)this.fragChunks.push(J);if(!Y)return;let Q=PV(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,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),G;if(J<126)G=[128|Y,128|J];else if(J<65536)G=[128|Y,254,J>>8&255,J&255];else{G=[128|Y,255];for(let K=7;K>=0;K--)G.push(J/2**(8*K)&255)}let $=new Uint8Array(J);for(let K=0;K<J;K++)$[K]=X[K]^Q[K%4];let W=new Uint8Array(G.length+4+J);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,X){return G6({component:"raw-ws-node",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function OV(Y){return Y}function _V(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function PV(Y){let X=0;for(let G of Y)X+=G.length;let J=new Uint8Array(X),Q=0;for(let G of Y)J.set(G,Q),Q+=G.length;return J}function qV(){return typeof globalThis.Bun?.connect==="function"}var OG=qV()?k4:x4;function b1(Y){return process.env[Y]??process.env[Y.toLowerCase()]}function EV(Y){let X=b1("NO_PROXY");if(!X)return!1;let J=Y.hostname.toLowerCase(),Q=X.split(",").map((G)=>G.trim().toLowerCase()).filter(Boolean);for(let G of Q){if(G==="*")return!0;if(G.startsWith(".")){if(J===G.slice(1)||J.endsWith(G))return!0}else if(J===G||J.endsWith(`.${G}`))return!0}return!1}function MV(Y){let X=new URL(Y);if(EV(X))return;if(X.protocol==="http:")return b1("HTTP_PROXY");if(X.protocol==="https:")return b1("HTTPS_PROXY")??b1("HTTP_PROXY");return}var _G={getProxyForUrl:MV};var AV=B0("quota"),l8=B0("transport"),AG="responses_websockets=2026-02-06",PG=["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"],TV=new Set([y8,"x-opencode-title"]);function RV(Y){let X=new Map;for(let Q of Object.keys(Y))X.set(Q.toLowerCase(),Q);let J={};for(let Q of PG){let G=X.get(Q),$=G===void 0?void 0:Y[G];if(G!==void 0&&$!==void 0)J[G]=$}for(let[Q,G]of Object.entries(Y))if(!PG.includes(Q.toLowerCase()))J[Q]=G;return J}function CV(Y){let X={};for(let[J,Q]of Object.entries(Y)){if(TV.has(J.toLowerCase()))continue;X[J]=Q}return X}function wV(Y){return Y.replace(/^http/,"ws")}function SV(Y){let X={};if(!Y)return X;if(Y instanceof Headers)return Y.forEach((J,Q)=>{X[Q.toLowerCase()]=J}),X;if(Array.isArray(Y)){for(let[J,Q]of Y)X[J.toLowerCase()]=Q;return X}for(let[J,Q]of Object.entries(Y))if(Q!=null)X[J.toLowerCase()]=String(Q);return X}function y4(Y){return Y instanceof DOMException&&Y.name==="AbortError"}var TG=new WeakSet;function IV(Y){return typeof Y==="object"&&Y!==null&&TG.has(Y)}var RG=new WeakSet;function bV(Y){return typeof Y==="object"&&Y!==null&&RG.has(Y)}function CG(Y){return RG.add(Y),Y}function qG(Y,X){let J=Error(Y,X===void 0?void 0:{cause:X});return TG.add(J),J}function kV(Y){return new Promise((X,J)=>{if(Y.signal?.aborted){J(v4(Y.signal));return}let Q={...Y.headers,"openai-beta":Y.headers["openai-beta"]??AG},G=Q[y8]??Q["session-id"];delete Q["content-length"],Q=RV(CV(Q));let $=typeof Bun>"u"?void 0:_G.getProxyForUrl(Y.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),W=!0,K=Y.rawWebSocket?new OG(Y.url,Q,{sessionID:G}):new globalThis.WebSocket(Y.url,{headers:Q,...$?{proxy:$}:{},perMessageDeflate:W}),U=Y.timeout?setTimeout(()=>{Z(),K.close(),J(Error("WebSocket connect timed out"))},Y.timeout):void 0;function Z(){if(U)clearTimeout(U);K.removeEventListener("open",B),K.removeEventListener("error",O),K.removeEventListener("close",N),Y.signal?.removeEventListener("abort",V)}function B(){Z(),X(K)}function O(D){Z(),J(qG(y6(D),D))}function N(D){Z(),J(qG(bG("WebSocket closed before open",D.code,D.reason)))}function V(){Z(),K.close(),J(v4(Y.signal))}K.addEventListener("open",B,{once:!0}),K.addEventListener("error",O,{once:!0}),K.addEventListener("close",N,{once:!0}),Y.signal?.addEventListener("abort",V,{once:!0})})}function xV(Y){let X=new TextEncoder,J=Y.socket,Q,G=()=>{},$=!1,W=0,K=!1,U=!1,Z,B=[],O=12,N=[],V=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,E={sessionID:Y.sessionID,codexSessionID:D},P,T=0,w,x=new Set,j={addedItemIds:new Set,reasoningItemIds:new Set,finished:!1,other:!1};function S(){if(Z)clearTimeout(Z);G(),Y.signal?.removeEventListener("abort",x0)}function h(r=J){r.close()}function M(){S(),Q?.enqueue(X.encode(`data: [DONE]
|
|
57
|
-
|
|
58
|
-
`)),Q?.close()}function y(r){u(r,r)}function n(){if(!U)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 o(){Q?.enqueue(X.encode(`data: ${JSON.stringify(uV)}
|
|
59
|
-
|
|
60
|
-
`)),M()}function V0(r){let _0={...E,openingFrameTypes:B,openingItemTypes:N,responseID:P,previousResponseID:V,hasContinuation:V!==void 0,framesSinceCreated:T,msSinceLastFrame:w===void 0?void 0:Date.now()-w},l=n();if(l==="finished-calls"){if($)return;l8.warn("stream failed after finished function calls only; ended as completed",{reason:r.message,emittedOutput:!0,outputShape:l,..._0}),$=!0,S(),Y.onConnectionInvalid?.(r),o();return}if(l==="other"){let p=h4;l8.warn("stream failed after output; not retried",{reason:r.message,emittedOutput:!0,outputShape:l,..._0}),u(Error(p,{cause:r}),new i0(p,{cause:r}));return}let I=j.reasoningItemIds.size;l8.warn(l==="unfinished-calls"?"stream failed after unfinished function calls only; retryable":I>0?"stream failed after reasoning without text only; retryable":"stream failed before output; retryable",{reason:r.message,emittedOutput:U,outputShape:l,emptyReasoningItems:I,..._0}),y(r)}function u(r,_0){if($)return;$=!0,S(),Y.onConnectionInvalid?.(_0),Q?.error(r)}function G0(r){if($)return;if(!Y.idleTimeout)return;if(Z)clearTimeout(Z);Z=setTimeout(()=>V0(new i0(r)),Y.idleTimeout)}async function J0(r){if($)return;if(typeof r.data!=="string"){V0(new i0("Unexpected binary WebSocket frame"));return}let _0=r.data,l=(()=>{try{let g=JSON.parse(_0);return typeof g==="object"&&g!==null?g:void 0}catch{return}})();if(l?.type==="codex.rate_limits"){AV.debug("codex.rate_limits frame received",{pid:process.pid}),G0("idle timeout waiting for websocket");let g=MG(l);Y.onQuota?.(g);return}let I=n(),p=I==="none"||I==="unfinished-calls"?A9(l):void 0;if(p&&l){$=!0,S(),Y.onRateLimitReached?.(p.window,p.resetAt),Y.onTerminal?.(l),Y.onFirstEvent?.(),Q?.error(new i0(`OpenAI account rate limit reached at admission (${p.window})`));return}if(l?.type==="error"&&Y.onRetryableTerminal){if(G(),Z)clearTimeout(Z);Z=void 0;try{let g=await Y.onRetryableTerminal(l);if($){if(g)h(g);return}if(g){H0(g);return}}catch(g){V0(new i0(g instanceof Error?g.message:String(g),{cause:g}));return}}let d=yV(l,_0);if(d&&l){if(!K)Y.onFirstEvent?.(d);$=!0,S(),Y.onTerminal?.(l);let g=new z6({message:d.message,url:J.url,requestBodyValues:Y.body,statusCode:d.status,responseHeaders:d.headers,responseBody:d.body}),W0=n();if(W0==="none"||W0==="unfinished-calls"){if(W0==="unfinished-calls")l8.warn("protocol error after unfinished function calls only; surfaced as before output",{...E,status:d.status,reason:d.message,outputShape:W0,responseID:P,previousResponseID:V});Q?.error(g);return}if(l8.warn(W0==="finished-calls"?"protocol error after finished function calls only; ended as completed":"protocol error after output; not retried",{...E,status:d.status,reason:d.message,outputShape:W0,responseID:P,previousResponseID:V}),W0==="finished-calls"){o();return}Q?.error(Error(h4,{cause:g}));return}if(s(l)&&l.type==="response.failed"){let g=s(l.response)?l.response.failed:void 0,W0=s(g)?g.rate_limit_reached_type:void 0;if(typeof W0==="string"){$=!0,S(),Y.onRateLimitReached?.(W0),Y.onTerminal?.(l);let q0=n();if(q0!=="none")l8.warn(q0==="other"?"rate limit reached after output; ended without retry":q0==="finished-calls"?"rate limit reached after finished function calls only; ended as completed":"rate limit reached after unfinished function calls only; retryable",{...E,outputShape:q0,responseID:P,previousResponseID:V});if(q0==="none"||q0==="unfinished-calls")Y.onFirstEvent?.(),Q?.error(new i0(`OpenAI account rate limit reached mid-stream (${W0})`));else if(q0==="finished-calls")o();else M();return}}if(!l){if(!K)Y.onFirstEvent?.();G0("idle timeout waiting for websocket");return}if(vV(l,x),!K)Y.onFirstEvent?.();if(Q?.enqueue(X.encode(`${_0.split(/\r?\n/).map((g)=>`data: ${g}`).join(`
|
|
61
|
-
`)}
|
|
62
|
-
|
|
63
|
-
`)),K=!0,w=Date.now(),P!==void 0)T++;if(B.length<O)B.push(String(l.type));if(l.type==="response.output_item.added"&&N.length<O)N.push(s(l.item)?String(l.item.type):"unknown");if(l.type==="response.created")P=mV(l),l8.debug("response created",{...E,responseID:P,previousResponseID:V,hasContinuation:V!==void 0});if(!SG(l.type))U=!0,cV(l,j);if(G0("idle timeout waiting for websocket"),l.type==="response.completed"||l.type==="response.done"){$=!0,hV(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 T0(r){V0(new i0(y6(r),{cause:r}))}function v(r){if($)return;let _0=r.code===1009,l=new i0(_0?IG:bG("WebSocket closed before response.completed",r.code,r.reason),{retryable:!_0});if(_0)l8.warn("websocket peer refused the request size",{...E,requestBytes:W,reason:r.reason.toString()});V0(_0?CG(l):l)}function x0(){let r=v4(Y.signal);if($)return;$=!0,S(),h(),Y.onAbort?.(r),Q?.error(r)}function R0(r){if($)return;$=!0,S(),h(),Y.onAbort?.(gV(r))}function H0(r){G(),J=r,J.addEventListener("message",J0),J.addEventListener("error",T0,{once:!0}),J.addEventListener("close",v,{once:!0}),G=()=>{J.removeEventListener("message",J0),J.removeEventListener("error",T0),J.removeEventListener("close",v)};let{background:_0,...l}=Y.body;G0("idle timeout sending websocket request");try{let I=JSON.stringify({type:"response.create",...l});W=I.length,J.send(I),G0("idle timeout waiting for websocket")}catch(I){if($)return;y(new i0(I instanceof Error?I.message:String(I),{cause:I}))}}return new Response(new ReadableStream({start(r){if(Q=r,Y.signal?.addEventListener("abort",x0,{once:!0}),Y.signal?.aborted){x0();return}H0(J)},cancel(r){R0(r)}}),{status:200,headers:{"content-type":"text/event-stream"}})}function vV(Y,X){if(Y.type!=="response.output_item.done")return;if(!s(Y.item))return;wG(Y.item,X)}function hV(Y,X){let J=Y.response;if(!s(J)||!Array.isArray(J.output))return;for(let Q of J.output)if(s(Q))wG(Q,X)}function wG(Y,X){if(Y.type!=="function_call"&&Y.type!=="custom_tool_call")return;let J=typeof Y.call_id==="string"?Y.call_id:typeof Y.id==="string"?Y.id:void 0;if(J)X.add(J)}function yV(Y,X){if(Y?.type!=="error")return;let J=Y.status??Y.status_code;if(typeof J!=="number"||J>=200&&J<300)return;return{status:J,headers:s(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:X,message:s(Y.error)&&typeof Y.error.message==="string"?Y.error.message:`${J}`}}function A9(Y){if(typeof Y==="string")try{return A9(JSON.parse(Y))}catch{return}if(!s(Y))return;let X=A9(Y.cause);if(X)return X;let J=A9(Y.body);if(J)return J;let Q=s(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:K}=Q,U=typeof W==="number"&&Number.isFinite(W)&&W>0?W*1000:typeof K==="number"&&Number.isFinite(K)&&K>0?Date.now()+K*1000:void 0;return{window:G??"primary",resetAt:U}}function gV(Y){if(y4(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function v4(Y){let X=Y?.reason;if(y4(X))return X;if(fV(X))return X;return new DOMException(X instanceof Error?X.message:"Aborted","AbortError")}function fV(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function mV(Y){let X=Y.response;if(!s(X))return;return typeof X.id==="string"?X.id:void 0}function cV(Y,X){let J=s(Y.item)?Y.item:void 0;switch(Y.type){case"response.output_item.added":if(J?.type==="function_call"&&typeof J.id==="string"){X.addedItemIds.add(J.id);return}if(EG(J)&&typeof J?.id==="string"){X.reasoningItemIds.add(J.id);return}break;case"response.function_call_arguments.delta":case"response.function_call_arguments.done":if(typeof Y.item_id==="string"&&X.addedItemIds.has(Y.item_id))return;break;case"response.output_item.done":if(J?.type==="function_call"&&J.status==="completed"&&typeof J.id==="string"&&typeof J.call_id==="string"&&typeof J.name==="string"&&typeof J.arguments==="string"){X.finished=!0;return}if(EG(J)&&typeof J?.id==="string"&&X.reasoningItemIds.has(J.id))return;break}X.other=!0}function EG(Y){if(Y?.type!=="reasoning")return!1;let X=(J)=>J===void 0||J===null||Array.isArray(J)&&J.length===0;return X(Y.summary)&&X(Y.content)}var uV={type:"response.completed",response:{status:"completed",incomplete_details:null,usage:{input_tokens:0,output_tokens:0,total_tokens:0}}};function SG(Y){return Y==="response.created"||Y==="response.in_progress"||Y.startsWith("codex.")}var h4="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.",IG="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 bG(Y,X,J){let Q=[`code ${X}`];if(J.length>0)Q.push(J.toString());return`${Y} (${Q.join(": ")})`}var f4="x-opencode-title",k1="x-openai-auth-quota-account",g4=new Set([f4,y8,k1,"x-opencode-session"]),lV=15000,dV=300000,iV=3300000,kG="websocket_connection_limit_reached";function nV(Y){let X=typeof Y["chatgpt-account-id"]==="string"?Y["chatgpt-account-id"]:"",J=typeof Y.authorization==="string"&&Y.authorization.startsWith("Bearer ")?Y.authorization.slice(7):"",Q=X?`acct:${X}`:`tok:${J}`;return pV("sha256").update(Q).digest("hex").slice(0,12)}function oV(Y){let X=Y?.httpFetch??globalThis.fetch,J=new Map,Q=Y?.connectTimeout??lV,G=Y?.idleTimeout??dV,$=Y?.maxConnectionAge??iV,W=Y?.streamRetries??5,K=Y?.firstEventGraceMs??250,U=Y?.rawWebSocket??!1,Z=Y?.onQuota,B=Y?.onRateLimitReached,O=setInterval(()=>E(),Math.min(G,60000));if(typeof O==="object"&&"unref"in O&&typeof O.unref==="function")O.unref();function N(w,x,j,S){if(!x||!j)return j;m4(w,xG(x),void 0,S);let h=new Headers(j.headers),M=h.get("x-codex-turn-metadata");if(!M)return j;let y=uG(M,w.turnID,w.turnStartedAt);if(!y)return j;return h.set("x-codex-turn-metadata",y),{...j,headers:h}}async function V(w,x){let j=w instanceof URL?w.toString():typeof w==="string"?w:w.url,S=y0.normalizeHeaders(x?.headers),h=nG(x),M=e9(h);if(x?.method!=="POST"||!new URL(j).pathname.endsWith("/responses"))return X(w,M);let y=(()=>{try{if(typeof x?.body!=="string")return;let H0=JSON.parse(x.body);return typeof H0==="object"&&H0!==null?H0:void 0}catch{return}})();if(!y?.stream)return X(w,M);if(S[f4]==="true")return X(w,M);let n=S[y8]??S["x-session-affinity"]??S["session-id"],o=n;if(!n)return X(w,M);let V0=y0.normalizeHeaders(h?.headers),u=nV(V0),G0=`${n}:${u}:conversation`,J0=typeof S[k1]==="string"?S[k1]:void 0,T0=B?(H0,r)=>B(H0,J0,r):void 0,v=J.get(G0)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};J.set(G0,v);let x0=xG(y),R0;if(v.fallback)return X(w,N(v,y,M,R0));if(v.busy)return X(w,N(v,y,M,R0));v.busy=!0,v.lastUsedAt=Date.now();try{R0=g6(v,x0);let H0=y0.normalizeHeaders(h?.headers),r=typeof H0.authorization==="string"&&H0.authorization.startsWith("Bearer ")?H0.authorization.slice(7):"",_0=typeof H0["chatgpt-account-id"]==="string"?H0["chatgpt-account-id"]:void 0,l=Z?(P0)=>Z(P0,r,J0,_0):void 0,I=!v.socket&&!v.continuation?QB(H0):H0;if(v.socket=await tV(v,Y?.url??j,I,Q,$,U,x?.signal),WB(v,x0,R0))await eV(v,x0,G,{signal:x?.signal??void 0,sessionID:o,url:Y?.url??j,headers:h?.headers,onRateLimitReached:T0});let p=()=>{},d=()=>{},g=new Promise((P0,K8)=>{p=P0,d=K8}),W0=$B(v,x0,R0),q0=T9(cG(v,W0,x0,R0)),Y8=typeof q0.previous_response_id==="string";await w6({sessionID:o,transport:"websocket",phase:"main",bodyText:()=>JSON.stringify(q0),url:Y?.url??j,method:h?.method,headers:h?.headers});let C0=y0.streamResponsesWebSocket({socket:v.socket,body:q0,sessionID:o??void 0,idleTimeout:G,signal:x?.signal??void 0,onQuota:l,onRateLimitReached:T0,onFirstEvent:(P0)=>p(P0??!0),onComplete:(P0,K8)=>{let m6=yG(P0);G6({component:"ws-pool",event:"main_completed",sessionID:o,responseID:hG(P0),usage:m6}),mG(v,x0,P0,K8,Y8,R0)},onTerminal:(P0)=>{if(v.busy=!1,v.lastUsedAt=Date.now(),v.streamFailures=0,P0.type!=="response.completed"&&P0.type!=="response.done")v.continuation=void 0,I8(v)},onConnectionInvalid:(P0)=>{if(v.busy=!1,v.lastUsedAt=Date.now(),y0.isOversizedFrame(P0))v.fallback=!0;if(!v.fallback)D(v);v.continuation=void 0,I8(v),p(!1)},onAbort:(P0)=>{v.busy=!1,v.lastUsedAt=Date.now(),v.streamFailures=0,v.continuation=void 0,I8(v),d(P0)},onRetryableTerminal:async(P0)=>{let K8=vG(P0);if(!K8)return;throw v.fallback=!0,K8}}),f0=await rV(g,K);if(f0!==!1){if(f0===!0||f0.status<200||f0.status>599)return C0;return new Response(f0.body,{status:f0.status,headers:{"content-type":"application/json",...f0.headers}})}let n0=()=>X(w,N(v,y,M,R0));if(!v.fallback)return sV(C0,n0);return n0()}catch(H0){if(v.busy=!1,v.lastUsedAt=Date.now(),y0.isAbortError(H0))throw v.streamFailures=0,v.continuation=void 0,I8(v),H0;let r=y0.parseRateLimitSignal(H0);if(r)T0?.(r.window,r.resetAt);if(y0.isUpgradeFailure(H0)&&!U)v.fallback=!0;if(D(v),v.continuation=void 0,I8(v),v.fallback)return X(w,N(v,y,M,R0));return aV(new i0(H0 instanceof Error?H0.message:String(H0),{cause:H0}))}}function D(w){if(w.streamFailures++,w.streamFailures>W)w.fallback=!0}function E(){let w=Date.now();for(let[x,j]of J){if(j.busy)continue;if(w-j.lastUsedAt<G)continue;I8(j),J.delete(x)}}function P(){clearInterval(O);for(let w of J.values())I8(w);J.clear()}function T(w){let x=`${w}:`;for(let[j,S]of J){if(!j.startsWith(x))continue;I8(S),J.delete(j)}}return Object.assign(V,{close:P,remove:T})}function vG(Y){if(Y.type!=="error"||!s(Y.error)||Y.error.code!==kG)return;return Error(typeof Y.error.message==="string"?Y.error.message:kG)}async function rV(Y,X){if(X<=0)return!1;return new Promise((J,Q)=>{let G=setTimeout(()=>J(!1),X);Y.then(($)=>{clearTimeout(G),J($)},($)=>{clearTimeout(G),Q($)})})}function sV(Y,X){let J=Y.body;if(!J)return Y;let Q=!1,G=new ReadableStream({async start($){let W=J.getReader(),K=async(U)=>{while(!0){let{done:Z,value:B}=await U.read();if(Z)return;if(B&&B.length>0)Q=!0,$.enqueue(B)}};try{await K(W),$.close()}catch(U){if(Q||!y0.isOversizedFrame(U)){$.error(U);return}try{let Z=await X();if(!Z.ok){$.error(new i0(`HTTP fallback after an oversized WebSocket frame failed with ${Z.status}`));return}if(Z.body)await K(Z.body.getReader());$.close()}catch(Z){$.error(Z)}}},cancel($){J.cancel($)}});return new Response(G,{status:Y.status,headers:Y.headers})}function aV(Y){return new Response(new ReadableStream({start(X){X.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function tV(Y,X,J,Q,G,$,W){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<G)return Y.socket;I8(Y);let K=await y0.connectResponsesWebSocket({url:y0.toWebSocketUrl(X),headers:J,timeout:Q,rawWebSocket:$,signal:W??void 0});return Y.connectedAt=Date.now(),K}function I8(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function eV(Y,X,J,Q){if(!Y.socket||!Array.isArray(X.input)||X.input.length===0)return;let G=XB(X);await w6({sessionID:Q.sessionID,transport:"websocket",phase:"prewarm",bodyText:()=>JSON.stringify(G),url:Q.url,method:"POST",headers:Q.headers});let $=y0.streamResponsesWebSocket({socket:Y.socket,body:G,sessionID:Q.sessionID,idleTimeout:J,signal:Q.signal,onRateLimitReached:Q.onRateLimitReached,onComplete:(W,K)=>{G6({component:"ws-pool",event:"prewarm_completed",sessionID:Q.sessionID,responseID:hG(W),usage:yG(W)}),mG(Y,G,W,K,!1,{input:$6([]),signature:dG(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 K=vG(W);if(!K)return;throw Y.fallback=!0,K}});await YB($)}function hG(Y){let X=Y.response;if(!s(X))return;return typeof X.id==="string"?X.id:void 0}function yG(Y){let X=Y.response;if(!s(X))return;return s(X.usage)?X.usage:void 0}async function YB(Y){let X=Y.body?.getReader();if(!X)return;while(!0)if((await X.read()).done)return}function XB(Y){return T9({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:JB(Y.client_metadata)})}function gG(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 JB(Y){if(!s(Y))return Y;if(typeof Y["x-codex-turn-metadata"]!=="string")return Y;try{let X=JSON.parse(Y["x-codex-turn-metadata"]);if(!s(X))return Y;return{...Y,"x-codex-turn-metadata":gG(X),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function QB(Y){let X=Y["x-codex-turn-metadata"];if(!X)return Y;try{let J=JSON.parse(X);if(!s(J))return Y;return{...Y,"x-codex-turn-metadata":gG(J)}}catch{return Y}}var fG=["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 xG(Y){let X={...Y};if(Array.isArray(Y.input))X.input=Y.input.map(GB);return X}function T9(Y){let X={};for(let J of fG)if(J in Y)X[J]=Y[J];for(let J of Object.keys(Y))if(!(J in X))X[J]=Y[J];return X}function GB(Y){if(!s(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 mG(Y,X,J,Q,G,$=g6(Y,X)){let W=J.response,K=s(W)&&typeof W.id==="string"?W.id:void 0;if(!K||!Array.isArray(X.input)){Y.continuation=void 0;return}let U=G?new Set(Y.continuation?.finalizedCallIds):new Set;for(let Z of Q)U.add(Z);Y.continuation={responseID:K,input:X.input,signature:$.signature,canonical:K9($.input),finalizedCallIds:U}}function m4(Y,X,J=X,Q=g6(Y,{...J,input:Array.isArray(J.input)?J.input:X.input})){let G=Array.isArray(X.input)?X.input:[],$=Array.isArray(J.input)?J.input:G,W=Q.signature,K=Y.turnInput&&Y.turnSignature===W?U9(pG(Q,Y.turnInput),Q.input):void 0,U=K===void 0?G:$.slice(K);if(U.length>0&&U.some(lG)||!Y.turnID)Y.turnID=W6(),Y.turnStartedAt=Date.now();Y.turnInput=$.slice(),Q.priorInputs.set(Y.turnInput,Q.input),Y.turnSignature=W,Y.turnCanonical=K9(Q.input)}function cG(Y,X,J=X,Q=g6(Y,{...J,input:Array.isArray(J.input)?J.input:X.input})){m4(Y,X,J,Q);let G=X.client_metadata;if(!s(G)||typeof G["x-codex-turn-metadata"]!=="string")return X;let $=uG(G["x-codex-turn-metadata"],Y.turnID,Y.turnStartedAt);if(!$)return X;return{...X,client_metadata:{...G,"x-codex-turn-metadata":$}}}function uG(Y,X,J){let Q;try{Q=JSON.parse(Y)}catch{return}if(!s(Q))return;return JSON.stringify({session_id:Q.session_id,thread_id:Q.thread_id,thread_source:Q.thread_source,turn_id:X,sandbox:Q.sandbox,turn_started_at_unix_ms:J,request_kind:"turn",window_id:Q.window_id})}function g6(Y,X){let J=Array.isArray(X.input)?X.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=$6(J,Y.turnCanonical??Y.continuation?.canonical);return Q.set(J,G),{input:G,signature:dG(X),priorInputs:Q}}function pG(Y,X){let J=Y.priorInputs.get(X);if(!J){for(let[Q,G]of Y.priorInputs)if(Q.length===X.length&&Q.every(($,W)=>$===X[W])){J=G;break}J??=$6(X),Y.priorInputs.set(X,J)}return J}function $B(Y,X,J=g6(Y,X)){let Q=Array.isArray(X.input)?X.input:void 0;if(!Q||!Y.continuation)return X;if(Y.continuation.signature!==J.signature)return Y.continuation=void 0,X;if(!iG(Y.continuation,J))return Y.continuation=void 0,X;if(Y.continuation.input.length===0)return{...X,previous_response_id:Y.continuation.responseID};let G=Q.slice(Y.continuation.input.length),$=zB(G,Y.continuation.finalizedCallIds);if($.length===0)return X;return{...X,previous_response_id:Y.continuation.responseID,input:$}}function WB(Y,X,J=g6(Y,X)){let Q=Array.isArray(X.input)?X.input:void 0;if(!Y.continuation)return!0;if(!Q)return!1;if(!iG(Y.continuation,J))return!0;return Q.slice(Y.continuation.input.length).some(lG)}function lG(Y){if(!s(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function zB(Y,X){return Y.filter((J)=>{if(!s(J))return!0;if(typeof J.type==="string"&&J.type.endsWith("_output"))return!0;if(J.type==="function_call_output"||J.type==="custom_tool_call_output")return!0;if(J.type==="function_call"||J.type==="custom_tool_call"){let Q=typeof J.call_id==="string"?J.call_id:typeof J.id==="string"?J.id:void 0;return Q?!X.has(Q):!0}if(J.type==="message")return J.role!=="assistant";if(typeof J.role==="string")return J.role!=="assistant";return!1})}function dG(Y){return b6(KB(Object.fromEntries(Object.entries(Y).filter(([X])=>X!=="input"&&X!=="stream"&&X!=="background"&&X!=="previous_response_id"&&X!=="generate"))))}function KB(Y){if(!s(Y.client_metadata))return Y;let X=Object.fromEntries(Object.entries(Y.client_metadata).filter(([J])=>J!=="x-codex-turn-metadata"&&J!=="x-codex-ws-stream-request-start-ms"));return{...Y,client_metadata:X}}function iG(Y,X){if(Y.input.length>=X.input.texts.length)return!1;return U9(pG(X,Y.input),X.input)!==void 0}function nG(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let X=new Headers(Y.headers);for(let J of g4)X.delete(J);return{...Y,headers:X}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((X)=>!g4.has(X[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([X])=>!g4.has(X.toLowerCase())))}}var FB=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),DB=new Set(["gpt-5.6","gpt-6","gpt-6.1"]);function OB(Y){if(FB.has(Y))return!0;if(DB.has(Y))return!1;let J=Y.match(/^gpt-(\d+(?:\.\d+)?)/)?.[1];return J?parseFloat(J)>5.4:!1}function _B(Y){if(Y.includes("gpt-5.5"))return{context:400000,input:272000,output:128000};if(Y.includes("gpt-6-astra"))return{context:872000,input:744000,output:128000};if(Y.includes("gpt-6.1-sol"))return{context:500000,input:372000,output:128000};if(Y.includes("gpt-5.6")||Y.includes("gpt-6-sol")||Y.includes("gpt-6-luna"))return{context:372000,input:244000,output:128000};return}var PB="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.",qB=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"]),EB="opencode-oauth-dummy-key",MB="terminal_resize_reflow",o4="0.159.0",AB=`codex_exec/${o4} (Debian 12.0.0; aarch64) unknown (codex_exec; ${o4})`,TB="seccomp",Wq=()=>a6,RB=120000,CB=90000,wB=4000,oG=50,rG=3,SB=25,IB=60000,bB="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",r4=!1,g1;function zq(){return g1}function Kq(){r4=!1,g1=void 0}var sG=B0("models"),aG=!1,tG=!1;class a4 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 g0 extends Error{code;constructor(Y,X){super(X);this.name="ResetTargetResolutionError",this.code=Y}}function u4(Y,X,J,Q){let G=(J?.refresh?.refreshBeforeExpiryMinutes??240)*60000;return!Y||!X||X-Q<=G}function kB(Y,X){let J=Y==="main",Q=X.row,G=()=>new g0("token_unavailable",J?"Main OpenAI account has no usable access token.":`Fallback account ${Y} has no usable access token.`);if(!Q){if(J)throw G();throw new g0("unknown_account",`Fallback account ${Y} was not found.`)}if(!Q.enabled)throw new g0("disabled_account",`${J?"Main":"Fallback"} account ${Y} is disabled.`);if(Q.type!=="oauth")throw new g0("non_oauth_account",`${J?"Main":"Fallback"} account ${Y} is not an OAuth account.`);if(!X.token)throw G();let $=N8(X.token);return{accountKey:Y,label:J?"Main account":Q.label??Y,accessToken:X.token,chatgptAccountId:Q.identity??($?j8($):void 0)}}function xB(Y){async function X(){let J=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),Q=o8(J);if(!J||!Q||c0(Q))throw new g0("token_unavailable","Main OpenAI account has no usable access token.");let G=Q;if(u4(G.access,G.expires,J,Y.now()))G=await(Y.refreshPoolMainRow??Y.refreshFallbackAccount)(G,J);if(!G.access)throw new g0("token_unavailable","Main OpenAI account has no usable access token.");let $=N8(G.access);return{accountKey:"main",label:"Main account",accessToken:G.access,chatgptAccountId:G.accountId??($?j8($):void 0)}}return async(J)=>{let Q=await Y.poolAccess?.(J);if(Q)return kB(J,Q);if(J==="main"){let B=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),O=await Y.getAuth();if(s0(O))return X();if(O.type!=="oauth")throw new g0("non_oauth_account","Main OpenAI account is not authenticated with OAuth.");if(u4(O.access,O.expires,B,Y.now()))try{O={type:"oauth",...await Y.refreshMainWithLease()}}catch(E){if(E instanceof r8)return X();throw E}if(!O.access)throw new g0("token_unavailable","Main OpenAI account has no usable access token.");let N=N8(O.access),V=N?j8(N):void 0,D=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath});return{accountKey:J,label:"Main account",accessToken:O.access,chatgptAccountId:V??D?.mainAccountId}}let G=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),$=G?.accounts.find((B)=>B.id===J);if(!G||!$)throw new g0("unknown_account",`Fallback account ${J} was not found.`);if($.enabled===!1)throw new g0("disabled_account",`Fallback account ${J} is disabled.`);if(!a0($))throw new g0("non_oauth_account",`Fallback account ${J} is not an OAuth account.`);let W=()=>new g0("token_unavailable",`Fallback account ${J} has no usable access token.`);if(c0($))throw W();let K=$;if(u4(K.access,K.expires,G,Y.now()))K=await Y.refreshFallbackAccount(K,G);if(!K.access)throw W();let U=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),Z=U?.accounts.find((B)=>B.id===J);if(!U||!Z)throw new g0("unknown_account",`Fallback account ${J} was not found.`);if(Z.enabled===!1)throw new g0("disabled_account",`Fallback account ${J} is disabled.`);if(!a0(Z))throw new g0("non_oauth_account",`Fallback account ${J} is not an OAuth account.`);return{accountKey:J,label:K.label??J,accessToken:K.access,chatgptAccountId:Z.accountId}}}function vB(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function p4(Y){return Y instanceof a4}function eG(){throw Error(bB)}async function hB(Y,X={}){let J=U0(Y0());if(QY(J.configPath)){await n8(_6(J),X.holdsMainRefreshLock?void 0:A8(J),(Q)=>{if(X.canWrite&&!X.canWrite())throw Error(Q6["vault-refused"]);Y(Q)});return}await i9((Q)=>{return Y(Q),Q},J,{canWrite:X.canWrite})}var x$=null;function Uq(){return x$}function yB(Y){return Math.floor(Math.random()*Y)}var gB=!0;function fB(Y){if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return typeof X==="object"&&X!==null&&!Array.isArray(X)?X:void 0}catch{return}}function mB(Y,X,J){let Q=Y.get(X);if(Q)return Q;let G=W6(),$={threadID:G,turnID:W6(),windowID:`${G}:0`};return Y.set(X,$),J?.(),$}function v$(){return jB(f9(),"openai-auth-sessions.json")}function cB(){let Y=new Map;try{let X=JSON.parse(VB(v$(),"utf8"));if(!s(X.sessions))return Y;for(let[J,Q]of Object.entries(X.sessions)){if(!s(Q)||typeof Q.threadID!=="string")continue;Y.set(J,{threadID:Q.threadID,turnID:W6(),windowID:`${Q.threadID}:0`})}}catch{}return Y}function uB(Y){let X=v$(),J=`${X}.tmp-${process.pid}`;try{ZB(f9(),{recursive:!0});let Q={version:1,sessions:Object.fromEntries([...Y.entries()].map(([G,$])=>[G,{threadID:$.threadID}]))};NB(J,`${JSON.stringify(Q,null,2)}
|
|
64
|
-
`,"utf8"),BB(J,X)}catch{}}function f1(Y,X){return s(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===X}function pB(Y,X,J){if(!Y.input)return X.length>0;let Q=Y.canonicalInput??$6(Y.input);if(U9(Q,J)===void 0)return!0;return X.slice(Y.input.length).some(($)=>f1($,"user")||f1($,"developer"))}function lB(Y,X){let J=Array.isArray(X?.input)?X.input:void 0,Q=J?$6(J,Y.canonicalInput):void 0;if(J&&Q&&(pB(Y,J,Q)||!Y.turnID))Y.turnID=W6(),Y.turnStartedAt=Date.now();else if(!Y.turnStartedAt)Y.turnStartedAt=Date.now();if(J&&Q)Y.input=J.slice(),Y.canonicalInput=K9(Q)}function dB(Y){let X=Y.headers.get(m1);if(Y.headers.delete(m1),!Y.metadata)return{init:Y.init};let J=fB(Y.init?.body);if(!Y.websocket)lB(Y.metadata,J);else if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Date.now();if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Date.now();let Q=JSON.stringify({session_id:Y.metadata.threadID,thread_id:Y.metadata.threadID,thread_source:"user",turn_id:Y.metadata.turnID,sandbox:TB,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",MB),Y.headers.set("x-codex-turn-metadata",Q),Y.headers.set("user-agent",AB),Y.headers.set("version",o4),Y.dumpSessionID)Y.headers.set(y8,Y.dumpSessionID);let G=J;if(!G)return{init:Y.init};let $=Y.responsesLite&&typeof G.model==="string"&&qB.has(G.model);if($&&!Y.websocket)Y.headers.set("x-openai-internal-codex-responses-lite","true");if(G.prompt_cache_key=Y.metadata.threadID,G.parallel_tool_calls??=!0,Array.isArray(G.tools))G.tools=G.tools.map(aB);if(rB(G,Y.metadata,X),$)sB(G);let W={...typeof G.client_metadata==="object"&&G.client_metadata!==null?G.client_metadata:{},"x-codex-installation-id":Y.installationID,"x-codex-window-id":Y.metadata.windowID};if(Y.websocket){if(W["x-codex-turn-metadata"]=Q,W["x-codex-ws-stream-request-start-ms"]=String(Date.now()),$)W.ws_request_header_x_openai_internal_codex_responses_lite="true"}return G.client_metadata=W,Y.headers.delete("content-length"),Y.headers.delete("Content-Length"),{init:{...Y.init,body:JSON.stringify(T9(G))}}}function iB(Y,X){return Y.find((J)=>J.enabled!==!1&&a0(J)&&(J.id===X||J.accountId===X))}function Y$(Y,X){if(!X)return Y;let J={...Y};for(let Q of["resetCreditsAvailable","resetCreditsApplicable"]){let G=X[Q];if(J[Q]===void 0&&G!==void 0)J[Q]=G}if(J.spendControl===void 0&&J.spendControlCleared!==!0&&X.spendControl!==void 0)J.spendControl=X.spendControl;return J}function x1(Y,X){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:X}}function h$(Y,X,J=Date.now(),Q=X.mainAccountId){let G=Y.getMain(),$=G?.quota;return{main:{quota:$?{...$,checkedAt:G.checkedAt,primary:x1($.primary,G.checkedAt),secondary:x1($.secondary,G.checkedAt)}:null,...typeof Q==="string"?{mainAccountId:Q}:{},killed:!1,...$?.resetCreditsAvailable!==void 0?{resetCredits:$.resetCreditsAvailable}:{}},fallbacks:X.accounts.filter((W)=>W.enabled).map((W)=>{let K=Y.getFallback(W.id),U=K?.quota;return{id:W.id,label:W.label,accountId:K?.accountId??W.accountId,quota:U?{...U,checkedAt:K.checkedAt,primary:x1(U.primary,K.checkedAt),secondary:x1(U.secondary,K.checkedAt)}:null,killed:!1,enabled:!0,...U?.resetCreditsAvailable!==void 0?{resetCredits:U.resetCreditsAvailable}:{}}}),route:X.routing?.mode??"main-first",lastUpdated:J}}function Hq(Y,X,J,Q=Date.now()){return{...h$(Y,X,Q),activeId:J}}function X$(Y,X){if(X?.headers!==void 0)return new Headers(X.headers);if(Y instanceof Request)return new Headers(Y.headers);return new Headers}async function l4(Y,X){if(!(Y instanceof Request))return X;let J=new Request(Y,X),Q=J.method.toUpperCase(),G=Q==="GET"||Q==="HEAD"||J.body===null?void 0:await J.text();return{method:J.method,headers:new Headers(J.headers),body:G,signal:J.signal,cache:J.cache,credentials:J.credentials,integrity:J.integrity,keepalive:J.keepalive,mode:J.mode,redirect:J.redirect,referrer:J.referrer,referrerPolicy:J.referrerPolicy}}function J$(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}function s4(Y){if(Array.isArray(Y)){let J=Y;for(let Q=0;Q<Y.length;Q++){let G=s4(Y[Q]);if(G===Y[Q])continue;if(J===Y)J=Y.slice();J[Q]=G}return J}if(!s(Y))return Y;let X=Y;for(let J of Object.keys(Y)){if(Y.type==="input_image"&&J==="detail"){if(X===Y)X={...Y};delete X[J];continue}let Q=s4(Y[J]);if(Q===Y[J])continue;if(X===Y)X={...Y};X[J]=Q}return X}var nB=new Set(["gpt-6-astra","gpt-6-sol","gpt-6-luna","gpt-6.1-sol"]),m1="x-openai-auth-agent",oB=new Set(["title","compaction","summary"]);function rB(Y,X,J){if(J!==null&&oB.has(J))return;let Q=typeof Y.model==="string"?Y.model:"";if(!nB.has(Q))return;let G=s(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;X.effortUpdates??=[];let K=X.effortUpdates,U=(N)=>UB("sha256").update(b6(N)).digest("hex").slice(0,16);if(X.pinnedEffort===void 0||K.some((N)=>!W||!f1(W[N.anchor],"user")||U(W[N.anchor])!==N.fingerprint)){X.pinnedEffort=$,X.effortUpdates=[];return}if(!W||W.length===0)return;let Z=W.findLastIndex((N)=>f1(N,"user")),B=K.at(-1),O=B?.effort??X.pinnedEffort;if(Z>=0&&$!==O)if(B?.anchor===Z){let N=K.at(-2)?.effort??X.pinnedEffort;if($===N)K.pop();else B.effort=$}else K.push({anchor:Z,fingerprint:U(W[Z]),effort:$});else if(Z<0&&$!==O)return;if(K.some((N,V)=>V>0&&N.anchor<=(K[V-1]?.anchor??-1))){X.pinnedEffort=$,X.effortUpdates=[];return}Y.reasoning={...G,effort:X.pinnedEffort};for(let N=K.length-1;N>=0;N--){let V=K[N];if(!V)continue;W.splice(V.anchor,0,{type:"configuration_update",reasoning:{effort:V.effort}})}}function sB(Y){let X=s(Y.reasoning)?{...Y.reasoning}:{};X.context="all_turns",Y.reasoning=X,Y.parallel_tool_calls=!1;let J=s4(Array.isArray(Y.input)?Y.input:[]),G=[{type:"additional_tools",role:"developer",tools:Array.isArray(Y.tools)?Y.tools.filter(($)=>!(s($)&&$.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,...J],delete Y.tools,delete Y.instructions}function aB(Y){if(!s(Y))return Y;if(Y.type!=="function")return Y;let X=s(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:U,...Z}=Y.parameters;return Z})():Y.parameters,{type:J,name:Q,description:G,strict:$,parameters:W,...K}=Y;return{type:J,name:Q,description:G,strict:$??!1,parameters:X,...K}}async function tB(Y,X={}){let J=X.codexApiEndpoint??r0().codexApiEndpoint,Q=crypto.randomUUID(),G=cB(),$=()=>uB(G),W=!1,K=!1,U=[],Z=null,B=O$(Y.client),O=new Map,N=new Map,V,D=!1,E,P=new Map,T,w,x=O3({host:"opencode",stateDir:X.vault?.stateDir??L$(U0(Y0()).statePath),...Y.directory?{projectRoot:Y.directory}:{},reservedRouteIds:()=>o?.peek().rows.map((I)=>I.id)??[],...X.vault?.connectionFile?{connectionFile:X.vault.connectionFile}:{},...X.vault?.connectScoped?{connectScoped:X.vault.connectScoped}:{},...X.vault?.connectEnrollment?{connectEnrollment:X.vault.connectEnrollment}:{},...X.vault?.pollIntervalMs!==void 0?{pollIntervalMs:X.vault.pollIntervalMs}:{},fetchImpl:()=>fetch},U0(Y0())),j=x.vault;await j.authority();let S=x.firstRoster,h=Promise.withResolvers(),M=Promise.race([S,h.promise]),y=X.vault?.firstRosterWaitMs??OY,n,o,{enabled:V0,...u}=X.poolMigration??{},G0=V0??gB;if(G0&&"reason"in B)(u.log??B0("pool")).warn("account pool migration is off for this OpenCode client",{reason:B.reason});let J0=G0&&"slot"in B?uJ({paths:()=>U0(Y0()),slot:B.slot,version:v8,...u,runDeps:{vaultServes:()=>j.serves(),...u.runDeps},paused:async()=>await j.authority()!=="local",migrate:async(I)=>{let p=await(u.migrate??J1)(I);return o?.load(),p},adopt:async(I)=>{if(!await X9(M,y))return{status:"retry",reason:"vault-roster-pending"};let p=await(u.adopt??Q1)(I);return o?.load(),p}}):void 0,T0=(I,p="")=>I?async()=>{let d=await I();return{url:d.url,instructions:d.instructions??p,method:"auto",callback:async()=>{try{let g=await d.tokens;return{type:"success",refresh:g.refresh_token,access:g.access_token,expires:Date.now()+(g.expires_in??3600)*1000,accountId:s8(g)}}finally{d.cleanup?.()}}}}:void 0,v=new HY(X.backgroundQuota),x0,R0=KJ({client:Y.client,getAuth:async()=>x0?.(),fetchImpl:fetch,dependencies:{...X.login?.authorize?{authorizeBrowser:T0(X.login.authorize.browser,"Complete authorization in your browser. This window will close automatically."),authorizeHeadless:T0(X.login.authorize.headless)}:{}},vault:j,onMainSlotWritten:async()=>{await J0?.requestAdoption()}}),H0=(I)=>async(p)=>{let d=await I(p);if(d.method!=="auto")return d;return{...d,callback:async()=>{let g=await d.callback();if(g.type==="success"&&"refresh"in g)r(g.refresh);return g}}};async function r(I){if(!J0||!("slot"in B))return;let p=X.login?.sleep??((d)=>Bun.sleep(d));for(let d=0;d<5000;d+=100){try{let g=await B.slot.get({path:{id:"openai"}});if(s(g)&&g.refresh===I){await J0.requestAdoption();return}}catch{}await p(100)}}let _0=R0.map((I)=>I.type==="oauth"?{...I,authorize:H0(I.authorize)}:I);async function l(I,p){let d=Y.client.session;if(typeof d?.promptAsync==="function"){let g=await o3(Y.client,I),W0={noReply:!0,parts:[{type:"text",text:p,ignored:!0}]};if(g?.agent)W0.agent=g.agent;if(g?.model)W0.model=g.model;if(g?.variant)W0.variant=g.variant;await d.promptAsync({path:{id:I},body:W0});return}}return{async dispose(){x.release(),J0?.dispose(),o?.dispose(),v.stop(),w?.stop(),V?.stopBackgroundRefresh(),V=void 0;for(let d of U)d.close();U.length=0;let I=globalThis;for(let[d,g]of O)if(I.__openaiAuthCacheKeepManagers?.get(d)===g)g.stop(),I.__openaiAuthCacheKeepManagers.delete(d);O.clear();for(let d of N.values())await d.release().catch(()=>{});N.clear();let p=n;n=void 0,await(await p)?.release()},async event(I){if(I.event.type!=="session.deleted")return;let p=I.event.properties.info,d=G.get(p.id);if(d)Z?.cacheKeepManager?.remove(d.threadID);if(G.delete(p.id))$();let g=L8(p.id);if(P.delete(g),w?.cancel(`pin:${g}`),E){let W0=(await A0(U0(Y0())))?.accounts;await R$(p.id,W0,E).catch(()=>{})}for(let W0 of U)W0.remove(p.id)},provider:{id:"openai",async models(I,p){if(p.auth?.type!=="oauth")return I.models;let d=await A0(U0(Y0())),g=!d||H$(d),W0=g?null:await l3();if(!g&&W0&&!aG)aG=!0,sG.debug("restoring OAuth model costs from models.dev catalog");if(!g&&!W0&&!tG)tG=!0,sG.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(I.models).filter(([,q0])=>q0.options.reasoningMode!=="pro"&&OB(q0.api.id)).map(([q0,Y8])=>[q0,{...Y8,cost:g?{input:0,output:0,cache:{read:0,write:0}}:W0?.[Y8.api.id]??W0?.[q0]??Y8.cost,limit:_B(Y8.id)??Y8.limit}]))}},auth:{provider:"openai",async loader(I){await j.authority(),x0=I,n??=N3({version:v8,logger:B0("heartbeat")}),await n,J0?.start();let p=await I();if(p.type!=="oauth")return h.resolve(),{};let d=n4(p).kind==="tombstone";x.start();let g=Y.directory?await _$(Y.directory):void 0,W0=g?.dir??Y0();async function q0(H,L={}){if(await j.authority()!=="local")return;return hB(H,{...L,canWrite:()=>!j.enrolled()})}let Y8=await j.authority()!=="local";if(!d&&!Y8)await V$({type:"oauth",access:p.access??"",refresh:p.refresh??"",expires:p.expires??0},U0(Y0()));let C0=await A0(U0(Y0())).catch(async(H)=>{if(await j.authority()!=="local")return null;let L=Y0();throw Error(`OpenAI auth store at ${L} is corrupt or unreadable: ${H instanceof Error?H.message:String(H)}. Fix or remove it to continue.`,{cause:H})});if(!Y8&&await v1(U0(Y0()),p)){if(J0)J0.noticePlaceholderWithoutMain();else if(!D)D=!0,B0("pool-migration").warn(P6,{reason:"placeholder-without-main"})}let f0,n0=C0;async function P0(){let H=Y0(),L;try{L=LB(H)}catch{L=void 0}if(L&&f0?.path===H&&f0.mtimeMs===L.mtimeMs&&f0.size===L.size)return f0.storage;if(!L)f0=void 0;let F=A0(U0(H)).catch(async(A)=>{if(await j.authority()!=="local")return n0;throw A}).then((A)=>{if(L)f0={path:H,mtimeMs:L.mtimeMs,size:L.size,storage:A};return n0=A,A});return X1(F,Y1,()=>n0)}function K8(){f0=void 0}if(C0&&p.access&&!d&&!Y8){let H=s8({id_token:"",access_token:p.access,refresh_token:p.refresh??""});if(H&&H!==C0.mainAccountId)await q0((L)=>{L.mainAccountId=H}),C0.mainAccountId=H,K8()}let m6=C0?.logging?.level;if(m6&&typeof m6==="string")r9(m6);let c6=B0("transport"),J8=B0("quota"),w9=B0("refresh"),U8=B0("accounts");c6.info("codex auth loader ready",{codexApiEndpoint:J,transport:r0().rawWebSocket?"raw-websocket":r0().webSockets?"websocket":"http"});let X0=new U$({storage:C0,configPath:Y0(),fetchQuotaFn:void 0}),u6,p6=0;o?.dispose();let E0=new _Y({paths:()=>U0(Y0()),refreshProvider:async(H)=>{let L=await R9({refreshToken:H.refresh,fetchImpl:fetch,now:Date.now}),F=s8({id_token:"",access_token:L.access,refresh_token:L.refresh});return{...L,...F?{identity:F}:{}}},pullQuota:async(H)=>{let L=H.credential;if(L.type!=="oauth"||!L.access)throw Error("the row holds no access token to poll with");let F=await t6({accessToken:L.access,fetchImpl:fetch,now:Date.now,...H.identity?{accountId:H.identity}:{},accountKey:H.id,logger:J8}),A=Date.now(),q={quota:F,refreshAfter:A+300000,checkedAt:A};if(H.id==="main")X0.setMain(L.access,q,H.identity,!0);else X0.setFallback(H.id,q,L.access,!0,H.identity);return A6(F,A,!0)},vaultIdentities:()=>j.identities(),vaultMode:()=>j.enrolled(),vaultAuthority:()=>j.authority(),vaultFirstRoster:S,vaultFirstRosterBackgroundWaitMs:y,log:B0("pool")});if(o=E0,!Y8)await E0.load();let X8=new B$({paths:U0(Y0()),refreshFn:async(H)=>{if(await j.authority()!=="local")throw Error(Q6["vault-refused"]);return R9({refreshToken:H.refreshToken,fetchImpl:H.fetchImpl,now:H.now})},quotaManager:X0,canWrite:()=>!j.enrolled(),onFallbackStorageChanged:K8,backgroundRefreshPaused:async()=>j.enrolled()||await E0.active()});if(C0&&C0.accounts.length>0)X8.startBackgroundRefresh();function c1(H){if(c0(H))return;return H.access||void 0}function S9(H={}){let{readSidebarState:L,respectBackoff:F,skipFresherThanMs:A}=H;return{getAuth:I,codexRefreshFn:R9,refreshMainWithLease:KX,fallbackManager:X8,quotaManager:X0,loadAccounts:A0,writeSidebarState:H8,client:Y.client,fetchImpl:fetch,now:Date.now,paths:U0(Y0()),readSidebarState:L??(()=>q$(l0)),storageMainAccountId:C0?.mainAccountId,isOAuthAccountFn:a0,whamFn:t6,...F===void 0?{}:{respectBackoff:F},...A===void 0?{}:{skipFresherThanMs:A}}}async function t4(H){return(await E0.pollRows(await A0(U0(Y0())),H?{ids:H}:{})).map((F)=>({account:F.id,ok:F.ok,...F.error!==void 0?{error:F.error}:{}}))}async function e4(H){return E0.accessFor(H,await A0(U0(Y0())))}let YX=B0("cachekeep"),I9=s9(C0),XX=I9?.enabled===!0,JX=I9?.subagents===!0,QX=I9?.sustain===!0,GX=wJ(C0?{...C0,cachekeep:I9}:C0),b9;async function y$(H){await new Promise((L)=>setTimeout(L,H))}async function g$(H){let L;for(let F=1;F<=rG;F++){if(await j.authority()!=="local")throw Error(Q6["vault-refused"]);try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:H.refresh,access:H.access,expires:H.expires}});return}catch(A){if(L=A,F<rG)await y$(SB*F)}}throw new a4(L)}async function k9(H){await q0((L)=>{L.refresh=L.refresh??{},H(L)},{holdsMainRefreshLock:!0}),K8()}async function u1(H){let L=Date.now()+wB;while(Date.now()<L){await new Promise((q)=>setTimeout(q,oG+yB(oG)));let F=await I();if(s0(F))throw new r8;if(F.type!=="oauth"||!F.access)continue;if((F.access!==H.access||F.refresh!==H.refresh||(F.expires??0)>(H.expires??0)+60000)&&(!F.expires||F.expires>Date.now()))return w9.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:F.expires?F.expires-Date.now():void 0}),{access:F.access,refresh:F.refresh??H.refresh??"",expires:F.expires??0}}return null}function $X(H){if(s0(H))throw new r8;if(H.type!=="oauth")throw Error("not oauth");if(c0(H))throw new z$;if(!H.refresh)throw Error("Token refresh failed: missing refresh token");return H.refresh}async function p1(){if(!b9)b9=(async()=>{let H=await I(),L=$X(H);if(H.type!=="oauth")throw Error("not oauth");let F=J9(L),A=await A0(U0(Y0())),q=A?.refresh?.mainLastRefreshError;if(q&&T8(q,L,Date.now()))throw Error(d4(q,Date.now()));if(A?.refresh?.mainRefreshLeaseUntil&&A.refresh.mainRefreshLeaseUntil>Date.now()&&A.refresh.mainRefreshLeaseTokenHash===F){let m=await u1(H);if(m)return m;throw Error("Codex OAuth refresh is already in progress")}let b=await a9({name:a6,ttlMs:RB,path:Y0(),renew:!0});if(!b){let m=await u1(H);if(m)return m;throw Error("Codex OAuth refresh is already in progress")}let R;try{let m=await I(),e=$X(m);if(m.type!=="oauth")throw Error("not oauth");if(e!==L){if(m.access&&(m.expires??0)>Date.now())return w9.debug("main token rotated while awaiting the lock",{pid:process.pid}),await b.release().catch(()=>{}),{access:m.access,refresh:e,expires:m.expires??0};let v0=(await A0(U0(Y0())))?.refresh?.mainLastRefreshError;if(v0&&T8(v0,e,Date.now()))throw Error(d4(v0,Date.now()))}R={...m,refresh:e}}catch(m){throw await b.release().catch(()=>{}),m}await D$(U0(Y0()),R.refresh,R.access!==void 0?{slotAccess:R.access}:{}).catch(()=>!1);let C=J9(R.refresh),c=crypto.randomUUID(),a=C;try{await k9((z0)=>{if(F$(Y0(),R.refresh))throw new i4;z0.refresh=z0.refresh??{},z0.refresh.mainRefreshLeaseId=c,z0.refresh.mainRefreshLeaseUntil=Date.now()+CB,z0.refresh.mainRefreshLeaseTokenHash=C});let m=await A0(U0(Y0()));if(m?.refresh?.mainRefreshLeaseId!==c||m.refresh.mainRefreshLeaseTokenHash!==C)throw Error("Codex OAuth refresh is already in progress");if(await j.authority()!=="local")throw Error(Q6["vault-refused"]);let e=await R9({refreshToken:R.refresh,fetchImpl:fetch,now:Date.now});return await g$(e),await k9((z0)=>{if(z0.refresh=z0.refresh??{},z0.refresh.mainLastRefreshError=void 0,z0.refresh.mainRefreshLeaseId===c)z0.refresh.mainRefreshLeaseId=void 0,z0.refresh.mainRefreshLeaseUntil=void 0,z0.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),a=void 0,e}catch(m){if(!(m instanceof i4)){if(!p4(m))await k9((e)=>{e.refresh=e.refresh??{},e.refresh.mainLastRefreshError=$$({error:m,now:Date.now(),refreshToken:R.refresh,previous:e.refresh.mainLastRefreshError})}).catch(()=>{});throw m}}finally{if(a)await k9((m)=>{if(m.refresh?.mainRefreshLeaseId===c&&m.refresh.mainRefreshLeaseTokenHash===a)m.refresh.mainRefreshLeaseId=void 0,m.refresh.mainRefreshLeaseUntil=void 0,m.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await b.release().catch(()=>{})}let f=await u1(R);if(f)return f;throw Error("Codex OAuth refresh is already in progress")})().finally(()=>{b9=void 0});return b9}function WX(H){return wX({storage:H,now:Date.now,refreshAccount:(L,F)=>X8.refreshAccount(L,F,{asPoolMain:!0}),warn:(L,F)=>w9.warn(L,{pid:process.pid,...F})})}async function zX(){let H=await WX(await A0(U0(Y0())));if(!H)throw Error("The main OpenAI account has no usable token in the account pool");return{access:H.token,refresh:H.account.refresh,expires:H.account.expires??0}}async function KX(){try{return await p1()}catch(H){if(H instanceof r8)return zX();throw H}}let UX=globalThis,l1=UX.__openaiAuthCacheKeepManagers??new Map;UX.__openaiAuthCacheKeepManagers=l1,l1.get(W0)?.stop();let l6=bJ({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 E0.active()){let L=await e4("main");if(!L)throw Error("main pool row has no usable token");return L.token}let H=await I();if(await j.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(s0(H))return(await zX()).access;if(H.type!=="oauth")throw Error("not oauth");if(!H.access||(H.expires??0)<Date.now())try{return(await KX()).access}catch(L){if(p4(L))throw L;if(H.access)return H.access;throw Error("main token refresh failed")}return H.access},refreshFallback:async(H)=>{if(await j.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(await E0.active()){let R=await e4(H);if(!R)throw Error(`no access token for ${H}`);return{token:R.token}}let L=await P0(),F=L?iB(L.accounts,H):void 0;if(!F)throw Error(`fallback account ${H} not found`);let A=L??{version:1,accounts:[F]},q=c0(F)?F:await X8.refreshAccount(F,A),b=c1(q);if(!b)throw Error(`no access token for ${H}`);return{token:b}},codexResponsesUrl:J,activeAccount:async(H)=>IJ(V6(await d8.read(),P),H),logger:YX,now:Date.now,getWindow:()=>GX,getSustain:()=>QX});l1.set(W0,l6),O.set(W0,l6);function B6(H,L,F,A,q=!1){try{f$(H,L,F,A,q)}catch(b){J8.warn("quota push failed",{pid:process.pid,accountId:F??"main",error:y6(b)})}}function f$(H,L,F,A,q){if(Object.keys(H).length===0&&!q)return;let b=Date.now(),R=H,C={quota:R,refreshAfter:b+300000,checkedAt:b},c;if(F&&F!=="main"){let f=L?N8(L):null,m=f?j8(f):void 0,e=X0.peekFallbackForPolicy(F)?.quota,z0=Y$(R,e);C={...C,quota:z0},X0.setFallback(F,C,L,q,m)}else{if(c=A,!c&&L){let e=N8(L);c=e?j8(e):void 0}if(c&&u6&&c!==u6){J8.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:c,currentMainIdentity:u6});return}let f=X0.peekMainForPolicy(c)?.quota,m=Y$(R,f);C={...C,quota:m},X0.setMain(L,C,c,q)}J8.debug("quota pushed",{pid:process.pid,accountId:F??"main",snapshot:C.quota}),E0.recordSnapshot(F&&F!=="main"?F:"main",H,L,q);let a=Boolean(F&&F!=="main");O8.enqueue("machine-state","quota",()=>{let f=n0;return H8(X0,f,a?f?.mainAccountId:c)})}function m$(H,L,F){let A=Q8(j.routes().find((q)=>q.id===H)?.quota)??(H==="main"?X0.peekMainForPolicy()?.quota:X0.peekFallbackForPolicy(H)?.quota);return K$(A,L,Date.now(),IB,F)}let x9=new Map,d6=new Map;function HX(){if(!j.enrolled())return;O8.enqueue("machine-state","quota",()=>H8(X0,n0))}let L6=X.experimentalWebSockets?b8.createWebSocketFetch({httpFetch:fetch,rawWebSocket:r0().rawWebSocket,onQuota:(H,L,F,A)=>{let q=F?x9.get(F):void 0;if(q){j.recordSnapshot(q.id,H,!0,q.receipt).then(HX);return}B6(H,L,F,!F||F==="main"?A:void 0,!0)},onRateLimitReached:(H,L,F)=>{if(!L)J8.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:H});let A=L?x9.get(L):void 0,q=A?.id??L??"main",b=m$(q,H,F);if(X0.markRateLimited(q,b),A)d6.set(q,Math.max(d6.get(q)??0,b));else E0.markRateLimited(q,b);J8.debug("mid-stream rate limit mark",{pid:process.pid,accountId:q,window:H})}}):void 0;if(L6)U.push(L6),W=!0;let l0=P$();E=l0;async function H8(H,L,F=L?.mainAccountId){if(j.enrolled()){await h1(U3(j.snapshot()?.rows??[],new Set(j.routes().map((q)=>q.id)),L,Date.now()),l0,{canWrite:()=>j.enrolled()});return}let A=await E0.current();if(A.active){await h1(H3(A.rows,L,Date.now(),(q)=>(q==="main"?H.getMain():H.getFallback(q))?.quota?.resetCreditsAvailable),l0,{canWrite:()=>!j.enrolled()});return}if(!L)return;await h1(h$(H,L,Date.now(),F),l0,{canWrite:()=>!j.enrolled()})}let d8=I$(l0);d8.read(),w?.stop();let O8=k$({logger:c6,onWritten:()=>d8.refreshInBackground()});if(w=O8,T!==l0)P.clear(),T=l0;function d1(H,L,F,A,q,b,R=!1){let C={canWrite:()=>j.enrolled()===R},c={activeId:F,route:A,updatedAt:Date.now()};if(!H){O8.enqueue("routing:legacy","routing",()=>T$(c,l0,C));return}if(O8.enqueue(`routing:${H}`,"routing",()=>y1({sessionId:H,...c},q,l0,C)),!L||L===H)return;if(A==="sticky-balanced"){let a=b.stickyAssignments?.[L8(L)]?.accountId,f=q===void 0||a==="main"||q.some((m)=>m.enabled!==!1&&m.id===a);if(!a||!f)return;O8.enqueue(`routing:${L}`,"routing",()=>y1({sessionId:L,activeId:a,route:A,updatedAt:Date.now()},q,l0,C));return}O8.enqueue(`routing:${L}`,"routing",()=>y1({sessionId:L,...c},q,l0,C))}V?.stopBackgroundRefresh(),V=X8;let i6=U0(Y0());if(Z=x$={accountStoragePath:i6.configPath,accountStatePath:i6.statePath,packageVersion:v8,quotaManager:X0,loadAccounts:A0,beginAccountLogin:d9,store:()=>_6(i6),migration:async()=>{if(await m9(i6,_6(i6))!==void 0)return{migrated:!0};let H=await(u.fence??(()=>E6({currentVersion:v8})))();return{migrated:!1,blockers:H.open?[]:H.blockers.map((L)=>({pid:L.pid,version:L.version}))}},afterWrite:()=>E0.load(),vault:j,resolveResetTarget:xB({getAuth:I,refreshMainWithLease:p1,refreshFallbackAccount:(H,L)=>X8.refreshAccount(H,L),refreshPoolMainRow:(H,L)=>X8.refreshAccount(H,L,{asPoolMain:!0}),poolAccess:async(H)=>E0.rowAccess(H,await A0(U0(Y0()))),loadAccounts:A0,accountStoragePath:Y0(),accountStatePath:j$(Y0()),now:Date.now}),...vB(),cacheKeepManager:l6,setCacheKeepEnabled:(H)=>{XX=H},setCacheKeepSubagents:(H)=>{JX=H},setCacheKeepSustain:(H)=>{QX=H},setCacheKeepWindow:(H)=>{GX=H},clearStickyRouting:async(H)=>{let L=L8(H),F=P.delete(L);return O8.cancel(`pin:${L}`),await S$(H,l0)||F},getStickyRouting:async(H)=>A$(V6(await d8.read(),P),H),refreshSidebar:async()=>{let H=await A0(U0(Y0()));await H8(X0,H)},refreshAllQuota:async()=>{if(await j.authority(),j.enrolled()){let H=await j.pollStale(0);return await H8(X0,n0),H.map((L)=>({account:L.id,ok:L.ok,...L.error!==void 0?{error:L.error}:{}}))}if(await E0.active()){let[H,L]=await Promise.all([t4(),j.pollStale(0)]);return await H8(X0,n0),[...H,...L.map((F)=>({account:F.id,ok:F.ok,...F.error!==void 0?{error:F.error}:{}}))]}return R6(S9())},refreshResetTargetQuota:async(H)=>{if(await j.authority(),j.enrolled())return{account:H,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};if(await E0.active()){let[F]=await t4([H]);return F??{account:H,ok:!1,error:"targeted quota refresh returned no result"}}return(await R6(S9({respectBackoff:!1}),{accountKey:H})).find((F)=>F.account===H)??{account:H,ok:!1,error:"targeted quota refresh returned no result"}}},g){let H=g;try{let L=await G$(s3,H.dir,()=>a3({dir:H.dir,secureDir:H.secureDir,sweepRoot:H.sweepRoot,drain:BJ,apply:async(F)=>{let A=Q$(F);if(!A)throw Error("not an /openai apply request");return _J(Z,A)}}));N.set(H.dir,L)}catch{}}async function N6(H,L,F,A,q="main",b){if(!F.trim())throw c6.warn("refusing to send a request with no access token",{account:q,accountId:A}),Error(PB);if(!b&&await j.authority()!=="local")return Response.json({error:{message:Q6["vault-refused"]}},{status:400});let R=X$(H,L);if(R.delete("x-api-key"),R.delete("api-key"),R.set("authorization",`Bearer ${F}`),A)R.set("ChatGPT-Account-Id",A);R.set(b8.QUOTA_ACCOUNT_HEADER,q);let C=J$(R),c=C?mB(G,C,$):void 0,a=H instanceof URL?H:new URL(typeof H==="string"?H:H.url),f=a.pathname.includes("/v1/responses")||a.pathname.includes("/chat/completions")?new URL(J):a,e=dB({init:{...L,headers:R},headers:R,metadata:c,installationID:Q,websocket:Boolean(L6&&a.pathname.endsWith("/responses")),responsesLite:X.responsesLite??!1,dumpSessionID:C}).init,z0=XX,v0=new Headers(e?.headers),t=CJ({enabled:z0,includeSubagents:JX,headers:v0,body:e?.body});if(z0)YX.trace("cachekeep headers",{pid:process.pid,hasParent:v0.has("x-parent-session-id"),sessionKey:t?.sessionKey,captured:Boolean(t),affinity:v0.get("x-session-affinity"),opencodeSession:v0.get("x-opencode-session"),sessionId:v0.get("session-id")});if(L6&&a.pathname.endsWith("/responses")){if(c6.debug("WS transport",{pid:process.pid,pathname:a.pathname,accountId:q}),t)l6.track({sessionKey:t.sessionKey,bodyText:t.bodyText,accountId:q,isSubagent:t.isSubagent,meta:{replayHeaders:t.replayHeaders,chatgptAccountId:A,routingSessionId:C}});if(!b)try{return await t8(await L6(f,e),F,"event-stream")}catch(M0){throw h8(M0,F)}let K0=`vault-stream:${HB()}`;x9.set(K0,{id:q,receipt:b});let Z8=new Headers(e?.headers);Z8.set(b8.QUOTA_ACCOUNT_HEADER,K0);let m0=()=>x9.delete(K0);try{let M0=await L6(f,{...e,headers:Z8});if(!M0.body)return m0(),M0;let _8=M0.body.getReader();return await t8(new Response(new ReadableStream({async pull(P8){try{let q8=await _8.read();if(q8.done)m0(),P8.close();else P8.enqueue(q8.value)}catch(q8){m0(),P8.error(h8(q8,F))}},cancel(P8){return m0(),_8.cancel(P8)}}),{status:M0.status,statusText:M0.statusText,headers:M0.headers}),F,"event-stream")}catch(M0){throw m0(),h8(M0,F)}}let L0=b8.withoutInternalHeaders(e);if(typeof L0?.body!=="string")try{return await t8(await fetch(f,L0),F,"event-stream")}catch(K0){throw h8(K0,F)}if(t)l6.track({sessionKey:t.sessionKey,bodyText:t.bodyText,accountId:q,isSubagent:t.isSubagent,meta:{replayHeaders:t.replayHeaders,chatgptAccountId:A,routingSessionId:C}});c6.debug("HTTP transport",{pid:process.pid,pathname:a.pathname,accountId:q});try{let K0=await fetch(f,L0);return await w6({sessionID:C,transport:"http",phase:"http",bodyText:L0.body,accountId:q,url:f.toString(),method:L0.method,headers:L0.headers,status:K0.status}),await t8(K0,F,"event-stream")}catch(K0){throw await w6({sessionID:C,transport:"http",phase:"http",bodyText:L0.body,accountId:q,url:f.toString(),method:L0.method,headers:L0.headers,error:K0 instanceof Error?K0.message:String(K0)}),h8(K0,F)}}function n6(H,L){if((L?.method??(H instanceof Request?H.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof L?.body!=="string")return!1;try{let A=H instanceof URL?H.toString():typeof H==="string"?H:H.url;return new URL(A).pathname.endsWith("/responses")}catch{return!1}}function c$(H){return X0.peekMainForPolicy(H)?.quota}function ZX(H,L){for(let F of[H?.primary?.checkedAt,H?.secondary?.checkedAt,H?.checkedAt,L])if(typeof F==="number"&&Number.isFinite(F))return F;return}function o6(H,L,F,A,q){let b=ZX(H,L),R=ZX(F),C=A===q&&F!=null&&(H===void 0||R!==void 0&&(b===void 0||R>b));return{quota:C?F:H,quotaCheckedAt:C?R:b,source:C?"file":"memory"}}function VX(H,L,F,A,q){let b=H?.quota,R=o6(b,H?.checkedAt,L,A,q),C=R.source,c=R.quota;if(!M$(c,F))return{exhausted:!1};let a=E$(c,F);if(!a)return{exhausted:!1};return{exhausted:!0,source:C,...a}}function BX(H,L){J8.debug("admission skip: exhausted account",{accountId:H,source:L.source,resetsAt:L.resetsAt})}function LX(H,L="killswitch",F,A){let q=Date.now(),b=A?A.main:X0.getMain()?.quota,R=A?A.fallbacks:(H?.accounts??[]).filter((m)=>m.enabled!==!1&&a0(m)).map((m)=>({accountId:m.id,quota:X0.getFallback(m.id)?.quota})),C=Z$(b,R,q,H);if(L==="quota-unknown")C=rJ;else if(L==="quota-exhausted"&&F!==void 0)C=Math.max(1,Math.ceil((F-q)/1000));else if(L==="mid-stream-rate-limit"&&F!==void 0){let m=Math.max(1,Math.ceil((F-q)/1000));C=Math.min(C,m)}let c=Math.floor(C/60),a=C%60,f=L==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${c}m ${a}s.`:L==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${c}m ${a}s.`:L==="quota-unknown"?`OpenAI quota is not known yet for any available account; checking it now. Retry in ${c}m ${a}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${c}m ${a}s.`;return new Response(JSON.stringify({error:{message:f,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(C)}})}function i1(H){let L=H?.resetCreditsAvailable;return typeof L==="number"&&Number.isFinite(L)?L:void 0}async function u$(H){let L=X6(H.storage),F=Date.now(),A=X0.peekMainForPolicy(H.mainAccountIdentity),q=o6(A?.quota,A?.checkedAt,H.sidebarState.main.quota,H.sidebarState.main.mainAccountId,H.mainAccountIdentity),b=L?J6(A?.quota,H.storage,void 0,F):void 0,R=H.mainUnavailable?[]:[{accountId:"main",wireAccountId:H.mainAccountIdentity,access:H.primaryAccess,keepwarmAccountKey:"main",quota:q.quota,quotaCheckedAt:q.quotaCheckedAt,reservePercent:Q9(H.storage),configuredOrder:0,resetCreditsApplicable:i1(q.quota),killswitchPasses:b}],C=await X8.getUsableFallbackAccounts(H.storage);if(!H.storage)return R;for(let c of C){let a=c1(c);if(!a)continue;let f=H.sidebarState.fallbacks.find((v0)=>v0.id===c.id),m=X0.peekFallbackForPolicy(c.id,c.accountId),e=o6(m?.quota,m?.checkedAt,f?.quota,f?.accountId,c.accountId),z0=L?J6(m?.quota,H.storage,c.id,F):void 0;R.push({accountId:c.id,wireAccountId:c.accountId,access:a,keepwarmAccountKey:c.id,fallback:c,quota:e.quota,quotaCheckedAt:e.quotaCheckedAt,reservePercent:Q9(H.storage,c.id),configuredOrder:R.length,resetCreditsApplicable:i1(e.quota),killswitchPasses:z0})}return R}function NX(H,L,F,A,q){let b=X6(q)?H.killswitchPasses:void 0;if(H.accountId==="main"){let a=X0.peekMainForPolicy(H.wireAccountId),f=o6(a?.quota,a?.checkedAt,L.main.quota,L.main.mainAccountId,H.wireAccountId);return kY({quota:f.quota,quotaCheckedAt:f.quotaCheckedAt,status:F,now:A,killswitchPasses:b})}let R=L.fallbacks.find((a)=>a.id===H.accountId),C=X0.peekFallbackForPolicy(H.accountId,H.wireAccountId),c=o6(C?.quota,C?.checkedAt,R?.quota,R?.accountId,H.wireAccountId);return kY({quota:c.quota,quotaCheckedAt:c.quotaCheckedAt,status:F,now:A,killswitchPasses:b})}function p$(H){return H.accountId==="main"?"main":H.keepwarmAccountKey}function jX(H){return X0.isRateLimited(p$(H))}function n1(H){let L=H.candidates.filter((b)=>!jX(b)),F=new Map(L.map((b)=>[b.accountId,b])),A=new Set(H.excludeAccountIds),q=FX({sessionId:H.sessionId,requestBytes:H.requestBytes,sidebarSnapshot:H.sidebarSnapshot,now:H.now,validPinnedAccountIds:[...F.keys()],excludeAccountIds:H.excludeAccountIds??[],quotaCheckedAtByAccount:Object.fromEntries(L.map((b)=>[b.accountId,b.quotaCheckedAt])),wireAccountIdByAccount:Object.fromEntries(L.map((b)=>[b.accountId,b.wireAccountId])),select:(b)=>{let R=L.filter((C)=>!A.has(C.accountId));if(R.length===0)return;return A3({candidates:R,pendingBytes:b,requestBytes:H.requestBytes,now:H.now,onEmptyWeightedSet:()=>{U8.debug("sticky routing: no fresh weighted candidates; using configured order")}})},persist:!0});return q?F.get(q.accountId):void 0}function FX(H){let L=void 0,F=H.validPinnedAccountIds,A=C$(V6(H.sidebarSnapshot,P),{sessionId:H.sessionId,requestBytes:H.requestBytes,now:H.now,validPinnedAccountIds:F,excludeAccountIds:H.excludeAccountIds,quotaCheckedAtByAccount:H.quotaCheckedAtByAccount,wireAccountIdByAccount:H.wireAccountIdByAccount,choose:(b)=>{let R=H.select(b);if(!R)return;return L={accountId:R.accountId,source:R.source,pendingBytes:b.get(R.accountId)??0},R}}),q=A.assignment;if(!H.persist)return q;if(L&&q?.accountId===L.accountId)U8.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:L8(H.sessionId),accountId:L.accountId,source:L.source,requestBytes:H.requestBytes,pendingBytes:L.pendingBytes});if(q&&A.next!==void 0){let b=L8(H.sessionId),R=b$(P,b,q);O8.enqueue(`pin:${b}`,"sticky-pin",async()=>{await w$({sessionId:H.sessionId,assignment:q,validPinnedAccountIds:F},l0),R.persistedAt=Date.now()})}return q}async function l$(H,L){let F=await X8.getUsableFallbackAccounts(H),A=[];if(!H)return{current:[],retained:[],skipped:[]};for(let f of F){let m=c1(f);if(!m)continue;A.push({access:m,accountId:f.accountId,keepwarmAccountKey:f.id,quotaAccountId:f.id,fallback:f})}let q=A.filter((f)=>!X0.isRateLimited(f.quotaAccountId)),b=X6(H)?q.filter((f)=>J6(X0.peekFallbackForPolicy(f.quotaAccountId,f.accountId)?.quota,H,f.quotaAccountId,Date.now())):q,R=new Map(L.fallbacks.map((f)=>[f.id,{quota:f.quota,accountId:f.accountId}])),C=[],c=[],a=Date.now();for(let f of b){let m=R.get(f.quotaAccountId),e=VX(X0.peekFallbackForPolicy(f.quotaAccountId,f.accountId),m?.quota,a,m?.accountId,f.accountId);if(e.exhausted)c.push({candidate:f,decision:e});else C.push(f)}return{current:b,retained:C,skipped:c}}function DX(H,L){if(H.retained.length===0&&!L)return H.current;for(let{candidate:F,decision:A}of H.skipped)BX(F.quotaAccountId,A);return H.retained}function OX(H,L){try{let F=a8(H.headers);B6(F,L.access,L.quotaAccountId,void 0,f6(H.headers))}catch{}}async function d$(H,L,F,A){for(let q of A){let b;try{b=await N6(H,L,q.access,q.accountId,q.keepwarmAccountKey)}catch(R){if((R instanceof Error||R instanceof DOMException)&&R.name==="AbortError")throw R;if(L?.signal?.aborted)throw R;throw U8.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:q.quotaAccountId}),R}if(!C9(b.status,F))return X8.markUsed(q.fallback),{response:b,accessToken:q.access,quotaAccountId:q.quotaAccountId,activeId:q.keepwarmAccountKey};OX(b,q),b.body?.cancel().catch(()=>{})}return}async function i$(H,L,F,A,q){if(!n6(H,L))return{response:F};if(!q.length)return{response:F};let b=F,R;for(let C of q){let c;try{c=await N6(H,L,C.access,C.accountId,C.keepwarmAccountKey)}catch(a){if((a instanceof Error||a instanceof DOMException)&&a.name==="AbortError")throw a;if(L?.signal?.aborted)throw a;return U8.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:C.quotaAccountId}),{response:b,...R}}if(b.body?.cancel().catch(()=>{}),b=c,R={accessToken:C.access,accountId:C.quotaAccountId},!C9(c.status,A))return X8.markUsed(C.fallback),{response:c,...R};OX(c,C)}return{response:b,...R}}if(C0){let H=[];for(let L of C0.accounts)if(a0(L))H.push(L);X0.seedFallbacksFromAccounts(H)}if(!r4)if(r4=!0,H8(X0,C0).catch(()=>{}),S.then(()=>j.enrolled()?H8(X0,n0):void 0).catch(()=>{}),!j.enrolled()&&!await E0.active())g1=R6(S9({respectBackoff:!0})).catch((H)=>J8.warn("boot quota seed failed",{pid:process.pid,error:y6(H)}));else g1=Promise.resolve();v.start(async()=>{if(await j.authority(),j.enrolled()){await H8(X0,n0);return}if(await E0.active()){let F=await AJ(E0,await A0(U0(Y0())),()=>UY(Y0()));if(F.length>0)await H8(X0,n0);let A=F.filter((q)=>!q.ok);if(A.length>0)J8.warn("background pool quota poll completed with failures",{pid:process.pid,failures:A});return}let L=(await EJ(S9({readSidebarState:async()=>(await d8.read()).state}))).filter((F)=>!F.ok);if(L.length>0)J8.warn("background quota refresh completed with failures",{pid:process.pid,failures:L})},(H)=>{J8.warn("background quota refresh failed",{pid:process.pid,error:H instanceof Error?H.message:String(H)})});async function o1(H,L,F,A,q,b){let R=F?.routing?.mode??"main-first",C=j.enrolled(),c=C?void 0:E0.peek().rows.find((t)=>t.id==="main"),a=!c&&!C?await I():void 0,f=!c&&a?.type==="oauth"&&c0(a),m=!c&&!C&&await v1(U0(Y0()),a);if(b===p6)u6=c?.identity;let e=await d8.get(),{response:z0,servedId:v0}=await K3({source:E0,...C?{vault:{routes:()=>j.routes(),awaitRoster:async()=>{await X9(j.awaitRequestRoster(),DY)},noRouteCause:()=>N$(j),send:(t,L0)=>j.send(t,L0,{site:"model",...L?.signal?{signal:L.signal}:{}}),requestReading:(t)=>j.requestReading(t),rateLimitMarks:()=>{for(let[t,L0]of d6)if(L0<=Date.now())d6.delete(t);return d6}}}:{},storage:F,mode:R,sessionId:A,body:typeof L?.body==="string"?L.body:void 0,replayable:n6(H,L),now:Date.now,send:(t,L0,K0)=>N6(H,L,L0,t.identity,t.id,K0),recordQuota:(t,L0,K0,Z8)=>{try{let m0=a8(t.headers),M0=f6(t.headers);if(!L0.row){if(Z8)j.recordSnapshot(L0.id,m0,M0,Z8).then(HX);return}B6(m0,K0,L0.id==="main"?void 0:L0.id,L0.id==="main"?L0.identity:void 0,M0)}catch{}},placePin:(t)=>FX({...t,sidebarSnapshot:e}),blocked:(t,L0,K0)=>{if(t.reason==="no-credential"){if(m&&!CY(K0))throw Error(P6);return new Response(Q6[CY(K0)?K0:f?"missing-main":K0??"unusable"],{status:401,headers:{"content-type":"text/plain; charset=utf-8"}})}return LX(F,t.reason,t.resetAtMs,L0)},resetCredits:(t)=>i1(t==="main"?X0.peekMainForPolicy(c?.identity)?.quota:X0.peekFallbackForPolicy(t)?.quota),isAbort:(t)=>(t instanceof Error||t instanceof DOMException)&&t.name==="AbortError"||Boolean(L?.signal?.aborted),log:U8});return d1(A,q,v0,R,C?j.routes().map((t)=>({id:t.id})):F?.accounts,V6(e,P),C),z0}return K=!0,{apiKey:EB,async fetch(H,L){let F=await j.authority(),A=X$(H,L),q=J$(A),b=A.get("x-parent-session-id")?.trim()||void 0,R=await P0();if(F!=="local")return L=await l4(H,L),o1(H,L,R,q,b,++p6);let C=await I();if(await j.authority()!=="local")return L=await l4(H,L),o1(H,L,R,q,b,++p6);let c=++p6;if(C.type!=="oauth")return A.delete(m1),fetch(H,{...L,headers:A});L=await l4(H,L);let a=(await E0.current()).active;if(s0(C)&&a)return o1(H,L,R,q,b,c);if(a)j.assertHostSlot(C);let f="",m=!1,e,z0=s0(C);if(J0?.migrated()&&!z0&&C.refresh?.trim()&&n4(C).kind==="real")J0.noticeRealSlot(C.refresh);let v0=async(N0=R)=>{if(z0=!0,e=await WX(N0),e)f=e.token;else f="",m=!0,U8.warn("main account in the pool has no usable token",{pid:process.pid})};if(z0)await v0();else if(c0(C))m=!0;else{if(!C.access||(C.expires??0)<Date.now()){w9.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(C.access),expiresInMs:C.expires?C.expires-Date.now():void 0});try{let N0=await p1();C.access=N0.access,C.refresh=N0.refresh,C.expires=N0.expires}catch(N0){if(p4(N0))throw N0;if(N0 instanceof r8)await v0(await A0(U0(Y0())))}}if(!z0)f=C.access??""}let t=z0?GY(R):R,L0=C,K0=e?.account.accountId??(z0?void 0:L0.accountId)??(f?j8(N8(f)??{}):void 0);if(c===p6)u6=K0;let Z8=R?.routing?.mode??"main-first",m0=await d8.get(),M0=m0.state;if(Z8==="sticky-balanced"&&q&&n6(H,L)&&typeof L?.body==="string"){let N0=Buffer.byteLength(L.body,"utf8"),b0=await u$({storage:t,sidebarState:M0,primaryAccess:f,mainAccountIdentity:K0,mainUnavailable:m}),S0=n1({sessionId:q,requestBytes:N0,candidates:b0,sidebarSnapshot:m0,now:Date.now()});if(S0){let AX=jX(S0)?{action:"migrate",reason:"exhausted"}:NX(S0,M0,void 0,Date.now(),R);if(AX.action==="migrate"){let o0=n1({sessionId:q,requestBytes:N0,candidates:b0,sidebarSnapshot:m0,excludeAccountIds:[S0.accountId],now:Date.now()});if(o0)U8.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:L8(q),fromAccountId:S0.accountId,toAccountId:o0.accountId,reason:AX.reason}),S0=o0}let V8=await N6(H,L,S0.access,S0.wireAccountId,S0.keepwarmAccountKey),TX=(o0,i8)=>{try{let n$=a8(o0.headers);B6(n$,i8.access,i8.accountId==="main"?void 0:i8.accountId,i8.accountId==="main"?i8.wireAccountId:void 0,f6(o0.headers))}catch{}};TX(V8,S0);let RX=NX(S0,M0,V8.status,Date.now(),R);if((V8.status===401||V8.status===403||V8.status===429)&&RX.action==="migrate"){let o0=n1({sessionId:q,requestBytes:N0,candidates:b0,sidebarSnapshot:m0,excludeAccountIds:[S0.accountId],now:Date.now()});if(o0){U8.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:L8(q),fromAccountId:S0.accountId,toAccountId:o0.accountId,reason:RX.reason});let i8=V8;V8=await N6(H,L,o0.access,o0.wireAccountId,o0.keepwarmAccountKey),i8.body?.cancel().catch(()=>{}),S0=o0,TX(V8,S0)}}if(S0.fallback&&!C9(V8.status,R))X8.markUsed(S0.fallback);return d1(q,b,S0.accountId,Z8,R?.accounts,V6(m0,P)),V8}}let _8=VX(X0.peekMainForPolicy(K0),M0.main.quota,Date.now(),M0.main.mainAccountId,K0),P8=X6(R)&&!J6(c$(K0),R,void 0,Date.now()),q8=X0.isRateLimited("main"),_X,r1=()=>{return _X??=l$(t,M0),_X},E8,j6,PX=!1,v9;if(Z8==="fallback-first"&&n6(H,L)){PX=!0;let N0=await r1();v9=DX(N0,!P8&&!q8&&!_8.exhausted);let b0=await d$(H,L,R,v9);if(b0)E8=b0.response,j6={accessToken:b0.accessToken,accountId:b0.quotaAccountId,activeId:b0.activeId}}if(!E8){let N0=_8.exhausted&&n6(H,L)&&(await r1()).retained.length>0;if(P8||q8||N0){let b0=P8?"killswitch":q8?"mid-stream-rate-limit":"quota-exhausted";if(b0==="quota-exhausted"&&_8.exhausted)BX("main",_8);U8.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:b0}),E8=LX(R,b0,b0==="quota-exhausted"&&_8.exhausted?_8.resetAtMs:q8?X0.rateLimitedUntil("main"):void 0)}else E8=m?new Response(null,{status:401}):await N6(H,L,f,K0,"main")}let s1=Boolean(j6),r6=E8,qX=j6?.accessToken??f,EX=j6?.accountId,MX=j6?.activeId??"main";if(!j6&&!PX&&C9(E8.status,R)){U8.debug("reactive fallback triggered",{pid:process.pid,status:E8.status}),v9??=DX(await r1(),!1);let N0=await i$(H,L,E8,R,v9),b0=N0.response;if(b0!==E8){if(s1=!0,r6=b0,qX=N0.accessToken??f,EX=N0.accountId,N0.accountId)MX=N0.accountId}}if(z0&&m&&!s1&&await v1(U0(Y0()),await I()))throw Error(P6);try{let N0=a8(r6.headers);if(s1)B6(N0,qX,EX,void 0,f6(r6.headers));else B6(N0,f,void 0,K0,f6(r6.headers))}catch{}return d1(q,b,MX,Z8,R?.accounts,V6(m0,P)),r6}}},methods:_0},"chat.headers":async(I,p)=>{if(I.model.providerID!=="openai")return;if(p.headers.originator="opencode",p.headers["User-Agent"]=`${W$(v8)} (${c4.platform()} ${c4.release()}; ${c4.arch()})`,p.headers["session-id"]=I.sessionID,K)p.headers[m1]=I.agent;if(W&&I.agent==="title")p.headers[b8.TITLE_HEADER]="true"},"chat.params":async(I,p)=>{if(I.model.providerID!=="openai")return;p.maxOutputTokens=void 0},config:async(I)=>{B0("commands").info("registering commands",{existing:Object.keys(I.command??{}).length,pid:process.pid}),I.command={...I.command??{},[k8]:{template:k8,description:"OpenAI accounts: quota, routing, limits, cache keep-warm, diagnostics and reset credits."}}},"command.execute.before":async(I)=>{if(B0("commands").info("command hook entered",{command:I.command,hasCmdCtx:Z!==null,pid:process.pid}),I.command!==k8)return;if(!Z)B0("commands").warn("command rejected: context not loaded",{command:I.command,pid:process.pid}),await l(I.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),eG();let p=await OJ(Z,I.sessionID);if(LJ(I.sessionID))n9(p,I.sessionID);else await l(I.sessionID,PJ(p.menu));eG()}}}var eB=async(Y)=>{let X=r0();return tB(Y,{codexApiEndpoint:X.codexApiEndpoint,experimentalWebSockets:X.webSockets,responsesLite:X.responsesLite})},Zq={id:"cortexkit-openai-auth",server:eB};
|
|
65
|
-
export{Y0 as d,r0 as e,QY as f,P6 as g,E6 as h,v8 as i,DY as j,OY as k,X9 as l,_Y as m,uJ as n,u0 as o,sJ as p,aJ as q,eJ as r,EY as s,X3 as t,J3 as u,Wz as v,N3 as w,O3 as x,A9 as y,SG as z,FB as A,DB as B,OB as C,_B as D,PB as E,qB as F,o4 as G,AB as H,Wq as I,RB as J,CB as K,zq as L,Kq as M,a4 as N,g0 as O,xB as P,vB as Q,Uq as R,gB as S,iB as T,Y$ as U,h$ as V,Hq as W,J$ as X,nB as Y,sB as Z,tB as _,eB as $,Zq as aa};
|