@cortexkit/opencode-openai-auth 1.0.5 → 1.2.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-C_6YRmsh.d.ts → codex-request-CjXETpTA.d.ts} +190 -27
- package/dist/index-03em8hv1.js +69 -0
- package/dist/index-6n4pnfkg.js +2 -0
- package/dist/{index-pg305s90.js → index-bc89akak.js} +1 -1
- package/dist/{index-y4gxyxqd.js → index-ehjj89rx.js} +2 -2
- package/dist/index-f21addzm.js +90 -0
- package/dist/{index-fsky1rsh.js → index-ffg0sgg5.js} +2 -2
- package/dist/{index-nx2qh047.js → index-ftkhhr6d.js} +1 -1
- package/dist/{index-826s1yxa.js → index-htvcmtcx.js} +2 -2
- package/dist/{index-fsxbncpw.js → index-qp5hdpw8.js} +1 -1
- package/dist/index-qxbchh2d.js +8 -0
- package/dist/{index-116q849r.js → index-r2s51ac1.js} +2 -2
- package/dist/index-rwbrhkse.js +65 -0
- package/dist/{index-66asrje2.js → index-xwvze96g.js} +1 -1
- package/dist/index.d.ts +18 -8
- package/dist/index.js +1 -1
- package/dist/{protocol-DctqemRI.d.ts → model-CQcw10oW.d.ts} +67 -25
- package/dist/{port-file-ZPlxXB4G.d.ts → port-file-BDJnzgHH.d.ts} +1 -1
- package/dist/protocol-C-kagE6O.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-z_M7Trnd.d.ts → sidebar-state-BfQ4mpZO.d.ts} +109 -10
- package/dist/sidebar-state.d.ts +2 -2
- package/dist/sidebar-state.js +1 -1
- package/dist/token-util-cf0nyh7n.js +1 -0
- package/dist/{token-bzhkgc29.js → token-z6qq7a1d.js} +1 -1
- package/dist/tui-preferences.js +1 -1
- package/dist/tui.d.ts +20 -2
- package/dist/v2/server.d.ts +180 -1
- package/dist/v2/server.js +3 -3
- package/package.json +3 -3
- package/src/tui-compiled/raw/shared/0332701351b3eeec-format.js +148 -26
- package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +371 -0
- package/src/tui-compiled/raw/shared/134b008900698fe0-backoff.js +92 -0
- package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +430 -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 +103 -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 +228 -70
- package/src/tui-compiled/runtime/shared/0332701351b3eeec-format.js +148 -26
- package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +371 -0
- package/src/tui-compiled/runtime/shared/134b008900698fe0-backoff.js +92 -0
- package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +430 -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 +103 -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 +351 -222
- package/dist/index-4fnghj9e.js +0 -65
- package/dist/index-a69gr76b.js +0 -2
- package/dist/index-h263aftt.js +0 -157
- package/dist/index-ssj7m2rd.js +0 -8
- package/dist/index-ydz3hbhc.js +0 -2
- package/dist/map-m6f5a_IA.d.ts +0 -56
- package/dist/token-util-4a2xxnpg.js +0 -1
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import{$a as X3,Aa as b3,Ab as o4,Ba as aJ,Bb as zX,Ca as KY,Da as tJ,Ea as eJ,Eb as q$,Ja as YX,Ka as JX,La as XX,Ma as QX,Na as E9,Oa as d1,Pa as k6,Qa as t8,Ra as n6,Sa as e8,Ta as YY,Ua as JY,Va as XY,Wa as QY,Ya as RY,Za as CY,_a as w9,ab as Q3,bb as G3,cb as $3,db as W3,eb as C9,gb as y6,ib as J9,jb as D$,kb as U0,mb as $X,nb as vJ,ob as hJ,pa as F9,pb as WX,qa as hX,qb as P$,ra as G$,rb as n4,sa as n,sb as _$,tb as r9,ub as y8,va as N$,vb as W8,wa as N3,wb as z8,xa as j3,xb as O9,ya as j$,yb as z3,za as F$,zb as s9}from"./index-03em8hv1.js";import{$b as f8,Gb as mY,Ib as nX,Kb as L6,Lb as M$,Ob as A$,Sb as f3,Tb as T$,Ub as R$,Vb as C$,_b as g8,ac as w$,bc as S$,ec as I$,fc as b$,gc as k$,ic as G8,jc as $8,kc as x$,lc as v$,mc as U9,nc as h$}from"./index-6n4pnfkg.js";import{$c as i1,$d as U1,Bd as xJ,Cc as Q8,Cd as R0,Dd as n1,Fd as B3,Gc as V3,Gd as w1,Hd as hY,Id as S1,Jc as kJ,Jd as e1,Kd as K1,Lc as z1,Ld as H9,Mc as W$,Md as V$,Nc as E6,Nd as B$,Oc as i4,Od as J3,Pc as z$,Pd as L3,Qc as uJ,Qd as Z6,Rc as pJ,Rd as n0,Sc as Y6,Sd as o6,Tc as J6,Td as WY,Uc as s6,Vc as lJ,Wc as dJ,Wd as L$,Xc as iJ,Xd as M9,Yc as nJ,Yd as A6,Zc as oJ,Zd as T6,_c as rJ,_d as F3,ad as Y9,ae as O$,bd as g9,be as O3,cd as AG,ce as D3,dd as iX,de as P3,ee as kY,fe as _3,ge as q3,he as E3,jd as sJ,pd as m0,qd as K$,rd as C1,sd as a9,td as U$,vc as X9,vd as H$,wd as o0,xc as j9,yd as Z$}from"./index-f21addzm.js";import{me as Y8}from"./index-qxbchh2d.js";import{re as wX,se as SX,te as IX,ue as s3,ve as $$,we as p1}from"./index-htvcmtcx.js";import{De as OX,Fe as t1,He as V0,Me as h9,Oe as GX}from"./index-ehjj89rx.js";import{Pe as V6,Qe as e9,Te as LX,Ue as NX,Ve as BY,We as jX,Ze as FX}from"./index-r2s51ac1.js";import{$e as bX,bf as E$}from"./index-bc89akak.js";import{df as iY}from"./index-xwvze96g.js";import{createHash as MB,randomUUID as AB}from"node:crypto";import{statSync as TB}from"node:fs";import u4 from"node:os";import{join as RB}from"node:path";import{readFile as DW}from"node:fs/promises";import{readFileSync as s$}from"node:fs";import{homedir as a$,tmpdir as t$}from"node:os";import{join as m1}from"node:path";var e$="https://chatgpt.com/backend-api/codex/responses",YW="openai-auth.json",x6={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 GY(){let Y=process.env[x6.configDir]?.trim();if(Y)return Y;return m1(process.env.XDG_CONFIG_HOME||m1(a$(),".config"),"opencode")}function X0(){return process.env[x6.configFile]?.trim()||m1(GY(),YW)}function JW(){try{let Y=JSON.parse(s$(X0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function XW(Y){let J=process.env[Y];if(J===void 0)return;let X=J.trim().toLowerCase();if(X==="1"||X==="true"||X==="yes"||X==="on")return!0;if(X===""||X==="0"||X==="false"||X==="no"||X==="off")return!1;return}function g1(Y,J,X){let Q=XW(Y);if(Q!==void 0)return Q;if(typeof J==="boolean")return J;return X}function QW(){let Y=JW(),J;if(Y.dump!==void 0&&Y.dump!==null){if(typeof Y.dump==="object")J=Y.dump.enabled;else if(typeof Y.dump==="boolean")J=Y.dump}return{webSockets:g1(x6.webSockets,Y.webSockets,!1),rawWebSocket:g1(x6.rawWebSocket,Y.rawWebSocket,!1),responsesLite:g1(x6.responsesLite,Y.responsesLite,!1),dump:g1(x6.dump,J,!1),dumpDir:process.env[x6.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():m1(t$(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[x6.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():e$)}}var f1;function i0(){if(!f1)f1=QW();return f1}function CJ(){return f1=void 0,i0()}import{readFileSync as GW}from"node:fs";var $W="The `main` account holds the login OpenCode signs in with (its login slot only points at it), so it cannot be removed. Sign in with another account through `opencode auth login` to replace it.";function WW(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 D9(Y,J={}){return F9({provider:"openai",configPath:Y.configPath,statePath:Y.statePath,quota:j9,...J})}function $Y(Y){try{let J=JSON.parse(GW(Y,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return!1;return r9(J).migratedAt!==void 0}catch{return!1}}async function c1(Y,J){if(!$Y(Y.configPath))return;let X=await J.read();return X.status==="ready"?X.rows:void 0}function u1(Y,J){if(Y===Z6)return $W;if(r9(J.config).pending?.rowId===Y)return WW(Y);return}function zW(Y,J){return O9(Y,Z6,J.legacyLocks).filter((X)=>X.name===s9)}function q6(Y,J={}){return zW(Y,J)}var P9="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 r6 extends Error{constructor(){super("The main OpenAI account lives in the account pool");this.name="MainAccountInPoolError"}}async function wJ(Y){let J=Y.storage,X=o6(J);if(!J||!X||m0(X))return;let Q=X,G=Y.now(),$=(J.refresh?.refreshBeforeExpiryMinutes??240)*60000;if((!Q.access||!Q.expires||Q.expires-G<=$)&&!E6(Q.lastRefreshError,Q.refresh,G))try{Q=await Y.refreshAccount(Q,J)}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 KW,readFile as UW}from"node:fs/promises";import{homedir as HW}from"node:os";import{join as _9}from"node:path";function IJ(){return process.env.XDG_STATE_HOME||_9(HW(),".local","state")}function ZW(Y=IJ()){return _9(Y,"cortexkit","openai-auth","processes")}function VW(Y=IJ()){return _9(Y,"cortexkit","openai-auth","rpc")}function BW(Y){try{return process.kill(Y,0),!0}catch(J){return J.code==="EPERM"}}function SJ(Y){let J=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z.-]+)?$/.exec(Y.trim());if(!J)return;return{core:[Number(J[1]),Number(J[2]),Number(J[3])],pre:J[4]?J[4].split("."):[]}}function LW(Y,J){let X=SJ(Y),Q=SJ(J);if(!X||!Q)return;for(let G=0;G<3;G++){let $=X.core[G]-Q.core[G];if($!==0)return Math.sign($)}if(X.pre.length===0||Q.pre.length===0)return Math.sign(Q.pre.length-X.pre.length);for(let G=0;G<Math.max(X.pre.length,Q.pre.length);G++){let $=X.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 H=Number($)-Number(W);if(H!==0)return Math.sign(H)}else if(K!==U)return K?-1:1;else if($!==W)return $<W?-1:1}return 0}async function zY(Y){try{return{ok:!0,names:await KW(Y)}}catch(J){let X=J.code;if(X==="ENOENT")return{ok:!0,names:[]};return{ok:!1,code:X,error:`${Y}: ${String(J)}`}}}async function NW(Y,J){let X;try{X=await UW(Y,"utf8")}catch(Q){if(Q.code==="ENOENT")return{kind:"gone"};return{kind:"unreadable"}}try{let Q=JSON.parse(X);if(Q!==null&&typeof Q==="object"&&Q.pid===J&&typeof Q.version==="string")return{kind:"ok",version:Q.version}}catch{}return{kind:"unreadable"}}async function q9(Y){let J=Y.isAlive??BW,X=Y.selfPid??process.pid,Q=new Map,G=(B)=>{let O=B.pid==="unknown"?`dir:${B.detail}`:B.pid;if(!Q.has(O))Q.set(O,B)},$=(B)=>{try{return J(B)}catch{return!0}},W=(B,O)=>{let q=O.exec(B),_=q?Number(q[1]):Number.NaN;return Number.isSafeInteger(_)&&_>=1?_:void 0},K=ZW(Y.stateHome),U=new Set,H=await zY(K);if(!H.ok)G({pid:"unknown",version:"unknown",detail:H.error});for(let B of H.ok?H.names:[]){let O=W(B,/^(\d+)\.json$/);if(O===void 0||O===X)continue;let q=_9(K,B),_=await NW(q,O);if(_.kind==="gone")continue;if(U.add(O),!$(O))continue;if(_.kind==="unreadable"){G({pid:O,version:"unknown",detail:q});continue}let M=LW(_.version,Y.currentVersion);if(M===void 0||M<0)G({pid:O,version:_.version,detail:q})}let V=Y.rpcDir??VW(Y.stateHome),D=await zY(V);if(!D.ok)G({pid:"unknown",version:"unknown",detail:D.error});for(let B of D.ok?D.names:[]){if(!p1(B))continue;let O=_9(V,B),q=await zY(O);if(!q.ok){if(q.code==="ENOTDIR")continue;G({pid:"unknown",version:"unknown",detail:q.error});continue}for(let _ of q.names){let M=W(_,/^port-(\d+)\.json$/);if(M===void 0||M===X||U.has(M))continue;if($(M))G({pid:M,version:"unknown",detail:_9(O,_)})}}let L=(B)=>B.pid==="unknown"?Number.POSITIVE_INFINITY:B.pid;return Q.size===0?{open:!0}:{open:!1,blockers:[...Q.values()].sort((B,O)=>L(B)-L(O))}}var v6="1.2.0";import{readFile as yJ}from"node:fs/promises";function l1(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}async function gJ(Y){let J=await xJ(Y.configPath),X=[];try{let G=JSON.parse(await yJ(Y.statePath,"utf8"));if(l1(G)){let $=G.accounts;if(l1($))X=Object.keys($)}}catch(G){if(G.code!=="ENOENT")throw G}return{rosterIds:J?[...J]:[],stateIds:X,orphanStateIds:J?X.filter((G)=>!J.has(G)):[]}}async function jW(Y){try{let J=JSON.parse(await yJ(Y.configPath,"utf8"));return l1(J)&&l1(J.claustrum)&&J.claustrum.mode==="claustrum"}catch{return!1}}var bJ="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 fJ(Y){if(!Y)return;let J=Y.accounts.find((X)=>X.id==="main"&&o0(X));if(J)return J;if(!Y.mainAccountId)return;return Y.accounts.find((X)=>o0(X)&&X.accountId===Y.mainAccountId)}function FW(Y,J){let X=Y.lastRefreshError;return E6(X,Y.refresh,J)&&X!==void 0&&X.nextRetryAt!==void 0&&X.nextRetryAt-X.checkedAt>=kJ}function OW(Y){let J=[],X=[],Q=Y.now??Date.now(),G=fJ(Y.storage),$=!1;if(m0(Y.auth))J.push({code:"tombstoned-host-slot",message:`OpenCode's OpenAI slot holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${bJ}`});else if(n0(Y.auth)){if(!o6(Y.storage))J.push({code:"main-pool-row-missing",message:"The main account was moved into the account pool, but the pool has no usable `main` row."})}else if(!Y.auth)J.push({code:"auth-slot-missing",message:"OpenCode's OpenAI auth slot is missing."}),$=!0;else if(Y.auth.type!=="oauth")J.push({code:"auth-slot-not-oauth",message:"OpenCode's OpenAI auth slot is not OAuth."}),$=!0;else if(G&&(!Y.auth.refresh||G.refresh!==Y.auth.refresh))J.push({code:"main-refresh-not-in-store",message:"OpenCode's main credential does not match the copy in the account store."}),$=!0;if($&&G){let U={type:"restore-main-credential"};X.push(U);let H=J.find((V)=>V.code==="auth-slot-missing"||V.code==="auth-slot-not-oauth"||V.code==="main-refresh-not-in-store");if(H)H.repair=U}let W=Y.storage?.accounts??[];if(W.length===0)J.push({code:"no-accounts",message:"The account store has no accounts."});else if(!W.some((U)=>U.enabled!==!1))J.push({code:"no-enabled-accounts",message:"The account store has no enabled accounts."});for(let U of W){if(!o0(U)||!m0(U))continue;J.push({code:"tombstoned-account",accountId:U.id,message:`Account ${U.id} holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${bJ}`})}if(Y.retiredCustodyMode)J.push({code:"retired-custody-mode",message:"The config still selects the vault custody mode of an older version (`claustrum.mode`). It is ignored, and dropped at the next settings write; vault accounts are served once this host is connected to the Claustrum vault."});for(let U of W){if(!o0(U))continue;if(!FW(U,Q))continue;let H={type:"clear-refresh-backoff",accountId:U.id};X.push(H),J.push({code:"armed-non-transient-refresh-backoff",accountId:U.id,message:`Account ${U.id} has an armed non-transient refresh backoff.`,repair:H})}let K=[...Y.orphanStateIds??[]];if(K.length>0){let U={type:"prune-orphan-state-ids",ids:K};X.push(U),J.push({code:"orphan-state-ids",message:`State contains ids absent from the config roster: ${K.join(", ")}.`,repair:U})}return{findings:J,repairs:X}}function mJ(Y){let J=(X)=>{if(X.type==="restore-main-credential")return{label:"Copy the stored main credential back into OpenCode's slot",apply:async()=>{if(n0(await Y.readAuth()))return;let Q=fJ(await Y.loadAccounts(Y.paths));if(!Q)return;await Y.setMainAuth({refresh:Q.refresh,access:Q.access??"",expires:Q.expires??0})}};if(Y.migrated)return;if(X.type==="prune-orphan-state-ids")return{label:`Drop the state entries of ${X.ids.join(", ")}`,apply:async()=>{await Y.mutateAccounts((Q)=>Q,Y.paths)}};return{label:`Clear the refresh backoff of ${X.accountId}`,apply:async()=>{await Y.mutateAccounts((Q)=>{let G=Q.accounts.find(($)=>$.id===X.accountId&&o0($));if(G)G.lastRefreshError=void 0;return Q},Y.paths)}}};return[{id:"openai-auth",run:async()=>{let[X,Q,G,$]=await Promise.all([Y.loadAccounts(Y.paths),Y.readStoreIds(Y.paths),Y.readAuth(),jW(Y.paths)]),W=OW({auth:G.type==="missing"?void 0:G,storage:X,orphanStateIds:Q.orphanStateIds,retiredCustodyMode:$,now:Y.now()}),K=await F9({provider:"openai",quota:j9,configPath:Y.paths.configPath,statePath:Y.paths.statePath}).read();if(K.status==="ready")for(let U of K.rows){if(U.disabledReason!==vJ)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. ${hJ}`})}return W.findings.map((U)=>{let H=U.repair?J(U.repair):void 0;return{code:U.code,message:U.message,...U.accountId!==void 0?{accountId:U.accountId}:{},...H?{repair:H}:{}}})}}]}var PW=GX,cJ="OpenAI accounts",_W="ChatGPT accounts in the vault",qW="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 EW(){let{redirectUri:Y}=await iJ(),J=await pJ(),X=uJ(crypto.getRandomValues(new Uint8Array(32)).buffer),Q=lJ(Y,J,X),G=nJ(J,X);return{url:Q,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let $=await G;return{type:"success",refresh:$.refresh_token,access:$.access_token,expires:Date.now()+($.expires_in??3600)*1000,accountId:s6($)}}finally{dJ(X)}}}}async function MW(Y){let{deviceData:J,url:X,instructions:Q}=await oJ(Y);return{url:X,instructions:Q,method:"auto",async callback(){try{let G=await rJ(J,Y);return{type:"success",refresh:G.refresh_token,access:G.access_token,expires:Date.now()+(G.expires_in??3600)*1000,accountId:s6(G)}}catch{return{type:"failed"}}}}}function KX({client:Y,getAuth:J,getPaths:X=()=>U0(X0()),fetchImpl:Q=fetch,packageVersion:G=v6,dependencies:$,onMainSlotWritten:W,vault:K}){let U={authorizeBrowser:$?.authorizeBrowser??EW,authorizeHeadless:$?.authorizeHeadless??(()=>MW(G)),beginAccountLogin:$?.beginAccountLogin??i1,loadAccounts:$?.loadAccounts??R0,mutateAccounts:$?.mutateAccounts??n1,readStoreIds:$?.readStoreIds??gJ,openBrowser:$?.openBrowser??PW,now:$?.now??Date.now,openAccountPool:$?.openAccountPool??D9,migrationBlockers:$?.migrationBlockers??(async()=>{let j=await q9({currentVersion:G});return j.open?[]:j.blockers.map((C)=>({pid:C.pid,version:C.version}))}),...$?.terminal?{terminal:$.terminal}:{},...$?.vaultWait?{vaultWait:$.vaultWait}:{}},H=async()=>await J?.().catch(()=>{return})??{type:"missing"},V=async()=>{if(K&&await K.authority()!=="local")return!0;if((await H()).type!=="missing")return!0;let j=X(),C=U.openAccountPool(j);if((await C.read()).status==="ready")return JX(C);return((await U.loadAccounts(j))?.accounts.length??0)>0},D=async(j)=>{if(await WX(X().configPath,async()=>{if(K&&await K.authority()!=="local")return!1;if(n0(await H()))return!1;return await Y.auth.set({path:{id:"openai"},body:{type:"oauth",...j}}),!0}))await W?.().catch(()=>{})},L=(j)=>({begin:async({headless:C,signal:h})=>{if(K&&await K.authority()!=="local")throw Error(E9);let A=await U.beginAccountLogin({version:G,headless:C,...h?{signal:h}:{}});return{url:A.url,instructions:A.instructions,completion:A.completion.then(async(g)=>{if(K&&await K.authority()!=="local")throw Error(E9);let r=await j.read(),i=r.status==="ready"?r.rows.find((B0)=>B0.id===Z6)?.identity:void 0;if(g.accountId&&i&&g.accountId===i)throw Error("that account is already the OpenCode main credential");return{id:g.id,credential:{type:"oauth",refresh:g.refresh,...g.access!==void 0?{access:g.access}:{},...g.expires!==void 0?{expires:g.expires}:{}},...g.accountId!==void 0?{identity:g.accountId}:{},...g.label!==void 0?{label:g.label}:{}}})}},openBrowser:(C)=>U.openBrowser(C)}),B=async(j)=>{if(K&&await K.authority()!=="local")throw Error(E9);let C=j.credential;if(C?.type!=="oauth"||!C.access)throw Error("no usable access token for a quota check");let h=await a9({accessToken:C.access,fetchImpl:Q,now:U.now,...j.identity?{accountId:j.identity}:{},accountKey:j.id});return M9(h,U.now(),!0)},O=(j)=>mJ({paths:X(),migrated:j,readAuth:H,loadAccounts:U.loadAccounts,readStoreIds:U.readStoreIds,mutateAccounts:U.mutateAccounts,setMainAuth:D,now:U.now}),q=(j,C)=>({title:cJ,store:t8(C,{rowLocks:(h)=>O9(j,h)}),...U.terminal?{terminal:U.terminal}:{},login:L(C),protect:(h,A)=>u1(h,A),extraLocks:q6(j),pollQuota:B,doctor:O(!0),status:async()=>{let h=await K?.status();if(K&&await K.authority()!=="local"&&h)return[KY(K.host,K.name,h.enrollment)];return[`Routing: ${(await U.loadAccounts(j))?.routing?.mode??"main-first"}`,...K?[KY(K.host,K.name,(await K.status()).enrollment)]:[]]},...K?{extraActions:[_(K)]}:{}}),_=(j)=>{let C=j.enrolled();return{id:C?"vault-disconnect":"vault-connect",label:C?"Disconnect from the Claustrum vault":"Connect to the Claustrum vault",hint:"serve OpenAI accounts held in the vault",run:async(h)=>{let A=await j.authority();if(C){if(A!=="local")await j.disconnect();h.print("Disconnected from the Claustrum vault.");return}if(A!=="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 g,r=await j.waitForApproval({...U.vaultWait,onPending:(i)=>{let Z0=i.state==="pending"?i.requestId??i.retryCode??"":i.state;if(Z0===g)return;g=Z0;for(let B0 of aJ(j.name,i))h.print(B0);h.print("Waiting for the approval… (stop with Ctrl-C; Connect picks the request up again)")}});h.print(tJ(j,r).text)}}},M=async()=>{let j=await U.migrationBlockers();return YX({title:cJ,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((C)=>` ${C.pid==="unknown"?"processes that could not be read":`pid ${C.pid}`}: version ${C.version}`)]:[]],actions:[eJ({checks:O(!1)})],...U.terminal?{terminal:U.terminal}:{}})},S=async(j)=>{let C=X(),h=U.openAccountPool(C);if(K&&await K.authority()!=="local")return d1(q(C,h),K);if(await c1(C,h)===void 0)return M();let A=q(C,h);return K?d1(A,K):XX(A)},x=(j)=>async()=>{if(K&&await K.authority()!=="local")throw Error(E9);let C=await j();if(C.method!=="auto")return C;return{...C,callback:async()=>{let h=await C.callback();if(K&&await K.authority()!=="local")return{type:"failed"};return h}}};return[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:QX({hasCredential:V,openMenu:S,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:_W,type:"oauth",authorize:async()=>({url:"",instructions:qW,method:"auto",callback:async()=>{if(await sJ(K.paths,K.name)!=="vault")return{type:"failed"};try{let j=JSON.parse(await DW(zX(),"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{...$X,type:"success"}}})}]:[]]}var UY=["type","model","instructions","previous_response_id","input","tools","tool_choice","parallel_tool_calls","reasoning","store","stream","include","prompt_cache_key","text","generate","client_metadata"];function a6(Y){let J={};for(let X of UY)if(X in Y)J[X]=Y[X];for(let X of Object.keys(Y))if(!(X in J))J[X]=Y[X];return J}import{createHash as pW}from"node:crypto";import{createHash as AW,randomBytes as UX}from"node:crypto";import{chmod as TW,lstat as HX,mkdir as RW,open as CW,readdir as DX,rename as wW,unlink as LY,writeFile as SW}from"node:fs/promises";import{join as o1,resolve as HY}from"node:path";var IW=100,ZY="session-unknown",bW=300000,kW=60000,xW=600000,vW=/\.(body|meta|request|response)\.json$/,hW=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-\d+-\d{6,}-[a-zA-Z0-9._-]+$/,yW=/\.[a-f0-9]{24}\.partial$/;function PX(Y){let J=Y.replace(vW,"");if(J===Y||!hW.test(J))return;return J}function gW(Y){let J=Y.replace(yW,"");return J!==Y&&PX(J)!==void 0}async function ZX(Y){let{dir:J,maxBytes:X}=Y,Q=Y.now??Date.now(),G=Y.minAgeMs??kW,$=Y.partialStaleMs??xW,W={removed:0,freedBytes:0};if(!(X>0))return W;try{if(V6)await LX(J,"directory");if((await HX(J)).isSymbolicLink())return W;let K=new Set((Y.protectedPaths??[]).map((_)=>HY(_))),U=await DX(J,{withFileTypes:!0}),H=[];await Promise.all(U.map(async(_)=>{if(!_.isFile())return;let M=gW(_.name),S=M?void 0:PX(_.name);if(!M&&S===void 0)return;let x=o1(J,_.name);try{let j=await HX(x);if(!j.isFile())return;H.push({path:x,size:j.size,mtimeMs:j.mtimeMs,group:S})}catch{}}));let V=H.reduce((_,M)=>_+M.size,0),D=0,L=0,B=async(_)=>{try{await LY(_.path),V-=_.size,L+=_.size,D+=1}catch{}};for(let _ of H){if(_.group!==void 0)continue;if(K.has(HY(_.path)))continue;if(Q-_.mtimeMs<$)continue;await B(_)}let O=new Map;for(let _ of H){if(_.group===void 0)continue;let M=O.get(_.group)??{files:[],newest:0};M.files.push(_),M.newest=Math.max(M.newest,_.mtimeMs),O.set(_.group,M)}let q=[...O.entries()].sort(([_,M],[S,x])=>M.newest-x.newest||_.localeCompare(S));for(let[,_]of q){if(V<=X)break;if(Q-_.newest<G)continue;if(_.files.some((M)=>K.has(HY(M.path))))continue;for(let M of _.files)await B(M)}if(D>0)Y.logger?.debug("removed old dump files",{removed:D,freedBytes:L});return{removed:D,freedBytes:L}}catch(K){if(K instanceof e9&&K.code==="ERR_PRIVATE_FILES_SECURITY")throw K;return W}}async function fW(Y,J,X){if(V6)return FX(Y,J,{stagePath:`${Y}.${X?X():UX(12).toString("hex")}.partial`});for(let Q=0;;Q+=1){let G=`${Y}.${X?X():UX(12).toString("hex")}.partial`,$=!1,W;try{W=await CW(G,"wx",384),$=!0,await W.writeFile(J,"utf8"),await W.chmod(384),await W.close(),W=void 0,await wW(G,Y);return}catch(K){if(await W?.close().catch(()=>{}),$)await LY(G).catch(()=>{});if(K.code==="EEXIST"&&Q===0)continue;throw K}}}function VY(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function t9(Y,J){let X=Y.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!X)return J;return X.slice(0,80)}function VX(Y){return AW("sha256").update(Y).digest("hex")}function mW(Y){return Y.toLowerCase().replace(/[-_]/g,"")}function BX(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function cW(Y,J){if(Y===void 0)return null;if(Y===J)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:Y.length,currentBytes:J.length};let X=0;while(X<Y.length&&X<J.length&&Y[X]===J[X])X++;let Q=Y.length-1,G=J.length-1;while(Q>=X&&G>=X&&Y[Q]===J[G])Q--,G--;return{changed:!0,firstByte:X,lastPreviousByte:Q,lastCurrentByte:G,changedPreviousBytes:Q-X+1,changedCurrentBytes:G-X+1,previousBytes:Y.length,currentBytes:J.length}}var uW=0;function _X(Y){let J=Y.enabled===!0,X=Y.pid??process.pid,Q=Y.now??Date.now,G=Y.logger,$=new Set((Y.secretKeys??[]).map(mW)),W=OX({extraSecretKeys:(A)=>$.has(A),extraValuePatterns:[...Y.secretPatterns??[]]}),K=new Set(Y.schemaKeys??["tools"]),U=new Map,H=()=>typeof Y.dir==="function"?Y.dir():Y.dir;function V(A){let g=W.redact({[A]:null})[A];return g===null?void 0:g}function D(A){if(Array.isArray(A))return A.map(D);if(BX(A)){let g={};for(let[r,i]of Object.entries(A)){let Z0=V(r);if(K.has(r))g[r]=W.redactStrings(i);else if(Z0!==void 0)g[r]=Z0;else g[r]=D(i)}return g}return W.redactStrings(A)}function L(A){let g;try{g=JSON.parse(A)}catch{return{text:W.redactStrings(A),parsed:void 0}}let r=D(g),i=JSON.stringify(r);return{text:JSON.stringify(g)===i?A:i,parsed:BX(r)?r:void 0}}async function B(A,g,r,i){let Z0=`-${t9(g,ZY)}-${t9(r,"channel")}`,B0;try{B0=await DX(A)}catch{return}let p=B0.filter((t)=>t.endsWith(".meta.json")&&t.includes(Z0)).sort().reverse();for(let t of p)try{if(JSON.parse(await BY(o1(A,t),V6))?.baselineKey!==i)continue;return await BY(o1(A,t.replace(/\.meta\.json$/,".body.json")),V6)}catch(L0){if(L0 instanceof e9&&(V6||L0.code==="ERR_PRIVATE_FILES_SECURITY"))throw L0}return}function O(A,g){if(!U.has(A))while(U.size>=IW){let r=U.keys().next().value;if(r===void 0)break;U.delete(r)}U.set(A,g)}async function q(A){if(!J)return;let g=++uW,r=A.session?.trim()||ZY,i=H(),Z0=new Date(Q()).toISOString(),B0=[Z0.replace(/[:.]/g,"-"),String(X),String(g).padStart(6,"0"),t9(r,ZY),t9(A.channel,"channel"),...A.phase?[t9(A.phase,"phase")]:[]].join("-"),p=o1(i,B0),t={body:`${p}.body.json`,metadata:`${p}.meta.json`,request:`${p}.request.json`},L0=VX(`${A.channel}\x00${r}`);try{if(V6)await NX(i);else await RW(i,{recursive:!0,mode:448}),await TW(i,448);let v=U.get(L0),x0=v===void 0?void 0:"memory";if(v===void 0){if(v=await B(i,r,A.channel,L0),v!==void 0)x0="disk"}let T0=L(A.bodyText),K0={id:B0,createdAt:Z0,pid:X,session:VY(r),channel:A.channel,...A.phase?{phase:A.phase}:{},accountId:A.accountId,status:A.status,error:A.error===void 0?void 0:W.redactStrings(A.error),baselineKey:L0,bodyBytes:Buffer.byteLength(A.bodyText,"utf8"),bodyHash:VX(A.bodyText),diff:cW(v,T0.text),baselineSource:x0,body:T0.parsed?{parseable:!0,...Y.summarize?.(T0.parsed)}:{parseable:!1},...A.meta?{extra:D(A.meta)}:{},files:t},s=D({url:A.url,method:A.method,accountId:A.accountId,headers:A.headers===void 0?void 0:Object.fromEntries(new Headers(A.headers).entries())}),_0=(d,y)=>V6?jX(d,y):SW(d,y,{encoding:"utf8",mode:384,flag:"wx"}),l=[[t.body,T0.text],[t.metadata,`${JSON.stringify(K0,null,2)}
|
|
2
|
+
`],[t.request,`${JSON.stringify(s,null,2)}
|
|
3
|
+
`]],I=await Promise.allSettled(l.map(([d,y])=>_0(d,y))),u=I.find((d)=>d.status==="rejected");if(u){if(Y.cleanupFailedDumps)await _(l,I);throw u.reason}return O(L0,T0.text),G?.debug("dumped request",{id:B0,session:VY(r),body:t.body}),C(i,Object.values(t)),{id:B0,files:t,responseFile:`${p}.response.json`}}catch(v){if(v instanceof e9&&(V6||v.code==="ERR_PRIVATE_FILES_SECURITY"))throw v;G?.warn("request dump failed",{session:VY(r),error:v instanceof Error?v.message:String(v)});return}}async function _(A,g){await Promise.all(A.map(async([r],i)=>{let Z0=g[i];if(Z0?.status==="rejected"&&Z0.reason?.code==="EEXIST")return;await LY(r).catch(()=>{})}))}let M=Y.maxBytes??0,S=Y.sweepIntervalMs??bW,x=0;function j(A,g){return{dir:A,maxBytes:M,protectedPaths:g,now:Q(),minAgeMs:Y.sweepMinAgeMs,partialStaleMs:Y.partialStaleMs,logger:G}}function C(A,g){if(!(M>0))return;let r=Q();if(r-x<S)return;x=r,ZX(j(A,g))}async function h(A,g){if(!A)return;let r=D({status:g.status,requestId:g.requestId,usage:g.usage,...g.fields,complete:g.complete??!0});try{return await fW(A.responseFile,`${JSON.stringify(r,null,2)}
|
|
4
|
+
`,Y.stageName),A.responseFile}catch(i){if(i instanceof e9&&(V6||i.code==="ERR_PRIVATE_FILES_SECURITY"))throw i;G?.warn("response dump failed",{id:A.id,error:i instanceof Error?i.message:String(i)});return}}return{isEnabled:()=>J,setEnabled:(A)=>{J=A},dump:q,dumpResponse:h,sweep:(A)=>ZX(j(H(),A))}}var EX=V0("dump"),h6="x-cortexkit-openai-auth-dump-session",lW=["chatgpt-account-id","email","org_name","organization_name"],dW=["tools"];function NY(Y){return pW("sha256").update(JSON.stringify(Y)).digest("hex")}function iW(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function nW(Y){let J=Array.isArray(Y.input)?Y.input:[],X=Array.isArray(Y.tools)?Y.tools:[],Q=Y.client_metadata!=null&&typeof Y.client_metadata==="object"&&!Array.isArray(Y.client_metadata)?Y.client_metadata:void 0;return{model:typeof Y.model==="string"?Y.model:void 0,stream:Y.stream,generate:Y.generate,store:Y.store,previousResponseID:typeof Y.previous_response_id==="string"?Y.previous_response_id:void 0,promptCacheKey:typeof Y.prompt_cache_key==="string"?Y.prompt_cache_key:void 0,reasoning:Y.reasoning,inputCount:J.length,inputHash:NY(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:NY(J[0]),toolsCount:X.length,toolTypes:X.map(iW),toolsHash:NY(X),clientMetadataKeys:Q?Object.keys(Q).sort():[]}}function oW(){return _X({dir:()=>i0().dumpDir,logger:EX,secretKeys:lW,schemaKeys:dW,summarize:nW})}var qX=oW();async function A9(Y){let J=i0().dump===!0;if(qX.setEnabled(J),!J)return;let X=typeof Y.bodyText==="function"?Y.bodyText():Y.bodyText;await qX.dump({session:Y.sessionID,channel:Y.transport,phase:Y.phase,bodyText:X,accountId:Y.accountId,url:Y.url,method:Y.method,headers:Y.headers,status:Y.status,error:Y.error})}async function t6(Y){if(!i0().dump)return;EX.debug("diagnostic",Y)}function T9(Y){return JSON.stringify(jY(Y))??"undefined"}function jY(Y){if(Array.isArray(Y))return Y.map(jY);if(!n(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((J)=>[J,jY(Y[J])]))}var rW=512,sW=2097152;function FY(Y,J){if(typeof Y==="function"||typeof J==="function")return!1;if(J!==null&&typeof J==="object"&&Object.hasOwn(J,"toJSON")&&typeof J.toJSON==="function")return!1;if(Y===J)return!0;if(Array.isArray(Y))return Array.isArray(J)&&Y.length===J.length&&Y.every(($,W)=>FY($,J[W]));if(Y===null||J===null||typeof Y!=="object"||typeof J!=="object"||Array.isArray(J))return!1;let X=Y,Q=J,G=Object.keys(X);return G.length===Object.keys(Q).length&&G.every(($)=>Object.prototype.propertyIsEnumerable.call(Q,$)&&FY(X[$],Q[$]))}function e6(Y,J){let X=[],Q=[],G=0;for(let $=0;$<Y.length;$++){let W=J?.texts[$],K=W!==void 0&&FY(J?.snapshots[$],Y[$]),U=K?W:T9(Y[$]);X.push(U),Q.push(K?J?.snapshots[$]:U==="undefined"?void 0:JSON.parse(U)),G+=U.length}return{texts:X,snapshots:Q,retainable:Y.length<=rW&&G<=sW}}function Y1(Y){return Y.retainable?Y:void 0}function J1(Y,J){if(Y.texts.length>J.texts.length)return;for(let X=0;X<Y.texts.length;X++)if(Y.texts[X]!==J.texts[X])return;return Y.texts.length}function M6(){let Y=crypto.getRandomValues(new Uint8Array(16)),J=Date.now();Y[0]=J/1099511627776&255,Y[1]=J/4294967296&255,Y[2]=J/16777216&255,Y[3]=J/65536&255,Y[4]=J/256&255,Y[5]=J&255,Y[6]=(Y[6]??0)&15|112,Y[8]=(Y[8]??0)&63|128;let X=Array.from(Y,(Q)=>Q.toString(16).padStart(2,"0")).join("");return`${X.slice(0,8)}-${X.slice(8,12)}-${X.slice(12,16)}-${X.slice(16,20)}-${X.slice(20)}`}var MX=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"]),aW="terminal_resize_reflow",r1="0.159.0",AX=`codex_exec/${r1} (Debian 12.0.0; aarch64) unknown (codex_exec; ${r1})`,tW="seccomp",X1="x-openai-auth-agent";function eW(Y){if(typeof Y!=="string")return;try{let J=JSON.parse(Y);return typeof J==="object"&&J!==null&&!Array.isArray(J)?J:void 0}catch{return}}function Q1(Y,J){return n(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===J}function Yz(Y,J,X){if(!Y.input)return J.length>0;let Q=Y.canonicalInput??e6(Y.input);if(J1(Q,X)===void 0)return!0;return J.slice(Y.input.length).some(($)=>Q1($,"user")||Q1($,"developer"))}function Jz(Y,J,X){let Q=Array.isArray(J?.input)?J.input:void 0,G=Q?e6(Q,Y.canonicalInput):void 0;if(Q&&G&&(Yz(Y,Q,G)||!Y.turnID))Y.turnID=(X?.uuid??M6)(),Y.turnStartedAt=(X?.now??Date.now)();else if(!Y.turnStartedAt)Y.turnStartedAt=(X?.now??Date.now)();if(Q&&G)Y.input=Q.slice(),Y.canonicalInput=Y1(G)}function TX(Y){let J=Y.headers.get(X1);if(Y.headers.delete(X1),!Y.metadata)return{init:Y.init};let X=eW(Y.init?.body),Q=Y.runtime?.now??Date.now;if(!Y.skipTurnUpdate){if(!Y.websocket)Jz(Y.metadata,X,Y.runtime);else if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Q();if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Q()}let G=JSON.stringify({session_id:Y.metadata.threadID,thread_id:Y.metadata.threadID,thread_source:"user",turn_id:Y.metadata.turnID,sandbox:tW,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",aW),Y.headers.set("x-codex-turn-metadata",G),Y.headers.set("user-agent",AX),Y.headers.set("version",r1),Y.dumpSessionID)Y.headers.set(h6,Y.dumpSessionID);let $=X;if(!$)return{init:Y.init};let W=Y.responsesLite&&typeof $.model==="string"&&MX.has($.model);if(W&&!Y.websocket)Y.headers.set("x-openai-internal-codex-responses-lite","true");if($.prompt_cache_key=Y.metadata.threadID,$.parallel_tool_calls??=!0,Array.isArray($.tools))$.tools=$.tools.map(Xz);if(Y.applyEffort?.($,Y.metadata,J),W)Y.rewriteLite($);let K={...typeof $.client_metadata==="object"&&$.client_metadata!==null?$.client_metadata:{},"x-codex-installation-id":Y.installationID,"x-codex-window-id":Y.metadata.windowID};if(Y.websocket){if(K["x-codex-turn-metadata"]=G,K["x-codex-ws-stream-request-start-ms"]=String(Q()),W)K.ws_request_header_x_openai_internal_codex_responses_lite="true"}return $.client_metadata=K,Y.headers.delete("content-length"),Y.headers.delete("Content-Length"),{init:{...Y.init,body:JSON.stringify(a6($))}}}function Xz(Y){if(!n(Y)||Y.type!=="function")return Y;let J=n(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:U,...H}=Y.parameters;return H})():Y.parameters,{type:X,name:Q,description:G,strict:$,parameters:W,...K}=Y;return{type:X,name:Q,description:G,strict:$??!1,parameters:J,...K}}import{mkdirSync as Qz,readFileSync as Gz,renameSync as $z,writeFileSync as Wz}from"node:fs";import{dirname as zz}from"node:path";function Kz(Y){let J=new Map,X=JSON.parse(Gz(Y,"utf8"));if(!n(X.sessions))return J;for(let[Q,G]of Object.entries(X.sessions)){if(!n(G)||typeof G.threadID!=="string")continue;J.set(Q,G.threadID)}return J}function RX(Y,J=M6){let X=new Map,Q;try{Q=Kz(Y)}catch{return X}for(let[G,$]of Q)X.set(G,{threadID:$,turnID:J(),windowID:`${$}:0`});return X}function Uz(Y,J){let X=`${Y}.tmp-${process.pid}`;Qz(zz(Y),{recursive:!0});let Q={version:1,sessions:Object.fromEntries([...J].map(([G,$])=>[G,{threadID:$}]))};Wz(X,`${JSON.stringify(Q,null,2)}
|
|
5
|
+
`,"utf8"),$z(X,Y)}function CX(Y,J){try{Uz(Y,[...J.entries()].map(([X,Q])=>[X,Q.threadID]))}catch{}}var OY={rpcRoot:"openai-auth",directoryPrefix:bX,registrationSessionId:"process"};function s1(Y,J){wX(OY,Y,J)}function kX(Y=0,J){return SX(OY,Y,J)}function xX(Y){return IX(OY,Y)}var a1=V0("commands");function R9(Y){return{configPath:Y.accountStoragePath,statePath:Y.accountStatePath}}function DY(Y){return`${String(Y.startHour).padStart(2,"0")}-${String(Y.endHour).padStart(2,"0")}`}function Hz(Y){let J=/^(\d{1,2})-(\d{1,2})$/.exec(Y.trim());if(!J)return{ok:!1,reason:"expected HH-HH, e.g. 9-18 or 22-6"};let X=Number(J[1]),Q=Number(J[2]);if(X>23||Q>23||X===Q)return{ok:!1,reason:"hours must be integers 0-23 and start ≠ end"};return{ok:!0,startHour:X,endHour:Q}}var Zz="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 Vz(Y){let J=(X)=>n6(Y.store(),q6(R9(Y)),(Q)=>{let G={...Q.cacheKeep??{}};X(G),Q.cacheKeep=G});return{title:"Cache",build:async()=>{let X=Y.cacheKeepManager;if(!X)return{lines:["Keep-warm unavailable"]};let Q=e1(await Y.loadAccounts(R9(Y))),G=Q?.enabled===!0,$=Q?.subagents===!0,W=X.status(),K=W.window?DY(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}`,...Y.cacheKeepNotice?[Y.cacheKeepNotice]:[],`TTL ${Math.round(W.ttlMs/1000)}s · lead ${Math.round(W.leadMs/1000)}s · idle cap ${Math.round(W.maxIdleWarmMs/60000)}min (subagents ${Math.round(W.maxSubagentIdleMs/60000)}min)`],items:W.targets.map((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 H=U.enabled===!0;if(await J((V)=>{V.enabled=H}),Y.setCacheKeepEnabled?.(H),H)X.start();else X.stop();return a1.info(H?"cachekeep enabled":"cachekeep disabled"),H?`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 H=U.subagents===!0;return await J((V)=>{V.subagents=H}),Y.setCacheKeepSubagents?.(H),`Subagent warming is ${H?"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 H=U.sustain===!0;return await J((V)=>{V.sustain=H}),Y.setCacheKeepSustain?.(H),H?Zz:"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:DY(W.window)}:{}}],run:async({values:U})=>{let H=U.window;if(typeof H!=="string"||H.trim()==="")return await J((B)=>{delete B.startHour,delete B.endHour}),Y.setCacheKeepWindow?.(void 0),"Warm window cleared: keep-warm warms at any hour (within idle caps).";let V=Hz(H);if(!V.ok)return{ok:!1,text:`Invalid window: ${V.reason}`};let{startHour:D,endHour:L}=V;return await J((B)=>{B.startHour=D,B.endHour=L}),Y.setCacheKeepWindow?.({startHour:D,endHour:L}),`Warming limited to ${DY(V)} local hours.`}}]}}}}var vX=["error","warn","info","debug","trace"];function Bz(Y){return{title:"Diagnostics",build:async()=>{let J=i0(),Q=(await Y.loadAccounts(R9(Y)))?.logging?.level??"info";return{lines:[`Dumps ${J.dump?"on":"off"}`,`Dump directory: ${J.dumpDir}`,`Log level: ${Q}`],actions:[{id:"dump",label:J.dump?"Turn request dumps off":"Turn request dumps on",knobs:[{kind:"toggle",id:"enabled",label:"Request dumps",value:!J.dump}],run:async({values:G})=>{let $=G.enabled===!0;await n6(Y.store(),q6(R9(Y)),(K)=>{K.dump={...K.dump??{},enabled:$}});let W=CJ();return a1.info($?"request dump enabled":"request dump disabled"),$?`Request dumps are on, written to ${W.dumpDir}.
|
|
6
|
+
|
|
7
|
+
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:vX.map((G)=>({value:G,label:G})),value:vX.includes(Q)?Q:"info"}],run:async({values:G})=>{let $=String(G.level);return await n6(Y.store(),q6(R9(Y)),(W)=>{W.logging={...W.logging??{},level:$}}),t1($),a1.info("log level changed",{level:$}),`Log level set to ${$}.`}}]}}}}async function Lz(Y){let J=await Y.store().read(),X=J.status==="ready"?J.rows:[];return[...new Set(["main",...X.filter((Q)=>Q.enabled&&Q.type==="oauth").map((Q)=>Q.id)])]}function yX(Y){let J=R9(Y),X=q6(J),Q=Y.quotaManager&&Y.resolveResetTarget&&Y.refreshResetTargetQuota&&Y.fetchImpl&&Y.now&&Y.randomUUID?XY({configPath:J.configPath,statePath:J.statePath,quotaManager:Y.quotaManager,loadAccounts:Y.loadAccounts,mutateAccounts:e8(Y.store(),X),resolveResetTarget:Y.resolveResetTarget,refreshResetTargetQuota:Y.refreshResetTargetQuota,fetchImpl:Y.fetchImpl,now:Y.now,randomUUID:Y.randomUUID,accountKeys:()=>Lz(Y)}):void 0,G=Y.beginAccountLogin;return QY({store:Y.store(),...Y.readOnly?{readOnly:!0}:{},...Y.allowAction?{allowAction:Y.allowAction}:{},...Y.unavailableSections?{unavailableSections:Y.unavailableSections}:{},...Y.vault?{vault:Y.vault}:{},...Y.now?{now:Y.now}:{},extraLocks:X,rowLocks:($)=>O9(J,$),migration:Y.migration,...G?{login:{begin:($)=>G({...$,version:Y.packageVersion}),mainIdentity:async()=>{let $=await Y.store().read();if($.status!=="ready")return;return $.rows.find((W)=>W.id==="main")?.identity}}}:{},protect:($,W)=>u1($,W),...Y.refreshAllQuota?{quotaCheck:async($)=>{if($.length===1){let U=Y.store();for(let H of $)await U.requestReading(H);await U.pullsSettled();return}let K=(await Y.refreshAllQuota?.()??[]).filter((U)=>!U.ok);if(K.length>0)throw new hX("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(`
|
|
8
|
+
`))}}:{},cache:Vz(Y),diagnostics:Bz(Y),extras:[...Q?[Q]:[],YY({...Y.getStickyRouting?{getPin:Y.getStickyRouting}:{},...Y.clearStickyRouting?{clearPin:Y.clearStickyRouting}:{}}),...Y.vault?[JY({vault:Y.vault,changed:Y.afterWrite})]:[]],afterApply:async()=>{await Y.afterWrite?.(),await Y.refreshSidebar?.().catch(()=>{})}})}function gX(Y){return(J,X="info")=>{a1.info("menu notification",{sessionId:Y,kind:X}),s1({command:k6,notify:{message:J,kind:X}},Y)}}function fX(Y,J){return yX(Y).open({...J!==void 0?{sessionId:J}:{},notify:gX(J)})}function mX(Y,J){return yX(Y).apply(J,{...J.sessionId!==void 0?{sessionId:J.sessionId}:{},notify:gX(J.sessionId)})}function cX(Y){let J=[`## ${Y.title}`];for(let X of Y.sections){J.push("",`### ${X.title}`);for(let Q of X.lines)J.push(Q);for(let Q of X.items){let G=Q.detail??Q.status;J.push(`- ${Q.label}${G?`: ${G}`:""}`)}}return J.push("","Open the OpenCode TUI to change these settings."),J.join(`
|
|
9
|
+
`)}var Nz=300000,jz=30000,uX=240000,Fz="bg-quota-refresh",Oz=120000;function PY(Y,J){return Y8({name:Fz,ttlMs:Oz,path:Y,renew:!0,...J})}function pX(Y,J=C9,X=()=>PY(Y.paths.configPath)){return Dz(Y,J,X)}function Dz(Y,J,X){return lX(async()=>J({...Y,respectBackoff:!0,skipFresherThanMs:uX}),X,[])}async function lX(Y,J,X){let Q;try{Q=await J()}catch{Q=void 0}if(Q===null)return X;try{return await Y()}finally{await Q?.release().catch(()=>{})}}function dX(Y,J,X){return lX(async()=>{return await Y.refreshDueTokens(J),Y.pollRows(J,{skipReadWithinMs:uX})},X,[])}class _Y{setIntervalFn;clearIntervalFn;random;onError;run;timer;tickPromise;stopped=!1;constructor(Y={}){this.setIntervalFn=Y.setIntervalFn??setInterval,this.clearIntervalFn=Y.clearIntervalFn??clearInterval,this.random=Y.random??Math.random,this.onError=Y.onError}start(Y,J=this.onError){if(this.run=Y,this.onError=J,this.stopped=!1,this.timer)return;let X=Math.round((this.random()*2-1)*jz);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},Nz+X),"unref"in this.timer)this.timer.unref()}stop(){if(this.stopped=!0,this.run=void 0,!this.timer)return;this.clearIntervalFn(this.timer),this.timer=void 0}isStopped(){return this.stopped}}function qY(Y){if(!Y||typeof Y!=="object")return;let J=Y,X=Number(J.startHour),Q=Number(J.endHour);if(!Number.isInteger(X)||!Number.isInteger(Q)||X<0||X>23||Q<0||Q>23||X===Q)return;return{startHour:X,endHour:Q}}function G1(Y,J=new Date){if(!Y)return!1;let X=J.getHours();if(Y.startHour<Y.endHour)return X>=Y.startHour&&X<Y.endHour;return X>=Y.startHour||X<Y.endHour}var Pz=300000,_z=3600000,qz=1800000,Ez=60000,Mz=32,Az=8388608,Tz=30000,Rz=600000;function B6(Y,J){return typeof Y==="number"&&Number.isFinite(Y)&&Y>0?Y:J}function J8(Y){return Y instanceof Error?Y.message:String(Y)}class $1{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=B6(Y.ttlMs,Pz),this.tickIntervalMs=B6(Y.tickIntervalMs,Ez),this.leadMs=B6(Y.leadMs,this.tickIntervalMs+15000),this.maxIdleWarmMs=B6(Y.maxIdleWarmMs,_z),this.maxSubagentIdleMs=B6(Y.maxSubagentIdleMs,qz),this.maxTargets=B6(Y.maxTargets,Mz),this.maxBytes=B6(Y.maxBytes,Az),this.warmTimeoutMs=B6(Y.warmTimeoutMs,Tz),this.backoff=Y.backoffMs??Rz,this.getWindow=Y.getWindow,this.getSustain=Y.getSustain,this.setIntervalImpl=Y.setIntervalImpl??globalThis.setInterval,this.clearIntervalImpl=Y.clearIntervalImpl??globalThis.clearInterval}track(Y){let{sessionKey:J,bodyText:X}=Y;this.pruneStale();let Q=Buffer.byteLength(X,"utf8");if(Q>this.maxBytes)return this.log?.debug("cachekeep track skipped (body exceeds maxBytes)",{sessionKey:J,bodyBytes:Q,maxBytes:this.maxBytes}),{tracked:!1,reason:"body-exceeds-max-bytes"};let G=this.getWindow?.();if(G&&!G1(G,new Date(this.now())))return this.log?.debug("cachekeep track skipped (outside window)",{sessionKey:J,startHour:G.startHour,endHour:G.endHour}),{tracked:!1,reason:"outside-window"};this.drop(J);while(this.targets.size>=this.maxTargets||this.totalBytes+Q>this.maxBytes&&this.targets.size>0){let V=this.leastRecentlyTouched();if(V===void 0)break;this.log?.debug("cachekeep evicted least recently used target",{sessionKey:V}),this.drop(V)}let $=Y.isSubagent===!0,W=Y.accountId||void 0,K=this.adapter.profile?.({bodyText:X,isSubagent:$,accountId:W,meta:Y.meta}),U=B6(K?.ttlMs,this.ttlMs),H=this.now();return this.targets.set(J,{bodyText:X,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?B6(K.maxIdleMs,this.idleDefault($)):void 0,cacheExpiresAt:H+U,lastRealRequestAt:H,failures:0,warmCount:0}),this.totalBytes+=Q,this.log?.debug("cachekeep captured target",{sessionKey:J,accountId:W}),this.start(),{tracked:!0}}remove(Y){if(this.drop(Y))this.log?.debug("cachekeep removed target",{sessionKey:Y})}start(){if(this.disposed=!1,this.timer)return;if(this.startedAt=this.now(),this.timer=this.setIntervalImpl(()=>{this.tick().catch((Y)=>{this.log?.warn("cachekeep tick failed",{error:J8(Y)})})},this.tickIntervalMs),typeof this.timer==="object"&&"unref"in this.timer)this.timer.unref();this.log?.debug("cachekeep started",{ttlMs:this.ttlMs,leadMs:this.leadMs,maxIdleWarmMs:this.maxIdleWarmMs})}stop(){if(this.disposed=!0,this.abortController.abort(),this.abortController=new AbortController,this.timer)this.clearIntervalImpl(this.timer),this.timer=null;this.startedAt=null,this.targets.clear(),this.totalBytes=0,this.log?.debug("cachekeep stopped")}status(){let Y=this.getWindow?.();return{running:this.timer!==null,tracked:this.targets.size,totalBytes:this.totalBytes,generatedAt:this.now(),startedAt:this.startedAt,ttlMs:this.ttlMs,leadMs:this.leadMs,maxIdleWarmMs:this.maxIdleWarmMs,maxSubagentIdleMs:this.maxSubagentIdleMs,sustain:this.getSustain?.()===!0,...Y?{window:Y}:{},targets:[...this.targets].map(([J,X])=>({sessionKey:J,accountId:X.accountId,isSubagent:X.isSubagent,cacheExpiresAt:X.cacheExpiresAt,lastRealRequestAt:X.lastRealRequestAt,...X.lastWarmedAt!==void 0?{lastWarmedAt:X.lastWarmedAt}:{},...X.backoffUntil!==void 0?{backoffUntil:X.backoffUntil}:{},failures:X.failures,warmCount:X.warmCount,ttlMs:X.ttlMs,bodyBytes:X.bodyBytes}))}}tick(){if(this.tickPromise)return this.tickPromise;let Y=this.runTick().finally(()=>{if(this.tickPromise===Y)this.tickPromise=null});return this.tickPromise=Y,Y}async runTick(){this.pruneStale();let Y=this.getWindow?.();if(Y&&!G1(Y,new Date(this.now())))return;let J=this.now(),X=J+this.leadMs;for(let[Q,G]of[...this.targets]){if(this.disposed)return;if(this.targets.get(Q)!==G)continue;if(G.backoffUntil!==void 0&&J<G.backoffUntil)continue;if(G.cacheExpiresAt>X)continue;await this.warm(Q,G)}}retireIfExpired(Y,J){if(this.now()<J.cacheExpiresAt)return!1;return this.log?.debug("cachekeep retired target (cache lifetime ended)",{sessionKey:Y,accountId:J.accountId,cacheExpiresAt:J.cacheExpiresAt,failures:J.failures}),this.drop(Y),!0}isCurrent(Y,J){return!this.disposed&&this.targets.get(Y)===J}view(Y,J){return{sessionKey:Y,accountId:J.accountId,bodyText:J.bodyText,isSubagent:J.isSubagent,meta:J.meta,warmCount:J.warmCount,ttlMs:J.ttlMs}}fail(Y,J,X,Q={}){if(!this.isCurrent(Y,J))return;J.failures+=1;let G=typeof this.backoff==="function"?this.backoff({sessionKey:Y,failures:J.failures}):this.backoff;J.backoffUntil=this.now()+(Number.isFinite(G)&&G>0?G:0),this.log?.warn(X,{sessionKey:Y,accountId:J.accountId,failures:J.failures,backoffUntil:J.backoffUntil,...Q})}async warm(Y,J){if(this.retireIfExpired(Y,J))return;let X=this.view(Y,J);if(this.adapter.activeAccount){let V;try{V=await this.adapter.activeAccount(Y,X)}catch(D){this.fail(Y,J,"cachekeep skip (active account unknown)",{error:J8(D)});return}if(!this.isCurrent(Y,J))return;if(V!==void 0&&V!==J.accountId){this.log?.debug("cachekeep dropped target (session changed account)",{sessionKey:Y,accountId:J.accountId,activeAccountId:V}),this.drop(Y);return}}let Q;try{Q=await this.adapter.buildBody(X)}catch(V){this.fail(Y,J,"cachekeep skip (replay body unbuildable)",{error:J8(V)});return}if(!this.isCurrent(Y,J))return;if(this.retireIfExpired(Y,J))return;let G=iX([AbortSignal.timeout(this.warmTimeoutMs),this.abortController.signal]),$=G.signal,W,K="";try{W=await this.adapter.send({target:X,body:Q,signal:$}),K=await W.text().catch(()=>"")}catch(V){this.fail(Y,J,"cachekeep failed",{error:J8(V)});return}finally{G.dispose()}if(!this.isCurrent(Y,J))return;if(!W.ok){this.fail(Y,J,"cachekeep failed",{status:W.status,responseBody:K.slice(0,600)});return}let U;try{U=this.adapter.readUsage?.({target:X,response:W,text:K})}catch{}let H=this.now();if(J.cacheExpiresAt=H+J.ttlMs,J.lastWarmedAt=H,J.backoffUntil=void 0,J.failures=0,J.warmCount+=1,this.log?.debug("cachekeep fired",{sessionKey:Y,accountId:J.accountId,warmCount:J.warmCount,...U}),J.maxWarms!==void 0&&J.warmCount>=J.maxWarms)this.log?.debug("cachekeep retired target (warm cap reached)",{sessionKey:Y,warmCount:J.warmCount}),this.drop(Y)}idleDefault(Y){return Y?this.maxSubagentIdleMs:this.maxIdleWarmMs}pruneStale(){let Y=this.now(),J=this.getSustain?.()===!0;for(let[X,Q]of[...this.targets]){if(this.retireIfExpired(X,Q))continue;if(J&&!Q.isSubagent)continue;let G=Q.maxIdleMs??this.idleDefault(Q.isSubagent);if(Q.lastRealRequestAt>=Y-G)continue;this.log?.debug("cachekeep pruned idle target",{sessionKey:X,accountId:Q.accountId,lastRealRequestAt:Q.lastRealRequestAt,maxIdleMs:G}),this.drop(X)}}leastRecentlyTouched(){let Y,J=Number.POSITIVE_INFINITY;for(let[X,Q]of this.targets){let G=Math.max(Q.lastRealRequestAt,Q.lastWarmedAt??0);if(G<J)Y=X,J=G}return Y}drop(Y){let J=this.targets.get(Y);if(!J)return!1;return this.totalBytes-=J.bodyBytes,this.targets.delete(Y),!0}}function EY(Y){if(typeof Y!=="string")return!1;try{let J=JSON.parse(Y);return n(J)&&n(J.client_metadata)&&J.client_metadata.ws_request_header_x_openai_internal_codex_responses_lite==="true"}catch{return!1}}function MY(Y){if(typeof Y!=="string")return Y;try{let J=JSON.parse(Y);if(!n(J)||!n(J.client_metadata))return Y;if(!(("x-codex-turn-metadata"in J.client_metadata)||("x-codex-ws-stream-request-start-ms"in J.client_metadata)||("ws_request_header_x_openai_internal_codex_responses_lite"in J.client_metadata)))return Y;let X={...J.client_metadata};return delete X["x-codex-turn-metadata"],delete X["x-codex-ws-stream-request-start-ms"],delete X.ws_request_header_x_openai_internal_codex_responses_lite,JSON.stringify({...J,client_metadata:X})}catch{return Y}}function X8(Y){if(Y?.method?.toUpperCase()!=="POST")return Y;let J=new Headers(Y.headers);if(J.set("accept","text/event-stream"),J.set("content-type","application/json"),EY(Y.body))J.set("x-openai-internal-codex-responses-lite","true");return{...Y,headers:J,body:MY(Y.body)}}var Nj=Object.freeze({maxTargets:32,maxBytes:8388608});function oX(Y){if(!Y.enabled||typeof Y.body!=="string")return;let J=Y.headers.has("x-parent-session-id");if(J&&!Y.includeSubagents)return;let X=Y.headers.get("session-id")??Y.headers.get("x-opencode-session")??Y.headers.get("x-session-affinity")??void 0;if(!X)return;let Q={};for(let G of["session-id","x-session-affinity","x-parent-session-id","user-agent","version","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-client-request-id","thread-id","x-openai-internal-codex-responses-lite"]){let $=Y.headers.get(G);if($)Q[G]=$}return{sessionKey:X,bodyText:Y.body,replayHeaders:Q,isSubagent:J}}function rX(Y){return qY(Y?.cachekeep)}var AY=1800000,Cz=2,wz=2*AY+900000,Sz=/^gpt-(\d+)(?:\.(\d+))?(?:-|$)/;function Iz(Y){try{let X=JSON.parse(Y).model;if(typeof X!=="string")return!1;let Q=Sz.exec(X);if(!Q)return!1;let G=Number(Q[1]),$=Q[2]===void 0?0:Number(Q[2]);return G>5||G===5&&$>=6}catch{return!1}}function bz(Y){if(!Iz(Y.bodyText))return;if(!Y.isSubagent)return{ttlMs:AY};return{ttlMs:AY,maxWarms:Cz,maxIdleMs:wz}}function kz(Y){let X=JSON.parse(Y);return X.store=!1,delete X.max_output_tokens,delete X.max_tokens,delete X.max_completion_tokens,JSON.stringify(X)}function TY(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function sX(Y){if(!Y||typeof Y!=="object")return TY();let J=Y,X=Number(J.input_tokens)||Number(J.prompt_tokens)||0,Q=Number(J.output_tokens)||Number(J.completion_tokens)||0,G=J.input_tokens_details??J.prompt_tokens_details,$=Number(G?.cached_tokens)||Number(J.cached_tokens)||0,W=X>0?$/X:null;return{input_tokens:X,output_tokens:Q,cached_tokens:$,hit_rate:W}}function xz(Y){try{let J=JSON.parse(Y);return sX(J.usage)}catch{return TY()}}function vz(Y){let J,X=[],Q,G=()=>{if(!X.length)return;let $=X.join(`
|
|
10
|
+
`).trim();X=[];let W=J;if(J=void 0,!$||$==="[DONE]")return;try{let K=JSON.parse($),U=K.type??W;if(U!=="response.completed"&&U!=="response.done")return;let H=K.response;Q=sX(H?.usage??K.usage)}catch{}};for(let $ of Y.split(/\r?\n/)){if($===""){G();continue}if($.startsWith("event:")){J=$.slice(6).trim();continue}if($.startsWith("data:"))X.push($.slice(5).trim())}return G(),Q??TY()}function aX(Y,J,X=Date.now()){if(!J)return;if(Y.route==="sticky-balanced"){let G=Y.stickyAssignments?.[L6(J)];if(!G)return;if(G.lastSeenAt<X-nX)return;return G.accountId}let Q=Y.activeRouting?.[J];if(!Q||Q.route!==Y.route)return;return Q.activeId}function hz(Y){let J=Y6(Y);return J?J6(J):void 0}function yz(Y){let{logger:J,activeAccount:X}=Y;return{buildBody:(Q)=>kz(Q.bodyText),async send({target:Q,body:G,signal:$}){let W=async(L,B,O)=>{if($.throwIfAborted(),Y.verifyCredential)await Y.verifyCredential({target:Q,mode:B?"vault":"local",identity:(B?B.accountIdentity:O)??hz(L)});let q={...Q.meta.replayHeaders,authorization:`Bearer ${L}`,"content-type":"application/json"};if(Q.meta.chatgptAccountId)q["ChatGPT-Account-Id"]=Q.meta.chatgptAccountId;else delete q["ChatGPT-Account-Id"];let _;try{let M=JSON.parse(G);_={warmBodyKeys:Object.keys(M),stream:M.stream,max_output_tokens:M.max_output_tokens,store:M.store,has_stream_options:"stream_options"in M,has_max_tokens:"max_tokens"in M,model:M.model}}catch{}J?.debug("cachekeep warm request",{..._,headerKeys:Object.keys(q),hasChatGptAccountId:"ChatGPT-Account-Id"in q});try{let M=await Y.fetchImpl(Q.meta.url??Y.codexResponsesUrl,X8({method:"POST",headers:q,body:G,signal:$}));return await J9(M,L,"event-stream")}catch(M){throw y6(M,L)}};if(Q.accountId&&Y.vault?.owns(Q.accountId)){let L=await Y.vault.send(Q.accountId,W,{site:"cachekeep",signal:$});if(!L)throw Error(`vault refused warm for ${Q.accountId}`);return L}if(Y.vault&&await Y.vault.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");let K,U,H,V=Y.resolveLocal?await Y.resolveLocal(Q):Q.accountId&&Q.accountId!=="main"?await Y.refreshFallback(Q.accountId):await Y.getMainToken();if(typeof V==="string")K=V;else K=V.token,U=V.identity,H=V.onAuthFailure;if(Y.vault&&await Y.vault.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");let D=await W(K,void 0,U);if(D.status===401)await H?.(D.status);return D},readUsage({response:Q,text:G}){let $=Q.headers.get("content-type")??"",W=$.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(G.slice(0,200));J?.debug("cachekeep warm response",{status:Q.status,contentType:$,bodyLen:G.length,isSse:W});let K=W?vz(G):xz(G),U=Y9(Q.headers);return{...K,quota_primary_pct:U.primary?.usedPercent??null,quota_secondary_pct:U.secondary?.usedPercent??null}},profile:bz,...X?{activeAccount:(Q,G)=>X(G.meta.routingSessionId)}:{}}}function tX(Y){let{fetchImpl:J,getMainToken:X,refreshFallback:Q,resolveLocal:G,vault:$,codexResponsesUrl:W,activeAccount:K,verifyCredential:U,logger:H,...V}=Y,D=Y.resolveLocal!==void 0?{resolveLocal:Y.resolveLocal}:{getMainToken:Y.getMainToken,refreshFallback:Y.refreshFallback};return new $1({...V,logger:H,adapter:yz({fetchImpl:J,...D,vault:$,codexResponsesUrl:W,activeAccount:K,verifyCredential:U,logger:H})})}function eX(Y){let J,X=0,Q=0,G=!1,$;return{read(){let W=Y.path(),K=Y.stat(W);if(K&&J?.path===W&&J.mtimeMs===K.mtimeMs&&J.size===K.size)return J.value;if(!K)J=void 0;let U=++X;return Y.read(W).catch(Y.fallback).then((H)=>{if(U>Q){if(Q=U,$=H,G=!0,K)J={...K,path:W,value:H};return Y.onRead(H),H}return G?$:H})},invalidate(){J=void 0}}}import{readFileSync as gz}from"node:fs";var fz=60000,mz=15000,wY=2000,SY=1e4;async function W1(Y,J){let X,Q=await Promise.race([Y.then(()=>!0,()=>!0),new Promise((G)=>{X=setTimeout(()=>G(!1),J),X.unref?.()})]);return clearTimeout(X),Q}function cz(Y){if(!X9(Y.quota))return;let J=Q8(Y.quota);return J.limits.some((X)=>X.kind==="reading")?J.checkedAt:void 0}function uz(Y){if(!Y)return;let J=Y6(Y);return J?J6(J):void 0}function Y3(Y){try{let J=JSON.parse(gz(Y,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return;return r9(J).migratedAt}catch{return}}function pz(Y){if(Y.type!=="oauth")return!1;return Y.candidate||Y.torn===!0&&Y.enabled}class IY{listeners=new Set;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??V0("pool"),this.vaultRosterSettled=Y.vaultFirstRoster===void 0;let J=()=>{this.vaultRosterSettled=!0};Y.vaultFirstRoster?.then(J,J)}async awaitVaultRoster(Y){let J=this.deps.vaultFirstRoster;if(this.vaultRosterSettled||!J)return;await W1(J,Y)}peek(){return{active:this.snapshot.active,rows:this.snapshot.rows}}subscribe(Y){return this.listeners.add(Y),()=>{this.listeners.delete(Y)}}async sidebarView(){let Y=this.deps.paths();if(Y3(Y.configPath)===void 0)return{active:!1,rows:[]};let J=await this.storeFor(Y).read();return J.status==="ready"?{active:!0,rows:this.withLocalState(J.rows)}:{active:!1,rows:[]}}changed(){for(let Y of this.listeners)Y()}async current(){if(this.disposed)return this.peek();let Y=this.filesKey();if(this.snapshot.key===Y)return this.peek();let J=this.startRead(Y),X=await $8(J,this.deps.readBudgetMs??G8,()=>this.snapshot);return{active:X.active,rows:X.rows}}async load(){if(this.disposed)return this.peek();if(await this.deps.vaultAuthority?.(),this.disposed)return this.peek();let Y=await this.startRead(this.filesKey());return{active:Y.active,rows:Y.rows}}filesKey(){let Y=this.deps.paths();return`${Y.configPath}|${CY(Y.configPath)}|${CY(Y.statePath)}`}storeFor(Y){if(this.store?.configPath===Y.configPath)return this.store.store;let J=F9({provider:"openai",configPath:Y.configPath,statePath:Y.statePath,quota:j9,now:this.now,pull:(X)=>this.coalescedPull(X),onPullFailure:(X,Q)=>{this.pollOutcomes.set(X,{id:X,ok:!1,error:Q.message}),this.log.warn("pool quota poll failed",{rowId:X,kind:Q.kind,error:Q.message})},logger:this.log,...this.deps.store,onStep:async(X,Q)=>{if(await this.deps.store?.onStep?.(X,Q),Q.operation!=="updateSettings"&&X.startsWith("before-")&&this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")throw Error("Local account writes are disabled while connected to the vault.")}});return this.store={configPath:Y.configPath,store:J},J}startRead(Y){if(this.disposed)return Promise.resolve(this.snapshot);if(this.inflightRead?.key===Y)return this.inflightRead.promise;let J=this.now(),X=this.read(Y,J),Q={key:Y,promise:X};this.inflightRead=Q;let G=()=>{if(this.inflightRead===Q)this.inflightRead=void 0};return X.then(G,G),X}async read(Y,J){let X=this.deps.paths(),Q={active:!1,rows:[],key:Y,readAt:J};try{if(Y3(X.configPath)!==void 0){let W=await this.storeFor(X).read();if(W.status==="ready")Q={active:!0,rows:W.rows,key:Y,readAt:J};else this.log.warn("migrated install has no readable account pool",{status:W.status,...W.status==="error"?{reason:W.reason}:{}})}}catch($){return this.log.warn("account pool read failed",{error:$ instanceof Error?$.message:String($)}),this.snapshot}if(this.disposed)return this.snapshot;let G=this.snapshot.active;if(J>=this.snapshot.readAt)this.snapshot={...Q,rows:this.withLocalState(Q.rows)},this.changed();if(this.snapshot.active){if(!G)this.log.info("account pool serves requests");this.pollUnseenRows()}return this.snapshot}withLocalState(Y){let J=this.now();return Y.map((X)=>{let Q=X,G=this.rotated.get(X.id),$=G?.credential;if(G&&G.credentialEpoch!==X.credentialEpoch)this.rotated.delete(X.id);else if($?.type==="oauth"&&X.credential?.type==="oauth"){let W=X.credential.lastRefreshedAt??0,K=$.lastRefreshedAt??0;if(W>=K)this.rotated.delete(X.id);else Q={...Q,credential:$}}return G3(Q,this.pending,J)})}replaceRow(Y,J){this.snapshot={...this.snapshot,rows:this.snapshot.rows.map((X)=>X.id===Y?J(X):X)},this.changed()}vaultOwned(Y){if(this.deps.vaultMode?.())return!0;return Y.identity!==void 0&&(this.deps.vaultIdentities?.().has(Y.identity)??!1)}pollUnseenRows(){if(this.disposed)return;let Y=this.deps.vaultFirstRoster;if(!this.vaultRosterSettled&&Y&&!this.deps.vaultMode?.()){if(this.pollsAwaitVault)return;this.pollsAwaitVault=!0,W1(Y,this.deps.vaultFirstRosterBackgroundWaitMs??SY).then((J)=>{if(this.pollsAwaitVault=!1,J)this.pollUnseenRows();else this.log.info("first quota polls skipped: the vault has not read its accounts yet")});return}for(let J of this.snapshot.rows){if(!pz(J)||this.vaultOwned(J))continue;let X=`${J.id}\x00${J.credentialEpoch??0}\x00${J.identity??""}`;if(this.polled.has(X))continue;this.polled.add(X),this.requestReading(J.id,!0)}}requestReading(Y,J=!1){if(this.disposed||this.deps.vaultMode?.())return;let X=this.now(),Q=this.lastPull.get(Y);if(!J&&Q!==void 0&&X-Q<(this.deps.pullRetryMs??mz))return this.storeFor(this.deps.paths()).pullsSettled();this.lastPull.set(Y,X);let G=this.storeFor(this.deps.paths());return G.requestReading(Y),G.pullsSettled()}coalescedPull(Y){let J=JSON.stringify([this.deps.paths().configPath,Y.id,Y.credentialEpoch,Y.identity]),X=this.quotaPulls.get(J);if(X)return X;let Q=this.pull(Y).finally(()=>this.quotaPulls.delete(J));return this.quotaPulls.set(J,Q),Q}async pull(Y){if(this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")throw Error("local accounts are not polled while this host is connected to the vault");let J;try{if(J=await this.deps.pullQuota(Y),!J)throw Error("the quota poll returned no reading")}catch(Q){throw this.pollOutcomes.set(Y.id,{id:Y.id,ok:!1,error:Q instanceof Error?Q.message:String(Q)}),Q}this.pollOutcomes.set(Y.id,{id:Y.id,ok:!0});let X=this.snapshot.rows.find((Q)=>Q.id===Y.id);if(X&&X.credentialEpoch===Y.credentialEpoch&&X.identity===Y.identity)this.applyObservation(X,J);return J}applyObservation(Y,J){Q3(this.pending,Y,J),this.replaceRow(Y.id,(X)=>({...X,quota:X3(X.quota,J),needsFirstReading:!1}))}recordSnapshot(Y,J,X,Q){if(!this.snapshot.active||this.disposed||this.deps.vaultMode?.())return;let G=this.snapshot.rows.find((L)=>L.id===Y);if(G?.type!=="oauth")return;let $=uz(X);if(!($&&G.identity?$===G.identity:w9(G)?.access===X))return;let K=M9(J,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}:{}},H=this.storeFor(this.deps.paths()),D=(this.writes.get(G.id)??Promise.resolve()).then(async()=>{if(this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")return;return H.recordQuota(G.id,U,K)}).catch((L)=>{this.log.warn("pool quota not recorded",{rowId:G.id,error:L instanceof Error?L.message:String(L)})});this.writes.set(G.id,D),D.finally(()=>{if(this.writes.get(G.id)===D)this.writes.delete(G.id)})}markRateLimited(Y,J){let X=this.snapshot.rows.find(($)=>$.id===Y);if(!X)return;let Q=RY(X),G=this.marks.get(Q);if(G!==void 0&&G>J)return;this.marks.set(Q,J)}rateLimitMarks(Y){let J=new Map;for(let X of Y){let Q=this.marks.get(RY(X));if(Q!==void 0)J.set(X.id,Q)}return J}async prepareTokens(Y,J,X={}){if(this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")return;if(!this.deps.vaultMode?.())await this.awaitVaultRoster(this.deps.vaultFirstRosterWaitMs??wY);let Q=this.now(),G=J3(J),$=[];for(let W of Y){if(!W.candidate||this.vaultOwned(W))continue;let K=w9(W);if(!K)continue;let U=(K.expires??0)-Q;if(!(!K.access||!K.expires||U<=G)||this.refreshBackedOff(W,J,Q))continue;let V=this.refresh(W.id);if(X.waitForAll||!K.access||!K.expires||U<=fz)$.push(V)}await Promise.all($)}refreshBackedOff(Y,J,X=this.now()){let Q=w9(Y);if(!Q)return!1;let G=z1(Q.refresh),$=this.backoff.get(Y.id);if($&&$.tokenHash===G&&$.nextRetryAt>X)return!0;let W=J?.accounts.find((K)=>K.id===Y.id);return Boolean(W?.type==="oauth"&&W.corrupt!==!0&&E6(W.lastRefreshError,Q.refresh,X))}usableToken(Y,J=this.now()){let X=this.snapshot.rows.find((G)=>G.id===Y.id);if(!X?.enabled||!X.candidate||X.type!=="oauth"||X.identity!==Y.identity||X.credentialEpoch!==Y.credentialEpoch||this.vaultOwned(X))return;let Q=w9(X);if(!Q?.access.trim())return;if(typeof Q.expires!=="number"||Q.expires<=J)return;return Q.access}refresh(Y){let J=this.refreshing.get(Y);if(J)return J;let X=this.runRefresh(Y).finally(()=>{if(this.refreshing.get(Y)===X)this.refreshing.delete(Y)});return this.refreshing.set(Y,X),X}async runRefresh(Y){if(this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")return;let J=this.deps.paths(),X=this.snapshot.rows.find((W)=>W.id===Y),Q=X?w9(X)?.refresh:void 0,G,$=(W,K)=>{return G=K.credentialEpoch,this.deps.refreshProvider(W,K)};try{let W=await z3({paths:J,store:this.storeFor(J),now:this.now,...this.deps.legacyLocks?{legacyLocks:this.deps.legacyLocks}:{}},Y,$);if(W.status==="rotated"){this.backoff.delete(Y),this.rotated.set(Y,{credential:W.credential,credentialEpoch:G}),this.replaceRow(Y,(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,J,X){if(this.log.warn("pool row refresh failed",{rowId:Y,error:X instanceof Error?X.message:String(X)}),!J)return;this.backoff.set(Y,$3(J,X,this.now(),this.backoff.get(Y)))}refreshBackoffFor(Y){return W3(Y,this.backoff,this.now(),(J,X)=>this.usableToken(J,X))}async active(){return(await this.current()).active}poolStore(){return this.storeFor(this.deps.paths())}async refreshDueTokens(Y){let J=await this.current();if(!J.active||this.disposed)return;await this.prepareTokens(J.rows,Y,{waitForAll:!0})}async pollRows(Y,J={}){let X=await this.load();if(!X.active||this.disposed)return[];let Q=this.now(),G=X.rows.filter(($)=>{if(!$.candidate||$.type!=="oauth"||this.vaultOwned($))return!1;if(J.ids&&!J.ids.includes($.id))return!1;if(J.skipReadWithinMs===void 0)return!0;let W=cz($);return W===void 0||Q-W>=J.skipReadWithinMs});if(G.length===0)return[];await this.prepareTokens(G,Y,{waitForAll:!0});for(let $ of G)this.pollOutcomes.delete($.id),this.requestReading($.id,!0);return await this.poolStore().pullsSettled(),G.map(($)=>this.pollOutcomes.get($.id)??{id:$.id,ok:!1,error:"the quota poll did not run"})}async accessFor(Y,J){let X=await this.current();if(!X.active)return;let Q=X.rows.find((W)=>W.id===Y);if(!Q?.candidate)return;await this.prepareTokens([Q],J);let G=this.snapshot.rows.find((W)=>W.id===Y)??Q;if(!G.candidate)return;let $=this.usableToken(G);return $?{row:G,token:$}:void 0}async rowAccess(Y,J){let X=await this.current();if(!X.active)return;let Q=X.rows.find(($)=>$.id===Y);if(!Q)return{};let G=await this.accessFor(Y,J);return{row:{id:Q.id,type:Q.type,enabled:Q.enabled,...Q.label!==void 0?{label:Q.label}:{},...Q.identity!==void 0?{identity:Q.identity}:{}},...G?{token:G.token}:{}}}dispose(){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 K3=60000,bY=900000,lz={set(Y,J){let X=setTimeout(Y,J);return X.unref?.(),X},clear(Y){clearTimeout(Y)}};function dz(Y){return Y.status==="completed"||Y.status==="already-migrated"||Y.status==="nothing-to-import"||Y.status==="ambiguous"}function U3(Y){return Y.status==="deferred"||Y.status==="retry"||Y.status==="error"}function H3(Y){let J=Y.log??V0("pool-migration"),X=Y.timers??lz,Q=Y.random??Math.random,G=Y.migrate??W8,$=Y.adopt??z8,W=Y.fence??(()=>q9({currentVersion:Y.version})),K=!1,U=new AbortController,H=!1,V=!1,D=0,L,B=Promise.resolve(),O,q,_,M=!1;function S(){if(M)return;M=!0,J.warn(P9,{reason:"placeholder-without-main"})}let x=()=>({paths:Y.paths(),slot:Y.slot,log:J,...Y.runDeps,signal:U.signal});function j(p){let t=B.then(p).catch((L0)=>{J.warn("account pool background run failed",{error:L0 instanceof Error?L0.message:String(L0)})});return B=t,t}function C(p){if(H)return;if(L!==void 0)X.clear(L);L=X.set(()=>{L=void 0,j(Z0)},p)}function h(){let p=Math.min(K3*2**Math.min(D,10),bY);return D++,A(p)}let A=(p)=>Math.round(p*(1-0.2*Q()));async function g(){if(!await Y.paused?.())return!1;return C(A(K3)),!0}async function r(){if(H||await g()||H)return;let p;try{p=await G({...x(),fence:W})}catch(t){J.warn("account pool migration failed; it will be tried again",{error:t instanceof Error?t.message:String(t)}),C(h());return}if(p.status==="refused"){if(p.reason==="placeholder-without-main")S();C(A(bY));return}if(dz(p)){if(V=!0,D=0,p.status==="completed")J.info("account pool migration completed",{rowId:p.rowId});await i();return}if(U3(p)){if(p.status!=="deferred")J.warn("account pool migration will be tried again",{outcome:p});C(h())}}async function i(){if(H||await g()||H)return;let p;try{let t=await W();if(H)return;if(!t.open){let L0=JSON.stringify(t.blockers);if(L0!==_)_=L0,J.info("host login adoption waits for older plugin versions",{blockers:t.blockers});C(h());return}p=await $(x())}catch(t){J.warn("adopting the host login into the account pool failed",{error:t instanceof Error?t.message:String(t)}),C(h());return}if(p.status==="not-migrated")return;if(p.status==="slot-read-only")return;if(V=!0,p.status==="completed")J.info("host login adopted into the account pool",{rowId:p.rowId,operation:p.operation});if(U3(p)){J.warn("host login adoption will be tried again",{outcome:p}),C(h());return}if(D=0,V)C(A(bY))}async function Z0(){if(H)return;if(V)await i();else await r()}function B0(){if(O)return O;let p=j(async()=>{if(O=void 0,!H)if(V)await i();else await r()});return O=p,p}return{start(){if(K||H)return;K=!0,j(r)},requestAdoption:B0,noticePlaceholderWithoutMain:S,noticeRealSlot(p){if(!V||H||p===q)return;q=p,B0()},dispose(){if(H=!0,U.abort(),L!==void 0)X.clear(L);L=void 0},idle:async()=>{for(;;){let p=B;if(await p,p===B)return}},migrated:()=>V}}var Q9={"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.",...j3};function yY(Y){return Y!==void 0&&N3.includes(Y)}function iz(Y,J,X,Q=new Set){return Y.filter((G)=>{if(!G.enabled||!G.candidate||G.type!=="oauth")return!1;if(G.credential?.type!=="oauth")return!1;if(m0(G.credential))return!1;if(G.identity!==void 0&&Q.has(G.identity))return!1;if(G.id===T6)return!0;if(L3(J,{accountId:G.identity}))return!1;return hY(A6(G.quota),J,X)})}function xY(Y){let J=Y.vault;return[...(J?[]:iz(Y.source.peek().rows,Y.storage,Y.now())).map((Q)=>({id:Q.id,kind:"oauth",...Q.identity!==void 0?{identity:Q.identity}:{},...Q.quota!==void 0?{quota:Q.quota}:{},row:Q})),...(J?.routes()??[]).filter((Q)=>hY(A6(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 nz(Y){return Y.flatMap((J)=>J.row?[J.row]:[])}function K8(Y,J){let X=Y.now(),Q=U1(J,Y.storage,X),G=J.map((U)=>({id:U.id,kind:U.kind,...X9(U.quota)?{quota:U.quota}:{}})),$=nz(J),W=new Set(J.filter((U)=>!U.row).map((U)=>U.id)),K=Y.source.rateLimitMarks($);for(let[U,H]of Y.vault?.rateLimitMarks?.()??[])if(W.has(U)&&H>X)K.set(U,H);return{rows:G,now:X,rateLimitMarks:K,refreshBackoff:Y.source.refreshBackoffFor($),killswitch:Q,requestPull:(U)=>W.has(U)?Y.vault?.requestReading(U):Y.source.requestReading(U)}}function Z3(Y){let J=Y.find((X)=>X.id===T6);return{main:J?A6(J.quota):void 0,fallbacks:Y.filter((X)=>X.id!==T6).map((X)=>{let Q=A6(X.quota);return{accountId:X.id,...Q?{quota:Q}:{}}})}}async function vY(Y,J){if(J.row){let X=Y.source.usableToken(J.row);if(!X)return;let Q=await Y.send(J,X);return Y.recordQuota(Q,J,X),Q}return Y.vault?.send(J.id,async(X,Q)=>{let G=await Y.send(J,X,Q);return Y.recordQuota(G,J,X,Q),G})}async function M3(Y){if(Y.vault)await Y.vault.awaitRoster();else await Y.source.current(),await Y.source.prepareTokens(Y.source.peek().rows,Y.storage);let J=xY(Y),X=Y.replayable===!1&&J.some((G)=>G.id===T6)?J.filter((G)=>G.id===T6):J,Q=D3(K8(Y,X));if(Q)await Q,J=xY(Y);if(Y.mode==="sticky-balanced"&&Y.sessionId&&Y.replayable&&Y.body!==void 0){let G=await rz(Y,J,Y.sessionId,Y.body);if(G)return G}return oz(Y,J)}async function oz(Y,J){let X=O3(Y.mode),Q=P3({...K8(Y,J),placement:X,mainId:Y.vault?Y.mode==="sticky-balanced"?null:F3(Y.vault.routes()):void 0,replayable:Y.replayable});if(Q.kind==="block")return Y.log.debug("pool admission blocked the request",{pid:process.pid,reason:Q.block.reason}),{response:Y.blocked(Q.block,Z3(J),Y.vault?J.length===0?Y.vault.noRouteCause():void 0:J.length===0?"no-accounts":"unusable"),servedId:T6};if(Q.lastPath)Y.log.debug("pool admission: every account is exhausted; probing anyway",{pid:process.pid,order:Q.order});let G=new Map(J.map((V)=>[V.id,V])),$=B3(Y.storage),W=[],K=new Set,U,H=!1;for(;;){let V=V3(Q.order.filter((B)=>!K.has(B)),W,$),D=V===void 0?void 0:G.get(V);if(!D)break;let L;try{L=await vY(Y,D)}catch(B){if(Y.isAbort(B)||!U||Y.mode==="fallback-first")throw B;return Y.log.debug("pool fallback attempt threw; stopping",{pid:process.pid,accountId:D.id}),U}if(!L){if(!D.row)H=!0;K.add(D.id);continue}U?.response.body?.cancel().catch(()=>{}),U={response:L,servedId:D.id},W.push({id:D.id,status:L.status})}if(U)return U;return{response:Y.blocked({reason:"no-credential"},Z3(J),H?"vault-refused":Y.vault?"vault-empty":"unusable"),servedId:T6}}async function rz(Y,J,X,Q){let G=Buffer.byteLength(Q,"utf8"),$=new Map(J.map((M)=>[M.id,M])),W=K8(Y,J),K=kY(W),U={requestBytes:G,reservePercent:(M)=>K1(Y.storage,M===T6?void 0:M),resetCredits:Y.resetCredits,onEmptyWeightedSet:()=>{Y.log.debug("sticky routing: no fresh weighted candidates; using configured order")}},H=(M,S)=>(x,j)=>{let C=new Set(x);return Y.placePin({sessionId:X,requestBytes:G,now:M.now,validPinnedAccountIds:M.rows.map((h)=>h.id).filter((h)=>!S.excluded.has(h)),excludeAccountIds:x,quotaCheckedAtByAccount:Object.fromEntries(M.rows.map((h)=>[h.id,S.projections.get(h.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(J.map((h)=>[h.id,h.identity])),select:(h)=>_3(M,U,C,h),persist:j})},V=H(W,K),D=V([],!0);if(!D)return;let L=D.accountId,B=(M)=>{let S=V([L],!0);if(!S)return!1;return Y.log.debug("sticky routing: migrated session pin",{pid:process.pid,fromAccountId:L,toAccountId:S.accountId,reason:M}),L=S.accountId,!0},O=q3(W,U,L);if(O.kind==="none")return;if(O.kind==="move"){if(!B(O.reason)&&O.reason==="killswitch")return}else if(O.kind==="detour"){let M=V([L],!1);if(!M)return;Y.log.debug("sticky routing: pinned account awaits a quota reading",{pid:process.pid,pinnedAccountId:L,servedAccountId:M.accountId}),L=M.accountId}let q=$.get(L);if(!q)return;let _=await vY(Y,q);if(!_)return;if(_.status===401||_.status===403||_.status===429){let M=xY(Y);W=K8(Y,M),K=kY(W),V=H(W,K);let S=E3(W,K,L,_.status);if(S.action==="migrate"){let x=L;if(B(S.reason)&&L!==x){let j=M.find((h)=>h.id===L),C=j?await vY(Y,j):void 0;if(j&&C){let h=_;_=C,h.body?.cancel().catch(()=>{}),q=j}else L=x}}}return{response:_,servedId:q.id}}var sz=new Map([["needs_reauth","needs sign-in"],["retired","turned off in vault"],["corrupt","unavailable"]]);function H1(Y){return typeof Y==="number"&&Number.isFinite(Y)}function az(Y){if(!X9(Y))return;let J=Y.budget;if(J?.kind!=="reading")return;let{limit:X,used:Q,remaining:G,usedPercent:$,remainingPercent:W}=J;if(!H1(X)||!H1(Q)||!H1(G)||!H1($)||!H1(W))return;return{limit:X,used:Q,remaining:G,usedPercent:$,remainingPercent:W,reached:J.reached,...J.resetsAt!==void 0?{resetsAt:J.resetsAt}:{},...J.unit!==void 0?{unit:J.unit}:{}}}function gY(Y,J){let X=A6(Y),Q=az(Y);if(!X&&!Q)return null;let G=X9(Y)?Q8(Y).checkedAt:void 0;return{...G!==void 0?{checkedAt:G}:{},...X?.primary?{primary:X.primary}:{},...X?.secondary?{secondary:X.secondary}:{},...Q?{spendControl:Q}:{},...J!==void 0?{resetCreditsAvailable:J}:{}}}function A3(Y,J,X,Q){let G=U1(Y.map(($)=>({id:$.routeId,quota:$.quota})),{version:1,accounts:[],...X},Q);return{main:{quota:null,killed:!1},fallbacks:[],vaultAccounts:Y.map(($)=>{let W=$.quota?.counters?.resetCredits?.value;return{id:$.routeId,credentialId:$.credentialId,label:$.email||$.label||$.routeId,...$.accountIdentity!==void 0?{accountId:$.accountIdentity}:{},quota:gY($.quota,W),killed:G.get($.routeId)===!1,enabled:$.enabled,routable:J.has($.routeId),...$.state!=="active"||$.stale||$.unclaimed||$.enabled&&!J.has($.routeId)?{vaultState:sz.get($.state)??"unavailable"}:{},...W!==void 0?{resetCredits:W}:{}}}),route:X?.routing?.mode??"main-first",lastUpdated:Q}}function T3(Y,J,X,Q=()=>{return}){let G=U1(Y,{version:1,accounts:[],...J},X),$=Y.find((K)=>K.id===Z6),W=$?Q($.id):void 0;return{main:{quota:$?gY($.quota,W):null,...$?.identity!==void 0?{mainAccountId:$.identity}:{},killed:G.get(Z6)===!1,...W!==void 0?{resetCredits:W}:{}},fallbacks:Y.filter((K)=>K.id!==Z6&&K.enabled).map((K)=>{let U=Q(K.id);return{id:K.id,label:K.label,...K.identity!==void 0?{accountId:K.identity}:{},quota:gY(K.quota,U),killed:G.get(K.id)===!1,enabled:!0,...U!==void 0?{resetCredits:U}:{}}}),route:J?.routing?.mode??"main-first",lastUpdated:X,accountPool:!0}}import{randomUUID as tz}from"node:crypto";import{chmod as ez,mkdir as YK,rename as JK,rm as C3,writeFile as XK}from"node:fs/promises";import{homedir as QK}from"node:os";import{join as fY}from"node:path";function w3(){let Y=process.env.XDG_STATE_HOME||fY(QK(),".local","state");return fY(Y,"cortexkit","openai-auth","processes")}function S3(Y=process.pid,J=w3()){return fY(J,`${Y}.json`)}var U8=0,R3;async function GK(Y,J){await YK(Y,{recursive:!0,mode:448}),await ez(Y,448);let X=S3(J.pid,Y),Q=`${X}.${tz()}.tmp`;try{await XK(Q,`${JSON.stringify(J)}
|
|
11
|
+
`,{mode:384}),await JK(Q,X)}catch(G){throw await C3(Q,{force:!0}).catch(()=>{}),G}return X}async function I3(Y){let J=Y.pid??process.pid,X=Y.dir??w3();R3??=(Y.now??Date.now)(),U8++;let Q;try{Q=await GK(X,{pid:J,version:Y.version,startedAt:R3})}catch($){Y.logger.warn("process heartbeat not written",{dir:X,error:$ instanceof Error?$.message:String($)})}let G=!1;return{path:Q,async release(){if(G)return;if(G=!0,U8=Math.max(0,U8-1),U8>0)return;await C3(S3(J,X),{force:!0}).catch(($)=>{Y.logger.warn("process heartbeat not removed",{dir:X,error:$ instanceof Error?$.message:String($)})})}}}import{resolve as H8}from"node:path";import{resolveClaustrumConnectionPath as $K}from"@cortexkit/claustrum-client";var WK=60000,zK=240000,k3=Symbol.for("@cortexkit/openai-auth/opencode-vaults"),x3=globalThis,Z1=x3[k3]??new Map;x3[k3]=Z1;function v3(Y,J){let X=Boolean(Y.connectScoped||Y.connectEnrollment),Q=H8(Y.stateDir),G=H8((Y.connectionFile??$K)()),$=JSON.stringify([Y.host,Q,G,H8(J.configPath),H8(J.statePath)]),W={reservedRouteIds:Y.reservedRouteIds??(()=>[])},K=X?void 0:Z1.get($);if(!K){let V=new Set;if(K={vault:new b3({...Y,stateDir:Q,connectionFile:()=>G,...!X?{projectRoot:Q}:{},reservedRouteIds:()=>new Set([...V].flatMap((L)=>[...L.reservedRouteIds()]))}),holders:V,firstRoster:Promise.withResolvers(),started:!1},!X)Z1.set($,K)}K.holders.add(W);let U=K,H=!1;return{vault:U.vault,firstRoster:U.firstRoster.promise,start(){if(H||U.started)return;U.started=!0;let V=async()=>{if(U.holders.size&&await U.vault.authority()!=="local")await U.vault.pollStale(zK)};U.vault.start(),U.vault.firstRoster().finally(()=>{U.firstRoster.resolve(),V()}),U.quotaPoll=setInterval(V,WK),U.quotaPoll.unref?.()},release(){if(H)return;if(H=!0,U.holders.delete(W),U.holders.size!==0)return;if(U.quotaPoll)clearInterval(U.quotaPoll);if(U.vault.close(),U.firstRoster.resolve(),!X&&Z1.get($)===U)Z1.delete($)}}}var m3=900000,KK=0.016666666666666666,h3=0.000001;function cY(Y,J){for(let X of[Y?.primary?.checkedAt,Y?.checkedAt,J])if(typeof X==="number"&&Number.isFinite(X))return X;return}function uY(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let J=cY(Y.quota,Y.quotaCheckedAt);if(J===void 0||!Number.isFinite(J)||Y.now-J>m3)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let X=mY(Y.quota).sort((G,$)=>{let W=G.windowMs,K=$.windowMs,U=typeof W==="number"&&Number.isFinite(W),H=typeof K==="number"&&Number.isFinite(K);if(U!==H)return U?-1:1;if(U&&H)return K-W;return 0});for(let{key:G,window:$}of X)if(Number.isFinite($.remainingPercent)&&$.remainingPercent<=0)return{action:"migrate",reason:"exhausted",windowKey:G,...typeof $.resetsAt==="string"?{resetsAt:$.resetsAt}:{}};let Q=f3(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 y3(Y,J,X){let Q=Math.max(0,Y.remainingPercent-J);if(Q<=0)return 0;if(!Y.resetsAt)return Q;let G=Date.parse(Y.resetsAt);if(!Number.isFinite(G)||G<=X)return Q;let $=Math.max((G-X)/3600000,KK);return Q/$}function g3(Y,J){if(Y<J)return-1;if(Y>J)return 1;return 0}function UK(Y,J){if(!Y.quota)return;let X=cY(Y.quota,Y.quotaCheckedAt);if(X===void 0||J-X>m3)return;let Q=mY(Y.quota).map(({key:W,window:K})=>{return y3(K,Y.reservePercent[W]??0,J)}),G=Y.quota.spendControl;if(G&&Number.isFinite(G.remainingPercent))Q.push(y3(G,0,J));let $=Q.length>0?Math.min(...Q):0;return $>0?{candidate:Y,quotaCheckedAt:X,weight:$}:void 0}function c3(Y){let J=Y.candidates.filter((G)=>G.killswitchPasses!==!1);if(Y.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if(J.length===0)return;let X=J.map((G)=>UK(G,Y.now)).filter((G)=>G!==void 0);if(X.length>0){X.sort(($,W)=>{let K=((Y.pendingBytes.get($.candidate.accountId)??0)+Y.requestBytes)/Math.max($.weight,h3),U=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,h3);return K-U||$.candidate.configuredOrder-W.candidate.configuredOrder||g3($.candidate.accountId,W.candidate.accountId)});let G=X[0];if(G)return{accountId:G.candidate.accountId,quotaCheckedAt:G.quotaCheckedAt,source:"weighted"}}Y.onEmptyWeightedSet?.();let Q=[...J].sort((G,$)=>{let W=(G.resetCreditsApplicable??0)>0?1:0;return(($.resetCreditsApplicable??0)>0?1:0)-W||G.configuredOrder-$.configuredOrder||g3(G.accountId,$.accountId)})[0];if(!Q)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Q.accountId,quotaCheckedAt:cY(Q.quota,Q.quotaCheckedAt),source:"mode-fallback"}}import{readFile as HK}from"node:fs/promises";import{homedir as ZK}from"node:os";import{join as u3}from"node:path";var VK="https://models.dev/api.json",BK="OPENCODE_OPENAI_AUTH_MODELS_CACHE",LK="OPENCODE_MODELS_PATH",NK="OPENCODE_DISABLE_MODELS_FETCH",jK=1e4,FK=300000;function g6(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function p3(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function pY(Y){let{input:J,output:X}=Y;if(typeof J!=="number"||!Number.isFinite(J)||J<0)return null;if(typeof X!=="number"||!Number.isFinite(X)||X<0)return null;let Q=p3(Y.cache_read),G=p3(Y.cache_write);if(Q===null||G===null)return null;return{input:J,output:X,cache:{read:Q,write:G}}}function OK(Y){let J=g6(Y);if(!J)return null;let X=pY(J);if(!X)return null;let Q=X;if(Array.isArray(J.tiers)){let W=[];for(let K of J.tiers){let U=g6(K);if(!U)continue;let H=g6(U.tier),V=H?.size;if(H?.type!=="context")continue;if(typeof V!=="number"||!Number.isFinite(V)||V<=0)continue;let D=pY(U);if(!D)continue;W.push({...D,tier:{type:"context",size:V}})}if(W.length>0)Q.tiers=W}let G=g6(J.context_over_200k),$=G?pY(G):null;if($)Q.experimentalOver200K=$;return Q}function l3(Y){let J=g6(Y),X=g6(J?.openai),Q=g6(X?.models);if(!Q)return null;let G={};for(let[$,W]of Object.entries(Q)){let K=g6(W),U=OK(K?.cost);if(U)G[$]=U}return Object.keys(G).length>0?G:null}function DK(){let Y=process.env[BK]?.trim();if(Y)return Y;let J=process.env[LK]?.trim();if(J)return J;let X=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||u3(ZK(),".cache");return u3(X,"opencode","models.json")}function PK(){let Y=process.env[NK]?.toLowerCase();return Y==="true"||Y==="1"}async function _K(){try{let Y=l3(JSON.parse(await HK(DK(),"utf8")));if(Y)return Y}catch{}if(PK())return null;try{let Y=await fetch(VK,{signal:AbortSignal.timeout(jK)});if(!Y.ok)return null;return l3(await Y.json())}catch{return null}}var S9;function d3(){let Y=Date.now();if(S9&&S9.expiresAt>Y)return S9.promise;let J={expiresAt:Y+FK,promise:_K()};return S9=J,J.promise.then((X)=>{if(X===null&&S9===J)S9=void 0}),J.promise}function I9(Y){return typeof Y==="object"&&Y!==null}function qK(Y){if(Array.isArray(Y))return Y;if(I9(Y)&&Array.isArray(Y.data))return Y.data;return[]}function EK(Y){if(!I9(Y)||!I9(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function i3(Y){if(!I9(Y)||!I9(Y.info))return null;let J=Y.info,X=I9(J.model)?J.model:void 0,Q=typeof J.agent==="string"?J.agent:void 0,G=typeof X?.providerID==="string"?X.providerID:typeof J.providerID==="string"?J.providerID:void 0,$=typeof X?.modelID==="string"?X.modelID:typeof J.modelID==="string"?J.modelID:void 0,W=typeof X?.variant==="string"?X.variant:typeof J.variant==="string"?J.variant:void 0;if(!Q&&(!G||!$)&&!W)return null;let K={};if(Q)K.agent=Q;if(G&&$)K.model={providerID:G,modelID:$};if(W)K.variant=W;return K}function n3(Y,J){return{agent:Y.agent??J.agent,model:Y.model??J.model,variant:Y.variant??J.variant}}function o3(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function r3(Y,J){if(!Y||!J)return null;let X=Y;if(typeof X.session?.messages!=="function")return null;let Q=[];try{Q=qK(await Promise.resolve(X.session.messages({path:{id:J},query:{limit:100}})))}catch{return null}if(Q.length===0)return null;let G={};for(let $=Q.length-1;$>=0;$--){if(EK(Q[$])!=="assistant")continue;let W=i3(Q[$]);if(!W)continue;if(G=n3(G,W),o3(G))return G}for(let $=Q.length-1;$>=0;$--){let W=i3(Q[$]);if(!W)continue;if(G=n3(G,W),o3(G))return G}if(!G.agent&&!G.model&&!G.variant)return null;return G}var MK=V0("rpc"),a3="__openaiAuthRpcServers";function t3(Y){return s3({...Y,isManagedDir:p1,log:MK,drain:(J,X)=>Y.drain(J,X),apply:async(J)=>await Y.apply(J)})}var b6={};iY(b6,{withoutInternalHeaders:()=>nG,sanitizeHttpFallbackBody:()=>MY,orderCodexBody:()=>a6,hasWebSocketResponsesLiteMetadata:()=>EY,createWebSocketFetch:()=>UB,applyTurnId:()=>cG,advanceTurn:()=>c4,TITLE_HEADER:()=>m4,QUOTA_ACCOUNT_HEADER:()=>v8,OpenAIWebSocketPool:()=>b6,CODEX_BODY_KEY_ORDER:()=>UY});import{createHash as GB}from"node:crypto";var AK=Symbol.for("vercel.ai.error"),R6=class Y extends Error{constructor({name:J,message:X,cause:Q}){super(X);this[AK]=!0,this.name=J,this.cause=Q}static isInstance(J){return Y.hasMarker(J,"vercel.ai.error")}static hasMarker(J,X){let Q=Symbol.for(X);return J!=null&&typeof J==="object"&&Q in J&&typeof J[Q]==="boolean"&&J[Q]===!0}},TK="AI_DecisionUnsupportedQuestionTypeError",VF=`vercel.ai.error.${TK}`;var e3="AI_APICallError",Y2=`vercel.ai.error.${e3}`,RK=Symbol.for(Y2),G9=class extends R6{constructor({message:Y,url:J,requestBodyValues:X,statusCode:Q,responseHeaders:G,responseBody:$,cause:W,isRetryable:K=Q!=null&&(Q===408||Q===409||Q===429||Q>=500),data:U}){super({name:e3,message:Y,cause:W});this[RK]=!0,this.url=J,this.requestBodyValues=X,this.statusCode=Q,this.responseHeaders=G,this.responseBody=$,this.isRetryable=K,this.data=U}static isInstance(Y){return R6.hasMarker(Y,Y2)}},CK="AI_EmptyResponseBodyError",BF=`vercel.ai.error.${CK}`;var wK="AI_DecisionRefusalError",LF=`vercel.ai.error.${wK}`;var J2="AI_InvalidArgumentError",X2=`vercel.ai.error.${J2}`,SK=Symbol.for(X2),lY=class extends R6{constructor({message:Y,cause:J,argument:X}){super({name:J2,message:Y,cause:J});this[SK]=!0,this.argument=X}static isInstance(Y){return R6.hasMarker(Y,X2)}},IK="AI_InvalidPromptError",NF=`vercel.ai.error.${IK}`;var bK="AI_InvalidResponseDataError",jF=`vercel.ai.error.${bK}`;var kK="AI_JSONParseError",FF=`vercel.ai.error.${kK}`;var xK="AI_LoadAPIKeyError",OF=`vercel.ai.error.${xK}`;var vK="AI_LoadSettingError",DF=`vercel.ai.error.${vK}`;var hK="AI_NoContentGeneratedError",PF=`vercel.ai.error.${hK}`;var yK="AI_NoSuchModelError",_F=`vercel.ai.error.${yK}`;var gK="AI_NoSuchProviderReferenceError",qF=`vercel.ai.error.${gK}`;var fK="AI_TooManyEmbeddingValuesForCallError",EF=`vercel.ai.error.${fK}`;var mK="AI_TypeValidationError",MF=`vercel.ai.error.${mK}`;var cK="AI_UnsupportedFunctionalityError",AF=`vercel.ai.error.${cK}`;var wF=Object.freeze({status:"aborted"});function P(Y,J,X){function Q(K,U){var H;Object.defineProperty(K,"_zod",{value:K._zod??{},enumerable:!1}),(H=K._zod).traits??(H.traits=new Set),K._zod.traits.add(Y),J(K,U);for(let V in W.prototype)if(!(V in K))Object.defineProperty(K,V,{value:W.prototype[V].bind(K)});K._zod.constr=W,K._zod.def=U}let G=X?.Parent??Object;class $ extends G{}Object.defineProperty($,"name",{value:Y});function W(K){var U;let H=X?.Parent?new $:this;Q(H,K),(U=H._zod).deferred??(U.deferred=[]);for(let V of H._zod.deferred)V();return H}return Object.defineProperty(W,"init",{value:Q}),Object.defineProperty(W,Symbol.hasInstance,{value:(K)=>{if(X?.Parent&&K instanceof X.Parent)return!0;return K?._zod?.traits?.has(Y)}}),Object.defineProperty(W,"name",{value:Y}),W}var SF=Symbol("zod_brand");class C6 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class V1 extends Error{constructor(Y){super(`Encountered unidirectional transform during encode: ${Y}`);this.name="ZodEncodeError"}}var Z8={};function N6(Y){if(Y)Object.assign(Z8,Y);return Z8}var Q0={};iY(Q0,{unwrapMessage:()=>B1,uint8ArrayToHex:()=>BU,uint8ArrayToBase64url:()=>ZU,uint8ArrayToBase64:()=>H2,stringifyPrimitive:()=>W2,shallowClone:()=>G2,safeExtend:()=>$U,required:()=>KU,randomString:()=>tK,propertyKeyTypes:()=>rY,promiseAllObject:()=>aK,primitiveTypes:()=>$2,prefixIssues:()=>S6,pick:()=>XU,partial:()=>zU,optionalKeys:()=>sY,omit:()=>QU,objectClone:()=>oK,numKeys:()=>eK,nullish:()=>N1,normalizeParams:()=>o,mergeDefs:()=>m6,merge:()=>WU,jsonStringifyReplacer:()=>b9,joinValues:()=>nK,issue:()=>x9,isPlainObject:()=>c6,isObject:()=>$9,hexToUint8Array:()=>VU,getSizableOrigin:()=>K2,getParsedType:()=>YU,getLengthableOrigin:()=>F1,getEnumValues:()=>L1,getElementAtPath:()=>sK,floatSafeRemainder:()=>nY,finalizeIssue:()=>G6,extend:()=>GU,escapeRegex:()=>w6,esc:()=>V8,defineLazy:()=>G0,createTransparentProxy:()=>JU,cloneDef:()=>rK,clone:()=>Q6,cleanRegex:()=>j1,cleanEnum:()=>UU,captureStackTrace:()=>B8,cached:()=>k9,base64urlToUint8Array:()=>HU,base64ToUint8Array:()=>U2,assignProp:()=>f6,assertNotEqual:()=>pK,assertNever:()=>dK,assertIs:()=>lK,assertEqual:()=>uK,assert:()=>iK,allowsEval:()=>oY,aborted:()=>u6,NUMBER_FORMAT_RANGES:()=>aY,Class:()=>Z2,BIGINT_FORMAT_RANGES:()=>z2});function uK(Y){return Y}function pK(Y){return Y}function lK(Y){}function dK(Y){throw Error()}function iK(Y){}function L1(Y){let J=Object.values(Y).filter((Q)=>typeof Q==="number");return Object.entries(Y).filter(([Q,G])=>J.indexOf(+Q)===-1).map(([Q,G])=>G)}function nK(Y,J="|"){return Y.map((X)=>W2(X)).join(J)}function b9(Y,J){if(typeof J==="bigint")return J.toString();return J}function k9(Y){return{get value(){{let X=Y();return Object.defineProperty(this,"value",{value:X}),X}throw Error("cached value already set")}}}function N1(Y){return Y===null||Y===void 0}function j1(Y){let J=Y.startsWith("^")?1:0,X=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(J,X)}function nY(Y,J){let X=(Y.toString().split(".")[1]||"").length,Q=J.toString(),G=(Q.split(".")[1]||"").length;if(G===0&&/\d?e-\d?/.test(Q)){let U=Q.match(/\d?e-(\d?)/);if(U?.[1])G=Number.parseInt(U[1])}let $=X>G?X:G,W=Number.parseInt(Y.toFixed($).replace(".","")),K=Number.parseInt(J.toFixed($).replace(".",""));return W%K/10**$}var Q2=Symbol("evaluating");function G0(Y,J,X){let Q=void 0;Object.defineProperty(Y,J,{get(){if(Q===Q2)return;if(Q===void 0)Q=Q2,Q=X();return Q},set(G){Object.defineProperty(Y,J,{value:G})},configurable:!0})}function oK(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function f6(Y,J,X){Object.defineProperty(Y,J,{value:X,writable:!0,enumerable:!0,configurable:!0})}function m6(...Y){let J={};for(let X of Y){let Q=Object.getOwnPropertyDescriptors(X);Object.assign(J,Q)}return Object.defineProperties({},J)}function rK(Y){return m6(Y._zod.def)}function sK(Y,J){if(!J)return Y;return J.reduce((X,Q)=>X?.[Q],Y)}function aK(Y){let J=Object.keys(Y),X=J.map((Q)=>Y[Q]);return Promise.all(X).then((Q)=>{let G={};for(let $=0;$<J.length;$++)G[J[$]]=Q[$];return G})}function tK(Y=10){let X="";for(let Q=0;Q<Y;Q++)X+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return X}function V8(Y){return JSON.stringify(Y)}var B8="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function $9(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var oY=k9(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function c6(Y){if($9(Y)===!1)return!1;let J=Y.constructor;if(J===void 0)return!0;let X=J.prototype;if($9(X)===!1)return!1;if(Object.prototype.hasOwnProperty.call(X,"isPrototypeOf")===!1)return!1;return!0}function G2(Y){if(c6(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function eK(Y){let J=0;for(let X in Y)if(Object.prototype.hasOwnProperty.call(Y,X))J++;return J}var YU=(Y)=>{let J=typeof Y;switch(J){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(Y)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(Y))return"array";if(Y===null)return"null";if(Y.then&&typeof Y.then==="function"&&Y.catch&&typeof Y.catch==="function")return"promise";if(typeof Map<"u"&&Y instanceof Map)return"map";if(typeof Set<"u"&&Y instanceof Set)return"set";if(typeof Date<"u"&&Y instanceof Date)return"date";if(typeof File<"u"&&Y instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${J}`)}},rY=new Set(["string","number","symbol"]),$2=new Set(["string","number","bigint","boolean","symbol","undefined"]);function w6(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Q6(Y,J,X){let Q=new Y._zod.constr(J??Y._zod.def);if(!J||X?.parent)Q._zod.parent=Y;return Q}function o(Y){let J=Y;if(!J)return{};if(typeof J==="string")return{error:()=>J};if(J?.message!==void 0){if(J?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");J.error=J.message}if(delete J.message,typeof J.error==="string")return{...J,error:()=>J.error};return J}function JU(Y){let J;return new Proxy({},{get(X,Q,G){return J??(J=Y()),Reflect.get(J,Q,G)},set(X,Q,G,$){return J??(J=Y()),Reflect.set(J,Q,G,$)},has(X,Q){return J??(J=Y()),Reflect.has(J,Q)},deleteProperty(X,Q){return J??(J=Y()),Reflect.deleteProperty(J,Q)},ownKeys(X){return J??(J=Y()),Reflect.ownKeys(J)},getOwnPropertyDescriptor(X,Q){return J??(J=Y()),Reflect.getOwnPropertyDescriptor(J,Q)},defineProperty(X,Q,G){return J??(J=Y()),Reflect.defineProperty(J,Q,G)}})}function W2(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function sY(Y){return Object.keys(Y).filter((J)=>{return Y[J]._zod.optin==="optional"&&Y[J]._zod.optout==="optional"})}var aY={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]},z2={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function XU(Y,J){let X=Y._zod.def,Q=m6(Y._zod.def,{get shape(){let G={};for(let $ in J){if(!($ in X.shape))throw Error(`Unrecognized key: "${$}"`);if(!J[$])continue;G[$]=X.shape[$]}return f6(this,"shape",G),G},checks:[]});return Q6(Y,Q)}function QU(Y,J){let X=Y._zod.def,Q=m6(Y._zod.def,{get shape(){let G={...Y._zod.def.shape};for(let $ in J){if(!($ in X.shape))throw Error(`Unrecognized key: "${$}"`);if(!J[$])continue;delete G[$]}return f6(this,"shape",G),G},checks:[]});return Q6(Y,Q)}function GU(Y,J){if(!c6(J))throw Error("Invalid input to extend: expected a plain object");let X=Y._zod.def.checks;if(X&&X.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let G=m6(Y._zod.def,{get shape(){let $={...Y._zod.def.shape,...J};return f6(this,"shape",$),$},checks:[]});return Q6(Y,G)}function $U(Y,J){if(!c6(J))throw Error("Invalid input to safeExtend: expected a plain object");let X={...Y._zod.def,get shape(){let Q={...Y._zod.def.shape,...J};return f6(this,"shape",Q),Q},checks:Y._zod.def.checks};return Q6(Y,X)}function WU(Y,J){let X=m6(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape,...J._zod.def.shape};return f6(this,"shape",Q),Q},get catchall(){return J._zod.def.catchall},checks:[]});return Q6(Y,X)}function zU(Y,J,X){let Q=m6(J._zod.def,{get shape(){let G=J._zod.def.shape,$={...G};if(X)for(let W in X){if(!(W in G))throw Error(`Unrecognized key: "${W}"`);if(!X[W])continue;$[W]=Y?new Y({type:"optional",innerType:G[W]}):G[W]}else for(let W in G)$[W]=Y?new Y({type:"optional",innerType:G[W]}):G[W];return f6(this,"shape",$),$},checks:[]});return Q6(J,Q)}function KU(Y,J,X){let Q=m6(J._zod.def,{get shape(){let G=J._zod.def.shape,$={...G};if(X)for(let W in X){if(!(W in $))throw Error(`Unrecognized key: "${W}"`);if(!X[W])continue;$[W]=new Y({type:"nonoptional",innerType:G[W]})}else for(let W in G)$[W]=new Y({type:"nonoptional",innerType:G[W]});return f6(this,"shape",$),$},checks:[]});return Q6(J,Q)}function u6(Y,J=0){if(Y.aborted===!0)return!0;for(let X=J;X<Y.issues.length;X++)if(Y.issues[X]?.continue!==!0)return!0;return!1}function S6(Y,J){return J.map((X)=>{var Q;return(Q=X).path??(Q.path=[]),X.path.unshift(Y),X})}function B1(Y){return typeof Y==="string"?Y:Y?.message}function G6(Y,J,X){let Q={...Y,path:Y.path??[]};if(!Y.message){let G=B1(Y.inst?._zod.def?.error?.(Y))??B1(J?.error?.(Y))??B1(X.customError?.(Y))??B1(X.localeError?.(Y))??"Invalid input";Q.message=G}if(delete Q.inst,delete Q.continue,!J?.reportInput)delete Q.input;return Q}function K2(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function F1(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function x9(...Y){let[J,X,Q]=Y;if(typeof J==="string")return{message:J,code:"custom",input:X,inst:Q};return{...J}}function UU(Y){return Object.entries(Y).filter(([J,X])=>{return Number.isNaN(Number.parseInt(J,10))}).map((J)=>J[1])}function U2(Y){let J=atob(Y),X=new Uint8Array(J.length);for(let Q=0;Q<J.length;Q++)X[Q]=J.charCodeAt(Q);return X}function H2(Y){let J="";for(let X=0;X<Y.length;X++)J+=String.fromCharCode(Y[X]);return btoa(J)}function HU(Y){let J=Y.replace(/-/g,"+").replace(/_/g,"/"),X="=".repeat((4-J.length%4)%4);return U2(J+X)}function ZU(Y){return H2(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function VU(Y){let J=Y.replace(/^0x/,"");if(J.length%2!==0)throw Error("Invalid hex string length");let X=new Uint8Array(J.length/2);for(let Q=0;Q<J.length;Q+=2)X[Q/2]=Number.parseInt(J.slice(Q,Q+2),16);return X}function BU(Y){return Array.from(Y).map((J)=>J.toString(16).padStart(2,"0")).join("")}class Z2{constructor(...Y){}}var V2=(Y,J)=>{Y.name="$ZodError",Object.defineProperty(Y,"_zod",{value:Y._zod,enumerable:!1}),Object.defineProperty(Y,"issues",{value:J,enumerable:!1}),Y.message=JSON.stringify(J,b9,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},L8=P("$ZodError",V2),tY=P("$ZodError",V2,{Parent:Error});function B2(Y,J=(X)=>X.message){let X={},Q=[];for(let G of Y.issues)if(G.path.length>0)X[G.path[0]]=X[G.path[0]]||[],X[G.path[0]].push(J(G));else Q.push(J(G));return{formErrors:Q,fieldErrors:X}}function L2(Y,J){let X=J||function($){return $.message},Q={_errors:[]},G=($)=>{for(let W of $.issues)if(W.code==="invalid_union"&&W.errors.length)W.errors.map((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(X(W));else{let K=Q,U=0;while(U<W.path.length){let H=W.path[U];if(U!==W.path.length-1)K[H]=K[H]||{_errors:[]};else K[H]=K[H]||{_errors:[]},K[H]._errors.push(X(W));K=K[H],U++}}};return G(Y),Q}var N8=(Y)=>(J,X,Q,G)=>{let $=Q?Object.assign(Q,{async:!1}):{async:!1},W=J._zod.run({value:X,issues:[]},$);if(W instanceof Promise)throw new C6;if(W.issues.length){let K=new(G?.Err??Y)(W.issues.map((U)=>G6(U,$,N6())));throw B8(K,G?.callee),K}return W.value};var j8=(Y)=>async(J,X,Q,G)=>{let $=Q?Object.assign(Q,{async:!0}):{async:!0},W=J._zod.run({value:X,issues:[]},$);if(W instanceof Promise)W=await W;if(W.issues.length){let K=new(G?.Err??Y)(W.issues.map((U)=>G6(U,$,N6())));throw B8(K,G?.callee),K}return W.value};var O1=(Y)=>(J,X,Q)=>{let G=Q?{...Q,async:!1}:{async:!1},$=J._zod.run({value:X,issues:[]},G);if($ instanceof Promise)throw new C6;return $.issues.length?{success:!1,error:new(Y??L8)($.issues.map((W)=>G6(W,G,N6())))}:{success:!0,data:$.value}},N2=O1(tY),D1=(Y)=>async(J,X,Q)=>{let G=Q?Object.assign(Q,{async:!0}):{async:!0},$=J._zod.run({value:X,issues:[]},G);if($ instanceof Promise)$=await $;return $.issues.length?{success:!1,error:new Y($.issues.map((W)=>G6(W,G,N6())))}:{success:!0,data:$.value}},j2=D1(tY),F2=(Y)=>(J,X,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return N8(Y)(J,X,G)};var O2=(Y)=>(J,X,Q)=>{return N8(Y)(J,X,Q)};var D2=(Y)=>async(J,X,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return j8(Y)(J,X,G)};var P2=(Y)=>async(J,X,Q)=>{return j8(Y)(J,X,Q)};var _2=(Y)=>(J,X,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return O1(Y)(J,X,G)};var q2=(Y)=>(J,X,Q)=>{return O1(Y)(J,X,Q)};var E2=(Y)=>async(J,X,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return D1(Y)(J,X,G)};var M2=(Y)=>async(J,X,Q)=>{return D1(Y)(J,X,Q)};var A2=/^[cC][^\s-]{8,}$/,T2=/^[0-9a-z]+$/,R2=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,C2=/^[0-9a-vA-V]{20}$/,w2=/^[A-Za-z0-9]{27}$/,S2=/^[a-zA-Z0-9_-]{21}$/,I2=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var b2=/^([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})$/,eY=(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 k2=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function x2(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var v2=/^(?:(?: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])$/,h2=/^(([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}|:))$/,y2=/^((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])$/,g2=/^(([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])$/,f2=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Y4=/^[A-Za-z0-9_-]*$/,m2=/^(?=.{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 c2=/^\+(?:[0-9]){6,14}[0-9]$/,u2="(?:(?:\\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])))",p2=new RegExp(`^${u2}$`);function l2(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 d2(Y){return new RegExp(`^${l2(Y)}$`)}function i2(Y){let J=l2({precision:Y.precision}),X=["Z"];if(Y.local)X.push("");if(Y.offset)X.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let Q=`${J}(?:${X.join("|")})`;return new RegExp(`^${u2}T(?:${Q})$`)}var n2=(Y)=>{let J=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${J}$`)};var o2=/^-?\d+$/,r2=/^-?\d+(?:\.\d+)?/,s2=/^(?:true|false)$/i,a2=/^null$/i;var t2=/^[^A-Z]*$/,e2=/^[^a-z]*$/;var k0=P("$ZodCheck",(Y,J)=>{var X;Y._zod??(Y._zod={}),Y._zod.def=J,(X=Y._zod).onattach??(X.onattach=[])}),Y7={number:"number",bigint:"bigint",object:"date"},J4=P("$ZodCheckLessThan",(Y,J)=>{k0.init(Y,J);let X=Y7[typeof J.value];Y._zod.onattach.push((Q)=>{let G=Q._zod.bag,$=(J.inclusive?G.maximum:G.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(J.value<$)if(J.inclusive)G.maximum=J.value;else G.exclusiveMaximum=J.value}),Y._zod.check=(Q)=>{if(J.inclusive?Q.value<=J.value:Q.value<J.value)return;Q.issues.push({origin:X,code:"too_big",maximum:J.value,input:Q.value,inclusive:J.inclusive,inst:Y,continue:!J.abort})}}),X4=P("$ZodCheckGreaterThan",(Y,J)=>{k0.init(Y,J);let X=Y7[typeof J.value];Y._zod.onattach.push((Q)=>{let G=Q._zod.bag,$=(J.inclusive?G.minimum:G.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(J.value>$)if(J.inclusive)G.minimum=J.value;else G.exclusiveMinimum=J.value}),Y._zod.check=(Q)=>{if(J.inclusive?Q.value>=J.value:Q.value>J.value)return;Q.issues.push({origin:X,code:"too_small",minimum:J.value,input:Q.value,inclusive:J.inclusive,inst:Y,continue:!J.abort})}}),J7=P("$ZodCheckMultipleOf",(Y,J)=>{k0.init(Y,J),Y._zod.onattach.push((X)=>{var Q;(Q=X._zod.bag).multipleOf??(Q.multipleOf=J.value)}),Y._zod.check=(X)=>{if(typeof X.value!==typeof J.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof X.value==="bigint"?X.value%J.value===BigInt(0):nY(X.value,J.value)===0)return;X.issues.push({origin:typeof X.value,code:"not_multiple_of",divisor:J.value,input:X.value,inst:Y,continue:!J.abort})}}),X7=P("$ZodCheckNumberFormat",(Y,J)=>{k0.init(Y,J),J.format=J.format||"float64";let X=J.format?.includes("int"),Q=X?"int":"number",[G,$]=aY[J.format];Y._zod.onattach.push((W)=>{let K=W._zod.bag;if(K.format=J.format,K.minimum=G,K.maximum=$,X)K.pattern=o2}),Y._zod.check=(W)=>{let K=W.value;if(X){if(!Number.isInteger(K)){W.issues.push({expected:Q,format:J.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:!J.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:!J.abort});return}}if(K<G)W.issues.push({origin:"number",input:K,code:"too_small",minimum:G,inclusive:!0,inst:Y,continue:!J.abort});if(K>$)W.issues.push({origin:"number",input:K,code:"too_big",maximum:$,inst:Y})}});var Q7=P("$ZodCheckMaxLength",(Y,J)=>{var X;k0.init(Y,J),(X=Y._zod.def).when??(X.when=(Q)=>{let G=Q.value;return!N1(G)&&G.length!==void 0}),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(J.maximum<G)Q._zod.bag.maximum=J.maximum}),Y._zod.check=(Q)=>{let G=Q.value;if(G.length<=J.maximum)return;let W=F1(G);Q.issues.push({origin:W,code:"too_big",maximum:J.maximum,inclusive:!0,input:G,inst:Y,continue:!J.abort})}}),G7=P("$ZodCheckMinLength",(Y,J)=>{var X;k0.init(Y,J),(X=Y._zod.def).when??(X.when=(Q)=>{let G=Q.value;return!N1(G)&&G.length!==void 0}),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(J.minimum>G)Q._zod.bag.minimum=J.minimum}),Y._zod.check=(Q)=>{let G=Q.value;if(G.length>=J.minimum)return;let W=F1(G);Q.issues.push({origin:W,code:"too_small",minimum:J.minimum,inclusive:!0,input:G,inst:Y,continue:!J.abort})}}),$7=P("$ZodCheckLengthEquals",(Y,J)=>{var X;k0.init(Y,J),(X=Y._zod.def).when??(X.when=(Q)=>{let G=Q.value;return!N1(G)&&G.length!==void 0}),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.minimum=J.length,G.maximum=J.length,G.length=J.length}),Y._zod.check=(Q)=>{let G=Q.value,$=G.length;if($===J.length)return;let W=F1(G),K=$>J.length;Q.issues.push({origin:W,...K?{code:"too_big",maximum:J.length}:{code:"too_small",minimum:J.length},inclusive:!0,exact:!0,input:Q.value,inst:Y,continue:!J.abort})}}),P1=P("$ZodCheckStringFormat",(Y,J)=>{var X,Q;if(k0.init(Y,J),Y._zod.onattach.push((G)=>{let $=G._zod.bag;if($.format=J.format,J.pattern)$.patterns??($.patterns=new Set),$.patterns.add(J.pattern)}),J.pattern)(X=Y._zod).check??(X.check=(G)=>{if(J.pattern.lastIndex=0,J.pattern.test(G.value))return;G.issues.push({origin:"string",code:"invalid_format",format:J.format,input:G.value,...J.pattern?{pattern:J.pattern.toString()}:{},inst:Y,continue:!J.abort})});else(Q=Y._zod).check??(Q.check=()=>{})}),W7=P("$ZodCheckRegex",(Y,J)=>{P1.init(Y,J),Y._zod.check=(X)=>{if(J.pattern.lastIndex=0,J.pattern.test(X.value))return;X.issues.push({origin:"string",code:"invalid_format",format:"regex",input:X.value,pattern:J.pattern.toString(),inst:Y,continue:!J.abort})}}),z7=P("$ZodCheckLowerCase",(Y,J)=>{J.pattern??(J.pattern=t2),P1.init(Y,J)}),K7=P("$ZodCheckUpperCase",(Y,J)=>{J.pattern??(J.pattern=e2),P1.init(Y,J)}),U7=P("$ZodCheckIncludes",(Y,J)=>{k0.init(Y,J);let X=w6(J.includes),Q=new RegExp(typeof J.position==="number"?`^.{${J.position}}${X}`:X);J.pattern=Q,Y._zod.onattach.push((G)=>{let $=G._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(Q)}),Y._zod.check=(G)=>{if(G.value.includes(J.includes,J.position))return;G.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:J.includes,input:G.value,inst:Y,continue:!J.abort})}}),H7=P("$ZodCheckStartsWith",(Y,J)=>{k0.init(Y,J);let X=new RegExp(`^${w6(J.prefix)}.*`);J.pattern??(J.pattern=X),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(X)}),Y._zod.check=(Q)=>{if(Q.value.startsWith(J.prefix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:J.prefix,input:Q.value,inst:Y,continue:!J.abort})}}),Z7=P("$ZodCheckEndsWith",(Y,J)=>{k0.init(Y,J);let X=new RegExp(`.*${w6(J.suffix)}$`);J.pattern??(J.pattern=X),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(X)}),Y._zod.check=(Q)=>{if(Q.value.endsWith(J.suffix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:J.suffix,input:Q.value,inst:Y,continue:!J.abort})}});var V7=P("$ZodCheckOverwrite",(Y,J)=>{k0.init(Y,J),Y._zod.check=(X)=>{X.value=J.tx(X.value)}});class Q4{constructor(Y=[]){if(this.content=[],this.indent=0,this)this.args=Y}indented(Y){this.indent+=1,Y(this),this.indent-=1}write(Y){if(typeof Y==="function"){Y(this,{execution:"sync"}),Y(this,{execution:"async"});return}let X=Y.split(`
|
|
12
|
+
`).filter(($)=>$),Q=Math.min(...X.map(($)=>$.length-$.trimStart().length)),G=X.map(($)=>$.slice(Q)).map(($)=>" ".repeat(this.indent*2)+$);for(let $ of G)this.content.push($)}compile(){let Y=Function,J=this?.args,Q=[...(this?.content??[""]).map((G)=>` ${G}`)];return new Y(...J,Q.join(`
|
|
13
|
+
`))}}var L7={major:4,minor:1,patch:8};var F0=P("$ZodType",(Y,J)=>{var X;Y??(Y={}),Y._zod.def=J,Y._zod.bag=Y._zod.bag||{},Y._zod.version=L7;let Q=[...Y._zod.def.checks??[]];if(Y._zod.traits.has("$ZodCheck"))Q.unshift(Y);for(let G of Q)for(let $ of G._zod.onattach)$(Y);if(Q.length===0)(X=Y._zod).deferred??(X.deferred=[]),Y._zod.deferred?.push(()=>{Y._zod.run=Y._zod.parse});else{let G=(W,K,U)=>{let H=u6(W),V;for(let D of K){if(D._zod.def.when){if(!D._zod.def.when(W))continue}else if(H)continue;let L=W.issues.length,B=D._zod.check(W);if(B instanceof Promise&&U?.async===!1)throw new C6;if(V||B instanceof Promise)V=(V??Promise.resolve()).then(async()=>{if(await B,W.issues.length===L)return;if(!H)H=u6(W,L)});else{if(W.issues.length===L)continue;if(!H)H=u6(W,L)}}if(V)return V.then(()=>{return W});return W},$=(W,K,U)=>{if(u6(W))return W.aborted=!0,W;let H=G(K,Q,U);if(H instanceof Promise){if(U.async===!1)throw new C6;return H.then((V)=>Y._zod.parse(V,U))}return Y._zod.parse(H,U)};Y._zod.run=(W,K)=>{if(K.skipChecks)return Y._zod.parse(W,K);if(K.direction==="backward"){let H=Y._zod.parse({value:W.value,issues:[]},{...K,skipChecks:!0});if(H instanceof Promise)return H.then((V)=>{return $(V,W,K)});return $(H,W,K)}let U=Y._zod.parse(W,K);if(U instanceof Promise){if(K.async===!1)throw new C6;return U.then((H)=>G(H,Q,K))}return G(U,Q,K)}}Y["~standard"]={validate:(G)=>{try{let $=N2(Y,G);return $.success?{value:$.data}:{issues:$.error?.issues}}catch($){return j2(Y,G).then((W)=>W.success?{value:W.data}:{issues:W.error?.issues})}},vendor:"zod",version:1}}),P8=P("$ZodString",(Y,J)=>{F0.init(Y,J),Y._zod.pattern=[...Y?._zod.bag?.patterns??[]].pop()??n2(Y._zod.bag),Y._zod.parse=(X,Q)=>{if(J.coerce)try{X.value=String(X.value)}catch(G){}if(typeof X.value==="string")return X;return X.issues.push({expected:"string",code:"invalid_type",input:X.value,inst:Y}),X}}),O0=P("$ZodStringFormat",(Y,J)=>{P1.init(Y,J),P8.init(Y,J)}),E7=P("$ZodGUID",(Y,J)=>{J.pattern??(J.pattern=b2),O0.init(Y,J)}),M7=P("$ZodUUID",(Y,J)=>{if(J.version){let Q={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[J.version];if(Q===void 0)throw Error(`Invalid UUID version: "${J.version}"`);J.pattern??(J.pattern=eY(Q))}else J.pattern??(J.pattern=eY());O0.init(Y,J)}),A7=P("$ZodEmail",(Y,J)=>{J.pattern??(J.pattern=k2),O0.init(Y,J)}),T7=P("$ZodURL",(Y,J)=>{O0.init(Y,J),Y._zod.check=(X)=>{try{let Q=X.value.trim(),G=new URL(Q);if(J.hostname){if(J.hostname.lastIndex=0,!J.hostname.test(G.hostname))X.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:m2.source,input:X.value,inst:Y,continue:!J.abort})}if(J.protocol){if(J.protocol.lastIndex=0,!J.protocol.test(G.protocol.endsWith(":")?G.protocol.slice(0,-1):G.protocol))X.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:J.protocol.source,input:X.value,inst:Y,continue:!J.abort})}if(J.normalize)X.value=G.href;else X.value=Q;return}catch(Q){X.issues.push({code:"invalid_format",format:"url",input:X.value,inst:Y,continue:!J.abort})}}}),R7=P("$ZodEmoji",(Y,J)=>{J.pattern??(J.pattern=x2()),O0.init(Y,J)}),C7=P("$ZodNanoID",(Y,J)=>{J.pattern??(J.pattern=S2),O0.init(Y,J)}),w7=P("$ZodCUID",(Y,J)=>{J.pattern??(J.pattern=A2),O0.init(Y,J)}),S7=P("$ZodCUID2",(Y,J)=>{J.pattern??(J.pattern=T2),O0.init(Y,J)}),I7=P("$ZodULID",(Y,J)=>{J.pattern??(J.pattern=R2),O0.init(Y,J)}),b7=P("$ZodXID",(Y,J)=>{J.pattern??(J.pattern=C2),O0.init(Y,J)}),k7=P("$ZodKSUID",(Y,J)=>{J.pattern??(J.pattern=w2),O0.init(Y,J)}),x7=P("$ZodISODateTime",(Y,J)=>{J.pattern??(J.pattern=i2(J)),O0.init(Y,J)}),v7=P("$ZodISODate",(Y,J)=>{J.pattern??(J.pattern=p2),O0.init(Y,J)}),h7=P("$ZodISOTime",(Y,J)=>{J.pattern??(J.pattern=d2(J)),O0.init(Y,J)}),y7=P("$ZodISODuration",(Y,J)=>{J.pattern??(J.pattern=I2),O0.init(Y,J)}),g7=P("$ZodIPv4",(Y,J)=>{J.pattern??(J.pattern=v2),O0.init(Y,J),Y._zod.onattach.push((X)=>{let Q=X._zod.bag;Q.format="ipv4"})}),f7=P("$ZodIPv6",(Y,J)=>{J.pattern??(J.pattern=h2),O0.init(Y,J),Y._zod.onattach.push((X)=>{let Q=X._zod.bag;Q.format="ipv6"}),Y._zod.check=(X)=>{try{new URL(`http://[${X.value}]`)}catch{X.issues.push({code:"invalid_format",format:"ipv6",input:X.value,inst:Y,continue:!J.abort})}}}),m7=P("$ZodCIDRv4",(Y,J)=>{J.pattern??(J.pattern=y2),O0.init(Y,J)}),c7=P("$ZodCIDRv6",(Y,J)=>{J.pattern??(J.pattern=g2),O0.init(Y,J),Y._zod.check=(X)=>{let Q=X.value.split("/");try{if(Q.length!==2)throw Error();let[G,$]=Q;if(!$)throw Error();let W=Number($);if(`${W}`!==$)throw Error();if(W<0||W>128)throw Error();new URL(`http://[${G}]`)}catch{X.issues.push({code:"invalid_format",format:"cidrv6",input:X.value,inst:Y,continue:!J.abort})}}});function u7(Y){if(Y==="")return!0;if(Y.length%4!==0)return!1;try{return atob(Y),!0}catch{return!1}}var p7=P("$ZodBase64",(Y,J)=>{J.pattern??(J.pattern=f2),O0.init(Y,J),Y._zod.onattach.push((X)=>{X._zod.bag.contentEncoding="base64"}),Y._zod.check=(X)=>{if(u7(X.value))return;X.issues.push({code:"invalid_format",format:"base64",input:X.value,inst:Y,continue:!J.abort})}});function NU(Y){if(!Y4.test(Y))return!1;let J=Y.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),X=J.padEnd(Math.ceil(J.length/4)*4,"=");return u7(X)}var l7=P("$ZodBase64URL",(Y,J)=>{J.pattern??(J.pattern=Y4),O0.init(Y,J),Y._zod.onattach.push((X)=>{X._zod.bag.contentEncoding="base64url"}),Y._zod.check=(X)=>{if(NU(X.value))return;X.issues.push({code:"invalid_format",format:"base64url",input:X.value,inst:Y,continue:!J.abort})}}),d7=P("$ZodE164",(Y,J)=>{J.pattern??(J.pattern=c2),O0.init(Y,J)});function jU(Y,J=null){try{let X=Y.split(".");if(X.length!==3)return!1;let[Q]=X;if(!Q)return!1;let G=JSON.parse(atob(Q));if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(J&&(!("alg"in G)||G.alg!==J))return!1;return!0}catch{return!1}}var i7=P("$ZodJWT",(Y,J)=>{O0.init(Y,J),Y._zod.check=(X)=>{if(jU(X.value,J.alg))return;X.issues.push({code:"invalid_format",format:"jwt",input:X.value,inst:Y,continue:!J.abort})}});var $4=P("$ZodNumber",(Y,J)=>{F0.init(Y,J),Y._zod.pattern=Y._zod.bag.pattern??r2,Y._zod.parse=(X,Q)=>{if(J.coerce)try{X.value=Number(X.value)}catch(W){}let G=X.value;if(typeof G==="number"&&!Number.isNaN(G)&&Number.isFinite(G))return X;let $=typeof G==="number"?Number.isNaN(G)?"NaN":!Number.isFinite(G)?"Infinity":void 0:void 0;return X.issues.push({expected:"number",code:"invalid_type",input:G,inst:Y,...$?{received:$}:{}}),X}}),n7=P("$ZodNumber",(Y,J)=>{X7.init(Y,J),$4.init(Y,J)}),o7=P("$ZodBoolean",(Y,J)=>{F0.init(Y,J),Y._zod.pattern=s2,Y._zod.parse=(X,Q)=>{if(J.coerce)try{X.value=Boolean(X.value)}catch($){}let G=X.value;if(typeof G==="boolean")return X;return X.issues.push({expected:"boolean",code:"invalid_type",input:G,inst:Y}),X}});var r7=P("$ZodNull",(Y,J)=>{F0.init(Y,J),Y._zod.pattern=a2,Y._zod.values=new Set([null]),Y._zod.parse=(X,Q)=>{let G=X.value;if(G===null)return X;return X.issues.push({expected:"null",code:"invalid_type",input:G,inst:Y}),X}});var s7=P("$ZodUnknown",(Y,J)=>{F0.init(Y,J),Y._zod.parse=(X)=>X}),a7=P("$ZodNever",(Y,J)=>{F0.init(Y,J),Y._zod.parse=(X,Q)=>{return X.issues.push({expected:"never",code:"invalid_type",input:X.value,inst:Y}),X}});function N7(Y,J,X){if(Y.issues.length)J.issues.push(...S6(X,Y.issues));J.value[X]=Y.value}var t7=P("$ZodArray",(Y,J)=>{F0.init(Y,J),Y._zod.parse=(X,Q)=>{let G=X.value;if(!Array.isArray(G))return X.issues.push({expected:"array",code:"invalid_type",input:G,inst:Y}),X;X.value=Array(G.length);let $=[];for(let W=0;W<G.length;W++){let K=G[W],U=J.element._zod.run({value:K,issues:[]},Q);if(U instanceof Promise)$.push(U.then((H)=>N7(H,X,W)));else N7(U,X,W)}if($.length)return Promise.all($).then(()=>X);return X}});function D8(Y,J,X,Q){if(Y.issues.length)J.issues.push(...S6(X,Y.issues));if(Y.value===void 0){if(X in Q)J.value[X]=void 0}else J.value[X]=Y.value}function e7(Y){let J=Object.keys(Y.shape);for(let Q of J)if(!Y.shape?.[Q]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${Q}": expected a Zod schema`);let X=sY(Y.shape);return{...Y,keys:J,keySet:new Set(J),numKeys:J.length,optionalKeys:new Set(X)}}function Y5(Y,J,X,Q,G,$){let W=[],K=G.keySet,U=G.catchall._zod,H=U.def.type;for(let V of Object.keys(J)){if(K.has(V))continue;if(H==="never"){W.push(V);continue}let D=U.run({value:J[V],issues:[]},Q);if(D instanceof Promise)Y.push(D.then((L)=>D8(L,X,V,J)));else D8(D,X,V,J)}if(W.length)X.issues.push({code:"unrecognized_keys",keys:W,input:J,inst:$});if(!Y.length)return X;return Promise.all(Y).then(()=>{return X})}var FU=P("$ZodObject",(Y,J)=>{F0.init(Y,J);let X=k9(()=>e7(J));G0(Y._zod,"propValues",()=>{let W=J.shape,K={};for(let U in W){let H=W[U]._zod;if(H.values){K[U]??(K[U]=new Set);for(let V of H.values)K[U].add(V)}}return K});let Q=$9,G=J.catchall,$;Y._zod.parse=(W,K)=>{$??($=X.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 H=[],V=$.shape;for(let D of $.keys){let B=V[D]._zod.run({value:U[D],issues:[]},K);if(B instanceof Promise)H.push(B.then((O)=>D8(O,W,D,U)));else D8(B,W,D,U)}if(!G)return H.length?Promise.all(H).then(()=>W):W;return Y5(H,U,W,K,X.value,Y)}}),J5=P("$ZodObjectJIT",(Y,J)=>{FU.init(Y,J);let X=Y._zod.parse,Q=k9(()=>e7(J)),G=(L)=>{let B=new Q4(["shape","payload","ctx"]),O=Q.value,q=(x)=>{let j=V8(x);return`shape[${j}]._zod.run({ value: input[${j}], issues: [] }, ctx)`};B.write("const input = payload.value;");let _=Object.create(null),M=0;for(let x of O.keys)_[x]=`key_${M++}`;B.write("const newResult = {};");for(let x of O.keys){let j=_[x],C=V8(x);B.write(`const ${j} = ${q(x)};`),B.write(`
|
|
14
|
+
if (${j}.issues.length) {
|
|
15
|
+
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
|
|
16
|
+
...iss,
|
|
17
|
+
path: iss.path ? [${C}, ...iss.path] : [${C}]
|
|
18
|
+
})));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
if (${j}.value === undefined) {
|
|
23
|
+
if (${C} in input) {
|
|
24
|
+
newResult[${C}] = undefined;
|
|
25
|
+
}
|
|
26
|
+
} else {
|
|
27
|
+
newResult[${C}] = ${j}.value;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
`)}B.write("payload.value = newResult;"),B.write("return payload;");let S=B.compile();return(x,j)=>S(L,x,j)},$,W=$9,K=!Z8.jitless,H=K&&oY.value,V=J.catchall,D;Y._zod.parse=(L,B)=>{D??(D=Q.value);let O=L.value;if(!W(O))return L.issues.push({expected:"object",code:"invalid_type",input:O,inst:Y}),L;if(K&&H&&B?.async===!1&&B.jitless!==!0){if(!$)$=G(J.shape);if(L=$(L,B),!V)return L;return Y5([],O,L,B,D,Y)}return X(L,B)}});function j7(Y,J,X,Q){for(let $ of Y)if($.issues.length===0)return J.value=$.value,J;let G=Y.filter(($)=>!u6($));if(G.length===1)return J.value=G[0].value,G[0];return J.issues.push({code:"invalid_union",input:J.value,inst:X,errors:Y.map(($)=>$.issues.map((W)=>G6(W,Q,N6())))}),J}var W4=P("$ZodUnion",(Y,J)=>{F0.init(Y,J),G0(Y._zod,"optin",()=>J.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),G0(Y._zod,"optout",()=>J.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),G0(Y._zod,"values",()=>{if(J.options.every((G)=>G._zod.values))return new Set(J.options.flatMap((G)=>Array.from(G._zod.values)));return}),G0(Y._zod,"pattern",()=>{if(J.options.every((G)=>G._zod.pattern)){let G=J.options.map(($)=>$._zod.pattern);return new RegExp(`^(${G.map(($)=>j1($.source)).join("|")})$`)}return});let X=J.options.length===1,Q=J.options[0]._zod.run;Y._zod.parse=(G,$)=>{if(X)return Q(G,$);let W=!1,K=[];for(let U of J.options){let H=U._zod.run({value:G.value,issues:[]},$);if(H instanceof Promise)K.push(H),W=!0;else{if(H.issues.length===0)return H;K.push(H)}}if(!W)return j7(K,G,Y,$);return Promise.all(K).then((U)=>{return j7(U,G,Y,$)})}}),X5=P("$ZodDiscriminatedUnion",(Y,J)=>{W4.init(Y,J);let X=Y._zod.parse;G0(Y._zod,"propValues",()=>{let G={};for(let $ of J.options){let W=$._zod.propValues;if(!W||Object.keys(W).length===0)throw Error(`Invalid discriminated union option at index "${J.options.indexOf($)}"`);for(let[K,U]of Object.entries(W)){if(!G[K])G[K]=new Set;for(let H of U)G[K].add(H)}}return G});let Q=k9(()=>{let G=J.options,$=new Map;for(let W of G){let K=W._zod.propValues?.[J.discriminator];if(!K||K.size===0)throw Error(`Invalid discriminated union option at index "${J.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(!$9(W))return G.issues.push({code:"invalid_type",expected:"object",input:W,inst:Y}),G;let K=Q.value.get(W?.[J.discriminator]);if(K)return K._zod.run(G,$);if(J.unionFallback)return X(G,$);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:J.discriminator,input:W,path:[J.discriminator],inst:Y}),G}}),Q5=P("$ZodIntersection",(Y,J)=>{F0.init(Y,J),Y._zod.parse=(X,Q)=>{let G=X.value,$=J.left._zod.run({value:G,issues:[]},Q),W=J.right._zod.run({value:G,issues:[]},Q);if($ instanceof Promise||W instanceof Promise)return Promise.all([$,W]).then(([U,H])=>{return F7(X,U,H)});return F7(X,$,W)}});function G4(Y,J){if(Y===J)return{valid:!0,data:Y};if(Y instanceof Date&&J instanceof Date&&+Y===+J)return{valid:!0,data:Y};if(c6(Y)&&c6(J)){let X=Object.keys(J),Q=Object.keys(Y).filter(($)=>X.indexOf($)!==-1),G={...Y,...J};for(let $ of Q){let W=G4(Y[$],J[$]);if(!W.valid)return{valid:!1,mergeErrorPath:[$,...W.mergeErrorPath]};G[$]=W.data}return{valid:!0,data:G}}if(Array.isArray(Y)&&Array.isArray(J)){if(Y.length!==J.length)return{valid:!1,mergeErrorPath:[]};let X=[];for(let Q=0;Q<Y.length;Q++){let G=Y[Q],$=J[Q],W=G4(G,$);if(!W.valid)return{valid:!1,mergeErrorPath:[Q,...W.mergeErrorPath]};X.push(W.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function F7(Y,J,X){if(J.issues.length)Y.issues.push(...J.issues);if(X.issues.length)Y.issues.push(...X.issues);if(u6(Y))return Y;let Q=G4(J.value,X.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return Y.value=Q.data,Y}var G5=P("$ZodRecord",(Y,J)=>{F0.init(Y,J),Y._zod.parse=(X,Q)=>{let G=X.value;if(!c6(G))return X.issues.push({expected:"record",code:"invalid_type",input:G,inst:Y}),X;let $=[];if(J.keyType._zod.values){let W=J.keyType._zod.values;X.value={};for(let U of W)if(typeof U==="string"||typeof U==="number"||typeof U==="symbol"){let H=J.valueType._zod.run({value:G[U],issues:[]},Q);if(H instanceof Promise)$.push(H.then((V)=>{if(V.issues.length)X.issues.push(...S6(U,V.issues));X.value[U]=V.value}));else{if(H.issues.length)X.issues.push(...S6(U,H.issues));X.value[U]=H.value}}let K;for(let U in G)if(!W.has(U))K=K??[],K.push(U);if(K&&K.length>0)X.issues.push({code:"unrecognized_keys",input:G,inst:Y,keys:K})}else{X.value={};for(let W of Reflect.ownKeys(G)){if(W==="__proto__")continue;let K=J.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){X.issues.push({code:"invalid_key",origin:"record",issues:K.issues.map((H)=>G6(H,Q,N6())),input:W,path:[W],inst:Y}),X.value[K.value]=K.value;continue}let U=J.valueType._zod.run({value:G[W],issues:[]},Q);if(U instanceof Promise)$.push(U.then((H)=>{if(H.issues.length)X.issues.push(...S6(W,H.issues));X.value[K.value]=H.value}));else{if(U.issues.length)X.issues.push(...S6(W,U.issues));X.value[K.value]=U.value}}}if($.length)return Promise.all($).then(()=>X);return X}});var $5=P("$ZodEnum",(Y,J)=>{F0.init(Y,J);let X=L1(J.entries),Q=new Set(X);Y._zod.values=Q,Y._zod.pattern=new RegExp(`^(${X.filter((G)=>rY.has(typeof G)).map((G)=>typeof G==="string"?w6(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:X,input:W,inst:Y}),G}}),W5=P("$ZodLiteral",(Y,J)=>{if(F0.init(Y,J),J.values.length===0)throw Error("Cannot create literal schema with no valid values");Y._zod.values=new Set(J.values),Y._zod.pattern=new RegExp(`^(${J.values.map((X)=>typeof X==="string"?w6(X):X?w6(X.toString()):String(X)).join("|")})$`),Y._zod.parse=(X,Q)=>{let G=X.value;if(Y._zod.values.has(G))return X;return X.issues.push({code:"invalid_value",values:J.values,input:G,inst:Y}),X}});var z5=P("$ZodTransform",(Y,J)=>{F0.init(Y,J),Y._zod.parse=(X,Q)=>{if(Q.direction==="backward")throw new V1(Y.constructor.name);let G=J.transform(X.value,X);if(Q.async)return(G instanceof Promise?G:Promise.resolve(G)).then((W)=>{return X.value=W,X});if(G instanceof Promise)throw new C6;return X.value=G,X}});function O7(Y,J){if(Y.issues.length&&J===void 0)return{issues:[],value:void 0};return Y}var K5=P("$ZodOptional",(Y,J)=>{F0.init(Y,J),Y._zod.optin="optional",Y._zod.optout="optional",G0(Y._zod,"values",()=>{return J.innerType._zod.values?new Set([...J.innerType._zod.values,void 0]):void 0}),G0(Y._zod,"pattern",()=>{let X=J.innerType._zod.pattern;return X?new RegExp(`^(${j1(X.source)})?$`):void 0}),Y._zod.parse=(X,Q)=>{if(J.innerType._zod.optin==="optional"){let G=J.innerType._zod.run(X,Q);if(G instanceof Promise)return G.then(($)=>O7($,X.value));return O7(G,X.value)}if(X.value===void 0)return X;return J.innerType._zod.run(X,Q)}}),U5=P("$ZodNullable",(Y,J)=>{F0.init(Y,J),G0(Y._zod,"optin",()=>J.innerType._zod.optin),G0(Y._zod,"optout",()=>J.innerType._zod.optout),G0(Y._zod,"pattern",()=>{let X=J.innerType._zod.pattern;return X?new RegExp(`^(${j1(X.source)}|null)$`):void 0}),G0(Y._zod,"values",()=>{return J.innerType._zod.values?new Set([...J.innerType._zod.values,null]):void 0}),Y._zod.parse=(X,Q)=>{if(X.value===null)return X;return J.innerType._zod.run(X,Q)}}),H5=P("$ZodDefault",(Y,J)=>{F0.init(Y,J),Y._zod.optin="optional",G0(Y._zod,"values",()=>J.innerType._zod.values),Y._zod.parse=(X,Q)=>{if(Q.direction==="backward")return J.innerType._zod.run(X,Q);if(X.value===void 0)return X.value=J.defaultValue,X;let G=J.innerType._zod.run(X,Q);if(G instanceof Promise)return G.then(($)=>D7($,J));return D7(G,J)}});function D7(Y,J){if(Y.value===void 0)Y.value=J.defaultValue;return Y}var Z5=P("$ZodPrefault",(Y,J)=>{F0.init(Y,J),Y._zod.optin="optional",G0(Y._zod,"values",()=>J.innerType._zod.values),Y._zod.parse=(X,Q)=>{if(Q.direction==="backward")return J.innerType._zod.run(X,Q);if(X.value===void 0)X.value=J.defaultValue;return J.innerType._zod.run(X,Q)}}),V5=P("$ZodNonOptional",(Y,J)=>{F0.init(Y,J),G0(Y._zod,"values",()=>{let X=J.innerType._zod.values;return X?new Set([...X].filter((Q)=>Q!==void 0)):void 0}),Y._zod.parse=(X,Q)=>{let G=J.innerType._zod.run(X,Q);if(G instanceof Promise)return G.then(($)=>P7($,Y));return P7(G,Y)}});function P7(Y,J){if(!Y.issues.length&&Y.value===void 0)Y.issues.push({code:"invalid_type",expected:"nonoptional",input:Y.value,inst:J});return Y}var B5=P("$ZodCatch",(Y,J)=>{F0.init(Y,J),G0(Y._zod,"optin",()=>J.innerType._zod.optin),G0(Y._zod,"optout",()=>J.innerType._zod.optout),G0(Y._zod,"values",()=>J.innerType._zod.values),Y._zod.parse=(X,Q)=>{if(Q.direction==="backward")return J.innerType._zod.run(X,Q);let G=J.innerType._zod.run(X,Q);if(G instanceof Promise)return G.then(($)=>{if(X.value=$.value,$.issues.length)X.value=J.catchValue({...X,error:{issues:$.issues.map((W)=>G6(W,Q,N6()))},input:X.value}),X.issues=[];return X});if(X.value=G.value,G.issues.length)X.value=J.catchValue({...X,error:{issues:G.issues.map(($)=>G6($,Q,N6()))},input:X.value}),X.issues=[];return X}});var L5=P("$ZodPipe",(Y,J)=>{F0.init(Y,J),G0(Y._zod,"values",()=>J.in._zod.values),G0(Y._zod,"optin",()=>J.in._zod.optin),G0(Y._zod,"optout",()=>J.out._zod.optout),G0(Y._zod,"propValues",()=>J.in._zod.propValues),Y._zod.parse=(X,Q)=>{if(Q.direction==="backward"){let $=J.out._zod.run(X,Q);if($ instanceof Promise)return $.then((W)=>O8(W,J.in,Q));return O8($,J.in,Q)}let G=J.in._zod.run(X,Q);if(G instanceof Promise)return G.then(($)=>O8($,J.out,Q));return O8(G,J.out,Q)}});function O8(Y,J,X){if(Y.issues.length)return Y.aborted=!0,Y;return J._zod.run({value:Y.value,issues:Y.issues},X)}var N5=P("$ZodReadonly",(Y,J)=>{F0.init(Y,J),G0(Y._zod,"propValues",()=>J.innerType._zod.propValues),G0(Y._zod,"values",()=>J.innerType._zod.values),G0(Y._zod,"optin",()=>J.innerType._zod.optin),G0(Y._zod,"optout",()=>J.innerType._zod.optout),Y._zod.parse=(X,Q)=>{if(Q.direction==="backward")return J.innerType._zod.run(X,Q);let G=J.innerType._zod.run(X,Q);if(G instanceof Promise)return G.then(_7);return _7(G)}});function _7(Y){return Y.value=Object.freeze(Y.value),Y}var j5=P("$ZodLazy",(Y,J)=>{F0.init(Y,J),G0(Y._zod,"innerType",()=>J.getter()),G0(Y._zod,"pattern",()=>Y._zod.innerType._zod.pattern),G0(Y._zod,"propValues",()=>Y._zod.innerType._zod.propValues),G0(Y._zod,"optin",()=>Y._zod.innerType._zod.optin??void 0),G0(Y._zod,"optout",()=>Y._zod.innerType._zod.optout??void 0),Y._zod.parse=(X,Q)=>{return Y._zod.innerType._zod.run(X,Q)}}),F5=P("$ZodCustom",(Y,J)=>{k0.init(Y,J),F0.init(Y,J),Y._zod.parse=(X,Q)=>{return X},Y._zod.check=(X)=>{let Q=X.value,G=J.fn(Q);if(G instanceof Promise)return G.then(($)=>q7($,X,Q,Y));q7(G,X,Q,Y);return}});function q7(Y,J,X,Q){if(!Y){let G={code:"custom",input:X,inst:Q,path:[...Q._zod.def.path??[]],continue:!Q._zod.def.abort};if(Q._zod.def.params)G.params=Q._zod.def.params;J.issues.push(x9(G))}}var dF=Symbol("ZodOutput"),iF=Symbol("ZodInput");class _8{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Y,...J){let X=J[0];if(this._map.set(Y,X),X&&typeof X==="object"&&"id"in X){if(this._idmap.has(X.id))throw Error(`ID ${X.id} already exists in the registry`);this._idmap.set(X.id,Y)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Y){let J=this._map.get(Y);if(J&&typeof J==="object"&&"id"in J)this._idmap.delete(J.id);return this._map.delete(Y),this}get(Y){let J=Y._zod.parent;if(J){let X={...this.get(J)??{}};delete X.id;let Q={...X,...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 OU(){return new _8}var W9=OU();function O5(Y,J){return new Y({type:"string",...o(J)})}function D5(Y,J){return new Y({type:"string",format:"email",check:"string_format",abort:!1,...o(J)})}function z4(Y,J){return new Y({type:"string",format:"guid",check:"string_format",abort:!1,...o(J)})}function P5(Y,J){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...o(J)})}function _5(Y,J){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...o(J)})}function q5(Y,J){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...o(J)})}function E5(Y,J){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...o(J)})}function M5(Y,J){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...o(J)})}function A5(Y,J){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...o(J)})}function T5(Y,J){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...o(J)})}function R5(Y,J){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...o(J)})}function C5(Y,J){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...o(J)})}function w5(Y,J){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...o(J)})}function S5(Y,J){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...o(J)})}function I5(Y,J){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...o(J)})}function b5(Y,J){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...o(J)})}function k5(Y,J){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...o(J)})}function x5(Y,J){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...o(J)})}function v5(Y,J){return new Y({type:"string",format:"cidrv6",check:"string_format",abort:!1,...o(J)})}function h5(Y,J){return new Y({type:"string",format:"base64",check:"string_format",abort:!1,...o(J)})}function y5(Y,J){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...o(J)})}function g5(Y,J){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...o(J)})}function f5(Y,J){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...o(J)})}function m5(Y,J){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...o(J)})}function c5(Y,J){return new Y({type:"string",format:"date",check:"string_format",...o(J)})}function u5(Y,J){return new Y({type:"string",format:"time",check:"string_format",precision:null,...o(J)})}function p5(Y,J){return new Y({type:"string",format:"duration",check:"string_format",...o(J)})}function l5(Y,J){return new Y({type:"number",checks:[],...o(J)})}function d5(Y,J){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...o(J)})}function i5(Y,J){return new Y({type:"boolean",...o(J)})}function n5(Y,J){return new Y({type:"null",...o(J)})}function o5(Y){return new Y({type:"unknown"})}function r5(Y,J){return new Y({type:"never",...o(J)})}function q8(Y,J){return new J4({check:"less_than",...o(J),value:Y,inclusive:!1})}function _1(Y,J){return new J4({check:"less_than",...o(J),value:Y,inclusive:!0})}function E8(Y,J){return new X4({check:"greater_than",...o(J),value:Y,inclusive:!1})}function q1(Y,J){return new X4({check:"greater_than",...o(J),value:Y,inclusive:!0})}function M8(Y,J){return new J7({check:"multiple_of",...o(J),value:Y})}function A8(Y,J){return new Q7({check:"max_length",...o(J),maximum:Y})}function v9(Y,J){return new G7({check:"min_length",...o(J),minimum:Y})}function T8(Y,J){return new $7({check:"length_equals",...o(J),length:Y})}function K4(Y,J){return new W7({check:"string_format",format:"regex",...o(J),pattern:Y})}function U4(Y){return new z7({check:"string_format",format:"lowercase",...o(Y)})}function H4(Y){return new K7({check:"string_format",format:"uppercase",...o(Y)})}function Z4(Y,J){return new U7({check:"string_format",format:"includes",...o(J),includes:Y})}function V4(Y,J){return new H7({check:"string_format",format:"starts_with",...o(J),prefix:Y})}function B4(Y,J){return new Z7({check:"string_format",format:"ends_with",...o(J),suffix:Y})}function z9(Y){return new V7({check:"overwrite",tx:Y})}function L4(Y){return z9((J)=>J.normalize(Y))}function N4(){return z9((Y)=>Y.trim())}function j4(){return z9((Y)=>Y.toLowerCase())}function F4(){return z9((Y)=>Y.toUpperCase())}function s5(Y,J,X){return new Y({type:"array",element:J,...o(X)})}function a5(Y,J,X){let Q=o(X);return Q.abort??(Q.abort=!0),new Y({type:"custom",check:"custom",fn:J,...Q})}function t5(Y,J,X){return new Y({type:"custom",check:"custom",fn:J,...o(X)})}function e5(Y){let J=DU((X)=>{return X.addIssue=(Q)=>{if(typeof Q==="string")X.issues.push(x9(Q,X.value,J._zod.def));else{let G=Q;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=X.value),G.inst??(G.inst=J),G.continue??(G.continue=!J._zod.def.abort),X.issues.push(x9(G))}},Y(X.value,X)});return J}function DU(Y,J){let X=new k0({check:"custom",...o(J)});return X._zod.check=Y,X}class O4{constructor(Y){this.counter=0,this.metadataRegistry=Y?.metadata??W9,this.target=Y?.target??"draft-2020-12",this.unrepresentable=Y?.unrepresentable??"throw",this.override=Y?.override??(()=>{}),this.io=Y?.io??"output",this.seen=new Map}process(Y,J={path:[],schemaPath:[]}){var X;let Q=Y._zod.def,G={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},$=this.seen.get(Y);if($){if($.count++,J.schemaPath.includes(Y))$.cycle=J.path;return $.schema}let W={schema:{},count:1,cycle:void 0,path:J.path};this.seen.set(Y,W);let K=Y._zod.toJSONSchema?.();if(K)W.schema=K;else{let V={...J,schemaPath:[...J.schemaPath,Y],path:J.path},D=Y._zod.parent;if(D)W.ref=D,this.process(D,V),this.seen.get(D).isParent=!0;else{let L=W.schema;switch(Q.type){case"string":{let B=L;B.type="string";let{minimum:O,maximum:q,format:_,patterns:M,contentEncoding:S}=Y._zod.bag;if(typeof O==="number")B.minLength=O;if(typeof q==="number")B.maxLength=q;if(_){if(B.format=G[_]??_,B.format==="")delete B.format}if(S)B.contentEncoding=S;if(M&&M.size>0){let x=[...M];if(x.length===1)B.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 B=L,{minimum:O,maximum:q,format:_,multipleOf:M,exclusiveMaximum:S,exclusiveMinimum:x}=Y._zod.bag;if(typeof _==="string"&&_.includes("int"))B.type="integer";else B.type="number";if(typeof x==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")B.minimum=x,B.exclusiveMinimum=!0;else B.exclusiveMinimum=x;if(typeof O==="number"){if(B.minimum=O,typeof x==="number"&&this.target!=="draft-4")if(x>=O)delete B.minimum;else delete B.exclusiveMinimum}if(typeof S==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")B.maximum=S,B.exclusiveMaximum=!0;else B.exclusiveMaximum=S;if(typeof q==="number"){if(B.maximum=q,typeof S==="number"&&this.target!=="draft-4")if(S<=q)delete B.maximum;else delete B.exclusiveMaximum}if(typeof M==="number")B.multipleOf=M;break}case"boolean":{let B=L;B.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")L.type="string",L.nullable=!0,L.enum=[null];else L.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":{L.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let B=L,{minimum:O,maximum:q}=Y._zod.bag;if(typeof O==="number")B.minItems=O;if(typeof q==="number")B.maxItems=q;B.type="array",B.items=this.process(Q.element,{...V,path:[...V.path,"items"]});break}case"object":{let B=L;B.type="object",B.properties={};let O=Q.shape;for(let M in O)B.properties[M]=this.process(O[M],{...V,path:[...V.path,"properties",M]});let q=new Set(Object.keys(O)),_=new Set([...q].filter((M)=>{let S=Q.shape[M]._zod;if(this.io==="input")return S.optin===void 0;else return S.optout===void 0}));if(_.size>0)B.required=Array.from(_);if(Q.catchall?._zod.def.type==="never")B.additionalProperties=!1;else if(!Q.catchall){if(this.io==="output")B.additionalProperties=!1}else if(Q.catchall)B.additionalProperties=this.process(Q.catchall,{...V,path:[...V.path,"additionalProperties"]});break}case"union":{let B=L,O=Q.options.map((q,_)=>this.process(q,{...V,path:[...V.path,"anyOf",_]}));B.anyOf=O;break}case"intersection":{let B=L,O=this.process(Q.left,{...V,path:[...V.path,"allOf",0]}),q=this.process(Q.right,{...V,path:[...V.path,"allOf",1]}),_=(S)=>("allOf"in S)&&Object.keys(S).length===1,M=[..._(O)?O.allOf:[O],..._(q)?q.allOf:[q]];B.allOf=M;break}case"tuple":{let B=L;B.type="array";let O=this.target==="draft-2020-12"?"prefixItems":"items",q=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",_=Q.items.map((j,C)=>this.process(j,{...V,path:[...V.path,O,C]})),M=Q.rest?this.process(Q.rest,{...V,path:[...V.path,q,...this.target==="openapi-3.0"?[Q.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(B.prefixItems=_,M)B.items=M}else if(this.target==="openapi-3.0"){if(B.items={anyOf:_},M)B.items.anyOf.push(M);if(B.minItems=_.length,!M)B.maxItems=_.length}else if(B.items=_,M)B.additionalItems=M;let{minimum:S,maximum:x}=Y._zod.bag;if(typeof S==="number")B.minItems=S;if(typeof x==="number")B.maxItems=x;break}case"record":{let B=L;if(B.type="object",this.target==="draft-7"||this.target==="draft-2020-12")B.propertyNames=this.process(Q.keyType,{...V,path:[...V.path,"propertyNames"]});B.additionalProperties=this.process(Q.valueType,{...V,path:[...V.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let B=L,O=L1(Q.entries);if(O.every((q)=>typeof q==="number"))B.type="number";if(O.every((q)=>typeof q==="string"))B.type="string";B.enum=O;break}case"literal":{let B=L,O=[];for(let q of Q.values)if(q===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof q==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else O.push(Number(q));else O.push(q);if(O.length===0);else if(O.length===1){let q=O[0];if(B.type=q===null?"null":typeof q,this.target==="draft-4"||this.target==="openapi-3.0")B.enum=[q];else B.const=q}else{if(O.every((q)=>typeof q==="number"))B.type="number";if(O.every((q)=>typeof q==="string"))B.type="string";if(O.every((q)=>typeof q==="boolean"))B.type="string";if(O.every((q)=>q===null))B.type="null";B.enum=O}break}case"file":{let B=L,O={type:"string",format:"binary",contentEncoding:"binary"},{minimum:q,maximum:_,mime:M}=Y._zod.bag;if(q!==void 0)O.minLength=q;if(_!==void 0)O.maxLength=_;if(M)if(M.length===1)O.contentMediaType=M[0],Object.assign(B,O);else B.anyOf=M.map((S)=>{return{...O,contentMediaType:S}});else Object.assign(B,O);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let B=this.process(Q.innerType,V);if(this.target==="openapi-3.0")W.ref=Q.innerType,L.nullable=!0;else L.anyOf=[B,{type:"null"}];break}case"nonoptional":{this.process(Q.innerType,V),W.ref=Q.innerType;break}case"success":{let B=L;B.type="boolean";break}case"default":{this.process(Q.innerType,V),W.ref=Q.innerType,L.default=JSON.parse(JSON.stringify(Q.defaultValue));break}case"prefault":{if(this.process(Q.innerType,V),W.ref=Q.innerType,this.io==="input")L._prefault=JSON.parse(JSON.stringify(Q.defaultValue));break}case"catch":{this.process(Q.innerType,V),W.ref=Q.innerType;let B;try{B=Q.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}L.default=B;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let B=L,O=Y._zod.pattern;if(!O)throw Error("Pattern not found in template literal");B.type="string",B.pattern=O.source;break}case"pipe":{let B=this.io==="input"?Q.in._zod.def.type==="transform"?Q.out:Q.in:Q.out;this.process(B,V),W.ref=B;break}case"readonly":{this.process(Q.innerType,V),W.ref=Q.innerType,L.readOnly=!0;break}case"promise":{this.process(Q.innerType,V),W.ref=Q.innerType;break}case"optional":{this.process(Q.innerType,V),W.ref=Q.innerType;break}case"lazy":{let B=Y._zod.innerType;this.process(B,V),W.ref=B;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"&&C0(Y))delete W.schema.examples,delete W.schema.default;if(this.io==="input"&&W.schema._prefault)(X=W.schema).default??(X.default=W.schema._prefault);return delete W.schema._prefault,this.seen.get(Y).schema}emit(Y,J){let X={cycles:J?.cycles??"ref",reused:J?.reused??"inline",external:J?.external??void 0},Q=this.seen.get(Y);if(!Q)throw Error("Unprocessed schema. This is a bug in Zod.");let G=(H)=>{let V=this.target==="draft-2020-12"?"$defs":"definitions";if(X.external){let O=X.external.registry.get(H[0])?.id,q=X.external.uri??((M)=>M);if(O)return{ref:q(O)};let _=H[1].defId??H[1].schema.id??`schema${this.counter++}`;return H[1].defId=_,{defId:_,ref:`${q("__shared")}#/${V}/${_}`}}if(H[1]===Q)return{ref:"#"};let L=`${"#"}/${V}/`,B=H[1].schema.id??`__schema${this.counter++}`;return{defId:B,ref:L+B}},$=(H)=>{if(H[1].schema.$ref)return;let V=H[1],{ref:D,defId:L}=G(H);if(V.def={...V.schema},L)V.defId=L;let B=V.schema;for(let O in B)delete B[O];B.$ref=D};if(X.cycles==="throw")for(let H of this.seen.entries()){let V=H[1];if(V.cycle)throw Error(`Cycle detected: #/${V.cycle?.join("/")}/<root>
|
|
31
|
+
|
|
32
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let H of this.seen.entries()){let V=H[1];if(Y===H[0]){$(H);continue}if(X.external){let L=X.external.registry.get(H[0])?.id;if(Y!==H[0]&&L){$(H);continue}}if(this.metadataRegistry.get(H[0])?.id){$(H);continue}if(V.cycle){$(H);continue}if(V.count>1){if(X.reused==="ref"){$(H);continue}}}let W=(H,V)=>{let D=this.seen.get(H),L=D.def??D.schema,B={...L};if(D.ref===null)return;let O=D.ref;if(D.ref=null,O){W(O,V);let q=this.seen.get(O).schema;if(q.$ref&&(V.target==="draft-7"||V.target==="draft-4"||V.target==="openapi-3.0"))L.allOf=L.allOf??[],L.allOf.push(q);else Object.assign(L,q),Object.assign(L,B)}if(!D.isParent)this.override({zodSchema:H,jsonSchema:L,path:D.path??[]})};for(let H of[...this.seen.entries()].reverse())W(H[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(X.external?.uri){let H=X.external.registry.get(Y)?.id;if(!H)throw Error("Schema is missing an `id` property");K.$id=X.external.uri(H)}Object.assign(K,Q.def);let U=X.external?.defs??{};for(let H of this.seen.entries()){let V=H[1];if(V.def&&V.defId)U[V.defId]=V.def}if(X.external);else if(Object.keys(U).length>0)if(this.target==="draft-2020-12")K.$defs=U;else K.definitions=U;try{return JSON.parse(JSON.stringify(K))}catch(H){throw Error("Error converting schema to JSON.")}}}function YQ(Y,J){if(Y instanceof _8){let Q=new O4(J),G={};for(let K of Y._idmap.entries()){let[U,H]=K;Q.process(H)}let $={},W={registry:Y,uri:J?.uri,defs:G};for(let K of Y._idmap.entries()){let[U,H]=K;$[U]=Q.emit(H,{...J,external:W})}if(Object.keys(G).length>0){let K=Q.target==="draft-2020-12"?"$defs":"definitions";$.__shared={[K]:G}}return{schemas:$}}let X=new O4(J);return X.process(Y),X.emit(Y,J)}function C0(Y,J){let X=J??{seen:new Set};if(X.seen.has(Y))return!1;X.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 C0(G.element,X);case"object":{for(let $ in G.shape)if(C0(G.shape[$],X))return!0;return!1}case"union":{for(let $ of G.options)if(C0($,X))return!0;return!1}case"intersection":return C0(G.left,X)||C0(G.right,X);case"tuple":{for(let $ of G.items)if(C0($,X))return!0;if(G.rest&&C0(G.rest,X))return!0;return!1}case"record":return C0(G.keyType,X)||C0(G.valueType,X);case"map":return C0(G.keyType,X)||C0(G.valueType,X);case"set":return C0(G.valueType,X);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return C0(G.innerType,X);case"lazy":return C0(G.getter(),X);case"default":return C0(G.innerType,X);case"prefault":return C0(G.innerType,X);case"custom":return!1;case"transform":return!0;case"pipe":return C0(G.in,X)||C0(G.out,X);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${G.type}`)}var AU=P("ZodISODateTime",(Y,J)=>{x7.init(Y,J),D0.init(Y,J)});function JQ(Y){return m5(AU,Y)}var TU=P("ZodISODate",(Y,J)=>{v7.init(Y,J),D0.init(Y,J)});function XQ(Y){return c5(TU,Y)}var RU=P("ZodISOTime",(Y,J)=>{h7.init(Y,J),D0.init(Y,J)});function QQ(Y){return u5(RU,Y)}var CU=P("ZodISODuration",(Y,J)=>{y7.init(Y,J),D0.init(Y,J)});function GQ(Y){return p5(CU,Y)}var $Q=(Y,J)=>{L8.init(Y,J),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(X)=>L2(Y,X)},flatten:{value:(X)=>B2(Y,X)},addIssue:{value:(X)=>{Y.issues.push(X),Y.message=JSON.stringify(Y.issues,b9,2)}},addIssues:{value:(X)=>{Y.issues.push(...X),Y.message=JSON.stringify(Y.issues,b9,2)}},isEmpty:{get(){return Y.issues.length===0}}})},qO=P("ZodError",$Q),r0=P("ZodError",$Q,{Parent:Error});var WQ=N8(r0),zQ=j8(r0),KQ=O1(r0),C8=D1(r0),UQ=F2(r0),HQ=O2(r0),ZQ=D2(r0),VQ=P2(r0),BQ=_2(r0),LQ=q2(r0),NQ=E2(r0),jQ=M2(r0);var P0=P("ZodType",(Y,J)=>{return F0.init(Y,J),Y.def=J,Y.type=J.type,Object.defineProperty(Y,"_def",{value:J}),Y.check=(...X)=>{return Y.clone({...J,checks:[...J.checks??[],...X.map((Q)=>typeof Q==="function"?{_zod:{check:Q,def:{check:"custom"},onattach:[]}}:Q)]})},Y.clone=(X,Q)=>Q6(Y,X,Q),Y.brand=()=>Y,Y.register=(X,Q)=>{return X.add(Y,Q),Y},Y.parse=(X,Q)=>WQ(Y,X,Q,{callee:Y.parse}),Y.safeParse=(X,Q)=>KQ(Y,X,Q),Y.parseAsync=async(X,Q)=>zQ(Y,X,Q,{callee:Y.parseAsync}),Y.safeParseAsync=async(X,Q)=>C8(Y,X,Q),Y.spa=Y.safeParseAsync,Y.encode=(X,Q)=>UQ(Y,X,Q),Y.decode=(X,Q)=>HQ(Y,X,Q),Y.encodeAsync=async(X,Q)=>ZQ(Y,X,Q),Y.decodeAsync=async(X,Q)=>VQ(Y,X,Q),Y.safeEncode=(X,Q)=>BQ(Y,X,Q),Y.safeDecode=(X,Q)=>LQ(Y,X,Q),Y.safeEncodeAsync=async(X,Q)=>NQ(Y,X,Q),Y.safeDecodeAsync=async(X,Q)=>jQ(Y,X,Q),Y.refine=(X,Q)=>Y.check(_H(X,Q)),Y.superRefine=(X)=>Y.check(qH(X)),Y.overwrite=(X)=>Y.check(z9(X)),Y.optional=()=>DQ(Y),Y.nullable=()=>PQ(Y),Y.nullish=()=>DQ(PQ(Y)),Y.nonoptional=(X)=>LH(Y,X),Y.array=()=>_4(Y),Y.or=(X)=>q4([Y,X]),Y.and=(X)=>GH(Y,X),Y.transform=(X)=>_Q(Y,KH(X)),Y.default=(X)=>ZH(Y,X),Y.prefault=(X)=>BH(Y,X),Y.catch=(X)=>jH(Y,X),Y.pipe=(X)=>_Q(Y,X),Y.readonly=()=>DH(Y),Y.describe=(X)=>{let Q=Y.clone();return W9.add(Q,{description:X}),Q},Object.defineProperty(Y,"description",{get(){return W9.get(Y)?.description},configurable:!0}),Y.meta=(...X)=>{if(X.length===0)return W9.get(Y);let Q=Y.clone();return W9.add(Q,X[0]),Q},Y.isOptional=()=>Y.safeParse(void 0).success,Y.isNullable=()=>Y.safeParse(null).success,Y}),qQ=P("_ZodString",(Y,J)=>{P8.init(Y,J),P0.init(Y,J);let X=Y._zod.bag;Y.format=X.format??null,Y.minLength=X.minimum??null,Y.maxLength=X.maximum??null,Y.regex=(...Q)=>Y.check(K4(...Q)),Y.includes=(...Q)=>Y.check(Z4(...Q)),Y.startsWith=(...Q)=>Y.check(V4(...Q)),Y.endsWith=(...Q)=>Y.check(B4(...Q)),Y.min=(...Q)=>Y.check(v9(...Q)),Y.max=(...Q)=>Y.check(A8(...Q)),Y.length=(...Q)=>Y.check(T8(...Q)),Y.nonempty=(...Q)=>Y.check(v9(1,...Q)),Y.lowercase=(Q)=>Y.check(U4(Q)),Y.uppercase=(Q)=>Y.check(H4(Q)),Y.trim=()=>Y.check(N4()),Y.normalize=(...Q)=>Y.check(L4(...Q)),Y.toLowerCase=()=>Y.check(j4()),Y.toUpperCase=()=>Y.check(F4())}),bU=P("ZodString",(Y,J)=>{P8.init(Y,J),qQ.init(Y,J),Y.email=(X)=>Y.check(D5(kU,X)),Y.url=(X)=>Y.check(M5(xU,X)),Y.jwt=(X)=>Y.check(f5(rU,X)),Y.emoji=(X)=>Y.check(A5(vU,X)),Y.guid=(X)=>Y.check(z4(FQ,X)),Y.uuid=(X)=>Y.check(P5(w8,X)),Y.uuidv4=(X)=>Y.check(_5(w8,X)),Y.uuidv6=(X)=>Y.check(q5(w8,X)),Y.uuidv7=(X)=>Y.check(E5(w8,X)),Y.nanoid=(X)=>Y.check(T5(hU,X)),Y.guid=(X)=>Y.check(z4(FQ,X)),Y.cuid=(X)=>Y.check(R5(yU,X)),Y.cuid2=(X)=>Y.check(C5(gU,X)),Y.ulid=(X)=>Y.check(w5(fU,X)),Y.base64=(X)=>Y.check(h5(iU,X)),Y.base64url=(X)=>Y.check(y5(nU,X)),Y.xid=(X)=>Y.check(S5(mU,X)),Y.ksuid=(X)=>Y.check(I5(cU,X)),Y.ipv4=(X)=>Y.check(b5(uU,X)),Y.ipv6=(X)=>Y.check(k5(pU,X)),Y.cidrv4=(X)=>Y.check(x5(lU,X)),Y.cidrv6=(X)=>Y.check(v5(dU,X)),Y.e164=(X)=>Y.check(g5(oU,X)),Y.datetime=(X)=>Y.check(JQ(X)),Y.date=(X)=>Y.check(XQ(X)),Y.time=(X)=>Y.check(QQ(X)),Y.duration=(X)=>Y.check(GQ(X))});function EQ(Y){return O5(bU,Y)}var D0=P("ZodStringFormat",(Y,J)=>{O0.init(Y,J),qQ.init(Y,J)}),kU=P("ZodEmail",(Y,J)=>{A7.init(Y,J),D0.init(Y,J)});var FQ=P("ZodGUID",(Y,J)=>{E7.init(Y,J),D0.init(Y,J)});var w8=P("ZodUUID",(Y,J)=>{M7.init(Y,J),D0.init(Y,J)});var xU=P("ZodURL",(Y,J)=>{T7.init(Y,J),D0.init(Y,J)});var vU=P("ZodEmoji",(Y,J)=>{R7.init(Y,J),D0.init(Y,J)});var hU=P("ZodNanoID",(Y,J)=>{C7.init(Y,J),D0.init(Y,J)});var yU=P("ZodCUID",(Y,J)=>{w7.init(Y,J),D0.init(Y,J)});var gU=P("ZodCUID2",(Y,J)=>{S7.init(Y,J),D0.init(Y,J)});var fU=P("ZodULID",(Y,J)=>{I7.init(Y,J),D0.init(Y,J)});var mU=P("ZodXID",(Y,J)=>{b7.init(Y,J),D0.init(Y,J)});var cU=P("ZodKSUID",(Y,J)=>{k7.init(Y,J),D0.init(Y,J)});var uU=P("ZodIPv4",(Y,J)=>{g7.init(Y,J),D0.init(Y,J)});var pU=P("ZodIPv6",(Y,J)=>{f7.init(Y,J),D0.init(Y,J)});var lU=P("ZodCIDRv4",(Y,J)=>{m7.init(Y,J),D0.init(Y,J)});var dU=P("ZodCIDRv6",(Y,J)=>{c7.init(Y,J),D0.init(Y,J)});var iU=P("ZodBase64",(Y,J)=>{p7.init(Y,J),D0.init(Y,J)});var nU=P("ZodBase64URL",(Y,J)=>{l7.init(Y,J),D0.init(Y,J)});var oU=P("ZodE164",(Y,J)=>{d7.init(Y,J),D0.init(Y,J)});var rU=P("ZodJWT",(Y,J)=>{i7.init(Y,J),D0.init(Y,J)});var MQ=P("ZodNumber",(Y,J)=>{$4.init(Y,J),P0.init(Y,J),Y.gt=(Q,G)=>Y.check(E8(Q,G)),Y.gte=(Q,G)=>Y.check(q1(Q,G)),Y.min=(Q,G)=>Y.check(q1(Q,G)),Y.lt=(Q,G)=>Y.check(q8(Q,G)),Y.lte=(Q,G)=>Y.check(_1(Q,G)),Y.max=(Q,G)=>Y.check(_1(Q,G)),Y.int=(Q)=>Y.check(OQ(Q)),Y.safe=(Q)=>Y.check(OQ(Q)),Y.positive=(Q)=>Y.check(E8(0,Q)),Y.nonnegative=(Q)=>Y.check(q1(0,Q)),Y.negative=(Q)=>Y.check(q8(0,Q)),Y.nonpositive=(Q)=>Y.check(_1(0,Q)),Y.multipleOf=(Q,G)=>Y.check(M8(Q,G)),Y.step=(Q,G)=>Y.check(M8(Q,G)),Y.finite=()=>Y;let X=Y._zod.bag;Y.minValue=Math.max(X.minimum??Number.NEGATIVE_INFINITY,X.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Y.maxValue=Math.min(X.maximum??Number.POSITIVE_INFINITY,X.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Y.isInt=(X.format??"").includes("int")||Number.isSafeInteger(X.multipleOf??0.5),Y.isFinite=!0,Y.format=X.format??null});function AQ(Y){return l5(MQ,Y)}var sU=P("ZodNumberFormat",(Y,J)=>{n7.init(Y,J),MQ.init(Y,J)});function OQ(Y){return d5(sU,Y)}var aU=P("ZodBoolean",(Y,J)=>{o7.init(Y,J),P0.init(Y,J)});function TQ(Y){return i5(aU,Y)}var tU=P("ZodNull",(Y,J)=>{r7.init(Y,J),P0.init(Y,J)});function RQ(Y){return n5(tU,Y)}var eU=P("ZodUnknown",(Y,J)=>{s7.init(Y,J),P0.init(Y,J)});function E1(){return o5(eU)}var YH=P("ZodNever",(Y,J)=>{a7.init(Y,J),P0.init(Y,J)});function P4(Y){return r5(YH,Y)}var JH=P("ZodArray",(Y,J)=>{t7.init(Y,J),P0.init(Y,J),Y.element=J.element,Y.min=(X,Q)=>Y.check(v9(X,Q)),Y.nonempty=(X)=>Y.check(v9(1,X)),Y.max=(X,Q)=>Y.check(A8(X,Q)),Y.length=(X,Q)=>Y.check(T8(X,Q)),Y.unwrap=()=>Y.element});function _4(Y,J){return s5(JH,Y,J)}var CQ=P("ZodObject",(Y,J)=>{J5.init(Y,J),P0.init(Y,J),Q0.defineLazy(Y,"shape",()=>J.shape),Y.keyof=()=>E4(Object.keys(Y._zod.def.shape)),Y.catchall=(X)=>Y.clone({...Y._zod.def,catchall:X}),Y.passthrough=()=>Y.clone({...Y._zod.def,catchall:E1()}),Y.loose=()=>Y.clone({...Y._zod.def,catchall:E1()}),Y.strict=()=>Y.clone({...Y._zod.def,catchall:P4()}),Y.strip=()=>Y.clone({...Y._zod.def,catchall:void 0}),Y.extend=(X)=>{return Q0.extend(Y,X)},Y.safeExtend=(X)=>{return Q0.safeExtend(Y,X)},Y.merge=(X)=>Q0.merge(Y,X),Y.pick=(X)=>Q0.pick(Y,X),Y.omit=(X)=>Q0.omit(Y,X),Y.partial=(...X)=>Q0.partial(vQ,Y,X[0]),Y.required=(...X)=>Q0.required(hQ,Y,X[0])});function wQ(Y,J){let X={type:"object",get shape(){return Q0.assignProp(this,"shape",Y?Q0.objectClone(Y):{}),this.shape},...Q0.normalizeParams(J)};return new CQ(X)}function SQ(Y,J){return new CQ({type:"object",get shape(){return Q0.assignProp(this,"shape",Q0.objectClone(Y)),this.shape},catchall:E1(),...Q0.normalizeParams(J)})}var IQ=P("ZodUnion",(Y,J)=>{W4.init(Y,J),P0.init(Y,J),Y.options=J.options});function q4(Y,J){return new IQ({type:"union",options:Y,...Q0.normalizeParams(J)})}var XH=P("ZodDiscriminatedUnion",(Y,J)=>{IQ.init(Y,J),X5.init(Y,J)});function bQ(Y,J,X){return new XH({type:"union",options:J,discriminator:Y,...Q0.normalizeParams(X)})}var QH=P("ZodIntersection",(Y,J)=>{Q5.init(Y,J),P0.init(Y,J)});function GH(Y,J){return new QH({type:"intersection",left:Y,right:J})}var $H=P("ZodRecord",(Y,J)=>{G5.init(Y,J),P0.init(Y,J),Y.keyType=J.keyType,Y.valueType=J.valueType});function kQ(Y,J,X){return new $H({type:"record",keyType:Y,valueType:J,...Q0.normalizeParams(X)})}var D4=P("ZodEnum",(Y,J)=>{$5.init(Y,J),P0.init(Y,J),Y.enum=J.entries,Y.options=Object.values(J.entries);let X=new Set(Object.keys(J.entries));Y.extract=(Q,G)=>{let $={};for(let W of Q)if(X.has(W))$[W]=J.entries[W];else throw Error(`Key ${W} not found in enum`);return new D4({...J,checks:[],...Q0.normalizeParams(G),entries:$})},Y.exclude=(Q,G)=>{let $={...J.entries};for(let W of Q)if(X.has(W))delete $[W];else throw Error(`Key ${W} not found in enum`);return new D4({...J,checks:[],...Q0.normalizeParams(G),entries:$})}});function E4(Y,J){let X=Array.isArray(Y)?Object.fromEntries(Y.map((Q)=>[Q,Q])):Y;return new D4({type:"enum",entries:X,...Q0.normalizeParams(J)})}var WH=P("ZodLiteral",(Y,J)=>{W5.init(Y,J),P0.init(Y,J),Y.values=new Set(J.values),Object.defineProperty(Y,"value",{get(){if(J.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return J.values[0]}})});function xQ(Y,J){return new WH({type:"literal",values:Array.isArray(Y)?Y:[Y],...Q0.normalizeParams(J)})}var zH=P("ZodTransform",(Y,J)=>{z5.init(Y,J),P0.init(Y,J),Y._zod.parse=(X,Q)=>{if(Q.direction==="backward")throw new V1(Y.constructor.name);X.addIssue=($)=>{if(typeof $==="string")X.issues.push(Q0.issue($,X.value,J));else{let W=$;if(W.fatal)W.continue=!1;W.code??(W.code="custom"),W.input??(W.input=X.value),W.inst??(W.inst=Y),X.issues.push(Q0.issue(W))}};let G=J.transform(X.value,X);if(G instanceof Promise)return G.then(($)=>{return X.value=$,X});return X.value=G,X}});function KH(Y){return new zH({type:"transform",transform:Y})}var vQ=P("ZodOptional",(Y,J)=>{K5.init(Y,J),P0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType});function DQ(Y){return new vQ({type:"optional",innerType:Y})}var UH=P("ZodNullable",(Y,J)=>{U5.init(Y,J),P0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType});function PQ(Y){return new UH({type:"nullable",innerType:Y})}var HH=P("ZodDefault",(Y,J)=>{H5.init(Y,J),P0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function ZH(Y,J){return new HH({type:"default",innerType:Y,get defaultValue(){return typeof J==="function"?J():Q0.shallowClone(J)}})}var VH=P("ZodPrefault",(Y,J)=>{Z5.init(Y,J),P0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType});function BH(Y,J){return new VH({type:"prefault",innerType:Y,get defaultValue(){return typeof J==="function"?J():Q0.shallowClone(J)}})}var hQ=P("ZodNonOptional",(Y,J)=>{V5.init(Y,J),P0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType});function LH(Y,J){return new hQ({type:"nonoptional",innerType:Y,...Q0.normalizeParams(J)})}var NH=P("ZodCatch",(Y,J)=>{B5.init(Y,J),P0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function jH(Y,J){return new NH({type:"catch",innerType:Y,catchValue:typeof J==="function"?J:()=>J})}var FH=P("ZodPipe",(Y,J)=>{L5.init(Y,J),P0.init(Y,J),Y.in=J.in,Y.out=J.out});function _Q(Y,J){return new FH({type:"pipe",in:Y,out:J})}var OH=P("ZodReadonly",(Y,J)=>{N5.init(Y,J),P0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType});function DH(Y){return new OH({type:"readonly",innerType:Y})}var PH=P("ZodLazy",(Y,J)=>{j5.init(Y,J),P0.init(Y,J),Y.unwrap=()=>Y._zod.def.getter()});function yQ(Y){return new PH({type:"lazy",getter:Y})}var M4=P("ZodCustom",(Y,J)=>{F5.init(Y,J),P0.init(Y,J)});function gQ(Y,J){return a5(M4,Y??(()=>!0),J)}function _H(Y,J={}){return t5(M4,Y,J)}function qH(Y){return e5(Y)}function fQ(Y,J={error:`Input not instance of ${Y.name}`}){let X=new M4({type:"custom",check:"custom",fn:(Q)=>Q instanceof Y,abort:!0,...Q0.normalizeParams(J)});return X._zod.bag.Class=Y,X}function rQ(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 sQ(Y){if(Y==null)return{};let J={};if(Y instanceof Headers)Y.forEach((X,Q)=>{J[Q.toLowerCase()]=X});else{if(!Array.isArray(Y))Y=Object.entries(Y);for(let[X,Q]of Y)if(Q!=null)J[X.toLowerCase()]=Q}return J}function aQ(Y,...J){let X=new Headers(sQ(Y)),Q=X.get("user-agent")||"";return X.set("user-agent",[Q,...J].filter(Boolean).join(" ")),Object.fromEntries(X.entries())}var TH=[{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]}],BD=[...TH,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];async function S8(Y){try{await Y.body?.cancel()}catch{}}var tQ="AI_DownloadError",eQ=`vercel.ai.error.${tQ}`,RH=Symbol.for(eQ),h0=class extends R6{constructor({url:Y,statusCode:J,statusText:X,cause:Q,message:G=Q==null?`Failed to download ${Y}: ${J} ${X}`:`Failed to download ${Y}: ${Q}`}){super({name:tQ,message:G,cause:Q});this[RH]=!0,this.url=Y,this.statusCode=J,this.statusText=X}static isInstance(Y){return R6.hasMarker(Y,eQ)}};function CH(Y=globalThis){return Y.window!=null}function R4(Y,J){try{return new URL(Y).origin===new URL(J).origin}catch{return!1}}function wH(Y){let J;try{J=new URL(Y)}catch{throw new h0({url:Y,message:`Invalid URL: ${Y}`})}if(J.protocol==="data:")return;if(J.protocol!=="http:"&&J.protocol!=="https:")throw new h0({url:Y,message:`URL scheme must be http, https, or data, got ${J.protocol}`});let X=J.hostname.toLowerCase().replace(/\.+$/,"");if(!X)throw new h0({url:Y,message:"URL must have a hostname"});if(X==="localhost"||X.endsWith(".local")||X.endsWith(".localhost"))throw new h0({url:Y,message:`URL with hostname ${X} is not allowed`});if(X.startsWith("[")&&X.endsWith("]")){if(YG(X.slice(1,-1)))throw new h0({url:Y,message:`URL with IPv6 address ${X} is not allowed`});return}if(w4(X)){if(S4(X))throw new h0({url:Y,message:`URL with IP address ${X} is not allowed`})}}function SH({address:Y,family:J,hostname:X}){if(J===4?!w4(Y)||S4(Y):J===6?YG(Y):!0)throw new h0({url:X,message:`Hostname ${X} resolved to disallowed IP address ${Y}`})}function w4(Y){let J=Y.split(".");if(J.length!==4)return!1;return J.every((X)=>{let Q=Number(X);return Number.isInteger(Q)&&Q>=0&&Q<=255&&String(Q)===X})}function S4(Y){let[J,X,Q]=Y.split(".").map(Number);if(J===0)return!0;if(J===10)return!0;if(J===100&&X>=64&&X<=127)return!0;if(J===127)return!0;if(J===169&&X===254)return!0;if(J===172&&X>=16&&X<=31)return!0;if(J===192&&X===0&&Q===0)return!0;if(J===192&&X===0&&Q===2)return!0;if(J===192&&X===168)return!0;if(J===198&&(X===18||X===19))return!0;if(J===198&&X===51&&Q===100)return!0;if(J===203&&X===0&&Q===113)return!0;if(J>=224)return!0;return!1}function IH(Y){let J=Y.toLowerCase(),X=J.indexOf("%");if(X!==-1)J=J.slice(0,X);let Q=J.split("::");if(Q.length>2)return null;let G=(W)=>{if(W==="")return[];let K=[],U=W.split(":");for(let H=0;H<U.length;H++){let V=U[H];if(V.includes(".")){if(H!==U.length-1||!w4(V))return null;let[D,L,B,O]=V.split(".").map(Number);K.push(D<<8|L,B<<8|O);continue}if(!/^[0-9a-f]{1,4}$/.test(V))return null;K.push(parseInt(V,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 YG(Y){let J=IH(Y);if(J===null)return!0;let X=(Q)=>J.slice(0,Q).every((G)=>G===0);if(X(7)&&(J[7]===0||J[7]===1))return!0;if((J[0]&65024)===64512)return!0;if((J[0]&65472)===65152)return!0;if((J[0]&65472)===65216)return!0;if((J[0]&65280)===65280)return!0;if(J[0]===8193&&J[1]===3512)return!0;if(J[0]===16383&&(J[1]&61440)===0)return!0;if(X(6)||X(5)&&J[5]===65535||X(4)&&J[4]===65535&&J[5]===0||J[0]===100&&J[1]===65435&&J[2]===0&&J[3]===0&&J[4]===0&&J[5]===0||J[0]===100&&J[1]===65435&&J[2]===1)return S4(`${J[6]>>8&255}.${J[6]&255}.${J[7]>>8&255}.${J[7]&255}`);return!1}function bH(Y){return(J,X,Q)=>{Y(J,{...X,all:!0},(G,$)=>{if(G){Q(G);return}try{let[W]=$;if(W==null)throw Error(`Hostname ${J} did not resolve to an address`);for(let{address:K,family:U}of $)SH({address:K,family:U,hostname:J});if(X.all===!0)Q(null,$);else Q(null,W.address,W.family)}catch(W){Q(W instanceof Error?W:Error(String(W)))}})}}var kH;function xH(){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 vH(){if(!xH())return globalThis.fetch;return kH??=Promise.resolve().then(hH)}function hH(){let Y=mQ("node:module"),{lookup:J}=mQ("node:dns"),{Agent:X,fetch:Q}=Y.createRequire(JG())("undici"),G=new X({connect:{lookup:bH(J)}});return($,W)=>Q($,{...W,dispatcher:G})}function mQ(Y){let J=globalThis.process?.getBuiltinModule?.(Y);if(J==null)throw Error(`Node.js built-in module ${Y} is unavailable`);return J}function JG(){let Y=Error.prepareStackTrace;try{Error.prepareStackTrace=(G,$)=>$;let J=Error("Capture current module path");Error.captureStackTrace(J,JG);let[X]=J.stack,Q=X?.getFileName();if(Q==null)throw Error("Unable to determine the current module path");return Q}finally{Error.prepareStackTrace=Y}}var yH=["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 J=new Headers(Y);for(let X of yH)J.delete(X);return J}var gH=10,fH=new Set([301,302,303,307,308]);async function mH(Y){return Y==null||Y===globalThis.fetch?await vH():Y}async function cH({url:Y,headers:J,abortSignal:X,maxRedirects:Q=gH,fetch:G,trustedOrigin:$}){let W=J===void 0?void 0:XG(J),K=(H)=>{let V={signal:X,redirect:H};if(W!==void 0)V.headers=new Headers(W);return V},U=Y;for(let H=0;H<=Q;H++){let V=$!==void 0&&R4(U,$);if(!V)wH(U);let D=V&&G!=null?G:V?globalThis.fetch:await mH(G),L=await D(U,K("manual"));if(L.type==="opaqueredirect"){if(!CH())throw new h0({url:Y,message:`Redirect from ${U} could not be validated and was blocked`});return await D(U,K("follow"))}let B=L.headers?.get("location");if(fH.has(L.status)&&B){S8(L);let O=new URL(B,U).toString();if(W!==void 0&&!R4(O,U)){let q=W.get("user-agent");W=new Headers(q==null?void 0:{"user-agent":q})}U=O;continue}return L}throw new h0({url:Y,message:`Too many redirects (max ${Q})`})}var uH=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 QG({headers:Y,credentialedOrigin:J,untrustedFirstHopHeaders:X,...Q}){let G;if(Y!==void 0){G=XG(Y);let $=J??Q.trustedOrigin;if($===void 0||!R4(Q.url,$)){let W=new Set([...uH,...(X??[]).map((K)=>K.toLowerCase())]);G=new Headers([...G].filter(([K])=>W.has(K)))}}return cH({...Q,headers:G})}var I4=2147483648;async function GG({response:Y,url:J,maxBytes:X=I4}){let Q=Y.headers.get("content-length");if(Q!=null){let V=parseInt(Q,10);if(!isNaN(V)&&V>X)throw await S8(Y),new h0({url:J,message:`Download of ${J} exceeded maximum size of ${X} bytes (Content-Length: ${V}).`})}let G=Y.body;if(G==null)return new Uint8Array(0);let $=G.getReader(),W=[],K=0;try{while(!0){let{done:V,value:D}=await $.read();if(V)break;if(K+=D.length,K>X)throw new h0({url:J,message:`Download of ${J} exceeded maximum size of ${X} bytes.`});W.push(D)}}finally{try{await $.cancel()}catch{}finally{$.releaseLock()}}let U=new Uint8Array(K),H=0;for(let V of W)U.set(V,H),H+=V.length;return U}var I0=({prefix:Y,size:J=16,alphabet:X="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:Q="-"}={})=>{let G=()=>{let $=X.length,W=Array(J);for(let K=0;K<J;K++)W[K]=X[Math.random()*$|0];return W.join("")};if(Y==null)return G;if(X.includes(Q))throw new lY({argument:"separator",message:`The separator "${Q}" must not be part of the alphabet "${X}".`});return()=>`${Y}${Q}${G()}`},$G=I0();function WG(Y){return globalThis.Buffer?.isBuffer(Y)??!1}function zG(Y){if(Y.type==="object"||Array.isArray(Y.type)&&Y.type.includes("object")){let{additionalProperties:X}=Y;Y.additionalProperties=X!=null&&typeof X!=="boolean"?p6(X):!1;let{properties:Q}=Y;if(Q!=null)for(let G of Object.keys(Q))Q[G]=p6(Q[G])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(p6):p6(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(p6);if(Y.allOf!=null)Y.allOf=Y.allOf.map(p6);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(p6);let{definitions:J}=Y;if(J!=null)for(let X of Object.keys(J))J[X]=p6(J[X]);return Y}function p6(Y){if(typeof Y==="boolean")return Y;return zG(Y)}var pH=Symbol("Let zodToJsonSchema decide on which parser to use"),cQ={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"},lH=(Y)=>typeof Y==="string"?{...cQ,name:Y}:{...cQ,...Y};function s0(){return{}}function dH(Y,J){let X={type:"array"};if(Y.type?._def&&Y.type?._def?.typeName!=="ZodAny")X.items=H0(Y.type._def,{...J,currentPath:[...J.currentPath,"items"]});if(Y.minLength)X.minItems=Y.minLength.value;if(Y.maxLength)X.maxItems=Y.maxLength.value;if(Y.exactLength)X.minItems=Y.exactLength.value,X.maxItems=Y.exactLength.value;return X}function iH(Y){let J={type:"integer",format:"int64"};if(!Y.checks)return J;for(let X of Y.checks)switch(X.kind){case"min":if(X.inclusive)J.minimum=X.value;else J.exclusiveMinimum=X.value;break;case"max":if(X.inclusive)J.maximum=X.value;else J.exclusiveMaximum=X.value;break;case"multipleOf":J.multipleOf=X.value}return J}function nH(){return{type:"boolean"}}function KG(Y,J){return H0(Y.type._def,J)}var oH=(Y,J)=>{return H0(Y.innerType._def,J)};function UG(Y,J,X){let Q=X??J.dateStrategy;if(Array.isArray(Q))return{anyOf:Q.map((G)=>UG(Y,J,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 rH(Y)}}var rH=(Y)=>{let J={type:"integer",format:"unix-time"};for(let X of Y.checks)switch(X.kind){case"min":J.minimum=X.value;break;case"max":J.maximum=X.value}return J};function sH(Y,J){return{...H0(Y.innerType._def,J),default:Y.defaultValue()}}function aH(Y,J){return J.effectStrategy==="input"?H0(Y.schema._def,J):s0()}function tH(Y){return{type:"string",enum:Array.from(Y.values)}}var eH=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function YZ(Y,J){let X=[H0(Y.left._def,{...J,currentPath:[...J.currentPath,"allOf","0"]}),H0(Y.right._def,{...J,currentPath:[...J.currentPath,"allOf","1"]})].filter((G)=>!!G),Q=[];return X.forEach((G)=>{if(eH(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 JZ(Y){let J=typeof Y.value;if(J!=="bigint"&&J!=="number"&&J!=="boolean"&&J!=="string")return{type:Array.isArray(Y.value)?"array":"object"};return{type:J==="bigint"?"integer":J,const:Y.value}}var A4=void 0,$6={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(A4===void 0)A4=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return A4},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 HG(Y,J){let X={type:"string"};if(Y.checks)for(let Q of Y.checks)switch(Q.kind){case"min":X.minLength=typeof X.minLength==="number"?Math.max(X.minLength,Q.value):Q.value;break;case"max":X.maxLength=typeof X.maxLength==="number"?Math.min(X.maxLength,Q.value):Q.value;break;case"email":switch(J.emailStrategy){case"format:email":W6(X,"email",Q.message,J);break;case"format:idn-email":W6(X,"idn-email",Q.message,J);break;case"pattern:zod":c0(X,$6.email,Q.message,J)}break;case"url":W6(X,"uri",Q.message,J);break;case"uuid":W6(X,"uuid",Q.message,J);break;case"regex":c0(X,Q.regex,Q.message,J);break;case"cuid":c0(X,$6.cuid,Q.message,J);break;case"cuid2":c0(X,$6.cuid2,Q.message,J);break;case"startsWith":c0(X,RegExp(`^${T4(Q.value,J)}`),Q.message,J);break;case"endsWith":c0(X,RegExp(`${T4(Q.value,J)}$`),Q.message,J);break;case"datetime":W6(X,"date-time",Q.message,J);break;case"date":W6(X,"date",Q.message,J);break;case"time":W6(X,"time",Q.message,J);break;case"duration":W6(X,"duration",Q.message,J);break;case"length":X.minLength=typeof X.minLength==="number"?Math.max(X.minLength,Q.value):Q.value,X.maxLength=typeof X.maxLength==="number"?Math.min(X.maxLength,Q.value):Q.value;break;case"includes":c0(X,RegExp(T4(Q.value,J)),Q.message,J);break;case"ip":if(Q.version!=="v6")W6(X,"ipv4",Q.message,J);if(Q.version!=="v4")W6(X,"ipv6",Q.message,J);break;case"base64url":c0(X,$6.base64url,Q.message,J);break;case"jwt":c0(X,$6.jwt,Q.message,J);break;case"cidr":if(Q.version!=="v6")c0(X,$6.ipv4Cidr,Q.message,J);if(Q.version!=="v4")c0(X,$6.ipv6Cidr,Q.message,J);break;case"emoji":c0(X,$6.emoji(),Q.message,J);break;case"ulid":c0(X,$6.ulid,Q.message,J);break;case"base64":switch(J.base64Strategy){case"format:binary":W6(X,"binary",Q.message,J);break;case"contentEncoding:base64":X.contentEncoding="base64";break;case"pattern:zod":c0(X,$6.base64,Q.message,J)}break;case"nanoid":c0(X,$6.nanoid,Q.message,J)}return X}function T4(Y,J){return J.patternStrategy==="escape"?QZ(Y):Y}var XZ=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function QZ(Y){let J="";for(let X=0;X<Y.length;X++){if(!XZ.has(Y[X]))J+="\\";J+=Y[X]}return J}function W6(Y,J,X,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:J,...X&&Q.errorMessages&&{errorMessage:{format:X}}})}else Y.format=J}function c0(Y,J,X,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:uQ(J,Q),...X&&Q.errorMessages&&{errorMessage:{pattern:X}}})}else Y.pattern=uQ(J,Q)}function uQ(Y,J){if(!J.applyRegexFlags||!Y.flags)return Y.source;let X={i:Y.flags.includes("i"),m:Y.flags.includes("m"),s:Y.flags.includes("s")},Q=X.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(X.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(X.m){if(Q[U]==="^"){G+=`(^|(?<=[\r
|
|
33
|
+
]))`;continue}else if(Q[U]==="$"){G+=`($|(?=[\r
|
|
34
|
+
]))`;continue}}if(X.s&&Q[U]==="."){G+=W?`${Q[U]}\r
|
|
35
|
+
`:`[${Q[U]}\r
|
|
36
|
+
]`;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 ${J.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Y.source}return G}function ZG(Y,J){let X={type:"object",additionalProperties:H0(Y.valueType._def,{...J,currentPath:[...J.currentPath,"additionalProperties"]})??J.allowedAdditionalProperties};if(Y.keyType?._def.typeName==="ZodString"&&Y.keyType._def.checks?.length){let{type:Q,...G}=HG(Y.keyType._def,J);return{...X,propertyNames:G}}else if(Y.keyType?._def.typeName==="ZodEnum")return{...X,propertyNames:{enum:Y.keyType._def.values}};else if(Y.keyType?._def.typeName==="ZodBranded"&&Y.keyType._def.type._def.typeName==="ZodString"&&Y.keyType._def.type._def.checks?.length){let{type:Q,...G}=KG(Y.keyType._def,J);return{...X,propertyNames:G}}return X}function GZ(Y,J){if(J.mapStrategy==="record")return ZG(Y,J);return{type:"array",maxItems:125,items:{type:"array",items:[H0(Y.keyType._def,{...J,currentPath:[...J.currentPath,"items","items","0"]})||s0(),H0(Y.valueType._def,{...J,currentPath:[...J.currentPath,"items","items","1"]})||s0()],minItems:2,maxItems:2}}}function $Z(Y){let J=Y.values,X=Object.keys(Y.values).filter((G)=>{return typeof J[J[G]]!=="number"}).map((G)=>J[G]),Q=Array.from(new Set(X.map((G)=>typeof G)));return{type:Q.length===1?Q[0]==="string"?"string":"number":["string","number"],enum:X}}function WZ(){return{not:s0()}}function zZ(){return{type:"null"}}var C4={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function KZ(Y,J){let X=Y.options instanceof Map?Array.from(Y.options.values()):Y.options;if(X.every((Q)=>(Q._def.typeName in C4)&&(!Q._def.checks||!Q._def.checks.length))){let Q=X.reduce((G,$)=>{let W=C4[$._def.typeName];return W&&!G.includes(W)?[...G,W]:G},[]);return{type:Q.length>1?Q:Q[0]}}else if(X.every((Q)=>Q._def.typeName==="ZodLiteral"&&!Q.description)){let Q=X.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===X.length){let G=Q.filter(($,W,K)=>K.indexOf($)===W);return{type:G.length>1?G:G[0],enum:X.reduce(($,W)=>{return $.includes(W._def.value)?$:[...$,W._def.value]},[])}}}else if(X.every((Q)=>Q._def.typeName==="ZodEnum"))return{type:"string",enum:X.reduce((Q,G)=>[...Q,...G._def.values.filter(($)=>!Q.includes($))],[])};return UZ(Y,J)}var UZ=(Y,J)=>{let X=(Y.options instanceof Map?Array.from(Y.options.values()):Y.options).map((Q,G)=>H0(Q._def,{...J,currentPath:[...J.currentPath,"anyOf",`${G}`]})).filter((Q)=>!!Q&&(!J.strictUnions||typeof Q==="object"&&Object.keys(Q).length>0));return X.length?{anyOf:X}:void 0};function HZ(Y,J){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Y.innerType._def.typeName)&&(!Y.innerType._def.checks||!Y.innerType._def.checks.length))return{type:[C4[Y.innerType._def.typeName],"null"]};let X=H0(Y.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","0"]});return X&&{anyOf:[X,{type:"null"}]}}function ZZ(Y){let J={type:"number"};if(!Y.checks)return J;for(let X of Y.checks)switch(X.kind){case"int":J.type="integer";break;case"min":if(X.inclusive)J.minimum=X.value;else J.exclusiveMinimum=X.value;break;case"max":if(X.inclusive)J.maximum=X.value;else J.exclusiveMaximum=X.value;break;case"multipleOf":J.multipleOf=X.value}return J}function VZ(Y,J){let X={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=LZ(K),H=H0(K._def,{...J,currentPath:[...J.currentPath,"properties",W],propertyPath:[...J.currentPath,"properties",W]});if(H===void 0)continue;if(X.properties[W]=H,!U)Q.push(W)}if(Q.length)X.required=Q;let $=BZ(Y,J);if($!==void 0)X.additionalProperties=$;return X}function BZ(Y,J){if(Y.catchall._def.typeName!=="ZodNever")return H0(Y.catchall._def,{...J,currentPath:[...J.currentPath,"additionalProperties"]});switch(Y.unknownKeys){case"passthrough":return J.allowedAdditionalProperties;case"strict":return J.rejectedAdditionalProperties;case"strip":return J.removeAdditionalStrategy==="strict"?J.allowedAdditionalProperties:J.rejectedAdditionalProperties}}function LZ(Y){try{return Y.isOptional()}catch{return!0}}var NZ=(Y,J)=>{if(J.currentPath.toString()===J.propertyPath?.toString())return H0(Y.innerType._def,J);let X=H0(Y.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","1"]});return X?{anyOf:[{not:s0()},X]}:s0()},jZ=(Y,J)=>{if(J.pipeStrategy==="input")return H0(Y.in._def,J);else if(J.pipeStrategy==="output")return H0(Y.out._def,J);let X=H0(Y.in._def,{...J,currentPath:[...J.currentPath,"allOf","0"]});return{allOf:[X,H0(Y.out._def,{...J,currentPath:[...J.currentPath,"allOf",X?"1":"0"]})].filter((Q)=>Q!==void 0)}};function FZ(Y,J){return H0(Y.type._def,J)}function OZ(Y,J){let X={type:"array",uniqueItems:!0,items:H0(Y.valueType._def,{...J,currentPath:[...J.currentPath,"items"]})};if(Y.minSize)X.minItems=Y.minSize.value;if(Y.maxSize)X.maxItems=Y.maxSize.value;return X}function DZ(Y,J){if(Y.rest)return{type:"array",minItems:Y.items.length,items:Y.items.map((X,Q)=>H0(X._def,{...J,currentPath:[...J.currentPath,"items",`${Q}`]})).reduce((X,Q)=>Q===void 0?X:[...X,Q],[]),additionalItems:H0(Y.rest._def,{...J,currentPath:[...J.currentPath,"additionalItems"]})};else return{type:"array",minItems:Y.items.length,maxItems:Y.items.length,items:Y.items.map((X,Q)=>H0(X._def,{...J,currentPath:[...J.currentPath,"items",`${Q}`]})).reduce((X,Q)=>Q===void 0?X:[...X,Q],[])}}function PZ(){return{not:s0()}}function _Z(){return s0()}var qZ=(Y,J)=>{return H0(Y.innerType._def,J)},EZ=(Y,J,X)=>{switch(J){case"ZodString":return HG(Y,X);case"ZodNumber":return ZZ(Y);case"ZodObject":return VZ(Y,X);case"ZodBigInt":return iH(Y);case"ZodBoolean":return nH();case"ZodDate":return UG(Y,X);case"ZodUndefined":return PZ();case"ZodNull":return zZ();case"ZodArray":return dH(Y,X);case"ZodUnion":case"ZodDiscriminatedUnion":return KZ(Y,X);case"ZodIntersection":return YZ(Y,X);case"ZodTuple":return DZ(Y,X);case"ZodRecord":return ZG(Y,X);case"ZodLiteral":return JZ(Y);case"ZodEnum":return tH(Y);case"ZodNativeEnum":return $Z(Y);case"ZodNullable":return HZ(Y,X);case"ZodOptional":return NZ(Y,X);case"ZodMap":return GZ(Y,X);case"ZodSet":return OZ(Y,X);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return FZ(Y,X);case"ZodNaN":case"ZodNever":return WZ();case"ZodEffects":return aH(Y,X);case"ZodAny":return s0();case"ZodUnknown":return _Z();case"ZodDefault":return sH(Y,X);case"ZodBranded":return KG(Y,X);case"ZodReadonly":return qZ(Y,X);case"ZodCatch":return oH(Y,X);case"ZodPipeline":return jZ(Y,X);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Q)=>{return})(J)}},MZ=(Y,J)=>{let X=0;for(;X<Y.length&&X<J.length;X++)if(Y[X]!==J[X])break;return[(Y.length-X).toString(),...J.slice(X)].join("/")};function H0(Y,J,X=!1){let Q=J.seen.get(Y);if(J.override){let K=J.override?.(Y,J,Q,X);if(K!==pH)return K}if(Q&&!X){let K=AZ(Q,J);if(K!==void 0)return K}let G={def:Y,path:J.currentPath,jsonSchema:void 0};J.seen.set(Y,G);let $=EZ(Y,Y.typeName,J),W=typeof $==="function"?H0($(),J):$;if(W)TZ(Y,J,W);if(J.postProcess){let K=J.postProcess(W,Y,J);return G.jsonSchema=W,K}return G.jsonSchema=W,W}var AZ=(Y,J)=>{switch(J.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:MZ(J.currentPath,Y.path)};case"none":case"seen":if(Y.path.length<J.currentPath.length&&Y.path.every((X,Q)=>J.currentPath[Q]===X))return console.warn(`Recursive reference detected at ${J.currentPath.join("/")}! Defaulting to any`),s0();return J.$refStrategy==="seen"?s0():void 0}},TZ=(Y,J,X)=>{if(Y.description)X.description=Y.description;return X},RZ=(Y)=>{let J=lH(Y),X=J.name!==void 0?[...J.basePath,J.definitionPath,J.name]:J.basePath;return{...J,currentPath:X,propertyPath:void 0,seen:new Map(Object.entries(J.definitions).map(([Q,G])=>[G._def,{def:G._def,path:[...J.basePath,J.definitionPath,Q],jsonSchema:void 0}]))}},CZ=(Y,J)=>{let X=RZ(J),Q=typeof J==="object"&&J.definitions?Object.entries(J.definitions).reduce((U,[H,V])=>({...U,[H]:H0(V._def,{...X,currentPath:[...X.basePath,X.definitionPath,H]},!0)??s0()}),{}):void 0,G=typeof J==="string"?J:J?.nameStrategy==="title"?void 0:J?.name,$=H0(Y._def,G===void 0?X:{...X,currentPath:[...X.basePath,X.definitionPath,G]},!1)??s0(),W=typeof J==="object"&&J.name!==void 0&&J.nameStrategy==="title"?J.name:void 0;if(W!==void 0)$.title=W;let K=G===void 0?Q?{...$,[X.definitionPath]:Q}:$:{$ref:[...X.$refStrategy==="relative"?[]:X.basePath,X.definitionPath,G].join("/"),[X.definitionPath]:{...Q,[G]:$}};return K.$schema="http://json-schema.org/draft-07/schema#",K},wZ=Symbol.for("vercel.ai.schema");function b4(Y){let J;return()=>{if(J==null)J=Y();return J}}function I8(Y,{validate:J}={}){return{[wZ]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:J}}function SZ(Y,J){let X=J?.useReferences??!1;return I8(()=>CZ(Y,{$refStrategy:X?"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 IZ(Y,J){let X=J?.useReferences??!1;return I8(()=>zG(YQ(Y,{target:"draft-7",io:"input",reused:X?"ref":"inline"})),{validate:async(Q)=>{let G=await C8(Y,Q);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function bZ(Y){return"_zod"in Y}function b8(Y,J){if(bZ(Y))return IZ(Y,J);else return SZ(Y,J)}var kZ="AI_SerializationError",LD=`vercel.ai.error.${kZ}`;var cZ="AI_InvalidArgumentError",eD=`vercel.ai.error.${cZ}`;var uZ="AI_InvalidStreamPartError",YP=`vercel.ai.error.${uZ}`;var pZ="AI_InvalidToolApprovalError",JP=`vercel.ai.error.${pZ}`;var lZ="AI_InvalidToolApprovalSignatureError",XP=`vercel.ai.error.${lZ}`;var dZ="AI_InvalidToolInputError",QP=`vercel.ai.error.${dZ}`;var iZ="AI_ToolCallNotFoundForApprovalError",GP=`vercel.ai.error.${iZ}`;var nZ="AI_MissingToolResultsError",$P=`vercel.ai.error.${nZ}`;var oZ="AI_NoImageGeneratedError",WP=`vercel.ai.error.${oZ}`;var rZ="AI_NoObjectGeneratedError",zP=`vercel.ai.error.${rZ}`;var sZ="AI_NoOutputGeneratedError",KP=`vercel.ai.error.${sZ}`;var aZ="AI_NoSpeechGeneratedError",UP=`vercel.ai.error.${aZ}`;var tZ="AI_NoTranscriptGeneratedError",HP=`vercel.ai.error.${tZ}`;var eZ="AI_NoTranslationGeneratedError",ZP=`vercel.ai.error.${eZ}`;var YV="AI_NoVideoGeneratedError",VP=`vercel.ai.error.${YV}`;var JV="AI_NoSuchToolError",BP=`vercel.ai.error.${JV}`;var XV="AI_StreamProviderError",LP=`vercel.ai.error.${XV}`;var QV="AI_ToolCallRepairError",NP=`vercel.ai.error.${QV}`;var GV="AI_ToolChoiceViolationError",jP=`vercel.ai.error.${GV}`;var $V="AI_UIMessageStreamError",FP=`vercel.ai.error.${$V}`;var WV="AI_InvalidDataContentError",OP=`vercel.ai.error.${WV}`;var zV="AI_InvalidMessageRoleError",DP=`vercel.ai.error.${zV}`;var KV="AI_MessageConversionError",PP=`vercel.ai.error.${KV}`;var UV="AI_RetryError",_P=`vercel.ai.error.${UV}`;var HV="7.0.140",ZV=async({url:Y,maxBytes:J,abortSignal:X})=>{let Q=Y.toString();try{let G=aQ({},`ai-sdk/${HV}`,rQ()),$=await QG({url:Q,headers:G,abortSignal:X});if(!$.ok)throw await S8($),new h0({url:Q,statusCode:$.status,statusText:$.statusText});return{data:await GG({response:$,url:Q,maxBytes:J??I4}),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:TQ,custom:gQ,discriminatedUnion:bQ,enum:E4,instanceof:fQ,lazy:yQ,literal:xQ,looseObject:SQ,never:P4,null:RQ,number:AQ,object:wQ,record:kQ,string:EQ,union:q4,unknown:E1},K9=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),K9.optional()),z.array(K9)])),k=z.record(z.string(),z.record(z.string(),K9.optional())),A1=z.union([z.string(),z.instanceof(Uint8Array),z.instanceof(ArrayBuffer),z.custom(WG,{message:"Must be a Buffer"})]),k4=z.record(z.string(),z.string()),VG=z.object({type:z.literal("text"),text:z.string(),providerOptions:k.optional()}),VV=z.object({type:z.literal("image"),image:z.union([A1,z.instanceof(URL),k4]),mediaType:z.string().optional(),providerOptions:k.optional()}),BG=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:A1}),z.object({type:z.literal("url"),url:z.instanceof(URL)}),z.object({type:z.literal("reference"),reference:k4}),z.object({type:z.literal("text"),text:z.string()})]),BV=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:A1}),z.object({type:z.literal("url"),url:z.instanceof(URL)})]),LG=z.object({type:z.literal("file"),data:z.union([BG,A1,z.instanceof(URL),k4]),filename:z.string().optional(),mediaType:z.string(),providerOptions:k.optional()}),LV=z.object({type:z.literal("reasoning"),text:z.string(),providerOptions:k.optional()}),NV=z.object({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerOptions:k.optional()}),jV=z.object({type:z.literal("reasoning-file"),data:z.union([BV,A1,z.instanceof(URL)]),mediaType:z.string(),providerOptions:k.optional()}),FV=z.object({type:z.literal("tool-call"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerOptions:k.optional(),providerExecuted:z.boolean().optional()}),OV=z.discriminatedUnion("type",[z.object({type:z.literal("text"),value:z.string(),providerOptions:k.optional()}),z.object({type:z.literal("json"),value:K9,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:K9,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:BG,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()})]))})]),NG=z.object({type:z.literal("tool-result"),toolCallId:z.string(),toolName:z.string(),output:OV,providerOptions:k.optional()}),DV=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()}),PV=z.object({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional()}),_V=z.object({role:z.literal("system"),content:z.string(),providerOptions:k.optional()}),qV=z.object({role:z.literal("user"),content:z.union([z.string(),z.array(z.union([VG,VV,LG]))]),providerOptions:k.optional()}),EV=z.object({role:z.literal("assistant"),content:z.union([z.string(),z.array(z.union([VG,NV,LG,LV,jV,FV,NG,DV]))]),providerOptions:k.optional()}),MV=z.object({role:z.literal("tool"),content:z.array(z.union([NG,PV])),providerOptions:k.optional()}),qP=z.union([_V,qV,EV,MV]);var EP=Symbol("ai-sdk-tool-call-input-schema-input");var MP=I0({prefix:"aitxt",size:24}),AP=I0({prefix:"call",size:24});var TP=class extends TransformStream{constructor(){super({transform(Y,J){J.enqueue(`data: ${JSON.stringify(Y)}
|
|
37
|
+
|
|
38
|
+
`)},flush(Y){Y.enqueue(`data: [DONE]
|
|
39
|
+
|
|
40
|
+
`)}})}};var jG=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()}),M1=z.record(z.string(),K9.optional()),RP=b4(()=>b8(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(jG).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:M1.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:M1.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:M1.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:M1.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:M1.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 CP=Symbol("streamRetryAttemptBoundary");var wP=I0({prefix:"aitxt",size:24}),SP=I0({prefix:"call",size:24});var IP=I0({prefix:"aitxt",size:24}),bP=I0({prefix:"call",size:24});var kP=Symbol("streamRetryBoundary");var p0=z.record(z.string(),K9.optional()),AV=z.record(z.string(),z.string());var xP=b4(()=>{let Y=z.object({id:z.string(),approved:z.never().optional(),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.never().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional(),inputSchemaInput:z.unknown().optional()}),J=Y.extend({approved:z.boolean(),reason:z.string().optional()}),X=J.extend({approved:z.literal(!0)}),Q=J.extend({approved:z.literal(!1)});return b8(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(jG).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:AV.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:p0.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:p0.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:p0.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:p0.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:J}),z.object({type:z.literal("dynamic-tool"),dynamic:z.literal(!1).optional(),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:p0.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:X.optional()}),z.object({type:z.literal("dynamic-tool"),dynamic:z.literal(!1).optional(),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:p0.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:X.optional()}),z.object({type:z.literal("dynamic-tool"),dynamic:z.literal(!1).optional(),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:p0.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:p0.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:p0.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:p0.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:p0.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:J}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:p0.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:X.optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:p0.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:X.optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:p0.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 vP=I0({prefix:"call",size:24});var hP=I0({prefix:"call",size:24});var yP=I0({prefix:"call",size:24});var gP=I0({prefix:"aiobj",size:24});function FG(Y){return({url:J,abortSignal:X})=>ZV({url:J,maxBytes:Y?.maxBytes,abortSignal:X})}var fP=I0({prefix:"aiobj",size:24});var mP=I0({prefix:"call",size:24});var cP=FG();var uP=z.object({token:z.string().refine((Y)=>Y.trim().length>0),url:z.string().refine((Y)=>{try{let J=new URL(Y);return(J.protocol==="ws:"||J.protocol==="wss:")&&J.hostname!==""}catch{return!1}}),expiresAt:z.number().positive().max(Number.MAX_SAFE_INTEGER).optional(),tools:z.array(z.object({type:z.literal("function"),name:z.string().min(1),description:z.string().optional(),parameters:z.record(z.string(),z.unknown())})).optional()});var TV="AI_NoSuchProviderError",pP=`vercel.ai.error.${TV}`;var lP=I0({prefix:"call",size:24});var dP=I0({prefix:"call",size:24}),iP=FG();var nP=I0({prefix:"call",size:24});class l0 extends G9{name="ProviderResponseStreamError";constructor(Y,J){super({message:Y,url:"",requestBodyValues:void 0,cause:J?.cause,isRetryable:J?.retryable??!0})}}var y0={};iY(y0,{toWebSocketUrl:()=>lV,streamResponsesWebSocket:()=>rV,parseRateLimitSignal:()=>R1,normalizeHeaders:()=>dV,markOversizedFrame:()=>wG,isUpgradeFailure:()=>iV,isOversizedFrame:()=>nV,isNonEmittingFrame:()=>IG,isAbortError:()=>g4,connectResponsesWebSocket:()=>oV,TERMINAL_AFTER_OUTPUT_MESSAGE:()=>y4,PROTOCOL_HEADER:()=>TG,OpenAIWebSocket:()=>y0,OVERSIZED_FRAME_MESSAGE:()=>bG});function T1(Y){let J=Number(Y.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(J)?J:void 0}function k8(Y,J,X=!1){let G=Buffer.from(Y.slice(0,J)).toString("latin1").split(`\r
|
|
41
|
+
`),$=G[0]??"",W=T1($);if(W===void 0||W===101)return;let K=Object.fromEntries(G.slice(1).flatMap((B)=>{let O=B.indexOf(":");return O===-1?[]:[[B.slice(0,O).trim().toLowerCase(),B.slice(O+1).trim()]]})),U=Y.slice(J+4),H=K["content-length"],V=Number(H);if(!X&&(H===void 0||Number.isFinite(V)&&U.length<V))return;let D=Buffer.from(U).toString("utf8"),L=(()=>{try{let B=JSON.parse(D);return n(B)?B:void 0}catch{return}})();return{message:`WS upgrade failed: ${$}`,status:W,status_code:W,headers:K,body:D,...n(L?.error)?{error:L.error}:{}}}var RV="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",OG=["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=[];writeQueue=[];constructor(Y,J,X){this.url=Y,this.sessionID=X?.sessionID,this.connect(Y,J)}addEventListener(Y,J,X){this.listeners[Y]?.add(J)}removeEventListener(Y,J){this.listeners[Y]?.delete(J)}peerClose;closeEmitted=!1;emitClose(Y,J){if(this.closeEmitted)return;this.closeEmitted=!0,this.emit("close",{code:Y,reason:J})}emit(Y,J){for(let X of[...this.listeners[Y]??[]])try{X(J)}catch{}}async connect(Y,J){let X=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),Q=X.hostname,G=X.port?Number(X.port):X.protocol==="https:"?443:80,$=`${X.pathname}${X.search}`,W=crypto.getRandomValues(new Uint8Array(16)),K=Buffer.from(W).toString("base64"),U=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(K+RV));this.expectedAccept=Buffer.from(new Uint8Array(U)).toString("base64");let H={};for(let[L,B]of Object.entries(J))H[L.toLowerCase()]=B;let V=[`GET ${$} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${K}`];for(let L of OG)if(H[L]!==void 0)V.push(`${CV(L)}: ${H[L]}`);for(let[L,B]of Object.entries(J))if(!OG.includes(L.toLowerCase())&&L.toLowerCase()!=="content-length")V.push(`${L}: ${B}`);let D=`${V.join(`\r
|
|
42
|
+
`)}\r
|
|
43
|
+
\r
|
|
44
|
+
`;try{this.log("connect_start",{host:Q,port:G,tls:X.protocol==="https:"});let L=globalThis.Bun?.connect;if(!L)throw Error("Bun.connect is not available");this.socket=await L({hostname:Q,port:G,tls:X.protocol==="https:"?{serverName:Q}:void 0,socket:{open:(B)=>{this.socket=B,this.enqueueWrite(new TextEncoder().encode(D))},data:(B,O)=>this.onData(O),drain:()=>this.flushWrites(),error:(B,O)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let q=O instanceof Error?O.message:String(O);this.log("socket_error",{message:q}),this.emit("error",{message:q})},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(L){this.readyState=3;let B=L instanceof Error?L.message:String(L);this.log("connect_exception",{message:B}),this.emit("error",{message:B})}}onData(Y){if(this.rxBuffer=wV(this.rxBuffer,Y),!this.handshakeDone){let J=Buffer.from(this.rxBuffer).toString("latin1"),X=J.indexOf(`\r
|
|
45
|
+
\r
|
|
46
|
+
`);if(X===-1)return;let Q=J.slice(0,X),G=Q.split(`\r
|
|
47
|
+
`)[0]??"",$=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=T1(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(X+4),this.log("open",{statusLine:G}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let J=Buffer.from(this.rxBuffer).indexOf(`\r
|
|
48
|
+
\r
|
|
49
|
+
`);if(J===-1)return!1;let X=k8(this.rxBuffer,J,Y);if(!X)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:X.status,partial:Y}),this.emit("error",X),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let J=Y[0],X=Y[1],Q=(J&128)!==0,G=J&15,$=(X&128)!==0,W=X&127,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 H=0;H<8;H++)W=W*256+Y[2+H];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,J,X){if(J===9){this.writeFrame(10,X);return}if(J===10)return;if(J===8){let G=1005,$="";if(X.length>=2)G=X[0]<<8|X[1],$=Buffer.from(X.slice(2)).toString("utf-8");this.readyState=3,this.peerClose={code:G,reason:$};try{this.socket?.end()}catch{}this.log("close_frame",{code:G,reason:$}),this.emitClose(G,$);return}if(J===1||J===2)this.fragOpcode=J,this.fragChunks=[X];else if(J===0)this.fragChunks.push(X);if(!Y)return;let Q=SV(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let G=Buffer.from(Q).toString("utf-8");this.emit("message",{data:G})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,J){let X=J.length,Q=crypto.getRandomValues(new Uint8Array(4)),G;if(X<126)G=[128|Y,128|X];else if(X<65536)G=[128|Y,254,X>>8&255,X&255];else{G=[128|Y,255];for(let K=7;K>=0;K--)G.push(X/2**(8*K)&255)}let $=new Uint8Array(X);for(let K=0;K<X;K++)$[K]=J[K]^Q[K%4];let W=new Uint8Array(G.length+4+X);W.set(G,0),W.set(Q,G.length),W.set($,G.length+4);try{this.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 J=this.writeQueue[0],X=Y.write(J);if(X<J.length){this.writeQueue[0]=J.slice(X),this.log("write_backpressure",{written:X,remaining:J.length-X});return}this.writeQueue.shift()}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,J){return t6({component:"raw-ws-bun",event:Y,sessionID:this.sessionID,url:this.url,...J})}}function CV(Y){return Y}function wV(Y,J){let X=new Uint8Array(Y.length+J.length);return X.set(Y,0),X.set(J,Y.length),X}function SV(Y){let J=0;for(let G of Y)J+=G.length;let X=new Uint8Array(J),Q=0;for(let G of Y)X.set(G,Q),Q+=G.length;return X}import{connect as IV}from"node:net";import{connect as bV}from"node:tls";var kV="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 v4{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];constructor(Y,J,X){this.url=Y,this.sessionID=X?.sessionID,this.connect(Y,J)}addEventListener(Y,J,X){this.listeners[Y]?.add(J)}removeEventListener(Y,J){this.listeners[Y]?.delete(J)}peerClose;closeEmitted=!1;emitClose(Y,J){if(this.closeEmitted)return;this.closeEmitted=!0,this.emit("close",{code:Y,reason:J})}emit(Y,J){for(let X of[...this.listeners[Y]??[]])try{X(J)}catch{}}async connect(Y,J){let X=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),Q=X.hostname,G=X.port?Number(X.port):X.protocol==="https:"?443:80,$=`${X.pathname}${X.search}`,W=crypto.getRandomValues(new Uint8Array(16)),K=Buffer.from(W).toString("base64"),U=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(K+kV));this.expectedAccept=Buffer.from(new Uint8Array(U)).toString("base64");let H={};for(let[L,B]of Object.entries(J))H[L.toLowerCase()]=B;let V=[`GET ${$} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${K}`];for(let L of DG)if(H[L]!==void 0)V.push(`${xV(L)}: ${H[L]}`);for(let[L,B]of Object.entries(J))if(!DG.includes(L.toLowerCase())&&L.toLowerCase()!=="content-length")V.push(`${L}: ${B}`);let D=`${V.join(`\r
|
|
50
|
+
`)}\r
|
|
51
|
+
\r
|
|
52
|
+
`;try{this.log("connect_start",{host:Q,port:G,tls:X.protocol==="https:"});let L=()=>{this.socket?.write(D)},B=X.protocol==="https:"?bV({host:Q,port:G,servername:Q},L):IV({host:Q,port:G},L);this.socket=B,B.on("data",(O)=>{this.onData(typeof O==="string"?Buffer.from(O,"binary"):O)}),B.on("error",(O)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let q=O instanceof Error?O.message:String(O);this.log("socket_error",{message:q}),this.emit("error",{message:q})}),B.on("close",(O)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close",{hadError:O}),this.emitClose(this.peerClose?.code??1006,this.peerClose?.reason??"socket closed")})}catch(L){this.readyState=3,this.log("connect_exception",{message:L instanceof Error?L.message:String(L)}),this.emit("error",{message:L instanceof Error?L.message:String(L)})}}onData(Y){if(this.rxBuffer=vV(this.rxBuffer,Y),!this.handshakeDone){let J=Buffer.from(this.rxBuffer).toString("latin1"),X=J.indexOf(`\r
|
|
53
|
+
\r
|
|
54
|
+
`);if(X===-1)return;let Q=J.slice(0,X),G=Q.split(`\r
|
|
55
|
+
`)[0]??"",$=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=T1(G);if(W!==101){if(W===void 0){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:G}),this.emit("error",{message:`WS upgrade failed: ${G}`});return}if(!this.emitRejectedUpgrade())return;this.socket?.destroy?.();return}if(!$||$[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:G}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(X+4),this.log("open",{statusLine:G}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let J=Buffer.from(this.rxBuffer).indexOf(`\r
|
|
56
|
+
\r
|
|
57
|
+
`);if(J===-1)return!1;let X=k8(this.rxBuffer,J,Y);if(!X)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:X.status,partial:Y}),this.emit("error",X),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let J=Y[0],X=Y[1],Q=(J&128)!==0,G=J&15,$=(X&128)!==0,W=X&127,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 H=0;H<8;H++)W=W*256+Y[2+H];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,J,X){if(J===9){this.writeFrame(10,X);return}if(J===10)return;if(J===8){let G=1005,$="";if(X.length>=2)G=X[0]<<8|X[1],$=Buffer.from(X.slice(2)).toString("utf-8");this.readyState=3,this.peerClose={code:G,reason:$};try{this.socket?.end()}catch{}this.log("close_frame",{code:G,reason:$}),this.emitClose(G,$);return}if(J===1||J===2)this.fragOpcode=J,this.fragChunks=[X];else if(J===0)this.fragChunks.push(X);if(!Y)return;let Q=hV(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let G=Buffer.from(Q).toString("utf-8");this.emit("message",{data:G})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,J){let X=J.length,Q=crypto.getRandomValues(new Uint8Array(4)),G;if(X<126)G=[128|Y,128|X];else if(X<65536)G=[128|Y,254,X>>8&255,X&255];else{G=[128|Y,255];for(let K=7;K>=0;K--)G.push(X/2**(8*K)&255)}let $=new Uint8Array(X);for(let K=0;K<X;K++)$[K]=J[K]^Q[K%4];let W=new Uint8Array(G.length+4+X);W.set(G,0),W.set(Q,G.length),W.set($,G.length+4);try{this.socket?.write(W)}catch{}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,J){return t6({component:"raw-ws-node",event:Y,sessionID:this.sessionID,url:this.url,...J})}}function xV(Y){return Y}function vV(Y,J){let X=new Uint8Array(Y.length+J.length);return X.set(Y,0),X.set(J,Y.length),X}function hV(Y){let J=0;for(let G of Y)J+=G.length;let X=new Uint8Array(J),Q=0;for(let G of Y)X.set(G,Q),Q+=G.length;return X}function yV(){return typeof globalThis.Bun?.connect==="function"}var PG=yV()?x4:v4;function x8(Y){return process.env[Y]??process.env[Y.toLowerCase()]}function gV(Y){let J=x8("NO_PROXY");if(!J)return!1;let X=Y.hostname.toLowerCase(),Q=J.split(",").map((G)=>G.trim().toLowerCase()).filter(Boolean);for(let G of Q){if(G==="*")return!0;if(G.startsWith(".")){if(X===G.slice(1)||X.endsWith(G))return!0}else if(X===G||X.endsWith(`.${G}`))return!0}return!1}function fV(Y){let J=new URL(Y);if(gV(J))return;if(J.protocol==="http:")return x8("HTTP_PROXY");if(J.protocol==="https:")return x8("HTTPS_PROXY")??x8("HTTP_PROXY");return}var _G={getProxyForUrl:fV};var mV=V0("quota"),l6=V0("transport"),TG="responses_websockets=2026-02-06",qG=["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"],cV=new Set([h6,"x-opencode-title"]);function uV(Y){let J=new Map;for(let Q of Object.keys(Y))J.set(Q.toLowerCase(),Q);let X={};for(let Q of qG){let G=J.get(Q),$=G===void 0?void 0:Y[G];if(G!==void 0&&$!==void 0)X[G]=$}for(let[Q,G]of Object.entries(Y))if(!qG.includes(Q.toLowerCase()))X[Q]=G;return X}function pV(Y){let J={};for(let[X,Q]of Object.entries(Y)){if(cV.has(X.toLowerCase()))continue;J[X]=Q}return J}function lV(Y){return Y.replace(/^http/,"ws")}function dV(Y){let J={};if(!Y)return J;if(Y instanceof Headers)return Y.forEach((X,Q)=>{J[Q.toLowerCase()]=X}),J;if(Array.isArray(Y)){for(let[X,Q]of Y)J[X.toLowerCase()]=Q;return J}for(let[X,Q]of Object.entries(Y))if(Q!=null)J[X.toLowerCase()]=String(Q);return J}function g4(Y){return Y instanceof DOMException&&Y.name==="AbortError"}var RG=new WeakSet;function iV(Y){return typeof Y==="object"&&Y!==null&&RG.has(Y)}var CG=new WeakSet;function nV(Y){return typeof Y==="object"&&Y!==null&&CG.has(Y)}function wG(Y){return CG.add(Y),Y}function EG(Y,J){let X=Error(Y,J===void 0?void 0:{cause:J});return RG.add(X),X}function oV(Y){return new Promise((J,X)=>{if(Y.signal?.aborted){X(h4(Y.signal));return}let Q={...Y.headers,"openai-beta":Y.headers["openai-beta"]??TG},G=Q[h6]??Q["session-id"];delete Q["content-length"],Q=uV(pV(Q));let $=typeof Bun>"u"?void 0:_G.getProxyForUrl(Y.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),W=!0,K=Y.rawWebSocket?new PG(Y.url,Q,{sessionID:G}):new globalThis.WebSocket(Y.url,{headers:Q,...$?{proxy:$}:{},perMessageDeflate:W}),U=Y.timeout?setTimeout(()=>{H(),K.close(),X(Error("WebSocket connect timed out"))},Y.timeout):void 0;function H(){if(U)clearTimeout(U);K.removeEventListener("open",V),K.removeEventListener("error",D),K.removeEventListener("close",L),Y.signal?.removeEventListener("abort",B)}function V(){H(),J(K)}function D(O){H(),X(EG(h9(O),O))}function L(O){H(),X(EG(kG("WebSocket closed before open",O.code,O.reason)))}function B(){H(),K.close(),X(h4(Y.signal))}K.addEventListener("open",V,{once:!0}),K.addEventListener("error",D,{once:!0}),K.addEventListener("close",L,{once:!0}),Y.signal?.addEventListener("abort",B,{once:!0})})}function rV(Y){let J=new TextEncoder,X=Y.socket,Q,G=()=>{},$=!1,W=0,K=!1,U=!1,H,V=[],D=12,L=[],B=typeof Y.body.previous_response_id==="string"?Y.body.previous_response_id:void 0,O=typeof Y.body.prompt_cache_key==="string"?Y.body.prompt_cache_key:void 0,q={sessionID:Y.sessionID,codexSessionID:O},_,M=0,S,x=new Set,j={addedItemIds:new Set,reasoningItemIds:new Set,finished:!1,other:!1};function C(){if(H)clearTimeout(H);G(),Y.signal?.removeEventListener("abort",x0)}function h(s=X){s.close()}function A(){C(),Q?.enqueue(J.encode(`data: [DONE]
|
|
58
|
+
|
|
59
|
+
`)),Q?.close()}function g(s){B0(s,s)}function r(){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 i(){Q?.enqueue(J.encode(`data: ${JSON.stringify(QB)}
|
|
60
|
+
|
|
61
|
+
`)),A()}function Z0(s){let _0={...q,openingFrameTypes:V,openingItemTypes:L,responseID:_,previousResponseID:B,hasContinuation:B!==void 0,framesSinceCreated:M,msSinceLastFrame:S===void 0?void 0:Date.now()-S},l=r();if(l==="finished-calls"){if($)return;l6.warn("stream failed after finished function calls only; ended as completed",{reason:s.message,emittedOutput:!0,outputShape:l,..._0}),$=!0,C(),Y.onConnectionInvalid?.(s),i();return}if(l==="other"){let u=y4;l6.warn("stream failed after output; not retried",{reason:s.message,emittedOutput:!0,outputShape:l,..._0}),B0(Error(u,{cause:s}),new l0(u,{cause:s}));return}let I=j.reasoningItemIds.size;l6.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:s.message,emittedOutput:U,outputShape:l,emptyReasoningItems:I,..._0}),g(s)}function B0(s,_0){if($)return;$=!0,C(),Y.onConnectionInvalid?.(_0),Q?.error(s)}function p(s){if($)return;if(!Y.idleTimeout)return;if(H)clearTimeout(H);H=setTimeout(()=>Z0(new l0(s)),Y.idleTimeout)}async function t(s){if($)return;if(typeof s.data!=="string"){Z0(new l0("Unexpected binary WebSocket frame"));return}let _0=s.data,l=(()=>{try{let y=JSON.parse(_0);return typeof y==="object"&&y!==null?y:void 0}catch{return}})();if(l?.type==="codex.rate_limits"){mV.debug("codex.rate_limits frame received",{pid:process.pid}),p("idle timeout waiting for websocket");let y=AG(l);Y.onQuota?.(y);return}let I=r(),u=I==="none"||I==="unfinished-calls"?R1(l):void 0;if(u&&l){$=!0,C(),Y.onRateLimitReached?.(u.window,u.resetAt),Y.onTerminal?.(l),Y.onFirstEvent?.(),Q?.error(new l0(`OpenAI account rate limit reached at admission (${u.window})`));return}if(l?.type==="error"&&Y.onRetryableTerminal){if(G(),H)clearTimeout(H);H=void 0;try{let y=await Y.onRetryableTerminal(l);if($){if(y)h(y);return}if(y){K0(y);return}}catch(y){Z0(new l0(y instanceof Error?y.message:String(y),{cause:y}));return}}let d=tV(l,_0);if(d&&l){if(!K)Y.onFirstEvent?.(d);$=!0,C(),Y.onTerminal?.(l);let y=new G9({message:d.message,url:X.url,requestBodyValues:Y.body,statusCode:d.status,responseHeaders:d.headers,responseBody:d.body}),$0=r();if($0==="none"||$0==="unfinished-calls"){if($0==="unfinished-calls")l6.warn("protocol error after unfinished function calls only; surfaced as before output",{...q,status:d.status,reason:d.message,outputShape:$0,responseID:_,previousResponseID:B});Q?.error(y);return}if(l6.warn($0==="finished-calls"?"protocol error after finished function calls only; ended as completed":"protocol error after output; not retried",{...q,status:d.status,reason:d.message,outputShape:$0,responseID:_,previousResponseID:B}),$0==="finished-calls"){i();return}Q?.error(Error(y4,{cause:y}));return}if(n(l)&&l.type==="response.failed"){let y=n(l.response)?l.response.failed:void 0,$0=n(y)?y.rate_limit_reached_type:void 0;if(typeof $0==="string"){$=!0,C(),Y.onRateLimitReached?.($0),Y.onTerminal?.(l);let E0=r();if(E0!=="none")l6.warn(E0==="other"?"rate limit reached after output; ended without retry":E0==="finished-calls"?"rate limit reached after finished function calls only; ended as completed":"rate limit reached after unfinished function calls only; retryable",{...q,outputShape:E0,responseID:_,previousResponseID:B});if(E0==="none"||E0==="unfinished-calls")Y.onFirstEvent?.(),Q?.error(new l0(`OpenAI account rate limit reached mid-stream (${$0})`));else if(E0==="finished-calls")i();else A();return}}if(!l){if(!K)Y.onFirstEvent?.();p("idle timeout waiting for websocket");return}if(sV(l,x),!K)Y.onFirstEvent?.();if(Q?.enqueue(J.encode(`${_0.split(/\r?\n/).map((y)=>`data: ${y}`).join(`
|
|
62
|
+
`)}
|
|
63
|
+
|
|
64
|
+
`)),K=!0,S=Date.now(),_!==void 0)M++;if(V.length<D)V.push(String(l.type));if(l.type==="response.output_item.added"&&L.length<D)L.push(n(l.item)?String(l.item.type):"unknown");if(l.type==="response.created")_=JB(l),l6.debug("response created",{...q,responseID:_,previousResponseID:B,hasContinuation:B!==void 0});if(!IG(l.type))U=!0,XB(l,j);if(p("idle timeout waiting for websocket"),l.type==="response.completed"||l.type==="response.done"){$=!0,aV(l,x),Y.onComplete?.(l,x),Y.onTerminal?.(l),A();return}if(l.type==="response.failed"||l.type==="response.incomplete"||l.type==="error")$=!0,Y.onTerminal?.(l),A()}function L0(s){Z0(new l0(h9(s),{cause:s}))}function v(s){if($)return;let _0=s.code===1009,l=new l0(_0?bG:kG("WebSocket closed before response.completed",s.code,s.reason),{retryable:!_0});if(_0)l6.warn("websocket peer refused the request size",{...q,requestBytes:W,reason:s.reason.toString()});Z0(_0?wG(l):l)}function x0(){let s=h4(Y.signal);if($)return;$=!0,C(),h(),Y.onAbort?.(s),Q?.error(s)}function T0(s){if($)return;$=!0,C(),h(),Y.onAbort?.(eV(s))}function K0(s){G(),X=s,X.addEventListener("message",t),X.addEventListener("error",L0,{once:!0}),X.addEventListener("close",v,{once:!0}),G=()=>{X.removeEventListener("message",t),X.removeEventListener("error",L0),X.removeEventListener("close",v)};let{background:_0,...l}=Y.body;p("idle timeout sending websocket request");try{let I=JSON.stringify({type:"response.create",...l});W=I.length,X.send(I),p("idle timeout waiting for websocket")}catch(I){if($)return;g(new l0(I instanceof Error?I.message:String(I),{cause:I}))}}return new Response(new ReadableStream({start(s){if(Q=s,Y.signal?.addEventListener("abort",x0,{once:!0}),Y.signal?.aborted){x0();return}K0(X)},cancel(s){T0(s)}}),{status:200,headers:{"content-type":"text/event-stream"}})}function sV(Y,J){if(Y.type!=="response.output_item.done")return;if(!n(Y.item))return;SG(Y.item,J)}function aV(Y,J){let X=Y.response;if(!n(X)||!Array.isArray(X.output))return;for(let Q of X.output)if(n(Q))SG(Q,J)}function SG(Y,J){if(Y.type!=="function_call"&&Y.type!=="custom_tool_call")return;let X=typeof Y.call_id==="string"?Y.call_id:typeof Y.id==="string"?Y.id:void 0;if(X)J.add(X)}function tV(Y,J){if(Y?.type!=="error")return;let X=Y.status??Y.status_code;if(typeof X!=="number"||X>=200&&X<300)return;return{status:X,headers:n(Y.headers)?Object.fromEntries(Object.entries(Y.headers).flatMap(([Q,G])=>typeof G==="string"||typeof G==="number"||typeof G==="boolean"?[[Q,String(G)]]:[])):void 0,body:J,message:n(Y.error)&&typeof Y.error.message==="string"?Y.error.message:`${X}`}}function R1(Y){if(typeof Y==="string")try{return R1(JSON.parse(Y))}catch{return}if(!n(Y))return;let J=R1(Y.cause);if(J)return J;let X=R1(Y.body);if(X)return X;let Q=n(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 eV(Y){if(g4(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function h4(Y){let J=Y?.reason;if(g4(J))return J;if(YB(J))return J;return new DOMException(J instanceof Error?J.message:"Aborted","AbortError")}function YB(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function JB(Y){let J=Y.response;if(!n(J))return;return typeof J.id==="string"?J.id:void 0}function XB(Y,J){let X=n(Y.item)?Y.item:void 0;switch(Y.type){case"response.output_item.added":if(X?.type==="function_call"&&typeof X.id==="string"){J.addedItemIds.add(X.id);return}if(MG(X)&&typeof X?.id==="string"){J.reasoningItemIds.add(X.id);return}break;case"response.function_call_arguments.delta":case"response.function_call_arguments.done":if(typeof Y.item_id==="string"&&J.addedItemIds.has(Y.item_id))return;break;case"response.output_item.done":if(X?.type==="function_call"&&X.status==="completed"&&typeof X.id==="string"&&typeof X.call_id==="string"&&typeof X.name==="string"&&typeof X.arguments==="string"){J.finished=!0;return}if(MG(X)&&typeof X?.id==="string"&&J.reasoningItemIds.has(X.id))return;break}J.other=!0}function MG(Y){if(Y?.type!=="reasoning")return!1;let J=(X)=>X===void 0||X===null||Array.isArray(X)&&X.length===0;return J(Y.summary)&&J(Y.content)}var QB={type:"response.completed",response:{status:"completed",incomplete_details:null,usage:{input_tokens:0,output_tokens:0,total_tokens:0}}};function IG(Y){return Y==="response.created"||Y==="response.in_progress"||Y.startsWith("codex.")}var y4="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.",bG="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 kG(Y,J,X){let Q=[`code ${J}`];if(X.length>0)Q.push(X.toString());return`${Y} (${Q.join(": ")})`}var m4="x-opencode-title",v8="x-openai-auth-quota-account",f4=new Set([m4,h6,v8,"x-opencode-session"]),$B=15000,WB=300000,zB=3300000,xG="websocket_connection_limit_reached";function KB(Y){let J=typeof Y["chatgpt-account-id"]==="string"?Y["chatgpt-account-id"]:"",X=typeof Y.authorization==="string"&&Y.authorization.startsWith("Bearer ")?Y.authorization.slice(7):"",Q=J?`acct:${J}`:`tok:${X}`;return GB("sha256").update(Q).digest("hex").slice(0,12)}function UB(Y){let J=Y?.httpFetch??globalThis.fetch,X=new Map,Q=Y?.connectTimeout??$B,G=Y?.idleTimeout??WB,$=Y?.maxConnectionAge??zB,W=Y?.streamRetries??5,K=Y?.firstEventGraceMs??250,U=Y?.rawWebSocket??!1,H=Y?.onQuota,V=Y?.onRateLimitReached,D=setInterval(()=>q(),Math.min(G,60000));if(typeof D==="object"&&"unref"in D&&typeof D.unref==="function")D.unref();function L(S,x,j,C){if(!x||!j)return j;c4(S,vG(x),void 0,C);let h=new Headers(j.headers),A=h.get("x-codex-turn-metadata");if(!A)return j;let g=uG(A,S.turnID,S.turnStartedAt);if(!g)return j;return h.set("x-codex-turn-metadata",g),{...j,headers:h}}async function B(S,x){let j=S instanceof URL?S.toString():typeof S==="string"?S:S.url,C=y0.normalizeHeaders(x?.headers),h=nG(x),A=X8(h);if(x?.method!=="POST"||!new URL(j).pathname.endsWith("/responses"))return J(S,A);let g=(()=>{try{if(typeof x?.body!=="string")return;let K0=JSON.parse(x.body);return typeof K0==="object"&&K0!==null?K0:void 0}catch{return}})();if(!g?.stream)return J(S,A);if(C[m4]==="true")return J(S,A);let r=C[h6]??C["x-session-affinity"]??C["session-id"],i=r;if(!r)return J(S,A);let Z0=y0.normalizeHeaders(h?.headers),B0=KB(Z0),p=`${r}:${B0}:conversation`,t=typeof C[v8]==="string"?C[v8]:void 0,L0=V?(K0,s)=>V(K0,t,s):void 0,v=X.get(p)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};X.set(p,v);let x0=vG(g),T0;if(v.fallback)return J(S,L(v,g,A,T0));if(v.busy)return J(S,L(v,g,A,T0));v.busy=!0,v.lastUsedAt=Date.now();try{T0=y9(v,x0);let K0=y0.normalizeHeaders(h?.headers),s=typeof K0.authorization==="string"&&K0.authorization.startsWith("Bearer ")?K0.authorization.slice(7):"",_0=typeof K0["chatgpt-account-id"]==="string"?K0["chatgpt-account-id"]:void 0,l=H?(q0)=>H(q0,s,t,_0):void 0,I=!v.socket&&!v.continuation?OB(K0):K0;if(v.socket=await BB(v,Y?.url??j,I,Q,$,U,x?.signal),_B(v,x0,T0))await LB(v,x0,G,{signal:x?.signal??void 0,sessionID:i,url:Y?.url??j,headers:h?.headers,onRateLimitReached:L0});let u=()=>{},d=()=>{},y=new Promise((q0,j6)=>{u=q0,d=j6}),$0=PB(v,x0,T0),E0=a6(cG(v,$0,x0,T0)),a0=typeof E0.previous_response_id==="string";await A9({sessionID:i,transport:"websocket",phase:"main",bodyText:()=>JSON.stringify(E0),url:Y?.url??j,method:h?.method,headers:h?.headers});let w0=y0.streamResponsesWebSocket({socket:v.socket,body:E0,sessionID:i??void 0,idleTimeout:G,signal:x?.signal??void 0,onQuota:l,onRateLimitReached:L0,onFirstEvent:(q0)=>u(q0??!0),onComplete:(q0,j6)=>{let Z9=gG(q0);t6({component:"ws-pool",event:"main_completed",sessionID:i,responseID:yG(q0),usage:Z9}),mG(v,x0,q0,j6,a0,T0)},onTerminal:(q0)=>{if(v.busy=!1,v.lastUsedAt=Date.now(),v.streamFailures=0,q0.type!=="response.completed"&&q0.type!=="response.done")v.continuation=void 0,I6(v)},onConnectionInvalid:(q0)=>{if(v.busy=!1,v.lastUsedAt=Date.now(),y0.isOversizedFrame(q0))v.fallback=!0;if(!v.fallback)O(v);v.continuation=void 0,I6(v),u(!1)},onAbort:(q0)=>{v.busy=!1,v.lastUsedAt=Date.now(),v.streamFailures=0,v.continuation=void 0,I6(v),d(q0)},onRetryableTerminal:async(q0)=>{let j6=hG(q0);if(!j6)return;throw v.fallback=!0,j6}}),t0=await HB(y,K);if(t0!==!1){if(t0===!0||t0.status<200||t0.status>599)return w0;return new Response(t0.body,{status:t0.status,headers:{"content-type":"application/json",...t0.headers}})}let f9=()=>J(S,L(v,g,A,T0));if(!v.fallback)return ZB(w0,f9);return f9()}catch(K0){if(v.busy=!1,v.lastUsedAt=Date.now(),y0.isAbortError(K0))throw v.streamFailures=0,v.continuation=void 0,I6(v),K0;let s=y0.parseRateLimitSignal(K0);if(s)L0?.(s.window,s.resetAt);if(y0.isUpgradeFailure(K0)&&!U)v.fallback=!0;if(O(v),v.continuation=void 0,I6(v),v.fallback)return J(S,L(v,g,A,T0));return VB(new l0(K0 instanceof Error?K0.message:String(K0),{cause:K0}))}}function O(S){if(S.streamFailures++,S.streamFailures>W)S.fallback=!0}function q(){let S=Date.now();for(let[x,j]of X){if(j.busy)continue;if(S-j.lastUsedAt<G)continue;I6(j),X.delete(x)}}function _(){clearInterval(D);for(let S of X.values())I6(S);X.clear()}function M(S){let x=`${S}:`;for(let[j,C]of X){if(!j.startsWith(x))continue;I6(C),X.delete(j)}}return Object.assign(B,{close:_,remove:M})}function hG(Y){if(Y.type!=="error"||!n(Y.error)||Y.error.code!==xG)return;return Error(typeof Y.error.message==="string"?Y.error.message:xG)}async function HB(Y,J){if(J<=0)return!1;return new Promise((X,Q)=>{let G=setTimeout(()=>X(!1),J);Y.then(($)=>{clearTimeout(G),X($)},($)=>{clearTimeout(G),Q($)})})}function ZB(Y,J){let X=Y.body;if(!X)return Y;let Q=!1,G=new ReadableStream({async start($){let W=X.getReader(),K=async(U)=>{while(!0){let{done:H,value:V}=await U.read();if(H)return;if(V&&V.length>0)Q=!0,$.enqueue(V)}};try{await K(W),$.close()}catch(U){if(Q||!y0.isOversizedFrame(U)){$.error(U);return}try{let H=await J();if(!H.ok){$.error(new l0(`HTTP fallback after an oversized WebSocket frame failed with ${H.status}`));return}if(H.body)await K(H.body.getReader());$.close()}catch(H){$.error(H)}}},cancel($){X.cancel($)}});return new Response(G,{status:Y.status,headers:Y.headers})}function VB(Y){return new Response(new ReadableStream({start(J){J.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function BB(Y,J,X,Q,G,$,W){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<G)return Y.socket;I6(Y);let K=await y0.connectResponsesWebSocket({url:y0.toWebSocketUrl(J),headers:X,timeout:Q,rawWebSocket:$,signal:W??void 0});return Y.connectedAt=Date.now(),K}function I6(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function LB(Y,J,X,Q){if(!Y.socket||!Array.isArray(J.input)||J.input.length===0)return;let G=jB(J);await A9({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:X,signal:Q.signal,onRateLimitReached:Q.onRateLimitReached,onComplete:(W,K)=>{t6({component:"ws-pool",event:"prewarm_completed",sessionID:Q.sessionID,responseID:yG(W),usage:gG(W)}),mG(Y,G,W,K,!1,{input:e6([]),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=hG(W);if(!K)return;throw Y.fallback=!0,K}});await NB($)}function yG(Y){let J=Y.response;if(!n(J))return;return typeof J.id==="string"?J.id:void 0}function gG(Y){let J=Y.response;if(!n(J))return;return n(J.usage)?J.usage:void 0}async function NB(Y){let J=Y.body?.getReader();if(!J)return;while(!0)if((await J.read()).done)return}function jB(Y){return a6({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:FB(Y.client_metadata)})}function fG(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 FB(Y){if(!n(Y))return Y;if(typeof Y["x-codex-turn-metadata"]!=="string")return Y;try{let J=JSON.parse(Y["x-codex-turn-metadata"]);if(!n(J))return Y;return{...Y,"x-codex-turn-metadata":fG(J),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function OB(Y){let J=Y["x-codex-turn-metadata"];if(!J)return Y;try{let X=JSON.parse(J);if(!n(X))return Y;return{...Y,"x-codex-turn-metadata":fG(X)}}catch{return Y}}function vG(Y){let J={...Y};if(Array.isArray(Y.input))J.input=Y.input.map(DB);return J}function DB(Y){if(!n(Y))return Y;if(typeof Y.type==="string")return Y;if(typeof Y.role!=="string")return Y;if(!("content"in Y))return Y;return{...Y,type:"message"}}function mG(Y,J,X,Q,G,$=y9(Y,J)){let W=X.response,K=n(W)&&typeof W.id==="string"?W.id:void 0;if(!K||!Array.isArray(J.input)){Y.continuation=void 0;return}let U=G?new Set(Y.continuation?.finalizedCallIds):new Set;for(let H of Q)U.add(H);Y.continuation={responseID:K,input:J.input,signature:$.signature,canonical:Y1($.input),finalizedCallIds:U}}function c4(Y,J,X=J,Q=y9(Y,{...X,input:Array.isArray(X.input)?X.input:J.input})){let G=Array.isArray(J.input)?J.input:[],$=Array.isArray(X.input)?X.input:G,W=Q.signature,K=Y.turnInput&&Y.turnSignature===W?J1(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=M6(),Y.turnStartedAt=Date.now();Y.turnInput=$.slice(),Q.priorInputs.set(Y.turnInput,Q.input),Y.turnSignature=W,Y.turnCanonical=Y1(Q.input)}function cG(Y,J,X=J,Q=y9(Y,{...X,input:Array.isArray(X.input)?X.input:J.input})){c4(Y,J,X,Q);let G=J.client_metadata;if(!n(G)||typeof G["x-codex-turn-metadata"]!=="string")return J;let $=uG(G["x-codex-turn-metadata"],Y.turnID,Y.turnStartedAt);if(!$)return J;return{...J,client_metadata:{...G,"x-codex-turn-metadata":$}}}function uG(Y,J,X){let Q;try{Q=JSON.parse(Y)}catch{return}if(!n(Q))return;return JSON.stringify({session_id:Q.session_id,thread_id:Q.thread_id,thread_source:Q.thread_source,turn_id:J,sandbox:Q.sandbox,turn_started_at_unix_ms:X,request_kind:"turn",window_id:Q.window_id})}function y9(Y,J){let X=Array.isArray(J.input)?J.input:[],Q=new Map;if(Y.turnInput&&Y.turnCanonical)Q.set(Y.turnInput,Y.turnCanonical);if(Y.continuation?.canonical)Q.set(Y.continuation.input,Y.continuation.canonical);let G=e6(X,Y.turnCanonical??Y.continuation?.canonical);return Q.set(X,G),{input:G,signature:dG(J),priorInputs:Q}}function pG(Y,J){let X=Y.priorInputs.get(J);if(!X){for(let[Q,G]of Y.priorInputs)if(Q.length===J.length&&Q.every(($,W)=>$===J[W])){X=G;break}X??=e6(J),Y.priorInputs.set(J,X)}return X}function PB(Y,J,X=y9(Y,J)){let Q=Array.isArray(J.input)?J.input:void 0;if(!Q||!Y.continuation)return J;if(Y.continuation.signature!==X.signature)return Y.continuation=void 0,J;if(!iG(Y.continuation,X))return Y.continuation=void 0,J;if(Y.continuation.input.length===0)return{...J,previous_response_id:Y.continuation.responseID};let G=Q.slice(Y.continuation.input.length),$=qB(G,Y.continuation.finalizedCallIds);if($.length===0)return J;return{...J,previous_response_id:Y.continuation.responseID,input:$}}function _B(Y,J,X=y9(Y,J)){let Q=Array.isArray(J.input)?J.input:void 0;if(!Y.continuation)return!0;if(!Q)return!1;if(!iG(Y.continuation,X))return!0;return Q.slice(Y.continuation.input.length).some(lG)}function lG(Y){if(!n(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function qB(Y,J){return Y.filter((X)=>{if(!n(X))return!0;if(typeof X.type==="string"&&X.type.endsWith("_output"))return!0;if(X.type==="function_call_output"||X.type==="custom_tool_call_output")return!0;if(X.type==="function_call"||X.type==="custom_tool_call"){let Q=typeof X.call_id==="string"?X.call_id:typeof X.id==="string"?X.id:void 0;return Q?!J.has(Q):!0}if(X.type==="message")return X.role!=="assistant";if(typeof X.role==="string")return X.role!=="assistant";return!1})}function dG(Y){return T9(EB(Object.fromEntries(Object.entries(Y).filter(([J])=>J!=="input"&&J!=="stream"&&J!=="background"&&J!=="previous_response_id"&&J!=="generate"))))}function EB(Y){if(!n(Y.client_metadata))return Y;let J=Object.fromEntries(Object.entries(Y.client_metadata).filter(([X])=>X!=="x-codex-turn-metadata"&&X!=="x-codex-ws-stream-request-start-ms"));return{...Y,client_metadata:J}}function iG(Y,J){if(Y.input.length>=J.input.texts.length)return!1;return J1(pG(J,Y.input),J.input)!==void 0}function nG(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let J=new Headers(Y.headers);for(let X of f4)J.delete(X);return{...Y,headers:J}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((J)=>!f4.has(J[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([J])=>!f4.has(J.toLowerCase())))}}var CB=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),wB=new Set(["gpt-5.6","gpt-6","gpt-6.1"]);function SB(Y){if(CB.has(Y))return!0;if(wB.has(Y))return!1;let X=Y.match(/^gpt-(\d+(?:\.\d+)?)/)?.[1];return X?parseFloat(X)>5.4:!1}function IB(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 bB="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.",kB="opencode-oauth-dummy-key",Pq=()=>s9,xB=120000,vB=90000,hB=4000,oG=50,rG=3,yB=25,gB=60000,fB="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",r4=!1,m8;function _q(){return m8}function qq(){r4=!1,m8=void 0}var sG=V0("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,J){super(J);this.name="ResetTargetResolutionError",this.code=Y}}function p4(Y,J,X,Q){let G=(X?.refresh?.refreshBeforeExpiryMinutes??240)*60000;return!Y||!J||J-Q<=G}function mB(Y,J){let X=Y==="main",Q=J.row,G=()=>new g0("token_unavailable",X?"Main OpenAI account has no usable access token.":`Fallback account ${Y} has no usable access token.`);if(!Q){if(X)throw G();throw new g0("unknown_account",`Fallback account ${Y} was not found.`)}if(!Q.enabled)throw new g0("disabled_account",`${X?"Main":"Fallback"} account ${Y} is disabled.`);if(Q.type!=="oauth")throw new g0("non_oauth_account",`${X?"Main":"Fallback"} account ${Y} is not an OAuth account.`);if(!J.token)throw G();let $=Y6(J.token);return{accountKey:Y,label:X?"Main account":Q.label??Y,accessToken:J.token,chatgptAccountId:Q.identity??($?J6($):void 0)}}function cB(Y){async function J(){let X=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),Q=o6(X);if(!X||!Q||m0(Q))throw new g0("token_unavailable","Main OpenAI account has no usable access token.");let G=Q;if(p4(G.access,G.expires,X,Y.now()))G=await(Y.refreshPoolMainRow??Y.refreshFallbackAccount)(G,X);if(!G.access)throw new g0("token_unavailable","Main OpenAI account has no usable access token.");let $=Y6(G.access);return{accountKey:"main",label:"Main account",accessToken:G.access,chatgptAccountId:G.accountId??($?J6($):void 0)}}return async(X)=>{let Q=await Y.poolAccess?.(X);if(Q)return mB(X,Q);if(X==="main"){let V=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),D=await Y.getAuth();if(n0(D))return J();if(D.type!=="oauth")throw new g0("non_oauth_account","Main OpenAI account is not authenticated with OAuth.");if(p4(D.access,D.expires,V,Y.now()))try{D={type:"oauth",...await Y.refreshMainWithLease()}}catch(q){if(q instanceof r6)return J();throw q}if(!D.access)throw new g0("token_unavailable","Main OpenAI account has no usable access token.");let L=Y6(D.access),B=L?J6(L):void 0,O=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath});return{accountKey:X,label:"Main account",accessToken:D.access,chatgptAccountId:B??O?.mainAccountId}}let G=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),$=G?.accounts.find((V)=>V.id===X);if(!G||!$)throw new g0("unknown_account",`Fallback account ${X} was not found.`);if($.enabled===!1)throw new g0("disabled_account",`Fallback account ${X} is disabled.`);if(!o0($))throw new g0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);let W=()=>new g0("token_unavailable",`Fallback account ${X} has no usable access token.`);if(m0($))throw W();let K=$;if(p4(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}),H=U?.accounts.find((V)=>V.id===X);if(!U||!H)throw new g0("unknown_account",`Fallback account ${X} was not found.`);if(H.enabled===!1)throw new g0("disabled_account",`Fallback account ${X} is disabled.`);if(!o0(H))throw new g0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);return{accountKey:X,label:K.label??X,accessToken:K.access,chatgptAccountId:H.accountId}}}function uB(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function l4(Y){return Y instanceof a4}function eG(){throw Error(fB)}async function pB(Y,J={}){let X=U0(X0());if($Y(X.configPath)){await n6(D9(X),J.holdsMainRefreshLock?void 0:q6(X),(Q)=>{if(J.canWrite&&!J.canWrite())throw Error(Q9["vault-refused"]);Y(Q)});return}await n1((Q)=>{return Y(Q),Q},X,{canWrite:J.canWrite})}var y$=null;function Eq(){return y$}function lB(Y){return Math.floor(Math.random()*Y)}var dB=!0;function iB(Y,J,X){let Q=Y.get(J);if(Q)return Q;let G=M6(),$={threadID:G,turnID:M6(),windowID:`${G}:0`};return Y.set(J,$),X?.(),$}function Y$(){return RB(GY(),"openai-auth-sessions.json")}function nB(Y,J){return Y.find((X)=>X.enabled!==!1&&o0(X)&&(X.id===J||X.accountId===J))}function J$(Y,J){if(!J)return Y;let X={...Y};for(let Q of["resetCreditsAvailable","resetCreditsApplicable"]){let G=J[Q];if(X[Q]===void 0&&G!==void 0)X[Q]=G}if(X.spendControl===void 0&&X.spendControlCleared!==!0&&J.spendControl!==void 0)X.spendControl=J.spendControl;return X}function h8(Y,J){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:J}}function g$(Y,J,X=Date.now(),Q=J.mainAccountId){let G=Y.getMain(),$=G?.quota;return{main:{quota:$?{...$,checkedAt:G.checkedAt,primary:h8($.primary,G.checkedAt),secondary:h8($.secondary,G.checkedAt)}:null,...typeof Q==="string"?{mainAccountId:Q}:{},killed:!H9($,J,void 0,X),...$?.resetCreditsAvailable!==void 0?{resetCredits:$.resetCreditsAvailable}:{}},fallbacks:J.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:h8(U.primary,K.checkedAt),secondary:h8(U.secondary,K.checkedAt)}:null,killed:!H9(U,J,W.id,X),enabled:!0,...U?.resetCreditsAvailable!==void 0?{resetCredits:U.resetCreditsAvailable}:{}}}),route:J.routing?.mode??"main-first",lastUpdated:X}}function Mq(Y,J,X,Q=Date.now()){return{...g$(Y,J,Q),activeId:X}}function X$(Y,J){if(J?.headers!==void 0)return new Headers(J.headers);if(Y instanceof Request)return new Headers(Y.headers);return new Headers}async function d4(Y,J){if(!(Y instanceof Request))return J;let X=new Request(Y,J),Q=X.method.toUpperCase(),G=Q==="GET"||Q==="HEAD"||X.body===null?void 0:await X.text();return{method:X.method,headers:new Headers(X.headers),body:G,signal:X.signal,cache:X.cache,credentials:X.credentials,integrity:X.integrity,keepalive:X.keepalive,mode:X.mode,redirect:X.redirect,referrer:X.referrer,referrerPolicy:X.referrerPolicy}}function Q$(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}var oB=new Set(["gpt-6-astra","gpt-6-sol","gpt-6-luna","gpt-6.1-sol"]),rB=new Set(["title","compaction","summary"]);function sB(Y,J,X){if(X!==null&&rB.has(X))return;let Q=typeof Y.model==="string"?Y.model:"";if(!oB.has(Q))return;let G=n(Y.reasoning)?Y.reasoning:void 0,$=typeof G?.effort==="string"?G.effort:void 0;if(!$)return;let W=Array.isArray(Y.input)?Y.input:void 0;J.effortUpdates??=[];let K=J.effortUpdates,U=(L)=>MB("sha256").update(T9(L)).digest("hex").slice(0,16);if(J.pinnedEffort===void 0||K.some((L)=>!W||!Q1(W[L.anchor],"user")||U(W[L.anchor])!==L.fingerprint)){J.pinnedEffort=$,J.effortUpdates=[];return}if(!W||W.length===0)return;let H=W.findLastIndex((L)=>Q1(L,"user")),V=K.at(-1),D=V?.effort??J.pinnedEffort;if(H>=0&&$!==D)if(V?.anchor===H){let L=K.at(-2)?.effort??J.pinnedEffort;if($===L)K.pop();else V.effort=$}else K.push({anchor:H,fingerprint:U(W[H]),effort:$});else if(H<0&&$!==D)return;if(K.some((L,B)=>B>0&&L.anchor<=(K[B-1]?.anchor??-1))){J.pinnedEffort=$,J.effortUpdates=[];return}Y.reasoning={...G,effort:J.pinnedEffort};for(let L=K.length-1;L>=0;L--){let B=K[L];if(!B)continue;W.splice(B.anchor,0,{type:"configuration_update",reasoning:{effort:B.effort}})}}function s4(Y){if(Array.isArray(Y)){let X=Y;for(let Q=0;Q<Y.length;Q++){let G=s4(Y[Q]);if(G===Y[Q])continue;if(X===Y)X=Y.slice();X[Q]=G}return X}if(!n(Y))return Y;let J=Y;for(let X of Object.keys(Y)){if(Y.type==="input_image"&&X==="detail"){if(J===Y)J={...Y};delete J[X];continue}let Q=s4(Y[X]);if(Q===Y[X])continue;if(J===Y)J={...Y};J[X]=Q}return J}function aB(Y){let J=n(Y.reasoning)?{...Y.reasoning}:{};J.context="all_turns",Y.reasoning=J,Y.parallel_tool_calls=!1;let X=s4(Array.isArray(Y.input)?Y.input:[]),G=[{type:"additional_tools",role:"developer",tools:Array.isArray(Y.tools)?Y.tools.filter(($)=>!(n($)&&$.type==="web_search")):[]}];if(typeof Y.instructions==="string"&&Y.instructions.length>0)G.push({type:"message",role:"developer",content:[{type:"input_text",text:Y.instructions}]});Y.input=[...G,...X],delete Y.tools,delete Y.instructions}async function tB(Y,J={}){let X=J.codexApiEndpoint??i0().codexApiEndpoint,Q=crypto.randomUUID(),G=RX(Y$()),$=()=>CX(Y$(),G),W=!1,K=!1,U=[],H=null,V=q$(Y.client),D=new Map,L=new Map,B,O=!1,q,_=new Map,M,S,x=v3({host:"opencode",stateDir:J.vault?.stateDir??N$(U0(X0()).statePath),...Y.directory?{projectRoot:Y.directory}:{},reservedRouteIds:()=>i?.peek().rows.map((I)=>I.id)??[],...J.vault?.connectionFile?{connectionFile:J.vault.connectionFile}:{},...J.vault?.connectScoped?{connectScoped:J.vault.connectScoped}:{},...J.vault?.connectEnrollment?{connectEnrollment:J.vault.connectEnrollment}:{},...J.vault?.pollIntervalMs!==void 0?{pollIntervalMs:J.vault.pollIntervalMs}:{},fetchImpl:()=>fetch},U0(X0())),j=x.vault;await j.authority();let C=x.firstRoster,h=Promise.withResolvers(),A=Promise.race([C,h.promise]),g=J.vault?.firstRosterWaitMs??SY,r,i,{enabled:Z0,...B0}=J.poolMigration??{},p=Z0??dB;if(p&&"reason"in V)(B0.log??V0("pool")).warn("account pool migration is off for this OpenCode client",{reason:V.reason});let t=p&&"slot"in V?H3({paths:()=>U0(X0()),slot:V.slot,version:v6,...B0,runDeps:{vaultServes:()=>j.serves(),...B0.runDeps},paused:async()=>await j.authority()!=="local",migrate:async(I)=>{let u=await(B0.migrate??W8)(I);return i?.load(),u},adopt:async(I)=>{if(!await W1(A,g))return{status:"retry",reason:"vault-roster-pending"};let u=await(B0.adopt??z8)(I);return i?.load(),u}}):void 0,L0=(I,u="")=>I?async()=>{let d=await I();return{url:d.url,instructions:d.instructions??u,method:"auto",callback:async()=>{try{let y=await d.tokens;return{type:"success",refresh:y.refresh_token,access:y.access_token,expires:Date.now()+(y.expires_in??3600)*1000,accountId:s6(y)}}finally{d.cleanup?.()}}}}:void 0,v=new _Y(J.backgroundQuota),x0,T0=KX({client:Y.client,getAuth:async()=>x0?.(),fetchImpl:fetch,dependencies:{...J.login?.authorize?{authorizeBrowser:L0(J.login.authorize.browser,"Complete authorization in your browser. This window will close automatically."),authorizeHeadless:L0(J.login.authorize.headless)}:{}},vault:j,onMainSlotWritten:async()=>{await t?.requestAdoption()}}),K0=(I)=>async(u)=>{let d=await I(u);if(d.method!=="auto")return d;return{...d,callback:async()=>{let y=await d.callback();if(y.type==="success"&&"refresh"in y)s(y.refresh);return y}}};async function s(I){if(!t||!("slot"in V))return;let u=J.login?.sleep??((d)=>Bun.sleep(d));for(let d=0;d<5000;d+=100){try{let y=await V.slot.get({path:{id:"openai"}});if(n(y)&&y.refresh===I){await t.requestAdoption();return}}catch{}await u(100)}}let _0=T0.map((I)=>I.type==="oauth"?{...I,authorize:K0(I.authorize)}:I);async function l(I,u){let d=Y.client.session;if(typeof d?.promptAsync==="function"){let y=await r3(Y.client,I),$0={noReply:!0,parts:[{type:"text",text:u,ignored:!0}]};if(y?.agent)$0.agent=y.agent;if(y?.model)$0.model=y.model;if(y?.variant)$0.variant=y.variant;await d.promptAsync({path:{id:I},body:$0});return}}return{async dispose(){x.release(),t?.dispose(),i?.dispose(),v.stop(),S?.stop(),B?.stopBackgroundRefresh(),B=void 0;for(let d of U)d.close();U.length=0;let I=globalThis;for(let[d,y]of D)if(I.__openaiAuthCacheKeepManagers?.get(d)===y)y.stop(),I.__openaiAuthCacheKeepManagers.delete(d);D.clear();for(let d of L.values())await d.release().catch(()=>{});L.clear();let u=r;r=void 0,await(await u)?.release()},async event(I){if(I.event.type!=="session.deleted")return;let u=I.event.properties.info,d=G.get(u.id);if(d)H?.cacheKeepManager?.remove(d.threadID);if(G.delete(u.id))$();let y=L6(u.id);if(_.delete(y),S?.cancel(`pin:${y}`),q){let $0=(await R0(U0(X0())))?.accounts;await S$(u.id,$0,q).catch(()=>{})}for(let $0 of U)$0.remove(u.id)},provider:{id:"openai",async models(I,u){if(u.auth?.type!=="oauth")return I.models;let d=await R0(U0(X0())),y=!d||Z$(d),$0=y?null:await d3();if(!y&&$0&&!aG)aG=!0,sG.debug("restoring OAuth model costs from models.dev catalog");if(!y&&!$0&&!tG)tG=!0,sG.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(I.models).filter(([,E0])=>E0.options.reasoningMode!=="pro"&&SB(E0.api.id)).map(([E0,a0])=>[E0,{...a0,cost:y?{input:0,output:0,cache:{read:0,write:0}}:$0?.[a0.api.id]??$0?.[E0]??a0.cost,limit:IB(a0.id)??a0.limit}]))}},auth:{provider:"openai",async loader(I){await j.authority(),x0=I,r??=I3({version:v6,logger:V0("heartbeat")}),await r,t?.start();let u=await I();if(u.type!=="oauth")return h.resolve(),{};let d=o4(u).kind==="tombstone";x.start();let y=Y.directory?await E$(Y.directory):void 0,$0=y?.dir??X0();async function E0(Z,N={}){if(await j.authority()!=="local")return;return pB(Z,{...N,canWrite:()=>!j.enrolled()})}let a0=await j.authority()!=="local";if(!d&&!a0)await B$({type:"oauth",access:u.access??"",refresh:u.refresh??"",expires:u.expires??0},U0(X0()));let w0=await R0(U0(X0())).catch(async(Z)=>{if(await j.authority()!=="local")return null;let N=X0();throw Error(`OpenAI auth store at ${N} is corrupt or unreadable: ${Z instanceof Error?Z.message:String(Z)}. Fix or remove it to continue.`,{cause:Z})});if(!a0&&await y8(U0(X0()),u)){if(t)t.noticePlaceholderWithoutMain();else if(!O)O=!0,V0("pool-migration").warn(P9,{reason:"placeholder-without-main"})}let t0=w0,f9=eX({path:X0,stat:(Z)=>{try{let N=TB(Z);return{mtimeMs:N.mtimeMs,size:N.size}}catch{return}},read:(Z)=>R0(U0(Z)),fallback:async(Z)=>{if(await j.authority()!=="local")return t0;throw Z},onRead:(Z)=>{t0=Z}});function q0(){return f9.read()}async function j6(){return $8(Promise.resolve(q0()),G8,()=>t0)}function Z9(){f9.invalidate()}if(w0&&u.access&&!d&&!a0){let Z=s6({id_token:"",access_token:u.access,refresh_token:u.refresh??""});if(Z&&Z!==w0.mainAccountId)await E0((N)=>{N.mainAccountId=Z}),w0.mainAccountId=Z,Z9()}let c8=w0?.logging?.level;if(c8&&typeof c8==="string")t1(c8);let m9=V0("transport"),X6=V0("quota"),I1=V0("refresh"),z6=V0("accounts");m9.info("codex auth loader ready",{codexApiEndpoint:X,transport:i0().rawWebSocket?"raw-websocket":i0().webSockets?"websocket":"http"});let J0=new H$({storage:w0,configPath:X0(),fetchQuotaFn:void 0}),c9,u9=0;i?.dispose();let M0=new IY({paths:()=>U0(X0()),refreshProvider:async(Z)=>{let N=await C1({refreshToken:Z.refresh,fetchImpl:fetch,now:Date.now}),F=s6({id_token:"",access_token:N.access,refresh_token:N.refresh});return{...N,...F?{identity:F}:{}}},pullQuota:async(Z)=>{let N=Z.credential;if(N.type!=="oauth"||!N.access)throw Error("the row holds no access token to poll with");let F=await a9({accessToken:N.access,fetchImpl:fetch,now:Date.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,logger:X6}),R=Date.now(),E={quota:F,refreshAfter:R+300000,checkedAt:R};if(Z.id==="main")J0.setMain(N.access,E,Z.identity,!0);else J0.setFallback(Z.id,E,N.access,!0,Z.identity);return M9(F,R,!0)},vaultIdentities:()=>j.identities(),vaultMode:()=>j.enrolled(),vaultAuthority:()=>j.authority(),vaultFirstRoster:C,vaultFirstRosterBackgroundWaitMs:g,log:V0("pool")});if(i=M0,!a0)await M0.load();let e0=new L$({paths:U0(X0()),refreshFn:async(Z)=>{if(await j.authority()!=="local")throw Error(Q9["vault-refused"]);return C1({refreshToken:Z.refreshToken,fetchImpl:Z.fetchImpl,now:Z.now})},quotaManager:J0,canWrite:()=>!j.enrolled(),onFallbackStorageChanged:Z9,backgroundRefreshPaused:async()=>j.enrolled()||await M0.active()});if(w0&&w0.accounts.length>0)e0.startBackgroundRefresh();function u8(Z){if(m0(Z))return;return Z.access||void 0}function b1(Z={}){let{readSidebarState:N,respectBackoff:F,skipFresherThanMs:R}=Z;return{getAuth:I,codexRefreshFn:C1,refreshMainWithLease:KJ,fallbackManager:e0,quotaManager:J0,loadAccounts:R0,writeSidebarState:(E)=>K6(E),client:Y.client,fetchImpl:fetch,now:Date.now,paths:U0(X0()),readSidebarState:N??(()=>A$(u0)),storageMainAccountId:w0?.mainAccountId,isOAuthAccountFn:o0,whamFn:a9,...F===void 0?{}:{respectBackoff:F},...R===void 0?{}:{skipFresherThanMs:R}}}async function t4(Z){return(await M0.pollRows(await R0(U0(X0())),Z?{ids:Z}:{})).map((F)=>({account:F.id,ok:F.ok,...F.error!==void 0?{error:F.error}:{}}))}async function e4(Z){return M0.accessFor(Z,await R0(U0(X0())))}let YJ=V0("cachekeep"),k1=e1(w0),JJ=k1?.enabled===!0,XJ=k1?.subagents===!0,QJ=k1?.sustain===!0,GJ=rX(w0?{...w0,cachekeep:k1}:w0),x1;async function f$(Z){await new Promise((N)=>setTimeout(N,Z))}async function m$(Z){let N;for(let F=1;F<=rG;F++){if(await j.authority()!=="local")throw Error(Q9["vault-refused"]);try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:Z.refresh,access:Z.access,expires:Z.expires}});return}catch(R){if(N=R,F<rG)await f$(yB*F)}}throw new a4(N)}async function v1(Z){await E0((N)=>{N.refresh=N.refresh??{},Z(N)},{holdsMainRefreshLock:!0}),Z9()}async function p8(Z){let N=Date.now()+hB;while(Date.now()<N){await new Promise((E)=>setTimeout(E,oG+lB(oG)));let F=await I();if(n0(F))throw new r6;if(F.type!=="oauth"||!F.access)continue;if((F.access!==Z.access||F.refresh!==Z.refresh||(F.expires??0)>(Z.expires??0)+60000)&&(!F.expires||F.expires>Date.now()))return I1.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:F.expires?F.expires-Date.now():void 0}),{access:F.access,refresh:F.refresh??Z.refresh??"",expires:F.expires??0}}return null}function $J(Z){if(n0(Z))throw new r6;if(Z.type!=="oauth")throw Error("not oauth");if(m0(Z))throw new K$;if(!Z.refresh)throw Error("Token refresh failed: missing refresh token");return Z.refresh}async function l8(){if(!x1)x1=(async()=>{let Z=await I(),N=$J(Z);if(Z.type!=="oauth")throw Error("not oauth");let F=z1(N),R=await R0(U0(X0())),E=R?.refresh?.mainLastRefreshError;if(E&&E6(E,N,Date.now()))throw Error(i4(E,Date.now()));if(R?.refresh?.mainRefreshLeaseUntil&&R.refresh.mainRefreshLeaseUntil>Date.now()&&R.refresh.mainRefreshLeaseTokenHash===F){let f=await p8(Z);if(f)return f;throw Error("Codex OAuth refresh is already in progress")}let b=await Y8({name:s9,ttlMs:xB,path:X0(),renew:!0});if(!b){let f=await p8(Z);if(f)return f;throw Error("Codex OAuth refresh is already in progress")}let T;try{let f=await I(),Y0=$J(f);if(f.type!=="oauth")throw Error("not oauth");if(Y0!==N){if(f.access&&(f.expires??0)>Date.now())return I1.debug("main token rotated while awaiting the lock",{pid:process.pid}),await b.release().catch(()=>{}),{access:f.access,refresh:Y0,expires:f.expires??0};let v0=(await R0(U0(X0())))?.refresh?.mainLastRefreshError;if(v0&&E6(v0,Y0,Date.now()))throw Error(i4(v0,Date.now()))}T={...f,refresh:Y0}}catch(f){throw await b.release().catch(()=>{}),f}await _$(U0(X0()),T.refresh,T.access!==void 0?{slotAccess:T.access}:{}).catch(()=>!1);let w=z1(T.refresh),m=crypto.randomUUID(),a=w;try{await v1((W0)=>{if(P$(X0(),T.refresh))throw new n4;W0.refresh=W0.refresh??{},W0.refresh.mainRefreshLeaseId=m,W0.refresh.mainRefreshLeaseUntil=Date.now()+vB,W0.refresh.mainRefreshLeaseTokenHash=w});let f=await R0(U0(X0()));if(f?.refresh?.mainRefreshLeaseId!==m||f.refresh.mainRefreshLeaseTokenHash!==w)throw Error("Codex OAuth refresh is already in progress");if(await j.authority()!=="local")throw Error(Q9["vault-refused"]);let Y0=await C1({refreshToken:T.refresh,fetchImpl:fetch,now:Date.now});return await m$(Y0),await v1((W0)=>{if(W0.refresh=W0.refresh??{},W0.refresh.mainLastRefreshError=void 0,W0.refresh.mainRefreshLeaseId===m)W0.refresh.mainRefreshLeaseId=void 0,W0.refresh.mainRefreshLeaseUntil=void 0,W0.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),a=void 0,Y0}catch(f){if(!(f instanceof n4)){if(!l4(f))await v1((Y0)=>{Y0.refresh=Y0.refresh??{},Y0.refresh.mainLastRefreshError=W$({error:f,now:Date.now(),refreshToken:T.refresh,previous:Y0.refresh.mainLastRefreshError})}).catch(()=>{});throw f}}finally{if(a)await v1((f)=>{if(f.refresh?.mainRefreshLeaseId===m&&f.refresh.mainRefreshLeaseTokenHash===a)f.refresh.mainRefreshLeaseId=void 0,f.refresh.mainRefreshLeaseUntil=void 0,f.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await b.release().catch(()=>{})}let c=await p8(T);if(c)return c;throw Error("Codex OAuth refresh is already in progress")})().finally(()=>{x1=void 0});return x1}function WJ(Z){return wJ({storage:Z,now:Date.now,refreshAccount:(N,F)=>e0.refreshAccount(N,F,{asPoolMain:!0}),warn:(N,F)=>I1.warn(N,{pid:process.pid,...F})})}async function zJ(){let Z=await WJ(await R0(U0(X0())));if(!Z)throw Error("The main OpenAI account has no usable token in the account pool");return{access:Z.token,refresh:Z.account.refresh,expires:Z.account.expires??0}}async function KJ(){try{return await l8()}catch(Z){if(Z instanceof r6)return zJ();throw Z}}let UJ=globalThis,d8=UJ.__openaiAuthCacheKeepManagers??new Map;UJ.__openaiAuthCacheKeepManagers=d8,d8.get($0)?.stop();let p9=tX({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 M0.active()){let N=await e4("main");if(!N)throw Error("main pool row has no usable token");return N.token}let Z=await I();if(await j.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(n0(Z))return(await zJ()).access;if(Z.type!=="oauth")throw Error("not oauth");if(!Z.access||(Z.expires??0)<Date.now())try{return(await KJ()).access}catch(N){if(l4(N))throw N;if(Z.access)return Z.access;throw Error("main token refresh failed")}return Z.access},refreshFallback:async(Z)=>{if(await j.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(await M0.active()){let T=await e4(Z);if(!T)throw Error(`no access token for ${Z}`);return{token:T.token}}let N=await j6(),F=N?nB(N.accounts,Z):void 0;if(!F)throw Error(`fallback account ${Z} not found`);let R=N??{version:1,accounts:[F]},E=m0(F)?F:await e0.refreshAccount(F,R),b=u8(E);if(!b)throw Error(`no access token for ${Z}`);return{token:b}},codexResponsesUrl:X,activeAccount:async(Z)=>aX(U9(await d6.read(),_),Z),logger:YJ,now:Date.now,getWindow:()=>GJ,getSustain:()=>QJ});d8.set($0,p9),D.set($0,p9);function V9(Z,N,F,R,E=!1){try{c$(Z,N,F,R,E)}catch(b){X6.warn("quota push failed",{pid:process.pid,accountId:F??"main",error:h9(b)})}}function c$(Z,N,F,R,E){if(Object.keys(Z).length===0&&!E)return;let b=Date.now(),T=Z,w={quota:T,refreshAfter:b+300000,checkedAt:b},m;if(F&&F!=="main"){let c=N?Y6(N):null,f=c?J6(c):void 0,Y0=J0.peekFallbackForPolicy(F)?.quota,W0=J$(T,Y0);w={...w,quota:W0},J0.setFallback(F,w,N,E,f)}else{if(m=R,!m&&N){let Y0=Y6(N);m=Y0?J6(Y0):void 0}if(m&&c9&&m!==c9){X6.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:m,currentMainIdentity:c9});return}let c=J0.peekMainForPolicy(m)?.quota,f=J$(T,c);w={...w,quota:f},J0.setMain(N,w,m,E)}X6.debug("quota pushed",{pid:process.pid,accountId:F??"main",snapshot:w.quota}),M0.recordSnapshot(F&&F!=="main"?F:"main",Z,N,E);let a=Boolean(F&&F!=="main");F6.enqueue("machine-state","quota",()=>K6(J0,a?void 0:m))}function u$(Z,N,F){let R=A6(j.routes().find((E)=>E.id===Z)?.quota)??(Z==="main"?J0.peekMainForPolicy()?.quota:J0.peekFallbackForPolicy(Z)?.quota);return U$(R,N,Date.now(),gB,F)}let h1=new Map,l9=new Map;function HJ(){if(!j.enrolled())return;F6.enqueue("machine-state","quota",()=>K6(J0))}let B9=J.experimentalWebSockets?b6.createWebSocketFetch({httpFetch:fetch,rawWebSocket:i0().rawWebSocket,onQuota:(Z,N,F,R)=>{let E=F?h1.get(F):void 0;if(E){j.recordSnapshot(E.id,Z,!0,E.receipt).then(HJ);return}V9(Z,N,F,!F||F==="main"?R:void 0,!0)},onRateLimitReached:(Z,N,F)=>{if(!N)X6.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:Z});let R=N?h1.get(N):void 0,E=R?.id??N??"main",b=u$(E,Z,F);if(J0.markRateLimited(E,b),R)l9.set(E,Math.max(l9.get(E)??0,b));else M0.markRateLimited(E,b);X6.debug("mid-stream rate limit mark",{pid:process.pid,accountId:E,window:Z})}}):void 0;if(B9)U.push(B9),W=!0;let u0=M$();q=u0;async function K6(Z,N){let F=q0(),R=F instanceof Promise?await F.catch(()=>t0):F,E=N??R?.mainAccountId;if(j.enrolled()){await g8(A3(j.snapshot()?.rows??[],new Set(j.routes().map((T)=>T.id)),R,Date.now()),u0,{canWrite:()=>j.enrolled()});return}let b=await M0.current();if(b.active){await g8(T3(b.rows,R,Date.now(),(T)=>(T==="main"?Z.getMain():Z.getFallback(T))?.quota?.resetCreditsAvailable),u0,{canWrite:()=>!j.enrolled()});return}if(!R)return;await g8(g$(Z,R,Date.now(),E),u0,{canWrite:()=>!j.enrolled()})}let d6=x$(u0);d6.read(),S?.stop();let F6=h$({logger:m9,onWritten:()=>d6.refreshInBackground()});if(S=F6,M!==u0)_.clear(),M=u0;function i8(Z,N,F,R,E,b,T=!1){let w={canWrite:()=>j.enrolled()===T},m={activeId:F,route:R,updatedAt:Date.now()};if(!Z){F6.enqueue("routing:legacy","routing",()=>w$(m,u0,w));return}if(F6.enqueue(`routing:${Z}`,"routing",()=>f8({sessionId:Z,...m},E,u0,w)),!N||N===Z)return;if(R==="sticky-balanced"){let a=b.stickyAssignments?.[L6(N)]?.accountId,c=E===void 0||a==="main"||E.some((f)=>f.enabled!==!1&&f.id===a);if(!a||!c)return;F6.enqueue(`routing:${N}`,"routing",()=>f8({sessionId:N,activeId:a,route:R,updatedAt:Date.now()},E,u0,w));return}F6.enqueue(`routing:${N}`,"routing",()=>f8({sessionId:N,...m},E,u0,w))}B?.stopBackgroundRefresh(),B=e0;let d9=U0(X0());if(H=y$={accountStoragePath:d9.configPath,accountStatePath:d9.statePath,packageVersion:v6,quotaManager:J0,loadAccounts:R0,beginAccountLogin:i1,store:()=>D9(d9),migration:async()=>{if(await c1(d9,D9(d9))!==void 0)return{migrated:!0};let Z=await(B0.fence??(()=>q9({currentVersion:v6})))();return{migrated:!1,blockers:Z.open?[]:Z.blockers.map((N)=>({pid:N.pid,version:N.version}))}},afterWrite:()=>M0.load(),vault:j,resolveResetTarget:cB({getAuth:I,refreshMainWithLease:l8,refreshFallbackAccount:(Z,N)=>e0.refreshAccount(Z,N),refreshPoolMainRow:(Z,N)=>e0.refreshAccount(Z,N,{asPoolMain:!0}),poolAccess:async(Z)=>M0.rowAccess(Z,await R0(U0(X0()))),loadAccounts:R0,accountStoragePath:X0(),accountStatePath:D$(X0()),now:Date.now}),...uB(),cacheKeepManager:p9,setCacheKeepEnabled:(Z)=>{JJ=Z},setCacheKeepSubagents:(Z)=>{XJ=Z},setCacheKeepSustain:(Z)=>{QJ=Z},setCacheKeepWindow:(Z)=>{GJ=Z},clearStickyRouting:async(Z)=>{let N=L6(Z),F=_.delete(N);return F6.cancel(`pin:${N}`),await k$(Z,u0)||F},getStickyRouting:async(Z)=>C$(U9(await d6.read(),_),Z),refreshSidebar:async()=>{Z9(),await K6(J0)},refreshAllQuota:async()=>{if(await j.authority(),j.enrolled()){let Z=await j.pollStale(0);return await K6(J0),Z.map((N)=>({account:N.id,ok:N.ok,...N.error!==void 0?{error:N.error}:{}}))}if(await M0.active()){let[Z,N]=await Promise.all([t4(),j.pollStale(0)]);return await K6(J0),[...Z,...N.map((F)=>({account:F.id,ok:F.ok,...F.error!==void 0?{error:F.error}:{}}))]}return C9(b1())},refreshResetTargetQuota:async(Z)=>{if(await j.authority(),j.enrolled())return{account:Z,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};if(await M0.active()){let[F]=await t4([Z]);return F??{account:Z,ok:!1,error:"targeted quota refresh returned no result"}}return(await C9(b1({respectBackoff:!1}),{accountKey:Z})).find((F)=>F.account===Z)??{account:Z,ok:!1,error:"targeted quota refresh returned no result"}}},y){let Z=y;try{let N=await $$(a3,Z.dir,()=>t3({dir:Z.dir,secureDir:Z.secureDir,sweepRoot:Z.sweepRoot,drain:kX,apply:async(F)=>{let R=G$(F);if(!R)throw Error("not an /openai apply request");return mX(H,R)}}));L.set(Z.dir,N)}catch{}}async function L9(Z,N,F,R,E="main",b){if(!F.trim())throw m9.warn("refusing to send a request with no access token",{account:E,accountId:R}),Error(bB);if(!b&&await j.authority()!=="local")return Response.json({error:{message:Q9["vault-refused"]}},{status:400});let T=X$(Z,N);if(T.delete("x-api-key"),T.delete("api-key"),T.set("authorization",`Bearer ${F}`),R)T.set("ChatGPT-Account-Id",R);T.set(b6.QUOTA_ACCOUNT_HEADER,E);let w=Q$(T),m=w?iB(G,w,$):void 0,a=Z instanceof URL?Z:new URL(typeof Z==="string"?Z:Z.url),c=a.pathname.includes("/v1/responses")||a.pathname.includes("/chat/completions")?new URL(X):a,Y0=TX({rewriteLite:aB,applyEffort:sB,init:{...N,headers:T},headers:T,metadata:m,installationID:Q,websocket:Boolean(B9&&a.pathname.endsWith("/responses")),responsesLite:J.responsesLite??!1,dumpSessionID:w}).init,W0=JJ,v0=new Headers(Y0?.headers),e=oX({enabled:W0,includeSubagents:XJ,headers:v0,body:Y0?.body});if(W0)YJ.trace("cachekeep headers",{pid:process.pid,hasParent:v0.has("x-parent-session-id"),sessionKey:e?.sessionKey,captured:Boolean(e),affinity:v0.get("x-session-affinity"),opencodeSession:v0.get("x-opencode-session"),sessionId:v0.get("session-id")});if(B9&&a.pathname.endsWith("/responses")){if(m9.debug("WS transport",{pid:process.pid,pathname:a.pathname,accountId:E}),e)p9.track({sessionKey:e.sessionKey,bodyText:e.bodyText,accountId:E,isSubagent:e.isSubagent,meta:{replayHeaders:e.replayHeaders,chatgptAccountId:R,routingSessionId:w}});if(!b)try{return await J9(await B9(c,Y0),F,"event-stream")}catch(A0){throw y6(A0,F)}let z0=`vault-stream:${AB()}`;h1.set(z0,{id:E,receipt:b});let U6=new Headers(Y0?.headers);U6.set(b6.QUOTA_ACCOUNT_HEADER,z0);let f0=()=>h1.delete(z0);try{let A0=await B9(c,{...Y0,headers:U6});if(!A0.body)return f0(),A0;let O6=A0.body.getReader();return await J9(new Response(new ReadableStream({async pull(D6){try{let P6=await O6.read();if(P6.done)f0(),D6.close();else D6.enqueue(P6.value)}catch(P6){f0(),D6.error(y6(P6,F))}},cancel(D6){return f0(),O6.cancel(D6)}}),{status:A0.status,statusText:A0.statusText,headers:A0.headers}),F,"event-stream")}catch(A0){throw f0(),y6(A0,F)}}let N0=b6.withoutInternalHeaders(Y0);if(typeof N0?.body!=="string")try{return await J9(await fetch(c,N0),F,"event-stream")}catch(z0){throw y6(z0,F)}if(e)p9.track({sessionKey:e.sessionKey,bodyText:e.bodyText,accountId:E,isSubagent:e.isSubagent,meta:{replayHeaders:e.replayHeaders,chatgptAccountId:R,routingSessionId:w}});m9.debug("HTTP transport",{pid:process.pid,pathname:a.pathname,accountId:E});try{let z0=await fetch(c,N0);return await A9({sessionID:w,transport:"http",phase:"http",bodyText:N0.body,accountId:E,url:c.toString(),method:N0.method,headers:N0.headers,status:z0.status}),await J9(z0,F,"event-stream")}catch(z0){throw await A9({sessionID:w,transport:"http",phase:"http",bodyText:N0.body,accountId:E,url:c.toString(),method:N0.method,headers:N0.headers,error:z0 instanceof Error?z0.message:String(z0)}),y6(z0,F)}}function i9(Z,N){if((N?.method??(Z instanceof Request?Z.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof N?.body!=="string")return!1;try{let R=Z instanceof URL?Z.toString():typeof Z==="string"?Z:Z.url;return new URL(R).pathname.endsWith("/responses")}catch{return!1}}function p$(Z){return J0.peekMainForPolicy(Z)?.quota}function ZJ(Z,N){for(let F of[Z?.primary?.checkedAt,Z?.secondary?.checkedAt,Z?.checkedAt,N])if(typeof F==="number"&&Number.isFinite(F))return F;return}function n9(Z,N,F,R,E){let b=ZJ(Z,N),T=ZJ(F),w=R===E&&F!=null&&(Z===void 0||T!==void 0&&(b===void 0||T>b));return{quota:w?F:Z,quotaCheckedAt:w?T:b,source:w?"file":"memory"}}function VJ(Z,N,F,R,E){let b=Z?.quota,T=n9(b,Z?.checkedAt,N,R,E),w=T.source,m=T.quota;if(!R$(m,F))return{exhausted:!1};let a=T$(m,F);if(!a)return{exhausted:!1};return{exhausted:!0,source:w,...a}}function BJ(Z,N){X6.debug("admission skip: exhausted account",{accountId:Z,source:N.source,resetsAt:N.resetsAt})}function LJ(Z,N="killswitch",F,R){let E=Date.now(),b=R?R.main:J0.getMain()?.quota,T=R?R.fallbacks:(Z?.accounts??[]).filter((f)=>f.enabled!==!1&&o0(f)).map((f)=>({accountId:f.id,quota:J0.getFallback(f.id)?.quota})),w=V$(b,T,E,Z);if(N==="quota-unknown")w=O$;else if(N==="quota-exhausted"&&F!==void 0)w=Math.max(1,Math.ceil((F-E)/1000));else if(N==="mid-stream-rate-limit"&&F!==void 0){let f=Math.max(1,Math.ceil((F-E)/1000));w=Math.min(w,f)}let m=Math.floor(w/60),a=w%60,c=N==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${m}m ${a}s.`:N==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${m}m ${a}s.`:N==="quota-unknown"?`OpenAI quota is not known yet for any available account; checking it now. Retry in ${m}m ${a}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${m}m ${a}s.`;return new Response(JSON.stringify({error:{message:c,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(w)}})}function n8(Z){let N=Z?.resetCreditsAvailable;return typeof N==="number"&&Number.isFinite(N)?N:void 0}async function l$(Z){let N=S1(Z.storage),F=Date.now(),R=J0.peekMainForPolicy(Z.mainAccountIdentity),E=n9(R?.quota,R?.checkedAt,Z.sidebarState.main.quota,Z.sidebarState.main.mainAccountId,Z.mainAccountIdentity),b=N?H9(R?.quota,Z.storage,void 0,F):void 0,T=Z.mainUnavailable?[]:[{accountId:"main",wireAccountId:Z.mainAccountIdentity,access:Z.primaryAccess,keepwarmAccountKey:"main",quota:E.quota,quotaCheckedAt:E.quotaCheckedAt,reservePercent:K1(Z.storage),configuredOrder:0,resetCreditsApplicable:n8(E.quota),killswitchPasses:b}],w=await e0.getUsableFallbackAccounts(Z.storage);if(!Z.storage)return T;for(let m of w){let a=u8(m);if(!a)continue;let c=Z.sidebarState.fallbacks.find((v0)=>v0.id===m.id),f=J0.peekFallbackForPolicy(m.id,m.accountId),Y0=n9(f?.quota,f?.checkedAt,c?.quota,c?.accountId,m.accountId),W0=N?H9(f?.quota,Z.storage,m.id,F):void 0;T.push({accountId:m.id,wireAccountId:m.accountId,access:a,keepwarmAccountKey:m.id,fallback:m,quota:Y0.quota,quotaCheckedAt:Y0.quotaCheckedAt,reservePercent:K1(Z.storage,m.id),configuredOrder:T.length,resetCreditsApplicable:n8(Y0.quota),killswitchPasses:W0})}return T}function NJ(Z,N,F,R,E){let b=S1(E)?Z.killswitchPasses:void 0;if(Z.accountId==="main"){let a=J0.peekMainForPolicy(Z.wireAccountId),c=n9(a?.quota,a?.checkedAt,N.main.quota,N.main.mainAccountId,Z.wireAccountId);return uY({quota:c.quota,quotaCheckedAt:c.quotaCheckedAt,status:F,now:R,killswitchPasses:b})}let T=N.fallbacks.find((a)=>a.id===Z.accountId),w=J0.peekFallbackForPolicy(Z.accountId,Z.wireAccountId),m=n9(w?.quota,w?.checkedAt,T?.quota,T?.accountId,Z.wireAccountId);return uY({quota:m.quota,quotaCheckedAt:m.quotaCheckedAt,status:F,now:R,killswitchPasses:b})}function d$(Z){return Z.accountId==="main"?"main":Z.keepwarmAccountKey}function jJ(Z){return J0.isRateLimited(d$(Z))}function o8(Z){let N=Z.candidates.filter((b)=>!jJ(b)),F=new Map(N.map((b)=>[b.accountId,b])),R=new Set(Z.excludeAccountIds),E=FJ({sessionId:Z.sessionId,requestBytes:Z.requestBytes,sidebarSnapshot:Z.sidebarSnapshot,now:Z.now,validPinnedAccountIds:[...F.keys()],excludeAccountIds:Z.excludeAccountIds??[],quotaCheckedAtByAccount:Object.fromEntries(N.map((b)=>[b.accountId,b.quotaCheckedAt])),wireAccountIdByAccount:Object.fromEntries(N.map((b)=>[b.accountId,b.wireAccountId])),select:(b)=>{let T=N.filter((w)=>!R.has(w.accountId));if(T.length===0)return;return c3({candidates:T,pendingBytes:b,requestBytes:Z.requestBytes,now:Z.now,onEmptyWeightedSet:()=>{z6.debug("sticky routing: no fresh weighted candidates; using configured order")}})},persist:!0});return E?F.get(E.accountId):void 0}function FJ(Z){let N=void 0,F=Z.validPinnedAccountIds,R=I$(U9(Z.sidebarSnapshot,_),{sessionId:Z.sessionId,requestBytes:Z.requestBytes,now:Z.now,validPinnedAccountIds:F,excludeAccountIds:Z.excludeAccountIds,quotaCheckedAtByAccount:Z.quotaCheckedAtByAccount,wireAccountIdByAccount:Z.wireAccountIdByAccount,choose:(b)=>{let T=Z.select(b);if(!T)return;return N={accountId:T.accountId,source:T.source,pendingBytes:b.get(T.accountId)??0},T}}),E=R.assignment;if(!Z.persist)return E;if(N&&E?.accountId===N.accountId)z6.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:L6(Z.sessionId),accountId:N.accountId,source:N.source,requestBytes:Z.requestBytes,pendingBytes:N.pendingBytes});if(E&&R.next!==void 0){let b=L6(Z.sessionId),T=v$(_,b,E);F6.enqueue(`pin:${b}`,"sticky-pin",async()=>{await b$({sessionId:Z.sessionId,assignment:E,validPinnedAccountIds:F},u0),T.persistedAt=Date.now()})}return E}async function i$(Z,N){let F=await e0.getUsableFallbackAccounts(Z),R=[];if(!Z)return{current:[],retained:[],skipped:[]};for(let c of F){let f=u8(c);if(!f)continue;R.push({access:f,accountId:c.accountId,keepwarmAccountKey:c.id,quotaAccountId:c.id,fallback:c})}let E=R.filter((c)=>!J0.isRateLimited(c.quotaAccountId)),b=S1(Z)?E.filter((c)=>H9(J0.peekFallbackForPolicy(c.quotaAccountId,c.accountId)?.quota,Z,c.quotaAccountId,Date.now())):E,T=new Map(N.fallbacks.map((c)=>[c.id,{quota:c.quota,accountId:c.accountId}])),w=[],m=[],a=Date.now();for(let c of b){let f=T.get(c.quotaAccountId),Y0=VJ(J0.peekFallbackForPolicy(c.quotaAccountId,c.accountId),f?.quota,a,f?.accountId,c.accountId);if(Y0.exhausted)m.push({candidate:c,decision:Y0});else w.push(c)}return{current:b,retained:w,skipped:m}}function OJ(Z,N){if(Z.retained.length===0&&!N)return Z.current;for(let{candidate:F,decision:R}of Z.skipped)BJ(F.quotaAccountId,R);return Z.retained}function DJ(Z,N){try{let F=Y9(Z.headers);V9(F,N.access,N.quotaAccountId,void 0,g9(Z.headers))}catch{}}async function n$(Z,N,F,R){for(let E of R){let b;try{b=await L9(Z,N,E.access,E.accountId,E.keepwarmAccountKey)}catch(T){if((T instanceof Error||T instanceof DOMException)&&T.name==="AbortError")throw T;if(N?.signal?.aborted)throw T;throw z6.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:E.quotaAccountId}),T}if(!w1(b.status,F))return e0.markUsed(E.fallback),{response:b,accessToken:E.access,quotaAccountId:E.quotaAccountId,activeId:E.keepwarmAccountKey};DJ(b,E),b.body?.cancel().catch(()=>{})}return}async function o$(Z,N,F,R,E){if(!i9(Z,N))return{response:F};if(!E.length)return{response:F};let b=F,T;for(let w of E){let m;try{m=await L9(Z,N,w.access,w.accountId,w.keepwarmAccountKey)}catch(a){if((a instanceof Error||a instanceof DOMException)&&a.name==="AbortError")throw a;if(N?.signal?.aborted)throw a;return z6.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:w.quotaAccountId}),{response:b,...T}}if(b.body?.cancel().catch(()=>{}),b=m,T={accessToken:w.access,accountId:w.quotaAccountId},!w1(m.status,R))return e0.markUsed(w.fallback),{response:m,...T};DJ(m,w)}return{response:b,...T}}if(w0){let Z=[];for(let N of w0.accounts)if(o0(N))Z.push(N);J0.seedFallbacksFromAccounts(Z)}if(!r4)if(r4=!0,K6(J0).catch(()=>{}),C.then(()=>j.enrolled()?K6(J0):void 0).catch(()=>{}),!j.enrolled()&&!await M0.active())m8=C9(b1({respectBackoff:!0})).catch((Z)=>X6.warn("boot quota seed failed",{pid:process.pid,error:h9(Z)}));else m8=Promise.resolve();v.start(async()=>{if(await j.authority(),j.enrolled()){await K6(J0);return}if(await M0.active()){let F=await dX(M0,await R0(U0(X0())),()=>PY(X0()));if(F.length>0)await K6(J0);let R=F.filter((E)=>!E.ok);if(R.length>0)X6.warn("background pool quota poll completed with failures",{pid:process.pid,failures:R});return}let N=(await pX(b1({readSidebarState:async()=>(await d6.read()).state}))).filter((F)=>!F.ok);if(N.length>0)X6.warn("background quota refresh completed with failures",{pid:process.pid,failures:N})},(Z)=>{X6.warn("background quota refresh failed",{pid:process.pid,error:Z instanceof Error?Z.message:String(Z)})});async function r8(Z,N,F,R,E,b){let T=F?.routing?.mode??"main-first",w=j.enrolled(),m=w?void 0:M0.peek().rows.find((e)=>e.id==="main"),a=!m&&!w?await I():void 0,c=!m&&a?.type==="oauth"&&m0(a),f=!m&&!w&&await y8(U0(X0()),a);if(b===u9)c9=m?.identity;let Y0=await d6.get(),{response:W0,servedId:v0}=await M3({source:M0,...w?{vault:{routes:()=>j.routes(),awaitRoster:async()=>{await W1(j.awaitRequestRoster(),wY)},noRouteCause:()=>F$(j),send:(e,N0)=>j.send(e,N0,{site:"model",...N?.signal?{signal:N.signal}:{}}),requestReading:(e)=>j.requestReading(e),rateLimitMarks:()=>{for(let[e,N0]of l9)if(N0<=Date.now())l9.delete(e);return l9}}}:{},storage:F,mode:T,sessionId:R,body:typeof N?.body==="string"?N.body:void 0,replayable:i9(Z,N),now:Date.now,send:(e,N0,z0)=>L9(Z,N,N0,e.identity,e.id,z0),recordQuota:(e,N0,z0,U6)=>{try{let f0=Y9(e.headers),A0=g9(e.headers);if(!N0.row){if(U6)j.recordSnapshot(N0.id,f0,A0,U6).then(HJ);return}V9(f0,z0,N0.id==="main"?void 0:N0.id,N0.id==="main"?N0.identity:void 0,A0)}catch{}},placePin:(e)=>FJ({...e,sidebarSnapshot:Y0}),blocked:(e,N0,z0)=>{if(e.reason==="no-credential"){if(f&&!yY(z0))throw Error(P9);return new Response(yY(z0)?j$(z0,j.name):Q9[c?"missing-main":z0??"unusable"],{status:401,headers:{"content-type":"text/plain; charset=utf-8"}})}return LJ(F,e.reason,e.resetAtMs,N0)},resetCredits:(e)=>n8(e==="main"?J0.peekMainForPolicy(m?.identity)?.quota:J0.peekFallbackForPolicy(e)?.quota),isAbort:(e)=>(e instanceof Error||e instanceof DOMException)&&e.name==="AbortError"||Boolean(N?.signal?.aborted),log:z6});return i8(R,E,v0,T,w?j.routes().map((e)=>({id:e.id})):F?.accounts,U9(Y0,_),w),W0}return K=!0,{apiKey:kB,async fetch(Z,N){let F=await j.authority(),R=X$(Z,N),E=Q$(R),b=R.get("x-parent-session-id")?.trim()||void 0,T=await j6();if(F!=="local")return N=await d4(Z,N),r8(Z,N,T,E,b,++u9);let w=await I();if(await j.authority()!=="local")return N=await d4(Z,N),r8(Z,N,T,E,b,++u9);let m=++u9;if(w.type!=="oauth")return R.delete(X1),fetch(Z,{...N,headers:R});N=await d4(Z,N);let a=(await M0.current()).active;if(n0(w)&&a)return r8(Z,N,T,E,b,m);if(a)j.assertHostSlot(w);let c="",f=!1,Y0,W0=n0(w);if(t?.migrated()&&!W0&&w.refresh?.trim()&&o4(w).kind==="real")t.noticeRealSlot(w.refresh);let v0=async(j0=T)=>{if(W0=!0,Y0=await WJ(j0),Y0)c=Y0.token;else c="",f=!0,z6.warn("main account in the pool has no usable token",{pid:process.pid})};if(W0)await v0();else if(m0(w))f=!0;else{if(!w.access||(w.expires??0)<Date.now()){I1.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(w.access),expiresInMs:w.expires?w.expires-Date.now():void 0});try{let j0=await l8();w.access=j0.access,w.refresh=j0.refresh,w.expires=j0.expires}catch(j0){if(l4(j0))throw j0;if(j0 instanceof r6)await v0(await R0(U0(X0())))}}if(!W0)c=w.access??""}let e=W0?WY(T):T,N0=w,z0=Y0?.account.accountId??(W0?void 0:N0.accountId)??(c?J6(Y6(c)??{}):void 0);if(m===u9)c9=z0;let U6=T?.routing?.mode??"main-first",f0=await d6.get(),A0=f0.state;if(U6==="sticky-balanced"&&E&&i9(Z,N)&&typeof N?.body==="string"){let j0=Buffer.byteLength(N.body,"utf8"),b0=await l$({storage:e,sidebarState:A0,primaryAccess:c,mainAccountIdentity:z0,mainUnavailable:f}),S0=o8({sessionId:E,requestBytes:j0,candidates:b0,sidebarSnapshot:f0,now:Date.now()});if(S0){let AJ=jJ(S0)?{action:"migrate",reason:"exhausted"}:NJ(S0,A0,void 0,Date.now(),T);if(AJ.action==="migrate"){let d0=o8({sessionId:E,requestBytes:j0,candidates:b0,sidebarSnapshot:f0,excludeAccountIds:[S0.accountId],now:Date.now()});if(d0)z6.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:L6(E),fromAccountId:S0.accountId,toAccountId:d0.accountId,reason:AJ.reason}),S0=d0}let H6=await L9(Z,N,S0.access,S0.wireAccountId,S0.keepwarmAccountKey),TJ=(d0,i6)=>{try{let r$=Y9(d0.headers);V9(r$,i6.access,i6.accountId==="main"?void 0:i6.accountId,i6.accountId==="main"?i6.wireAccountId:void 0,g9(d0.headers))}catch{}};TJ(H6,S0);let RJ=NJ(S0,A0,H6.status,Date.now(),T);if((H6.status===401||H6.status===403||H6.status===429)&&RJ.action==="migrate"){let d0=o8({sessionId:E,requestBytes:j0,candidates:b0,sidebarSnapshot:f0,excludeAccountIds:[S0.accountId],now:Date.now()});if(d0){z6.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:L6(E),fromAccountId:S0.accountId,toAccountId:d0.accountId,reason:RJ.reason});let i6=H6;H6=await L9(Z,N,d0.access,d0.wireAccountId,d0.keepwarmAccountKey),i6.body?.cancel().catch(()=>{}),S0=d0,TJ(H6,S0)}}if(S0.fallback&&!w1(H6.status,T))e0.markUsed(S0.fallback);return i8(E,b,S0.accountId,U6,T?.accounts,U9(f0,_)),H6}}let O6=VJ(J0.peekMainForPolicy(z0),A0.main.quota,Date.now(),A0.main.mainAccountId,z0),D6=S1(T)&&!H9(p$(z0),T,void 0,Date.now()),P6=J0.isRateLimited("main"),PJ,s8=()=>{return PJ??=i$(e,A0),PJ},_6,N9,_J=!1,y1;if(U6==="fallback-first"&&i9(Z,N)){_J=!0;let j0=await s8();y1=OJ(j0,!D6&&!P6&&!O6.exhausted);let b0=await n$(Z,N,T,y1);if(b0)_6=b0.response,N9={accessToken:b0.accessToken,accountId:b0.quotaAccountId,activeId:b0.activeId}}if(!_6){let j0=O6.exhausted&&i9(Z,N)&&(await s8()).retained.length>0;if(D6||P6||j0){let b0=D6?"killswitch":P6?"mid-stream-rate-limit":"quota-exhausted";if(b0==="quota-exhausted"&&O6.exhausted)BJ("main",O6);z6.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:b0}),_6=LJ(T,b0,b0==="quota-exhausted"&&O6.exhausted?O6.resetAtMs:P6?J0.rateLimitedUntil("main"):void 0)}else _6=f?new Response(null,{status:401}):await L9(Z,N,c,z0,"main")}let a8=Boolean(N9),o9=_6,qJ=N9?.accessToken??c,EJ=N9?.accountId,MJ=N9?.activeId??"main";if(!N9&&!_J&&w1(_6.status,T)){z6.debug("reactive fallback triggered",{pid:process.pid,status:_6.status}),y1??=OJ(await s8(),!1);let j0=await o$(Z,N,_6,T,y1),b0=j0.response;if(b0!==_6){if(a8=!0,o9=b0,qJ=j0.accessToken??c,EJ=j0.accountId,j0.accountId)MJ=j0.accountId}}if(W0&&f&&!a8&&await y8(U0(X0()),await I()))throw Error(P9);try{let j0=Y9(o9.headers);if(a8)V9(j0,qJ,EJ,void 0,g9(o9.headers));else V9(j0,c,void 0,z0,g9(o9.headers))}catch{}return i8(E,b,MJ,U6,T?.accounts,U9(f0,_)),o9}}},methods:_0},"chat.headers":async(I,u)=>{if(I.model.providerID!=="openai")return;if(u.headers.originator="opencode",u.headers["User-Agent"]=`${z$(v6)} (${u4.platform()} ${u4.release()}; ${u4.arch()})`,u.headers["session-id"]=I.sessionID,K)u.headers[X1]=I.agent;if(W&&I.agent==="title")u.headers[b6.TITLE_HEADER]="true"},"chat.params":async(I,u)=>{if(I.model.providerID!=="openai")return;u.maxOutputTokens=void 0},config:async(I)=>{V0("commands").info("registering commands",{existing:Object.keys(I.command??{}).length,pid:process.pid}),I.command={...I.command??{},[k6]:{template:k6,description:"OpenAI accounts: quota, routing, limits, cache keep-warm, diagnostics and reset credits."}}},"command.execute.before":async(I)=>{if(V0("commands").info("command hook entered",{command:I.command,hasCmdCtx:H!==null,pid:process.pid}),I.command!==k6)return;if(!H)V0("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 u=await fX(H,I.sessionID);if(xX(I.sessionID))s1(u,I.sessionID);else await l(I.sessionID,cX(u.menu));eG()}}}var eB=async(Y)=>{let J=i0();return tB(Y,{codexApiEndpoint:J.codexApiEndpoint,experimentalWebSockets:J.webSockets,responsesLite:J.responsesLite})},Aq={id:"cortexkit-openai-auth",server:eB};
|
|
65
|
+
export{GY as d,X0 as e,i0 as f,$Y as g,P9 as h,q9 as i,v6 as j,A9 as k,M6 as l,MX as m,r1 as n,AX as o,Q1 as p,TX as q,Kz as r,RX as s,Uz as t,s1 as u,kX as v,xX as w,fX as x,mX as y,Nj as z,rX as A,tX as B,wY as C,SY as D,W1 as E,IY as F,H3 as G,iz as H,A3 as I,T3 as J,I3 as K,v3 as L,a3 as M,t3 as N,R1 as O,IG as P,CB as Q,wB as R,SB as S,IB as T,bB as U,Pq as V,xB as W,vB as X,_q as Y,qq as Z,a4 as _,g0 as $,mB as aa,cB as ba,uB as ca,Eq as da,dB as ea,nB as fa,J$ as ga,g$ as ha,Mq as ia,Q$ as ja,oB as ka,aB as la,tB as ma,eB as na,Aq as oa};
|