@cortexkit/opencode-openai-auth 0.9.1 → 0.11.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/README.md +4 -6
- package/dist/index.js +53 -66
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -1,123 +1,110 @@
|
|
|
1
|
-
import{A as
|
|
2
|
-
`);for(let
|
|
3
|
-
`)}var
|
|
4
|
-
`)return"enter";if(
|
|
5
|
-
`),N+=1},q=
|
|
1
|
+
import{A as x4,B as b4,C as v4,D as h4,c as k9,e as kX,h as GY,i as _4,j as YY,m as a1,q as oQ,r as I4,s as S4,t as k4,y as $8,z as LX}from"./index-g3hsdjh4.js";import{I as B5,J as F5}from"./index-4effjmr6.js";import{$ as JQ,$a as A9,Aa as m8,Ba as t9,Ca as HX,Da as RY,Ea as L1,Fa as w4,Ga as TY,Ha as O0,Ia as A4,Ja as c1,Ka as d8,L as J4,La as w0,M as Q4,Ma as m1,N as $4,Na as ZX,O as l8,Oa as P0,P as j4,Pa as JY,Q as q4,Qa as QY,R as EY,Ra as Q8,S as D4,Sa as $Y,T as wQ,Ta as R4,U as A0,Ua as T4,V as f0,Va as v1,W as CY,Wa as M1,X as yX,Xa as C4,Y as eQ,Ya as i,Z as j0,Za as M9,_ as P4,_a as w9,aa as QQ,ab as R9,ba as W1,bb as T9,ca as z1,cb as C9,da as J9,db as _9,ea as $Q,eb as I9,fa as GQ,fb as S9,ga as WQ,gb as qX,ha as zQ,hb as E1,ia as KQ,ja as UQ,ka as HQ,la as AY,ma as $9,na as g1,oa as t1,pa as E4,qa as V1,ra as b0,sa as G4,ta as sJ,ua as WX,va as J8,wa as W4,xa as M4,ya as aJ,za as f8}from"./index-sq36b120.js";import{kb as g4}from"./index-jwn4r3sw.js";import{mb as Q9,nb as XY,ob as bK}from"./index-hh52v8sb.js";import{sb as nX}from"./index-9ehhb051.js";import{mkdirSync as EF,readFileSync as y4,renameSync as MF,statSync as wF,writeFileSync as AF}from"node:fs";import zX from"node:os";import{join as G8}from"node:path";import{execFileSync as MU}from"node:child_process";import{readFileSync as QU}from"node:fs";import{homedir as $U,tmpdir as GU}from"node:os";import{join as OY}from"node:path";var WU="https://chatgpt.com/backend-api/codex/responses",zU="openai-auth.json",P1={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 jY(){let Y=process.env[P1.configDir]?.trim();if(Y)return Y;return OY(process.env.XDG_CONFIG_HOME||OY($U(),".config"),"opencode")}function t(){return process.env[P1.configFile]?.trim()||OY(jY(),zU)}function KU(){try{let Y=JSON.parse(QU(t(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function UU(Y){let X=process.env[Y];if(X===void 0)return;let J=X.trim().toLowerCase();if(J==="1"||J==="true"||J==="yes"||J==="on")return!0;if(J===""||J==="0"||J==="false"||J==="no"||J==="off")return!1;return}function BY(Y,X,J){let Q=UU(Y);if(Q!==void 0)return Q;if(typeof X==="boolean")return X;return J}function HU(){let Y=KU(),X;if(Y.dump!==void 0&&Y.dump!==null){if(typeof Y.dump==="object")X=Y.dump.enabled;else if(typeof Y.dump==="boolean")X=Y.dump}return{webSockets:BY(P1.webSockets,Y.webSockets,!1),rawWebSocket:BY(P1.rawWebSocket,Y.rawWebSocket,!1),responsesLite:BY(P1.responsesLite,Y.responsesLite,!1),dump:BY(P1.dump,X,!1),dumpDir:process.env[P1.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():OY(GU(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[P1.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():WU)}}var FY;function s0(){if(!FY)FY=HU();return FY}function OX(){return FY=void 0,s0()}import{realpathSync as g8}from"node:fs";import{homedir as ZU}from"node:os";import{basename as LU,dirname as VU,join as DY,resolve as c8}from"node:path";function NU(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return DY(process.env.XDG_CONFIG_HOME||DY(ZU(),".config"),"opencode")}function u8(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||DY(NU(),f8)}function qY(Y,X){let J=c8(Y);return X==="win32"||X==="darwin"?J.toLowerCase():J}function y8(Y){try{return g8.native(Y)}catch{try{return DY(g8.native(VU(Y)),LU(Y))}catch{return}}}function BU(Y,X,J=process.platform){if(qY(Y,J)===qY(X,J))return!0;let Q=y8(Y),$=y8(X);return Q!==void 0&&$!==void 0&&qY(Q,J)===qY($,J)}function PY(Y=u8()){let X=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(X){if(BU(Y,X))throw Error(`OPENCODE_OPENAI_AUTH_STATE_FILE resolves to the config path (${c8(Y)}). Set OPENCODE_OPENAI_AUTH_STATE_FILE to a different file.`);return X}return m8(Y)}function r(Y=u8()){return{configPath:Y,statePath:PY(Y)}}var E9="0.11.0";import{readFile as FU}from"node:fs/promises";function p8(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}async function i8(Y){let X=await d8(Y.configPath),J=[];try{let $=JSON.parse(await FU(Y.statePath,"utf8"));if(p8($)){let G=$.accounts;if(p8(G))J=Object.keys(G)}}catch($){if($.code!=="ENOENT")throw $}return{rosterIds:X?[...X]:[],stateIds:J,orphanStateIds:X?J.filter(($)=>!X.has($)):[]}}function jX(Y){if(!Y)return;let X=Y.accounts.find((J)=>J.id==="main"&&O0(J));if(X)return X;if(!Y.mainAccountId)return;return Y.accounts.find((J)=>O0(J)&&J.accountId===Y.mainAccountId)}function OU(Y,X){let J=Y.lastRefreshError;return EY(J,Y.refresh,X)&&J!==void 0&&J.nextRetryAt!==void 0&&J.nextRetryAt-J.checkedAt>=l8}function n8(Y){let X=[],J=[],Q=Y.now??Date.now(),$=jX(Y.storage),G=!1;if(!Y.auth)X.push({code:"auth-slot-missing",message:"OpenCode's OpenAI auth slot is missing."}),G=!0;else if(Y.auth.type!=="oauth")X.push({code:"auth-slot-not-oauth",message:"OpenCode's OpenAI auth slot is not OAuth."}),G=!0;else if($&&(!Y.auth.refresh||$.refresh!==Y.auth.refresh))X.push({code:"main-refresh-not-in-store",message:"OpenCode's main credential does not match the copy in the account store."}),G=!0;if(G&&$){let H={type:"restore-main-credential"};J.push(H);let U=X.find((Z)=>Z.code==="auth-slot-missing"||Z.code==="auth-slot-not-oauth"||Z.code==="main-refresh-not-in-store");if(U)U.repair=H}let W=Y.storage?.accounts??[];if(W.length===0)X.push({code:"no-accounts",message:"The account store has no accounts."});else if(!W.some((H)=>H.enabled!==!1))X.push({code:"no-enabled-accounts",message:"The account store has no enabled accounts."});for(let H of W){if(!O0(H))continue;if(!OU(H,Q))continue;let U={type:"clear-refresh-backoff",accountId:H.id};J.push(U),X.push({code:"armed-non-transient-refresh-backoff",accountId:H.id,message:`Account ${H.id} has an armed non-transient refresh backoff.`,repair:U})}let K=[...Y.orphanStateIds??[]];if(K.length>0){let H={type:"prune-orphan-state-ids",ids:K};J.push(H),X.push({code:"orphan-state-ids",message:`State contains ids absent from the config roster: ${K.join(", ")}.`,repair:H})}return{findings:X,repairs:J}}function o8(Y){let X=["OpenAI auth doctor"];if(Y.findings.length===0)return X.push("No problems found."),X.join(`
|
|
2
|
+
`);for(let J of Y.findings){let Q=J.repair?" (repair available)":"";X.push(`- ${J.message}${Q}`)}return X.join(`
|
|
3
|
+
`)}var e={hide:"\x1B[?25l",show:"\x1B[?25h",up:(Y=1)=>`\x1B[${Y}A`,clearLine:"\x1B[2K",clearScreen:"\x1B[2J",moveTo:(Y,X)=>`\x1B[${Y};${X}H`,cyan:"\x1B[36m",green:"\x1B[32m",red:"\x1B[31m",dim:"\x1B[2m",reset:"\x1B[0m"};function r8(Y){let X=Y.toString();if(X==="\x1B[A"||X==="\x1BOA")return"up";if(X==="\x1B[B"||X==="\x1BOB")return"down";if(X==="\r"||X===`
|
|
4
|
+
`)return"enter";if(X==="\x03")return"escape";if(X==="\x1B")return"escape-start";return null}function s8(){return Boolean(process.stdin.isTTY)}var jU=50,a8=`${String.fromCharCode(27)}\\[[0-9;]*m`,qU=new RegExp(a8,"g"),DU=new RegExp(`^${a8}`);function PU(Y){return Y.replace(qU,"")}function MY(Y,X){if(X<=0)return"";if(PU(Y).length<=X)return Y;let J=X>=3?"...":".".repeat(X),Q=Math.max(0,X-J.length),$="",G=0,W=0;while(G<Y.length&&W<Q){if(Y[G]==="\x1B"){let K=Y.slice(G).match(DU);if(K){$+=K[0],G+=K[0].length;continue}}$+=Y[G],G+=1,W+=1}return $.includes("\x1B[")?`${$}${e.reset}${J}`:$+J}function EU(Y){if(Y==="red")return e.red;if(Y==="cyan")return e.cyan;return""}async function wY(Y,X){if(!s8())throw Error("Interactive select requires a TTY terminal");if(Y.length===0)throw Error("No menu items provided");if(Y.length===1)return Y[0]?.value??null;let{stdin:J,stdout:Q}=process,$=0,G=null,W=!1,K=0,H=()=>{let U=Q.columns??80,Z=Q.rows??24,F=K;if(X.clearScreen)Q.write(e.clearScreen+e.moveTo(1,1));else if(F>0)Q.write(e.up(F));let N=0,V=(E)=>{Q.write(`${e.clearLine}${E}
|
|
5
|
+
`),N+=1},q=X.subtitle?3:0,R=Math.max(1,Math.min(Y.length,Z-(1+q+2)-1)),k=Math.max(0,Math.min($-Math.floor(R/2),Math.max(0,Y.length-R))),u=Y.slice(k,k+R);if(V(`${e.dim}┌ ${e.reset}${MY(X.message,Math.max(1,U-4))}`),X.subtitle)V(`${e.dim}│${e.reset}`),V(`${e.cyan}◆${e.reset} ${MY(X.subtitle,Math.max(1,U-4))}`),V("");for(let E=0;E<u.length;E++){let S=u[E];if(!S)continue;let c=k+E===$,o=EU(S.color),J0=o?`${c?"":e.dim}${o}${S.label}${e.reset}`:c?S.label:`${e.dim}${S.label}${e.reset}`;J0=MY(J0,Math.max(1,U-8)),V(c?`${e.cyan}│${e.reset} ${e.green}●${e.reset} ${J0}`:`${e.cyan}│${e.reset} ${e.dim}○${e.reset} ${J0}`)}let C=u.length<Y.length?` (${k+1}-${k+u.length}/${Y.length})`:"";V(`${e.cyan}│${e.reset} ${e.dim}${MY(`Up/Down to select | Enter: confirm | Esc: back${C}`,Math.max(1,U-6))}${e.reset}`),V(`${e.cyan}└${e.reset}`);for(let E=N;E<F;E++)V("");K=N};return new Promise((U)=>{let Z=J.isRaw??!1,F=()=>{if(W)return;if(W=!0,G)clearTimeout(G);J.removeListener("data",q);try{J.setRawMode(Z),J.pause(),Q.write(e.show)}catch{}process.removeListener("SIGINT",V),process.removeListener("SIGTERM",V)},N=(R)=>{F(),U(R)},V=()=>N(null),q=(R)=>{if(G)clearTimeout(G),G=null;switch(r8(R)){case"up":$=($-1+Y.length)%Y.length,H();break;case"down":$=($+1)%Y.length,H();break;case"enter":N(Y[$]?.value??null);break;case"escape":N(null);break;case"escape-start":G=setTimeout(()=>N(null),jU);break}};process.once("SIGINT",V),process.once("SIGTERM",V);try{J.setRawMode(!0)}catch{F(),U(null);return}J.resume(),Q.write(e.hide),H(),J.on("data",q)})}var t8=[{label:"Add account",value:"add-account",color:"cyan"},{label:"Auth current",value:"auth-current",color:"cyan"},{label:"Check quotas",value:"check-quotas",color:"cyan"},{label:"Auth doctor",value:"auth-doctor",color:"cyan"},{label:"Apply repairs",value:"apply-repairs",color:"cyan"},{label:"Delete all accounts",value:"delete-all",color:"red"}],MO=t8.map((Y)=>Y.label);async function e8(){return await wY(t8,{message:"OpenAI accounts",subtitle:"Select an account action",clearScreen:!0})??"cancel"}async function YQ(Y,X=!1){return await wY(X?[{label:"Yes",value:!0},{label:"No",value:!1}]:[{label:"No",value:!1},{label:"Yes",value:!0}],{message:Y})??!1}function wU(Y,X=process.platform,J=MU){try{if(X==="win32")J("cmd",["/c","start","",Y],{stdio:"ignore",timeout:3000});else J(X==="darwin"?"open":"xdg-open",[Y],{stdio:"ignore",timeout:3000});return!0}catch{return!1}}function AU(){return{url:"",instructions:"",method:"auto",callback:async()=>({type:"failed"})}}async function RU(){let{redirectUri:Y}=await WQ(),X=await QQ(),J=JQ(crypto.getRandomValues(new Uint8Array(32)).buffer),Q=$Q(Y,X,J),$=zQ(X,J);return{url:Q,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let G=await $;return{type:"success",refresh:G.refresh_token,access:G.access_token,expires:Date.now()+(G.expires_in??3600)*1000,accountId:J9(G)}}finally{GQ(J)}}}}async function TU(Y){let{deviceData:X,url:J,instructions:Q}=await KQ(Y);return{url:J,instructions:Q,method:"auto",async callback(){try{let $=await UQ(X,Y);return{type:"success",refresh:$.refresh_token,access:$.access_token,expires:Date.now()+($.expires_in??3600)*1000,accountId:J9($)}}catch{return{type:"failed"}}}}}function XQ(Y){if(console.log(`
|
|
6
6
|
Open this URL in your browser and complete sign-in:
|
|
7
7
|
`),console.log(`${Y.url}
|
|
8
8
|
`),Y.instructions)console.log(`${Y.instructions}
|
|
9
|
-
`)}function
|
|
10
|
-
`),E=await W.beginAccountLogin({version:$,headless:!0}),
|
|
11
|
-
`),knobs:{config:Q,accountIds:$}}}if(G[0]==="on"){let W={...Q,enabled:!0,main:Q.main??{primary:
|
|
9
|
+
`)}function ZQ({client:Y,getAuth:X,getPaths:J=()=>r(t()),fetchImpl:Q=fetch,packageVersion:$=E9,dependencies:G}){let W={authorizeBrowser:G?.authorizeBrowser??RU,authorizeHeadless:G?.authorizeHeadless??(()=>TU($)),beginAccountLogin:G?.beginAccountLogin??AY,loadAccounts:G?.loadAccounts??w0,mutateAccounts:G?.mutateAccounts??P0,refreshAllQuota:G?.refreshAllQuota??E1,showAuthMenu:G?.showAuthMenu??e8,confirm:G?.confirm??YQ,readStoreIds:G?.readStoreIds??i8,openBrowser:G?.openBrowser??wU,now:G?.now??Date.now,custodyQuotaDeps:G?.custodyQuotaDeps??{}},K=async()=>await X?.().catch(()=>{return})??{type:"missing"},H=async()=>{if((await K()).type!=="missing")return!0;return((await W.loadAccounts(J()))?.accounts.length??0)>0},U=async(C)=>{await Y.auth.set({path:{id:"openai"},body:{type:"oauth",...C}})},Z=async()=>{let C=new AbortController,E=await W.beginAccountLogin({version:$,signal:C.signal});E.completion.catch(()=>{}),XQ(E);let S=!1;try{S=await W.openBrowser(E.url)!==!1}catch{S=!1}if(!S)C.abort(),console.log(`Could not open a browser. Switching to device authorization.
|
|
10
|
+
`),E=await W.beginAccountLogin({version:$,headless:!0}),XQ(E);return E.completion},F=async()=>{let C=await W.loadAccounts(J());if(m1(C)==="claustrum"){console.log("That account cannot be added while Claustrum mode is active. Run `/openai-account local` first.");return}let E=await Z(),S=!1;if(await W.mutateAccounts((c)=>{if(E.accountId&&c.mainAccountId&&E.accountId===c.mainAccountId)return S=!0,c;return HQ(c.accounts,E),c},J()),S){console.log("That account is already the OpenCode main credential.");return}console.log(`Added fallback account ${E.id}.`)},N=async()=>{let C=await Z();await U({refresh:C.refresh,access:C.access??"",expires:C.expires??0}),console.log("Updated the OpenCode main credential.")},V=async()=>{let C=J(),E=await W.loadAccounts(C),S=new TY({storage:E,configPath:C.configPath,fetchImpl:Q,now:W.now}),c={refreshAccount:async(K0)=>K0},o=async()=>{throw Error("No usable main access token for quota check")},J0=async(K0)=>{let B0=await W.loadAccounts(K0);if(!B0)return null;return{...B0,accounts:B0.accounts.map((u0)=>O0(u0)?{...u0,lastRefreshError:void 0}:{...u0})}},L0=await W.refreshAllQuota({getAuth:K,codexRefreshFn:o,refreshMainWithLease:o,fallbackManager:c,quotaManager:S,loadAccounts:J0,writeSidebarState:async()=>{},client:{auth:{set:async()=>{throw Error("Quota checks cannot write credentials")}}},fetchImpl:Q,now:W.now,paths:C,storageMainAccountId:E?.mainAccountId,isOAuthAccountFn:O0,whamFn:RY,respectBackoff:!1,readSidebarState:async()=>({main:{},fallbacks:[]}),...W.custodyQuotaDeps});CU(L0)},q=async()=>{let C=J(),[E,S,c]=await Promise.all([W.loadAccounts(C),W.readStoreIds(C),K()]),o=n8({auth:c.type==="missing"?void 0:c,storage:E,orphanStateIds:S.orphanStateIds,now:W.now()});return console.log(o8(o)),o},R=async()=>{let C=await q();if(C.repairs.length===0){console.log("No repairs are available.");return}if(!await W.confirm("Apply the listed auth repairs?")){console.log("Repairs cancelled.");return}let E=J();for(let S of C.repairs){if(S.type==="restore-main-credential"){let c=await W.loadAccounts(E),o=jX(c);if(!o)continue;await U({refresh:o.refresh,access:o.access??"",expires:o.expires??0});continue}if(S.type==="prune-orphan-state-ids"){await W.mutateAccounts((c)=>c,E);continue}await W.mutateAccounts((c)=>{let o=c.accounts.find((J0)=>J0.id===S.accountId&&O0(J0));if(o)o.lastRefreshError=void 0;return c},E)}console.log(`Applied ${C.repairs.length} auth repair(s).`)},k=async()=>{if(!await W.confirm("Delete all fallback accounts?")){console.log("Delete cancelled.");return}let C=[];await W.mutateAccounts((E,S)=>{let c=new Set([...S?.rawRosterIds??[],...E.accounts.map((o)=>o.id)].filter((o)=>o!=="main"));return C.splice(0,C.length,...c),E.accounts=E.accounts.filter((o)=>o.id==="main"),E},J(),{allowDrop:C}),console.log("Deleted all fallback accounts.")},u=async(C)=>{switch(C){case"add-account":await F();break;case"auth-current":await N();break;case"check-quotas":await V();break;case"auth-doctor":await q();break;case"apply-repairs":await R();break;case"delete-all":await k();break;case"cancel":break}};return[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:async(C)=>{if(C&&await H())return await u(await W.showAuthMenu()),AU();return W.authorizeBrowser()}},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:W.authorizeHeadless},{label:"Manually enter API Key",type:"api"}]}function CU(Y){for(let X of Y)console.log(X.ok?`${X.account}: quota refreshed`:`${X.account}: ${X.error??"quota refresh failed"}`)}var a0=j0("commands");function x0(Y){return{configPath:Y.accountStoragePath,statePath:Y.accountStatePath}}async function SU(Y,X){let J=await X.loadAccounts(x0(X))??{version:1,accounts:[]},Q=J.killswitch??{},$=(J.accounts??[]).filter((W)=>W.enabled!==!1).map((W)=>W.id),G=Y.trim().toLowerCase().split(/\s+/).filter(Boolean);if(G.length===0){let W=Q.enabled===!0,K=["## Killswitch","",`Status: **${W?"ON":"OFF"}**`];if(W){K.push(""),K.push("| Account | primary threshold | secondary threshold |"),K.push("| ------- | ------------ | ------------ |");let H=Q.main??{},U=H.primary??H["5h"]??c1.primary,Z=H.secondary??H["1w"]??c1.secondary;K.push(`| main | ≥ ${U}% | ≥ ${Z}% |`);for(let F of $){let N=Q.accounts?.[F]??Q.main??{},V=N.primary??N["5h"]??c1.primary,q=N.secondary??N["1w"]??c1.secondary;K.push(`| ${F} | ≥ ${V}% | ≥ ${q}% |`)}}return K.push(""),K.push("Commands: `/openai-killswitch on` | `/openai-killswitch off` | `/openai-killswitch set <acct>:<5h>,<1w> ...`"),{command:"openai-killswitch",text:K.join(`
|
|
11
|
+
`),knobs:{config:Q,accountIds:$}}}if(G[0]==="on"){let W={...Q,enabled:!0,main:Q.main??{primary:c1.primary,secondary:c1.secondary}};return await P0((K)=>{return K.killswitch=W,K},x0(X)),a0.info("killswitch enabled"),{command:"openai-killswitch",text:"## Killswitch Enabled",knobs:{config:W,accountIds:$}}}if(G[0]==="off"){let W={...Q,enabled:!1};return await P0((K)=>{return K.killswitch=W,K},x0(X)),a0.info("killswitch disabled"),{command:"openai-killswitch",text:"## Killswitch Disabled",knobs:{config:W,accountIds:$}}}if(G[0]==="set"&&G.length>1){let W={...Q,enabled:!0,accounts:{...Q.accounts??{}}};for(let K=1;K<G.length;K++){let H=G[K]?.match(/^([^:]+):(\d+),(\d+)$/);if(!H)continue;let[,U,Z,F]=H,N={primary:Number.parseInt(Z,10),secondary:Number.parseInt(F,10)};if(U==="main")W.main=N;else if(U==="all"){W.main=N;for(let V of $)W.accounts[V]=N}else W.accounts[U]=N}return await P0((K)=>{return K.killswitch=W,K},x0(X)),a0.info("killswitch thresholds updated",{count:G.length-1}),{command:"openai-killswitch",text:"## Killswitch Updated",knobs:{config:W,accountIds:$}}}return{command:"openai-killswitch",text:"Usage: `/openai-killswitch`, `/openai-killswitch on`, `/openai-killswitch off`, `/openai-killswitch set <acct>:<5h>,<1w> ...`",knobs:{config:Q,accountIds:$}}}async function kU(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),Q=s0(),$=Q.dump;if(J.length===0)return{command:"openai-dump",text:`## Request Dump
|
|
12
12
|
|
|
13
13
|
- Enabled: ${$?"ON":"OFF"}
|
|
14
14
|
- Directory: ${Q.dumpDir}
|
|
15
15
|
|
|
16
|
-
Usage: \`/openai-dump on\` or \`/openai-dump off\``,knobs:{enabled:$}};if(
|
|
16
|
+
Usage: \`/openai-dump on\` or \`/openai-dump off\``,knobs:{enabled:$}};if(J[0]==="on"){await P0((W)=>{return W.dump={...W.dump??{},enabled:!0},W},x0(X));let G=OX();return a0.info("request dump enabled"),{command:"openai-dump",text:`## Request Dump Enabled
|
|
17
17
|
|
|
18
18
|
Dump directory: ${G.dumpDir}
|
|
19
19
|
|
|
20
|
-
Warning: body dumps may contain prompt/session content. Turn this off after debugging.`,knobs:{enabled:!0}}}if(
|
|
20
|
+
Warning: body dumps may contain prompt/session content. Turn this off after debugging.`,knobs:{enabled:!0}}}if(J[0]==="off")return await P0((G)=>{return G.dump={...G.dump??{},enabled:!1},G},x0(X)),OX(),a0.info("request dump disabled"),{command:"openai-dump",text:"## Request Dump Disabled",knobs:{enabled:!1}};return{command:"openai-dump",text:"Usage: `/openai-dump`, `/openai-dump on`, or `/openai-dump off`.",knobs:{enabled:$}}}async function xU(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),Q=["error","warn","info","debug","trace"];if(J.length===0){let W=(await X.loadAccounts(x0(X)))?.logging?.level??"info";return{command:"openai-logging",text:`## Logging
|
|
21
21
|
|
|
22
22
|
- Level: \`${W}\`
|
|
23
23
|
|
|
24
24
|
Valid levels: ${Q.map((K)=>`\`${K}\``).join(", ")}
|
|
25
25
|
|
|
26
|
-
Usage: \`/openai-logging <level>\``,knobs:{level:W}}}let $=
|
|
26
|
+
Usage: \`/openai-logging <level>\``,knobs:{level:W}}}let $=J[0];if($&&Q.includes($)){let G=$;return CY(G),await P0((W)=>{return W.logging={...W.logging??{},level:G},W},x0(X)),a0.info("log level changed",{level:G}),{command:"openai-logging",text:`## Logging Updated
|
|
27
27
|
|
|
28
28
|
Level set to \`${G}\`.`,knobs:{level:G}}}return{command:"openai-logging",text:`## Invalid Level
|
|
29
29
|
|
|
30
|
-
Valid levels: ${Q.map((G)=>`\`${G}\``).join(", ")}`,knobs:{level:"info"}}}function
|
|
30
|
+
Valid levels: ${Q.map((G)=>`\`${G}\``).join(", ")}`,knobs:{level:"info"}}}function bU(Y){let X=/^(\d{1,2})-(\d{1,2})$/.exec(Y.trim());if(!X)return{ok:!1,reason:"expected HH-HH, e.g. 9-18 or 22-6"};let J=Number(X[1]),Q=Number(X[2]);if(!Number.isInteger(J)||!Number.isInteger(Q)||J<0||J>23||Q<0||Q>23||J===Q)return{ok:!1,reason:"hours must be integers 0-23 and start ≠ end"};return{ok:!0,startHour:J,endHour:Q}}async function vU(Y,X){let J=X.cacheKeepManager,Q=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),$=await X.loadAccounts(x0(X)),G=$?.cachekeep?.enabled===!0;if(Q.length===0||Q[0]==="status"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
|
|
31
31
|
|
|
32
|
-
Status: **not available** (manager not wired)`,knobs:{}};let K=
|
|
33
|
-
`),knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:K.sustain,window:
|
|
32
|
+
Status: **not available** (manager not wired)`,knobs:{}};let K=J.status(),H=K.window,U=H?`${String(H.startHour).padStart(2,"0")}-${String(H.endHour).padStart(2,"0")}`:"always (no window)",Z=["## Cachekeep","",`Status: **${G?"ON":"OFF"}**`,`Timer: **${K.running?"armed":"idle"}**`,`Subagent warming: **${$?.cachekeep?.subagents===!0?"ON":"OFF"}**`,`Idle policy: **sustain ${K.sustain?"ON":"OFF"} (main only)**`,`Window: **${U}**`];if(Z.push(`Tracked sessions: **${K.tracked}**`),K.targets.length>0){Z.push("");for(let N of K.targets){let V=N.sessionKey.length>12?`${N.sessionKey.slice(0,12)}…`:N.sessionKey,q=Math.ceil((N.cacheExpiresAt-K.generatedAt)/1000);Z.push(`- \`${V}\` (${N.accountId??"main"}) — expires in ${q}s`+(N.lastWarmedAt?`, last warm ${Math.ceil((K.generatedAt-N.lastWarmedAt)/1000)}s ago`:"")+(N.backoffUntil&&N.backoffUntil>K.generatedAt?`, backoff ${Math.ceil((N.backoffUntil-K.generatedAt)/1000)}s`:""))}}Z.push(""),Z.push(`TTL: ${Math.round(K.ttlMs/1000)}s | Lead: ${Math.round(K.leadMs/1000)}s | Max idle warm: ${Math.round(K.maxIdleWarmMs/60000)}min`),Z.push(""),Z.push("Commands: `/openai-cachekeep on` | `/openai-cachekeep off` | `/openai-cachekeep sustain on` | `/openai-cachekeep sustain off` | `/openai-cachekeep HH-HH` | `/openai-cachekeep window clear` | `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off` | `/openai-cachekeep`");let F=Math.max(0,...K.targets.map((N)=>N.lastWarmedAt??0));return{command:"openai-cachekeep",text:Z.join(`
|
|
33
|
+
`),knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:K.sustain,window:H,running:K.running,tracked:K.tracked,lastWarmAt:F||void 0,generatedAt:K.generatedAt,maxIdleWarmMs:K.maxIdleWarmMs,maxSubagentIdleMs:K.maxSubagentIdleMs}}}if(Q[0]==="on"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
|
|
34
34
|
|
|
35
|
-
Cannot start: manager not wired.`,knobs:{}};await
|
|
35
|
+
Cannot start: manager not wired.`,knobs:{}};await P0((U)=>{return U.cachekeep={...U.cachekeep??{},enabled:!0},U},x0(X)),a0.info("cachekeep enabled"),X.setCacheKeepEnabled?.(!0),J.start();let K=J.status(),H=Math.max(0,...K.targets.map((U)=>U.lastWarmedAt??0));return{command:"openai-cachekeep",text:`## Cachekeep Enabled
|
|
36
36
|
|
|
37
|
-
TTL: ${Math.round(K.ttlMs/1000)}s | Max idle warm ${Math.round(K.maxIdleWarmMs/60000)}min`,knobs:{enabled:!0,subagents:$?.cachekeep?.subagents===!0,sustain:K.sustain,window:K.window,running:K.running,tracked:K.tracked,lastWarmAt:
|
|
37
|
+
TTL: ${Math.round(K.ttlMs/1000)}s | Max idle warm ${Math.round(K.maxIdleWarmMs/60000)}min`,knobs:{enabled:!0,subagents:$?.cachekeep?.subagents===!0,sustain:K.sustain,window:K.window,running:K.running,tracked:K.tracked,lastWarmAt:H||void 0,generatedAt:K.generatedAt,maxIdleWarmMs:K.maxIdleWarmMs,maxSubagentIdleMs:K.maxSubagentIdleMs}}}if(Q[0]==="off")return await P0((K)=>{return K.cachekeep={...K.cachekeep??{},enabled:!1},K},x0(X)),a0.info("cachekeep disabled"),X.setCacheKeepEnabled?.(!1),J?.stop(),{command:"openai-cachekeep",text:"## Cachekeep Disabled",knobs:{enabled:!1,sustain:$?.cachekeep?.sustain===!0,running:!1,tracked:0}};if(Q[0]==="sustain"){let K=Q[1];if(Q.length!==2||K!=="on"&&K!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep sustain on` | `/openai-cachekeep sustain off`",knobs:{}};let H=K==="on";await P0((Z)=>{return Z.cachekeep={...Z.cachekeep??{},sustain:H},Z},x0(X)),a0.info(`cachekeep sustain ${H?"enabled":"disabled"}`),X.setCacheKeepSustain?.(H);let U=J?.status();return{command:"openai-cachekeep",text:H?`## Cachekeep Sustain Enabled
|
|
38
38
|
|
|
39
39
|
Sustain keeps main-agent sessions warming past the idle cap for this process. Clock windows still apply.
|
|
40
40
|
|
|
41
41
|
Before 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.`:`## Cachekeep Sustain Disabled
|
|
42
42
|
|
|
43
|
-
Main-agent sessions again stop warming at the configured idle cap.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:
|
|
43
|
+
Main-agent sessions again stop warming at the configured idle cap.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:H,window:U?.window,running:U?.running??!1,tracked:U?.tracked??0,generatedAt:U?.generatedAt??Date.now(),maxIdleWarmMs:U?.maxIdleWarmMs??3600000,maxSubagentIdleMs:U?.maxSubagentIdleMs??1800000}}}if(Q[0]==="subagents"){let K=Q[1];if(!K||K!=="on"&&K!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off`",knobs:{}};let H=K==="on";await P0((Z)=>{return Z.cachekeep={...Z.cachekeep??{},subagents:H},Z},x0(X)),a0.info(H?"cachekeep subagent warming enabled":"cachekeep subagent warming disabled"),X.setCacheKeepSubagents?.(H);let U=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Subagent Warming
|
|
44
44
|
|
|
45
|
-
Subagent warming: **${
|
|
45
|
+
Subagent warming: **${H?"ON":"OFF"}**`,knobs:{enabled:G,subagents:H,sustain:U?.sustain??$?.cachekeep?.sustain===!0,window:U?.window,running:U?.running??!1,tracked:U?.tracked??0,generatedAt:U?.generatedAt??Date.now(),maxIdleWarmMs:U?.maxIdleWarmMs??3600000,maxSubagentIdleMs:U?.maxSubagentIdleMs??1800000}}}if(Q[0]==="window"){let K=Q[1];if(K==="clear"||K==="off"){await P0((U)=>{if(U.cachekeep)delete U.cachekeep.startHour,delete U.cachekeep.endHour;return U},x0(X)),X.setCacheKeepWindow?.(void 0),a0.info("cachekeep window cleared");let H=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Cleared
|
|
46
46
|
|
|
47
|
-
Cachekeep will now warm on every tick (within idle caps).`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:
|
|
47
|
+
Cachekeep will now warm on every tick (within idle caps).`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:H?.sustain??$?.cachekeep?.sustain===!0,window:void 0,running:H?.running??!1,tracked:H?.tracked??0,generatedAt:H?.generatedAt??Date.now(),maxIdleWarmMs:H?.maxIdleWarmMs??3600000,maxSubagentIdleMs:H?.maxSubagentIdleMs??1800000}}}return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep window clear`",knobs:{}}}let W=Q[0];if(W&&/^\d{1,2}-\d{1,2}$/.test(W)){let K=bU(W);if(!K.ok)return{command:"openai-cachekeep",text:`## Cachekeep Window Invalid
|
|
48
48
|
|
|
49
|
-
${K.reason}`,knobs:{}};let{startHour:
|
|
49
|
+
${K.reason}`,knobs:{}};let{startHour:H,endHour:U}=K;await P0((N)=>{return N.cachekeep={...N.cachekeep??{},startHour:H,endHour:U},N},x0(X)),X.setCacheKeepWindow?.({startHour:H,endHour:U}),a0.info("cachekeep window set",{startHour:H,endHour:U});let Z=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Set
|
|
50
50
|
|
|
51
|
-
Warming limited to **${`${String(
|
|
52
|
-
`).trim();X=[];let W=J;if(J=void 0,!G||G==="[DONE]")return;try{let K=JSON.parse(G),Z=K.type??W;if(Z!=="response.completed"&&Z!=="response.done")return;let U=K.response;Q=AQ(U?.usage??K.usage)}catch{}};for(let G of Y.split(/\r?\n/)){if(G===""){$();continue}if(G.startsWith("event:")){J=G.slice(6).trim();continue}if(G.startsWith("data:"))X.push(G.slice(5).trim())}return $(),Q??TJ()}class CJ{targets=new Map;fetchImpl;getMainToken;refreshFallback;codexResponsesUrl;log;now;ttlMs;leadMs;maxIdleWarmMs;maxSubagentIdleMs;tickIntervalMs;maxTargets;maxBytes;getWindow;getSustain;timer=null;startedAt=null;totalBytes=0;tickInFlight=!1;disposed=!1;abortController=new AbortController;logPayload(Y={}){return{pid:process.pid,...Y}}constructor(Y){this.fetchImpl=Y.fetchImpl,this.getMainToken=Y.getMainToken,this.refreshFallback=Y.refreshFallback,this.codexResponsesUrl=Y.codexResponsesUrl,this.log=Y.logger,this.now=Y.now,this.ttlMs=Y.ttlMs??YZ,this.tickIntervalMs=Y.tickIntervalMs??DQ,this.leadMs=Y.leadMs??this.tickIntervalMs+15000;let J=Y.maxIdleWarmMs??Y.maxDurationMs;this.maxIdleWarmMs=typeof J==="number"&&Number.isFinite(J)&&J>0?J:JZ;let X=Y.maxSubagentIdleMs??qQ;this.maxSubagentIdleMs=typeof X==="number"&&Number.isFinite(X)&&X>0?X:qQ,this.tickIntervalMs=Y.tickIntervalMs??DQ,this.maxTargets=Y.maxTargets??XZ,this.maxBytes=Y.maxBytes??QZ,this.getWindow=Y.getWindow,this.getSustain=Y.getSustain}track(Y,J,X,Q,$={},G=!1){this.pruneStale();let W=J.length;if(W>this.maxBytes){this.log.debug("cachekeep track skipped (body exceeds maxBytes)",this.logPayload({sessionKey:Y,bodyBytes:W,maxBytes:this.maxBytes}));return}let K=this.getWindow?.();if(K&&!jQ(K,new Date(this.now()))){this.log.debug("cachekeep track skipped (outside window)",this.logPayload({sessionKey:Y,startHour:K.startHour,endHour:K.endHour}));return}if(this.targets.has(Y)){let L=this.targets.get(Y);if(L)this.totalBytes-=L.bodyText.length;this.targets.delete(Y)}else this.log.debug("cachekeep captured target",this.logPayload({sessionKey:Y,accountId:X}));while(this.targets.size>=this.maxTargets||this.totalBytes+W>this.maxBytes&&this.targets.size>0){let L,j=Number.POSITIVE_INFINITY;for(let[V,q]of this.targets){let T=Math.max(q.lastRealRequestAt,q.lastWarmedAt??0);if(T<j)L=V,j=T}if(L===void 0)break;let N=this.targets.get(L);if(N)this.totalBytes-=N.bodyText.length;this.targets.delete(L)}let Z=GZ(J,this.ttlMs),U={bodyText:J,accountId:X||void 0,chatgptAccountId:Q,route:"main",ttlMs:Z,cacheExpiresAt:this.now()+Z,warmCount:0,lastRealRequestAt:this.now(),replayHeaders:$,isSubagent:G,is56:wQ(J)};this.targets.set(Y,U),this.totalBytes+=W,this.start()}isGpt56Subagent(Y){return Y.isSubagent===!0&&Y.is56}pruneStale(){let Y=this.now(),J=Y-this.maxIdleWarmMs,X=Y-this.maxSubagentIdleMs,Q=Y-OQ;for(let[$,G]of this.targets){let W,K;if(this.isGpt56Subagent(G))W=Q,K=OQ;else W=G.isSubagent?X:J,K=G.isSubagent?this.maxSubagentIdleMs:this.maxIdleWarmMs;if(!(G.isSubagent!==!0&&this.getSustain?.()===!0)&&G.lastRealRequestAt<W)this.log.debug("cachekeep pruned idle target",this.logPayload({sessionKey:$,accountId:G.accountId??"main",lastRealRequestAt:G.lastRealRequestAt,maxIdleWarmMs:K})),this.totalBytes-=G.bodyText.length,this.targets.delete($)}}start(){if(this.disposed=!1,this.timer)return;if(this.startedAt=this.now(),this.log.debug("cachekeep started",this.logPayload({ttlMs:this.ttlMs,leadMs:this.leadMs,maxIdleWarmMs:this.maxIdleWarmMs})),this.timer=setInterval(()=>{this.tick().catch(()=>{})},this.tickIntervalMs),"unref"in this.timer)this.timer.unref()}stop(){if(this.disposed=!0,this.abortController.abort(),this.abortController=new AbortController,this.timer)clearInterval(this.timer),this.timer=null;this.startedAt=null,this.targets.clear(),this.totalBytes=0,this.log.debug("cachekeep stopped",this.logPayload())}remove(Y){let J=this.targets.get(Y);if(J)this.totalBytes-=J.bodyText.length,this.targets.delete(Y),this.log.debug("cachekeep removed target",this.logPayload({sessionKey:Y}))}status(){let Y=this.now(),J=Array.from(this.targets.entries()).map(([X,Q])=>({sessionKey:X,accountId:Q.accountId,route:Q.route,cacheExpiresAt:Q.cacheExpiresAt,lastRealRequestAt:Q.lastRealRequestAt,lastWarmedAt:Q.lastWarmedAt,backoffUntil:Q.backoffUntil,bodyBytes:Q.bodyText.length}));return{running:this.timer!=null,tracked:this.targets.size,generatedAt:Y,startedAt:this.startedAt,maxIdleWarmMs:this.maxIdleWarmMs,maxSubagentIdleMs:this.maxSubagentIdleMs,ttlMs:this.ttlMs,leadMs:this.leadMs,sustain:this.getSustain?.()===!0,window:this.getWindow?.(),targets:J}}async tick(){if(this.tickInFlight)return;this.tickInFlight=!0;try{this.pruneStale();let Y=this.getWindow?.();if(Y&&!jQ(Y,new Date(this.now())))return;let J=this.now(),X=J+this.leadMs;for(let[Q,$]of this.targets)if($.backoffUntil&&J>=$.backoffUntil&&$.cacheExpiresAt<=X)await this.prewarm(Q,$);for(let[Q,$]of this.targets){if($.backoffUntil&&J<$.backoffUntil)continue;if($.cacheExpiresAt<=X)await this.prewarm(Q,$)}}finally{this.tickInFlight=!1}}async prewarm(Y,J){let X,Q;try{if(J.accountId&&J.accountId!=="main"){let G=await this.refreshFallback(J.accountId);if(typeof G==="string")X=G;else X=G.token,Q=G.onAuthFailure}else X=await this.getMainToken()}catch(G){if(!this.disposed&&this.targets.get(Y)===J)J.backoffUntil=this.now()+RJ;this.log.debug("cachekeep skip (no token)",this.logPayload({sessionKey:Y,accountId:J.accountId??"main",error:G instanceof Error?G.message:String(G)}));return}if(this.disposed||this.targets.get(Y)!==J)return;let $={...J.replayHeaders,authorization:`Bearer ${X}`,"content-type":"application/json"};if(J.chatgptAccountId)$["ChatGPT-Account-Id"]=J.chatgptAccountId;else delete $["ChatGPT-Account-Id"];try{let G=$Z(J.bodyText),W;try{let S=JSON.parse(G);W={warmBodyKeys:Object.keys(S),stream:S.stream,max_output_tokens:S.max_output_tokens,store:S.store,has_stream_options:"stream_options"in S,has_max_tokens:"max_tokens"in S,model:S.model}}catch{}this.log.debug("cachekeep warm request",this.logPayload({...W,headerKeys:Object.keys($),hasChatGptAccountId:"ChatGPT-Account-Id"in $}));let K=_Y({method:"POST",headers:$,body:G,signal:AbortSignal.any([AbortSignal.timeout(30000),this.abortController.signal])}),Z=await this.fetchImpl(this.codexResponsesUrl,K),U="";try{U=await Z.text()}catch{}if(this.disposed||this.targets.get(Y)!==J)return;if(!Z.ok){if(J.backoffUntil=this.now()+RJ,Z.status===401)await Q?.(Z.status);this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:J.accountId??"main",status:Z.status,error:`HTTP ${Z.status}`,responseBody:U.slice(0,600)}));return}let L=Z.headers.get("content-type")??"",j=L.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(U.slice(0,200));this.log.debug("cachekeep warm response",this.logPayload({status:Z.status,contentType:L,bodyLen:U.length,isSse:j}));let N=j?zZ(U):WZ(U),V=X9(Z.headers),q=V.primary?.usedPercent??null,T=V.secondary?.usedPercent??null;if(this.log.debug("cachekeep fired",this.logPayload({session:Y,accountId:J.accountId??"main",input_tokens:N.input_tokens,cached_tokens:N.cached_tokens,hit_rate:N.hit_rate,output_tokens:N.output_tokens,quota_primary_pct:q,quota_secondary_pct:T})),J.cacheExpiresAt=this.now()+J.ttlMs,J.lastWarmedAt=this.now(),J.backoffUntil=void 0,J.warmCount+=1,this.isGpt56Subagent(J)&&J.warmCount>=2){if(this.targets.get(Y)===J)this.totalBytes-=J.bodyText.length,this.targets.delete(Y);return}}catch(G){if(this.disposed||this.targets.get(Y)!==J)return;J.backoffUntil=this.now()+RJ,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:J.accountId??"main",error:G instanceof Error?G.message:String(G)}))}}}import{createHash as ZZ}from"node:crypto";import{isAbsolute as KZ,join as RQ}from"node:path";var UZ=B0("custody"),TQ=new Set;function _J(Y=process.env){let J=Y.CLAUSTRUM_OPENCODE_HANDLES;if(J&&KZ(J))return J;if(J&&!TQ.has(J))TQ.add(J),UZ.warn("ignoring non-absolute CLAUSTRUM_OPENCODE_HANDLES",{configuredPath:J});let X=Y.XDG_CONFIG_HOME||(Y.HOME?RQ(Y.HOME,".config"):".config");return RQ(X,"cortexkit","opencode-handles.json")}function s0(Y=_J(),J={}){return CQ(Y,J)}var IJ="openai",_Q=250,bQ=new Set;function vQ(Y){if(typeof Y.access!=="string"||typeof Y.refresh!=="string")return;let J=Buffer.from(Y.access),X=Buffer.from(Y.refresh),Q=($)=>{let G=Buffer.alloc(4);return G.writeUInt32BE($.length),G};return ZZ("sha256").update(Q(J)).update(J).update(Q(X)).update(X).digest("hex")}function hQ(Y){let J=vQ(Y);if(J)bQ.add(J)}function LZ(Y){let J=vQ(Y);return J!==void 0&&bQ.has(J)}function gQ(Y){if(!Y||typeof Y!=="object")return;let J=Y;if(J.type!=="oauth")return;return{type:"oauth",...typeof J.access==="string"?{access:J.access}:{},...typeof J.refresh==="string"?{refresh:J.refresh}:{},...typeof J.expires==="number"?{expires:J.expires}:{}}}function SY(Y){let J=gQ(Y);if(typeof J?.access!=="string"||typeof J.refresh!=="string")return;return{access:J.access,refresh:J.refresh,...typeof J.expires==="number"?{expires:J.expires}:{}}}function IY(Y){let J=gQ(Y);if(!J)return{kind:"indeterminate"};if(!k0({id:"main",type:"oauth",access:J.access??"",refresh:J.refresh??"",expires:J.expires??0,addedAt:0},IJ))return{kind:"real",oauth:J};let X=V1(IJ);if(J.access===X.access&&J.expires===X.expires)return{kind:"tombstone",oauth:J};return{kind:"empty",oauth:J}}async function IQ(Y){if(!Y.auth.get)return;return Y.auth.get({path:{id:IJ}})}async function SQ(Y){if(!Y.auth.all)return!1;return Object.keys(await Y.auth.all()).length>0}async function HZ(Y){let J=await IQ(Y.client);if(J!==void 0)return IY(J);let X=await SQ(Y.client),Q=Y.now();if(await Y.sleep(_Q),Y.now()-Q<_Q)return{kind:"indeterminate"};let $=await IQ(Y.client);if($!==void 0)return IY($);let G=await SQ(Y.client);return X&&G?{kind:"slot-absent"}:{kind:"indeterminate"}}function VZ(Y){if(Y.ok)return"present";return Y.reason==="absent"?"absent":"unreadable"}function k9(Y){let J=Q1(Y);return J?$1(J):void 0}async function kQ(Y){let J=y0(Y.manifest).get("main");if(!J)return"no_handle";if(!Y.getCredential)return"cold";try{let X=await Y.getCredential(J),Q=k9(X.access);if(Y.mainAccountId&&Q&&Q!==Y.mainAccountId)return"identity_mismatch";return"serves"}catch{return Y.isReauth?.(J)?"needs_reauth":"cold"}}function xQ(Y){return Y.kind==="real"&&LZ(Y.oauth)}async function yQ(Y){let J=await HZ(Y);if(J.kind==="indeterminate")return;let X=VZ(Y.manifest);if(J.kind==="slot-absent"){let $=await kQ(Y);return S9({mode:Y.mode,manifest:X,local:J.kind,verifiedInProcessLogin:xQ(J),vault:()=>$==="no_handle"||$==="identity_mismatch"?$:"serves"})}let Q=await kQ(Y);return S9({mode:Y.mode,manifest:X,local:J.kind,verifiedInProcessLogin:xQ(J),vault:()=>Q})}import{createHash as NZ}from"node:crypto";var dQ="claustrum-mode",c1="main-refresh",fQ=Promise.resolve();async function kJ(){let Y,J=new Promise(($)=>{Y=$}),X=fQ;fQ=X.then(()=>J),await X;let Q=!1;return{async release(){if(Q)return;Q=!0,Y()}}}async function iQ(Y){let J=Y.now()+5000;while(Y.now()<J){try{let X=await Y.getAuth();if(X?.access===Y.accessToken&&X.refresh===Y.refreshToken){await Y.onObserved?.({access:X.access,refresh:X.refresh}),await Y.release();return}}catch{}await Y.sleep(Math.max(0,Math.min(100,J-Y.now())))}Y.warn("host write not observed within 5s; lease released"),await Y.release()}function mQ(Y){return Y.accounts.filter((J)=>V0(J)&&J.enabled!==!1)}function SJ(Y,J){return Y<J?-1:Y>J?1:0}function cQ(Y,J){return[{id:"main",accountId:J?.mainAccountId,kind:"main"},...Y.map((X)=>({id:X,accountId:J?.accounts.find((Q)=>Q.id===X)?.accountId,kind:"fallback"}))].sort((X,Q)=>SJ(X.id,Q.id))}function BZ(Y){return Y.kind==="main"?c1:M1(Y.id)}function uQ(Y){return Y.access?Q9(Y.access,Y.refresh):void 0}function pQ(Y){return Object.values(Y).some((J)=>J==="new-local-family-under-claustrum"||J==="torn-read-deferred"||J.startsWith("aborted:"))}async function oQ(Y){let J=await kJ(),X=[],Q={},$=!1,G=async(W)=>{await Y.onStep?.(W)};try{if(await G("mutex-acquired"),Y.accountIds.includes("main")||new Set(Y.accountIds).size!==Y.accountIds.length)return{status:"aborted",outcomes:Q,reason:"duplicate-account-lock"};let W=await Y.acquireLock({name:dQ,renew:!0});if(!W)return{status:"aborted",outcomes:Q,reason:"mode-lock-unavailable"};X.push(W),Y.warn?.(`transition deps: ${JSON.stringify({acquireLock:typeof Y.acquireLock,withStoreTransaction:typeof Y.withStoreTransaction,readManifest:typeof Y.readManifest,preflight:typeof Y.preflight,auth:typeof Y.auth,authAll:typeof Y.auth?.all,authGet:typeof Y.auth?.get,authSet:typeof Y.auth?.set,accountIds:Y.accountIds?.length})}`);let K=cQ(Y.accountIds);Y.warn?.(`transition participants: ${K.map((Z)=>Z.id).join(",")}`);for(let Z of K){let U=await Y.acquireLock({name:BZ(Z),renew:!0});if(!U)return{status:"aborted",outcomes:Q,reason:`account-lock-unavailable:${Z.id}`};X.push(U)}return await Y.withStoreTransaction(async(Z)=>{let U=await Z.read(),L=cQ(Y.accountIds,U),j=mQ(U).map((E)=>E.id).sort(SJ),N=[...Y.accountIds].sort(SJ);if(j.length!==N.length||j.some((E,b)=>E!==N[b]))return{status:"aborted",outcomes:Q,reason:"account-roster-changed"};let V=await Y.readManifest();if(!V.ok)return{status:"aborted",outcomes:Q,reason:`manifest-${V.reason}`};let q=y0(V),T=U.claustrum?.mode==="claustrum"?U.claustrum?.transition:void 0,S=T?T.fingerprints:{fallbacks:{}},c=T?.storeGeneration??lQ(U);if(!T){Y.warn?.(`capturing main slot fingerprint; auth.get is ${typeof Y.auth?.get}`);let E=SY(await Y.auth.get({path:{id:"openai"}}));if(Y.warn?.(`main slot captured: ${E?"complete":"absent"}`),E)S.main=Q9(E.access,E.refresh);for(let b of mQ(U)){let f=uQ(b);if(f)S.fallbacks[b.id]=f}}await G("captured"),Y.warn?.(`handles resolved: isMap=${q instanceof Map} size=${q instanceof Map?q.size:"n/a"}`);for(let E of L){let b=q.get(E.id);if(Y.warn?.(`participant ${E.id}: handle=${b?"yes":"NO"}`),!b){Q[E.id]="no-handle";continue}let f=await Y.preflight({id:E.id,accountId:E.accountId,handle:b});Q[E.id]=f}if(await G("preflight"),Object.values(Q).some((E)=>E!=="ready"))return{status:"aborted",outcomes:Q,reason:"preflight-failed"};if(!T){let E=await Y.readManifest(),b=await Z.read();if(!E.ok||E.revision!==V.revision)return{status:"aborted",outcomes:Q,reason:"manifest-revision-changed"};if(lQ(b)!==c)return{status:"aborted",outcomes:Q,reason:"store-generation-changed"};await G("revalidated"),await Z.writeMode("claustrum",{manifestRevision:V.revision,storeGeneration:c,fingerprints:S}),await G("mode-written")}let _=!1;for(let E of K){if(E.kind==="main")continue;let b=await Z.read(),f=b.accounts.find((W0)=>W0.id===E.id&&W0.type==="oauth");if(f&&k0(f,"openai")){Q[E.id]="tombstoned";continue}let o=S.fallbacks[E.id];if(!f||!o||uQ(f)!==o){Q[E.id]="new-local-family-under-claustrum";continue}let t=structuredClone(b),N0=t.accounts.find((W0)=>W0.id===E.id&&W0.type==="oauth");if(!N0){Q[E.id]="new-local-family-under-claustrum";continue}Object.assign(N0,V1("openai"));try{await Z.write(t);let W0=(await Z.read()).accounts.find((O0)=>O0.id===E.id&&O0.type==="oauth");Q[E.id]=W0&&k0(W0,"openai")?"tombstoned":"aborted:post-write-readback"}catch{Q[E.id]="aborted:write-failed",_=!0;break}}if(_)return await G("material-written"),{status:"incomplete",outcomes:Q};if(Q.main=S.main?await xJ(S.main,{auth:Y.auth,warn:(E)=>{if($)return;$=!0,Y.warn?.(E)}}):"new-local-family-under-claustrum",await G("material-written"),!pQ(Q))await Z.writeMode("claustrum");return{status:pQ(Q)?"incomplete":"completed",outcomes:Q}})}finally{for(let W of X.reverse())await W.release().catch(()=>{});await J.release(),await G("mutex-released").catch(()=>{})}}async function xJ(Y,J){let X=SY(await J.auth.get({path:{id:"openai"}}));if(X&&k0({id:"main",type:"oauth",access:X.access,refresh:X.refresh,expires:X.expires??0},"openai"))return"tombstoned";if(!X||Q9(X.access,X.refresh)!==Y)return"new-local-family-under-claustrum";let Q=await J.auth.all();if(Object.keys(Q).length===0)return J.warn?.("host auth store read empty; refusing to write — possible torn read"),"torn-read-deferred";try{let $=V1("openai");await J.auth.set.bind(J.auth)({path:{id:"openai"},body:$});let W=SY(await J.auth.get({path:{id:"openai"}}));return W&&W.access===$.access&&W.refresh===$.refresh&&W.expires===$.expires?"tombstoned":"new-local-family-under-claustrum"}catch{return"aborted:write-failed"}}async function nQ(Y){let J=await Y.acquireLock({name:dQ,renew:!0});if(!J)throw Error("Claustrum mode lock unavailable");try{await Y.withStoreTransaction(async(X)=>{return await X.writeMode("local"),{status:"completed",outcomes:{}}})}finally{await J.release()}}function lQ(Y){let J=Y.accounts.filter((X)=>X.type==="oauth").map((X)=>({id:X.id,enabled:X.enabled!==!1,accountId:X.accountId??"",access:X.access??"",refresh:X.refresh,expires:X.expires??null})).sort((X,Q)=>X.id<Q.id?-1:X.id>Q.id?1:0);return NZ("sha256").update(JSON.stringify(J)).digest("hex")}var eQ=900000,FZ=0.016666666666666666,rQ=0.000001;function vJ(Y,J){for(let X of[Y?.primary?.checkedAt,Y?.checkedAt,J])if(typeof X==="number"&&Number.isFinite(X))return X;return}function hJ(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let J=vJ(Y.quota,Y.quotaCheckedAt);if(J===void 0||!Number.isFinite(J)||Y.now-J>eQ)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let X=bJ(Y.quota).sort(($,G)=>{let W=$.windowMs,K=G.windowMs,Z=typeof W==="number"&&Number.isFinite(W),U=typeof K==="number"&&Number.isFinite(K);if(Z!==U)return Z?-1:1;if(Z&&U)return K-W;return 0});for(let{key:$,window:G}of X)if(Number.isFinite(G.remainingPercent)&&G.remainingPercent<=0)return{action:"migrate",reason:"exhausted",windowKey:$,...typeof G.resetsAt==="string"?{resetsAt:G.resetsAt}:{}};let Q=tQ(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 sQ(Y,J,X){let Q=Math.max(0,Y.remainingPercent-J);if(Q<=0)return 0;if(!Y.resetsAt)return Q;let $=Date.parse(Y.resetsAt);if(!Number.isFinite($)||$<=X)return Q;let G=Math.max(($-X)/3600000,FZ);return Q/G}function aQ(Y,J){if(Y<J)return-1;if(Y>J)return 1;return 0}function jZ(Y,J){if(!Y.quota)return;let X=vJ(Y.quota,Y.quotaCheckedAt);if(X===void 0||J-X>eQ)return;let Q=bJ(Y.quota).map(({key:W,window:K})=>{return sQ(K,Y.reservePercent[W]??0,J)}),$=Y.quota.spendControl;if($&&Number.isFinite($.remainingPercent))Q.push(sQ($,0,J));let G=Q.length>0?Math.min(...Q):0;return G>0?{candidate:Y,quotaCheckedAt:X,weight:G}:void 0}function Y5(Y){let J=Y.candidates.filter(($)=>$.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(($)=>jZ($,Y.now)).filter(($)=>$!==void 0);if(X.length>0){X.sort((G,W)=>{let K=((Y.pendingBytes.get(G.candidate.accountId)??0)+Y.requestBytes)/Math.max(G.weight,rQ),Z=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,rQ);return K-Z||G.candidate.configuredOrder-W.candidate.configuredOrder||aQ(G.candidate.accountId,W.candidate.accountId)});let $=X[0];if($)return{accountId:$.candidate.accountId,quotaCheckedAt:$.quotaCheckedAt,source:"weighted"}}Y.onEmptyWeightedSet?.();let Q=[...J].sort(($,G)=>{let W=($.resetCreditsApplicable??0)>0?1:0;return((G.resetCreditsApplicable??0)>0?1:0)-W||$.configuredOrder-G.configuredOrder||aQ($.accountId,G.accountId)})[0];if(!Q)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Q.accountId,quotaCheckedAt:vJ(Q.quota,Q.quotaCheckedAt),source:"mode-fallback"}}import{createHash as OZ}from"node:crypto";import{chmod as qZ,mkdir as DZ,readdir as PZ,readFile as EZ,writeFile as gJ}from"node:fs/promises";import{join as $5}from"node:path";var cJ=B0("dump"),w1="x-cortexkit-openai-auth-dump-session",MZ=["http","prewarm","main"],J5=0,$9=new Map,wZ=100;function yJ(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function G5(Y){let J=Y.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!J)return"session-unknown";return J.length<=80?J:J.slice(0,80)}function W5(Y){return OZ("sha256").update(Y).digest("hex")}function fJ(Y){return W5(JSON.stringify(Y))}function z5(Y){try{let J=JSON.parse(Y);return J!=null&&typeof J==="object"&&!Array.isArray(J)?J:void 0}catch{return}}function AZ(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,$=J.length-1;while(Q>=X&&$>=X&&Y[Q]===J[$])Q--,$--;return{changed:!0,firstByte:X,lastPreviousByte:Q,lastCurrentByte:$,changedPreviousBytes:Q-X+1,changedCurrentBytes:$-X+1,previousBytes:Y.length,currentBytes:J.length}}function RZ(Y,J){if(!$9.has(Y))while($9.size>=wZ){let X=$9.keys().next().value;if(X===void 0)break;$9.delete(X)}$9.set(Y,J)}var X5=new Set;async function TZ(Y,J,X){let Q=G5(J),$=MZ.map((G)=>`-${Q}-${X}-${G}.body.json`);try{let W=(await PZ(Y)).filter((K)=>$.some((Z)=>K.endsWith(Z))).sort().pop();if(!W)return;return await EZ($5(Y,W),"utf8")}catch{return}}function CZ(Y){if(Y===void 0)return;return Object.fromEntries(new Headers(Y).entries())}function uJ(Y){if(Array.isArray(Y))return Y.map(uJ);if(Y==null||typeof Y!=="object")return Y;let J={};for(let[X,Q]of Object.entries(Y)){let $=X.toLowerCase();if($==="authorization"||$==="chatgpt-account-id"||$==="cookie"||$==="set-cookie"){J[X]="[redacted]";continue}J[X]=uJ(Q)}return J}function _Z(Y){let J=z5(Y);if(J===void 0)return Y;let X=IZ(J),Q=JSON.stringify(X);if(Q===void 0)return Y;return JSON.stringify(J)===Q?Y:Q}function IZ(Y){if(!h(Y))return mJ(Y);let J={};for(let[X,Q]of Object.entries(Y))J[X]=X==="tools"?Q5(Q):mJ({[X]:Q})[X];return J}function SZ(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function kZ(Y){let J=z5(Y);if(!J)return{parseable:!1};let X=Array.isArray(J.input)?J.input:[],Q=Array.isArray(J.tools)?J.tools:[],$=Q.map(SZ),G=J.client_metadata!=null&&typeof J.client_metadata==="object"&&!Array.isArray(J.client_metadata)?J.client_metadata:void 0;return{parseable:!0,model:typeof J.model==="string"?J.model:void 0,stream:J.stream,generate:J.generate,store:J.store,previousResponseID:typeof J.previous_response_id==="string"?J.previous_response_id:void 0,promptCacheKey:typeof J.prompt_cache_key==="string"?J.prompt_cache_key:void 0,reasoning:J.reasoning,inputCount:X.length,inputHash:fJ(X),inputBytes:JSON.stringify(X).length,firstInputHash:X[0]===void 0?null:fJ(X[0]),toolsCount:Q.length,toolTypes:$,toolsHash:fJ(Q),hasWebSearch:$.includes("web_search"),clientMetadataKeys:G?Object.keys(G).sort():[]}}async function G9(Y){let J=g0();if(!J.dump)return;J5++;let X=Y.sessionID?.trim()||"session-unknown",Q=`${new Date().toISOString().replace(/[:.]/g,"-")}-${process.pid}-${String(J5).padStart(5,"0")}-${G5(X)}-${Y.transport}-${Y.phase}`,$=$5(J.dumpDir,Q),G={body:`${$}.body.json`,metadata:`${$}.meta.json`,request:`${$}.request.json`},W=`${Y.transport}:${X}`,K=$9.get(W),Z=K?"memory":void 0;if(K===void 0&&!X5.has(W)){if(X5.add(W),K=await TZ(J.dumpDir,X,Y.transport),K!==void 0)Z="disk"}try{await DZ(J.dumpDir,{recursive:!0,mode:448}),await qZ(J.dumpDir,448).catch(()=>{});let U=_Z(Y.bodyText),L={id:Q,createdAt:new Date().toISOString(),session:yJ(X),transport:Y.transport,phase:Y.phase,accountId:Y.accountId,status:Y.status,error:Y.error,bodyBytes:Y.bodyText.length,bodyHash:W5(Y.bodyText),diff:AZ(K,U),baselineSource:Z,body:kZ(Y.bodyText),files:G};await Promise.all([gJ(G.body,U,{encoding:"utf8",mode:384}),gJ(G.metadata,`${JSON.stringify(L,null,2)}
|
|
53
|
-
`,{encoding:"utf8",mode:384}),
|
|
54
|
-
`,{encoding:"utf8",mode:384})]),cJ.debug("dumped request",{id:Q,session:yJ(X),body:G.body,meta:G.metadata}),RZ(W,U)}catch(U){cJ.warn("request dump failed",{session:yJ(X),error:U instanceof Error?U.message:String(U)})}}async function N1(Y){if(!g0().dump)return;cJ.debug("diagnostic",Y)}import{tool as x9}from"@opencode-ai/plugin";var kY="ws_",Z5=new Map,L5=x9({description:"Provider-executed OpenAI web search. This tool is handled server-side by OpenAI; the local plugin records the hosted action for deterministic replay.",args:{type:x9.schema.string().optional(),query:x9.schema.string().optional(),queries:x9.schema.array(x9.schema.string()).optional()},async execute(Y){return{title:"OpenAI Web Search",output:JSON.stringify({action:Y}),metadata:{action:Y}}}});function lJ(Y){if(xZ(Y))return;if(!vZ(Y))return Y;let J=Y.item;return Z5.set(J.id,J),{...Y,item:{type:"function_call",id:J.id,call_id:J.id,name:"web_search",arguments:JSON.stringify(h(J.action)?J.action:{})}}}function H5(Y){if(!Y.body)return Y;if(!(Y.headers.get("content-type")??"").includes("text/event-stream"))return Y;return new Response(bZ(Y.body),{status:Y.status,statusText:Y.statusText,headers:Y.headers})}function V5(Y){if(!Array.isArray(Y.input))return!1;let J=!1,X=new Map,Q=[],$=new Map,G=new Map;for(let W of Y.input)if(h(W)&&typeof W.call_id==="string"&&W.call_id.startsWith(kY)){if(W.type==="function_call")$.set(W.call_id,W);else if(W.type==="function_call_output"&&typeof W.output==="string")G.set(W.call_id,W.output)}for(let W of Y.input){if(hZ(W)){X.set(W.call_id,W),J=!0;continue}if(gZ(W,X)){Q.push(pJ(W.call_id,W.output,X.get(W.call_id))),J=!0;continue}if(yZ(W)){let K=Z5.get(W.id);if(K)Q.push(pJ(W.id,K));else{let Z=$.get(W.id),U=G.get(W.id);if(Z||U)Q.push(pJ(W.id,U,Z));else Q.push(W)}J=!0;continue}Q.push(W)}if(J)Y.input=Q;return J}function xZ(Y){if(typeof Y.type==="string"&&Y.type.startsWith("response.web_search_call."))return!0;return Y.type==="response.output_item.added"&&h(Y.item)&&Y.item.type==="web_search_call"}function bZ(Y){let J=new TextDecoder,X=new TextEncoder,Q="";return Y.pipeThrough(new TransformStream({transform($,G){Q+=J.decode($,{stream:!0});let W=K5(Q);while(W){let K=Q.slice(0,W.index);Q=Q.slice(W.index+W.length);let Z=U5(K);if(Z)G.enqueue(X.encode(Z));W=K5(Q)}},flush($){if(Q+=J.decode(),!Q)return;let G=U5(Q);if(G)$.enqueue(X.encode(G))}}))}function K5(Y){let J=Y.indexOf(`
|
|
55
|
-
|
|
56
|
-
`),X=Y.indexOf(`\r
|
|
57
|
-
|
|
58
|
-
`);if(J
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
`;if(J==="[DONE]")return`data: [DONE]
|
|
62
|
-
|
|
63
|
-
`;try{let X=JSON.parse(J);if(!h(X))return`${Y}
|
|
64
|
-
|
|
65
|
-
`;let Q=lJ(X);if(!Q)return"";return`data: ${JSON.stringify(Q)}
|
|
66
|
-
|
|
67
|
-
`}catch{return`${Y}
|
|
68
|
-
|
|
69
|
-
`}}function vZ(Y){return Y.type==="response.output_item.done"&&h(Y.item)&&Y.item.type==="web_search_call"&&typeof Y.item.id==="string"}function hZ(Y){return h(Y)&&Y.type==="function_call"&&Y.name==="web_search"&&typeof Y.call_id==="string"&&Y.call_id.startsWith(kY)}function gZ(Y,J){return h(Y)&&Y.type==="function_call_output"&&typeof Y.call_id==="string"&&typeof Y.output==="string"&&Y.call_id.startsWith(kY)&&J.has(Y.call_id)}function yZ(Y){return h(Y)&&Y.type==="item_reference"&&typeof Y.id==="string"&&Y.id.startsWith(kY)}function pJ(Y,J,X){let Q=fZ(J),$=h(Q?.action)?Q.action:mZ(X?.arguments);return{type:"web_search_call",status:"completed",...$?{action:$}:{}}}function fZ(Y){if(h(Y))return Y;if(typeof Y!=="string")return;try{let J=JSON.parse(Y);return h(J)?J:void 0}catch{return}}function mZ(Y){if(h(Y))return Y;if(typeof Y!=="string")return;try{let J=JSON.parse(Y);return h(J)?J:void 0}catch{return}}import{readFile as cZ}from"node:fs/promises";import{homedir as uZ}from"node:os";import{join as N5}from"node:path";var pZ="https://models.dev/api.json",lZ="OPENCODE_OPENAI_AUTH_MODELS_CACHE",dZ="OPENCODE_MODELS_PATH",iZ="OPENCODE_DISABLE_MODELS_FETCH",oZ=1e4,nZ=300000;function A1(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function B5(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function dJ(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=B5(Y.cache_read),$=B5(Y.cache_write);if(Q===null||$===null)return null;return{input:J,output:X,cache:{read:Q,write:$}}}function rZ(Y){let J=A1(Y);if(!J)return null;let X=dJ(J);if(!X)return null;let Q=X;if(Array.isArray(J.tiers)){let W=[];for(let K of J.tiers){let Z=A1(K);if(!Z)continue;let U=A1(Z.tier),L=U?.size;if(U?.type!=="context")continue;if(typeof L!=="number"||!Number.isFinite(L)||L<=0)continue;let j=dJ(Z);if(!j)continue;W.push({...j,tier:{type:"context",size:L}})}if(W.length>0)Q.tiers=W}let $=A1(J.context_over_200k),G=$?dJ($):null;if(G)Q.experimentalOver200K=G;return Q}function F5(Y){let J=A1(Y),X=A1(J?.openai),Q=A1(X?.models);if(!Q)return null;let $={};for(let[G,W]of Object.entries(Q)){let K=A1(W),Z=rZ(K?.cost);if(Z)$[G]=Z}return Object.keys($).length>0?$:null}function sZ(){let Y=process.env[lZ]?.trim();if(Y)return Y;let J=process.env[dZ]?.trim();if(J)return J;let X=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||N5(uZ(),".cache");return N5(X,"opencode","models.json")}function aZ(){let Y=process.env[iZ]?.toLowerCase();return Y==="true"||Y==="1"}async function tZ(){try{let Y=F5(JSON.parse(await cZ(sZ(),"utf8")));if(Y)return Y}catch{}if(aZ())return null;try{let Y=await fetch(pZ,{signal:AbortSignal.timeout(oZ)});if(!Y.ok)return null;return F5(await Y.json())}catch{return null}}var W9;function j5(){let Y=Date.now();if(W9&&W9.expiresAt>Y)return W9.promise;let J={expiresAt:Y+nZ,promise:tZ()};return W9=J,J.promise.then((X)=>{if(X===null&&W9===J)W9=void 0}),J.promise}function z9(Y){return typeof Y==="object"&&Y!==null}function eZ(Y){if(Array.isArray(Y))return Y;if(z9(Y)&&Array.isArray(Y.data))return Y.data;return[]}function YL(Y){if(!z9(Y)||!z9(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function O5(Y){if(!z9(Y)||!z9(Y.info))return null;let J=Y.info,X=z9(J.model)?J.model:void 0,Q=typeof J.agent==="string"?J.agent:void 0,$=typeof X?.providerID==="string"?X.providerID:typeof J.providerID==="string"?J.providerID:void 0,G=typeof X?.modelID==="string"?X.modelID:typeof J.modelID==="string"?J.modelID:void 0,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:$,modelID:G};if(W)K.variant=W;return K}function q5(Y,J){return{agent:Y.agent??J.agent,model:Y.model??J.model,variant:Y.variant??J.variant}}function D5(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function P5(Y,J){if(!Y||!J)return null;let X=Y;if(typeof X.session?.messages!=="function")return null;let Q=[];try{Q=eZ(await Promise.resolve(X.session.messages({path:{id:J},query:{limit:100}})))}catch{return null}if(Q.length===0)return null;let $={};for(let G=Q.length-1;G>=0;G--){if(YL(Q[G])!=="assistant")continue;let W=O5(Q[G]);if(!W)continue;if($=q5($,W),D5($))return $}for(let G=Q.length-1;G>=0;G--){let W=O5(Q[G]);if(!W)continue;if($=q5($,W),D5($))return $}if(!$.agent&&!$.model&&!$.variant)return null;return $}var R1=[],JL=1,E5=new Map;function iJ(Y,J){if(R1.push({id:JL++,type:"open-dialog",payload:Y,sessionId:J}),R1.length>100)R1=R1.slice(R1.length-100)}function M5(Y=0,J){let X=Date.now();if(J!==void 0)E5.set(J,X);let Q=($)=>J===void 0||$.sessionId===void 0||$.sessionId===J;if(Y>0)R1=R1.filter(($)=>{if($.id>Y)return!0;if(J===void 0)return!0;return $.sessionId!==J});return R1.filter(($)=>$.id>Y&&Q($))}function w5(Y){let J=Date.now(),X=E5.get(Y)??0;return X>0&&J-X<3000}import{randomBytes as XL,timingSafeEqual as QL}from"node:crypto";import{readFile as $L,unlink as GL}from"node:fs/promises";import{createServer as WL}from"node:http";import{join as zL}from"node:path";var oJ=B0("rpc");function KL(Y){return new Promise((J,X)=>{let Q=[],$=0;Y.on("data",(G)=>{if($+=G.length,$>1e6){Y.destroy(),X(Error("body too large"));return}Q.push(G)}),Y.on("end",()=>J(Buffer.concat(Q).toString("utf8"))),Y.on("error",X)})}function UL(Y,J){if(!Y?.startsWith("Bearer "))return!1;let X=Buffer.from(Y.slice(7)),Q=Buffer.from(J);return X.length===Q.length&&QL(X,Q)}async function T5(Y){let J=XL(32).toString("hex"),X=Y.timeoutMs??90000,Q=Y.receiptTimeoutMs??2000,$=!1,G=WL((Z,U)=>{Z.setTimeout(X,()=>{Z.socket.destroy()}),W(Z,U)});G.requestTimeout=Q,G.headersTimeout=Q;async function W(Z,U){let L=(j,N)=>{if(U.headersSent||U.writableEnded||U.destroyed)return;U.writeHead(j,{"content-type":"application/json"}),U.end(JSON.stringify(N))};try{let j=Z.url??"";if(Z.method==="GET"&&j==="/health")return L(200,{ok:!0});if(Z.method!=="POST"||!j.startsWith("/rpc/"))return L(404,{error:"not found"});if(!UL(Z.headers.authorization,J))return L(401,{error:"unauthorized"});let N=j.slice(5),V=await KL(Z),q=JSON.parse(V||"{}");if(N==="pending-notifications"){let T=typeof q.sessionId==="string"?q.sessionId:void 0;if(T===void 0&&!$)$=!0,oJ.warn("rpc notification drain missing session id",{pid:process.pid});let S=Y.drain(Number(q.lastReceivedId??0),T);return L(200,{messages:S})}if(N==="apply"){let T=await Y.apply(q);return L(200,T)}return L(404,{error:"unknown method"})}catch(j){L(500,{error:j instanceof Error?j.message:String(j)})}}let K=await new Promise((Z,U)=>{G.on("error",U),G.listen(0,"127.0.0.1",()=>{let L=G.address();if(L&&typeof L==="object")Z(L.port);else U(Error("no port"))})});if(G.unref(),Y.sweepRoot)try{await R5(Y.sweepRoot,Y.dir)}catch(Z){oJ.warn("rpc state sweep failed",{pid:process.pid,error:Z instanceof Error?Z.message:String(Z)})}try{await A5(Y.dir,{port:K,token:J,pid:process.pid},{secureDir:Y.secureDir}),oJ.debug("rpc server pid",{pid:process.pid,rpcPort:K})}catch(Z){throw await new Promise((U)=>G.close(()=>U())),Z}return{port:K,token:J,async stop(){await new Promise((L)=>G.close(()=>L()));let Z=zL(Y.dir,`port-${process.pid}.json`),U=await $L(Z,"utf8").then((L)=>JSON.parse(L)).catch(()=>{return});if(U?.port===K&&U.token===J)await GL(Z).catch(()=>{})}}}function B1(Y){return JSON.stringify(nJ(Y))??"undefined"}function nJ(Y){if(Array.isArray(Y))return Y.map(nJ);if(!h(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((J)=>[J,nJ(Y[J])]))}function u1(){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 x1={};aJ(x1,{withoutInternalHeaders:()=>L4,sanitizeHttpFallbackBody:()=>AJ,orderCodexBody:()=>e9,hasWebSocketResponsesLiteMetadata:()=>wJ,createWebSocketFetch:()=>VF,applyTurnId:()=>z4,advanceTurn:()=>rX,TITLE_HEADER:()=>nX,QUOTA_ACCOUNT_HEADER:()=>zJ,OpenAIWebSocketPool:()=>x1,CODEX_BODY_KEY_ORDER:()=>G4});import{createHash as KF}from"node:crypto";var W$="vercel.ai.error",ZL=Symbol.for(W$),C5,_5,R=class Y extends(_5=Error,C5=ZL,_5){constructor({name:J,message:X,cause:Q}){super(X);this[C5]=!0,this.name=J,this.cause=Q}static isInstance(J){return Y.hasMarker(J,W$)}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}},z$="AI_APICallError",K$=`vercel.ai.error.${z$}`,LL=Symbol.for(K$),I5,S5,b9=class extends(S5=R,I5=LL,S5){constructor({message:Y,url:J,requestBodyValues:X,statusCode:Q,responseHeaders:$,responseBody:G,cause:W,isRetryable:K=Q!=null&&(Q===408||Q===409||Q===429||Q>=500),data:Z}){super({name:z$,message:Y,cause:W});this[I5]=!0,this.url=J,this.requestBodyValues=X,this.statusCode=Q,this.responseHeaders=$,this.responseBody=G,this.isRetryable=K,this.data=Z}static isInstance(Y){return R.hasMarker(Y,K$)}},U$="AI_EmptyResponseBodyError",Z$=`vercel.ai.error.${U$}`,HL=Symbol.for(Z$),k5,x5,VL=class extends(x5=R,k5=HL,x5){constructor({message:Y="Empty response body"}={}){super({name:U$,message:Y});this[k5]=!0}static isInstance(Y){return R.hasMarker(Y,Z$)}},L$="AI_EvaluationUnsupportedQuestionTypeError",H$=`vercel.ai.error.${L$}`,NL=Symbol.for(H$),b5,v5,BL=class extends(v5=R,b5=NL,v5){constructor({questionId:Y,questionType:J,provider:X,modelId:Q,message:$=`Question "${Y}" has type "${J}", which is not supported by provider "${X}" and model "${Q}".`}){super({name:L$,message:$});this[b5]=!0,this.questionId=Y,this.questionType=J,this.provider=X,this.modelId=Q}static isInstance(Y){return R.hasMarker(Y,H$)}};function p1(Y){if(Y==null)return"unknown error";if(typeof Y==="string")return Y;if(Y instanceof Error)return Y.toString();return JSON.stringify(Y)}var V$="AI_InvalidArgumentError",N$=`vercel.ai.error.${V$}`,FL=Symbol.for(N$),h5,g5,B$=class extends(g5=R,h5=FL,g5){constructor({message:Y,cause:J,argument:X}){super({name:V$,message:Y,cause:J});this[h5]=!0,this.argument=X}static isInstance(Y){return R.hasMarker(Y,N$)}},F$="AI_InvalidPromptError",j$=`vercel.ai.error.${F$}`,jL=Symbol.for(j$),y5,f5,OL=class extends(f5=R,y5=jL,f5){constructor({prompt:Y,message:J,cause:X}){super({name:F$,message:`Invalid prompt: ${J}`,cause:X});this[y5]=!0,this.prompt=Y}static isInstance(Y){return R.hasMarker(Y,j$)}},O$="AI_InvalidResponseDataError",q$=`vercel.ai.error.${O$}`,qL=Symbol.for(q$),m5,c5,DL=class extends(c5=R,m5=qL,c5){constructor({data:Y,message:J=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:O$,message:J});this[m5]=!0,this.data=Y}static isInstance(Y){return R.hasMarker(Y,q$)}},D$="AI_JSONParseError",P$=`vercel.ai.error.${D$}`,PL=Symbol.for(P$),u5,p5,xY=class extends(p5=R,u5=PL,p5){constructor({text:Y,cause:J}){super({name:D$,message:`JSON parsing failed: Text: ${Y}.
|
|
70
|
-
Error message: ${p1(J)}`,cause:J});this[u5]=!0,this.text=Y}static isInstance(Y){return R.hasMarker(Y,P$)}},E$="AI_LoadAPIKeyError",M$=`vercel.ai.error.${E$}`,EL=Symbol.for(M$),l5,d5,ML=class extends(d5=R,l5=EL,d5){constructor({message:Y}){super({name:E$,message:Y});this[l5]=!0}static isInstance(Y){return R.hasMarker(Y,M$)}},w$="AI_LoadSettingError",A$=`vercel.ai.error.${w$}`,wL=Symbol.for(A$),i5,o5,AL=class extends(o5=R,i5=wL,o5){constructor({message:Y}){super({name:w$,message:Y});this[i5]=!0}static isInstance(Y){return R.hasMarker(Y,A$)}},R$="AI_NoContentGeneratedError",T$=`vercel.ai.error.${R$}`,RL=Symbol.for(T$),n5,r5,TL=class extends(r5=R,n5=RL,r5){constructor({message:Y="No content generated."}={}){super({name:R$,message:Y});this[n5]=!0}static isInstance(Y){return R.hasMarker(Y,T$)}},C$="AI_NoSuchModelError",_$=`vercel.ai.error.${C$}`,CL=Symbol.for(_$),s5,a5,rJ=class extends(a5=R,s5=CL,a5){constructor({errorName:Y=C$,modelId:J,modelType:X,message:Q=`No such ${X}: ${J}`}){super({name:Y,message:Q});this[s5]=!0,this.modelId=J,this.modelType=X}static isInstance(Y){return R.hasMarker(Y,_$)}},I$="AI_NoSuchProviderReferenceError",S$=`vercel.ai.error.${I$}`,_L=Symbol.for(S$),t5,e5,IL=class extends(e5=R,t5=_L,e5){constructor({provider:Y,reference:J,message:X=`No provider reference found for provider '${Y}'. Available providers: ${Object.keys(J).join(", ")}`}){super({name:I$,message:X});this[t5]=!0,this.provider=Y,this.reference=J}static isInstance(Y){return R.hasMarker(Y,S$)}},k$="AI_TooManyEmbeddingValuesForCallError",x$=`vercel.ai.error.${k$}`,SL=Symbol.for(x$),Y$,J$,kL=class extends(J$=R,Y$=SL,J$){constructor(Y){super({name:k$,message:`Too many values for a single embedding call. The ${Y.provider} model "${Y.modelId}" can only embed up to ${Y.maxEmbeddingsPerCall} values per call, but ${Y.values.length} values were provided.`});this[Y$]=!0,this.provider=Y.provider,this.modelId=Y.modelId,this.maxEmbeddingsPerCall=Y.maxEmbeddingsPerCall,this.values=Y.values}static isInstance(Y){return R.hasMarker(Y,x$)}},b$="AI_TypeValidationError",v$=`vercel.ai.error.${b$}`,xL=Symbol.for(v$),X$,Q$,r0=class Y extends(Q$=R,X$=xL,Q$){constructor({value:J,cause:X,context:Q}){let $="Type validation failed";if(Q==null?void 0:Q.field)$+=` for ${Q.field}`;if((Q==null?void 0:Q.entityName)||(Q==null?void 0:Q.entityId)){$+=" (";let G=[];if(Q.entityName)G.push(Q.entityName);if(Q.entityId)G.push(`id: "${Q.entityId}"`);$+=G.join(", "),$+=")"}super({name:b$,message:`${$}: Value: ${JSON.stringify(J)}.
|
|
71
|
-
Error message: ${p1(X)}`,cause:X});this[X$]=!0,this.value=J,this.context=Q}static isInstance(J){return R.hasMarker(J,v$)}static wrap({value:J,cause:X,context:Q}){var $,G,W;if(Y.isInstance(X)&&X.value===J&&(($=X.context)==null?void 0:$.field)===(Q==null?void 0:Q.field)&&((G=X.context)==null?void 0:G.entityName)===(Q==null?void 0:Q.entityName)&&((W=X.context)==null?void 0:W.entityId)===(Q==null?void 0:Q.entityId))return X;return new Y({value:J,cause:X,context:Q})}},h$="AI_UnsupportedFunctionalityError",g$=`vercel.ai.error.${h$}`,bL=Symbol.for(g$),$$,G$,vL=class extends(G$=R,$$=bL,G$){constructor({functionality:Y,message:J=`'${Y}' functionality not supported.`}){super({name:h$,message:J});this[$$]=!0,this.functionality=Y}static isInstance(Y){return R.hasMarker(Y,g$)}};var Tq=Object.freeze({status:"aborted"});function P(Y,J,X){function Q(K,Z){var U;Object.defineProperty(K,"_zod",{value:K._zod??{},enumerable:!1}),(U=K._zod).traits??(U.traits=new Set),K._zod.traits.add(Y),J(K,Z);for(let L in W.prototype)if(!(L in K))Object.defineProperty(K,L,{value:W.prototype[L].bind(K)});K._zod.constr=W,K._zod.def=Z}let $=X?.Parent??Object;class G extends ${}Object.defineProperty(G,"name",{value:Y});function W(K){var Z;let U=X?.Parent?new G:this;Q(U,K),(Z=U._zod).deferred??(Z.deferred=[]);for(let L of U._zod.deferred)L();return U}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 Cq=Symbol("zod_brand");class F1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class v9 extends Error{constructor(Y){super(`Encountered unidirectional transform during encode: ${Y}`);this.name="ZodEncodeError"}}var bY={};function G1(Y){if(Y)Object.assign(bY,Y);return bY}var a={};aJ(a,{unwrapMessage:()=>h9,uint8ArrayToHex:()=>zH,uint8ArrayToBase64url:()=>GH,uint8ArrayToBase64:()=>d$,stringifyPrimitive:()=>c$,shallowClone:()=>f$,safeExtend:()=>eL,required:()=>XH,randomString:()=>iL,propertyKeyTypes:()=>YX,promiseAllObject:()=>dL,primitiveTypes:()=>m$,prefixIssues:()=>O1,pick:()=>sL,partial:()=>JH,optionalKeys:()=>JX,omit:()=>aL,objectClone:()=>uL,numKeys:()=>oL,nullish:()=>y9,normalizeParams:()=>i,mergeDefs:()=>C1,merge:()=>YH,jsonStringifyReplacer:()=>K9,joinValues:()=>cL,issue:()=>Z9,isPlainObject:()=>_1,isObject:()=>l1,hexToUint8Array:()=>WH,getSizableOrigin:()=>p$,getParsedType:()=>nL,getLengthableOrigin:()=>m9,getEnumValues:()=>g9,getElementAtPath:()=>lL,floatSafeRemainder:()=>tJ,finalizeIssue:()=>t0,extend:()=>tL,escapeRegex:()=>j1,esc:()=>vY,defineLazy:()=>J0,createTransparentProxy:()=>rL,cloneDef:()=>pL,clone:()=>a0,cleanRegex:()=>f9,cleanEnum:()=>QH,captureStackTrace:()=>hY,cached:()=>U9,base64urlToUint8Array:()=>$H,base64ToUint8Array:()=>l$,assignProp:()=>T1,assertNotEqual:()=>gL,assertNever:()=>fL,assertIs:()=>yL,assertEqual:()=>hL,assert:()=>mL,allowsEval:()=>eJ,aborted:()=>I1,NUMBER_FORMAT_RANGES:()=>XX,Class:()=>i$,BIGINT_FORMAT_RANGES:()=>u$});function hL(Y){return Y}function gL(Y){return Y}function yL(Y){}function fL(Y){throw Error()}function mL(Y){}function g9(Y){let J=Object.values(Y).filter((Q)=>typeof Q==="number");return Object.entries(Y).filter(([Q,$])=>J.indexOf(+Q)===-1).map(([Q,$])=>$)}function cL(Y,J="|"){return Y.map((X)=>c$(X)).join(J)}function K9(Y,J){if(typeof J==="bigint")return J.toString();return J}function U9(Y){return{get value(){{let X=Y();return Object.defineProperty(this,"value",{value:X}),X}throw Error("cached value already set")}}}function y9(Y){return Y===null||Y===void 0}function f9(Y){let J=Y.startsWith("^")?1:0,X=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(J,X)}function tJ(Y,J){let X=(Y.toString().split(".")[1]||"").length,Q=J.toString(),$=(Q.split(".")[1]||"").length;if($===0&&/\d?e-\d?/.test(Q)){let Z=Q.match(/\d?e-(\d?)/);if(Z?.[1])$=Number.parseInt(Z[1])}let G=X>$?X:$,W=Number.parseInt(Y.toFixed(G).replace(".","")),K=Number.parseInt(J.toFixed(G).replace(".",""));return W%K/10**G}var y$=Symbol("evaluating");function J0(Y,J,X){let Q=void 0;Object.defineProperty(Y,J,{get(){if(Q===y$)return;if(Q===void 0)Q=y$,Q=X();return Q},set($){Object.defineProperty(Y,J,{value:$})},configurable:!0})}function uL(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function T1(Y,J,X){Object.defineProperty(Y,J,{value:X,writable:!0,enumerable:!0,configurable:!0})}function C1(...Y){let J={};for(let X of Y){let Q=Object.getOwnPropertyDescriptors(X);Object.assign(J,Q)}return Object.defineProperties({},J)}function pL(Y){return C1(Y._zod.def)}function lL(Y,J){if(!J)return Y;return J.reduce((X,Q)=>X?.[Q],Y)}function dL(Y){let J=Object.keys(Y),X=J.map((Q)=>Y[Q]);return Promise.all(X).then((Q)=>{let $={};for(let G=0;G<J.length;G++)$[J[G]]=Q[G];return $})}function iL(Y=10){let X="";for(let Q=0;Q<Y;Q++)X+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return X}function vY(Y){return JSON.stringify(Y)}var hY="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function l1(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var eJ=U9(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function _1(Y){if(l1(Y)===!1)return!1;let J=Y.constructor;if(J===void 0)return!0;let X=J.prototype;if(l1(X)===!1)return!1;if(Object.prototype.hasOwnProperty.call(X,"isPrototypeOf")===!1)return!1;return!0}function f$(Y){if(_1(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function oL(Y){let J=0;for(let X in Y)if(Object.prototype.hasOwnProperty.call(Y,X))J++;return J}var nL=(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}`)}},YX=new Set(["string","number","symbol"]),m$=new Set(["string","number","bigint","boolean","symbol","undefined"]);function j1(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function a0(Y,J,X){let Q=new Y._zod.constr(J??Y._zod.def);if(!J||X?.parent)Q._zod.parent=Y;return Q}function i(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 rL(Y){let J;return new Proxy({},{get(X,Q,$){return J??(J=Y()),Reflect.get(J,Q,$)},set(X,Q,$,G){return J??(J=Y()),Reflect.set(J,Q,$,G)},has(X,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,$){return J??(J=Y()),Reflect.defineProperty(J,Q,$)}})}function c$(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function JX(Y){return Object.keys(Y).filter((J)=>{return Y[J]._zod.optin==="optional"&&Y[J]._zod.optout==="optional"})}var XX={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]},u$={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function sL(Y,J){let X=Y._zod.def,Q=C1(Y._zod.def,{get shape(){let $={};for(let G in J){if(!(G in X.shape))throw Error(`Unrecognized key: "${G}"`);if(!J[G])continue;$[G]=X.shape[G]}return T1(this,"shape",$),$},checks:[]});return a0(Y,Q)}function aL(Y,J){let X=Y._zod.def,Q=C1(Y._zod.def,{get shape(){let $={...Y._zod.def.shape};for(let G in J){if(!(G in X.shape))throw Error(`Unrecognized key: "${G}"`);if(!J[G])continue;delete $[G]}return T1(this,"shape",$),$},checks:[]});return a0(Y,Q)}function tL(Y,J){if(!_1(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 $=C1(Y._zod.def,{get shape(){let G={...Y._zod.def.shape,...J};return T1(this,"shape",G),G},checks:[]});return a0(Y,$)}function eL(Y,J){if(!_1(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 T1(this,"shape",Q),Q},checks:Y._zod.def.checks};return a0(Y,X)}function YH(Y,J){let X=C1(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape,...J._zod.def.shape};return T1(this,"shape",Q),Q},get catchall(){return J._zod.def.catchall},checks:[]});return a0(Y,X)}function JH(Y,J,X){let Q=C1(J._zod.def,{get shape(){let $=J._zod.def.shape,G={...$};if(X)for(let W in X){if(!(W in $))throw Error(`Unrecognized key: "${W}"`);if(!X[W])continue;G[W]=Y?new Y({type:"optional",innerType:$[W]}):$[W]}else for(let W in $)G[W]=Y?new Y({type:"optional",innerType:$[W]}):$[W];return T1(this,"shape",G),G},checks:[]});return a0(J,Q)}function XH(Y,J,X){let Q=C1(J._zod.def,{get shape(){let $=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;G[W]=new Y({type:"nonoptional",innerType:$[W]})}else for(let W in $)G[W]=new Y({type:"nonoptional",innerType:$[W]});return T1(this,"shape",G),G},checks:[]});return a0(J,Q)}function I1(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 O1(Y,J){return J.map((X)=>{var Q;return(Q=X).path??(Q.path=[]),X.path.unshift(Y),X})}function h9(Y){return typeof Y==="string"?Y:Y?.message}function t0(Y,J,X){let Q={...Y,path:Y.path??[]};if(!Y.message){let $=h9(Y.inst?._zod.def?.error?.(Y))??h9(J?.error?.(Y))??h9(X.customError?.(Y))??h9(X.localeError?.(Y))??"Invalid input";Q.message=$}if(delete Q.inst,delete Q.continue,!J?.reportInput)delete Q.input;return Q}function p$(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function m9(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function Z9(...Y){let[J,X,Q]=Y;if(typeof J==="string")return{message:J,code:"custom",input:X,inst:Q};return{...J}}function QH(Y){return Object.entries(Y).filter(([J,X])=>{return Number.isNaN(Number.parseInt(J,10))}).map((J)=>J[1])}function l$(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 d$(Y){let J="";for(let X=0;X<Y.length;X++)J+=String.fromCharCode(Y[X]);return btoa(J)}function $H(Y){let J=Y.replace(/-/g,"+").replace(/_/g,"/"),X="=".repeat((4-J.length%4)%4);return l$(J+X)}function GH(Y){return d$(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function WH(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 zH(Y){return Array.from(Y).map((J)=>J.toString(16).padStart(2,"0")).join("")}class i${constructor(...Y){}}var o$=(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,K9,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},gY=P("$ZodError",o$),QX=P("$ZodError",o$,{Parent:Error});function n$(Y,J=(X)=>X.message){let X={},Q=[];for(let $ of Y.issues)if($.path.length>0)X[$.path[0]]=X[$.path[0]]||[],X[$.path[0]].push(J($));else Q.push(J($));return{formErrors:Q,fieldErrors:X}}function r$(Y,J){let X=J||function(G){return G.message},Q={_errors:[]},$=(G)=>{for(let W of G.issues)if(W.code==="invalid_union"&&W.errors.length)W.errors.map((K)=>$({issues:K}));else if(W.code==="invalid_key")$({issues:W.issues});else if(W.code==="invalid_element")$({issues:W.issues});else if(W.path.length===0)Q._errors.push(X(W));else{let K=Q,Z=0;while(Z<W.path.length){let U=W.path[Z];if(Z!==W.path.length-1)K[U]=K[U]||{_errors:[]};else K[U]=K[U]||{_errors:[]},K[U]._errors.push(X(W));K=K[U],Z++}}};return $(Y),Q}var yY=(Y)=>(J,X,Q,$)=>{let G=Q?Object.assign(Q,{async:!1}):{async:!1},W=J._zod.run({value:X,issues:[]},G);if(W instanceof Promise)throw new F1;if(W.issues.length){let K=new($?.Err??Y)(W.issues.map((Z)=>t0(Z,G,G1())));throw hY(K,$?.callee),K}return W.value};var fY=(Y)=>async(J,X,Q,$)=>{let G=Q?Object.assign(Q,{async:!0}):{async:!0},W=J._zod.run({value:X,issues:[]},G);if(W instanceof Promise)W=await W;if(W.issues.length){let K=new($?.Err??Y)(W.issues.map((Z)=>t0(Z,G,G1())));throw hY(K,$?.callee),K}return W.value};var c9=(Y)=>(J,X,Q)=>{let $=Q?{...Q,async:!1}:{async:!1},G=J._zod.run({value:X,issues:[]},$);if(G instanceof Promise)throw new F1;return G.issues.length?{success:!1,error:new(Y??gY)(G.issues.map((W)=>t0(W,$,G1())))}:{success:!0,data:G.value}},s$=c9(QX),u9=(Y)=>async(J,X,Q)=>{let $=Q?Object.assign(Q,{async:!0}):{async:!0},G=J._zod.run({value:X,issues:[]},$);if(G instanceof Promise)G=await G;return G.issues.length?{success:!1,error:new Y(G.issues.map((W)=>t0(W,$,G1())))}:{success:!0,data:G.value}},a$=u9(QX),t$=(Y)=>(J,X,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return yY(Y)(J,X,$)};var e$=(Y)=>(J,X,Q)=>{return yY(Y)(J,X,Q)};var YG=(Y)=>async(J,X,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return fY(Y)(J,X,$)};var JG=(Y)=>async(J,X,Q)=>{return fY(Y)(J,X,Q)};var XG=(Y)=>(J,X,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return c9(Y)(J,X,$)};var QG=(Y)=>(J,X,Q)=>{return c9(Y)(J,X,Q)};var $G=(Y)=>async(J,X,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return u9(Y)(J,X,$)};var GG=(Y)=>async(J,X,Q)=>{return u9(Y)(J,X,Q)};var WG=/^[cC][^\s-]{8,}$/,zG=/^[0-9a-z]+$/,KG=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,UG=/^[0-9a-vA-V]{20}$/,ZG=/^[A-Za-z0-9]{27}$/,LG=/^[a-zA-Z0-9_-]{21}$/,HG=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var VG=/^([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})$/,$X=(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 NG=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function BG(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var FG=/^(?:(?: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])$/,jG=/^(([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}|:))$/,OG=/^((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])$/,qG=/^(([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])$/,DG=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,GX=/^[A-Za-z0-9_-]*$/,PG=/^(?=.{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 EG=/^\+(?:[0-9]){6,14}[0-9]$/,MG="(?:(?:\\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])))",wG=new RegExp(`^${MG}$`);function AG(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 RG(Y){return new RegExp(`^${AG(Y)}$`)}function TG(Y){let J=AG({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(`^${MG}T(?:${Q})$`)}var CG=(Y)=>{let J=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${J}$`)};var _G=/^-?\d+$/,IG=/^-?\d+(?:\.\d+)?/,SG=/^(?:true|false)$/i,kG=/^null$/i;var xG=/^[^A-Z]*$/,bG=/^[^a-z]*$/;var w0=P("$ZodCheck",(Y,J)=>{var X;Y._zod??(Y._zod={}),Y._zod.def=J,(X=Y._zod).onattach??(X.onattach=[])}),vG={number:"number",bigint:"bigint",object:"date"},WX=P("$ZodCheckLessThan",(Y,J)=>{w0.init(Y,J);let X=vG[typeof J.value];Y._zod.onattach.push((Q)=>{let $=Q._zod.bag,G=(J.inclusive?$.maximum:$.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(J.value<G)if(J.inclusive)$.maximum=J.value;else $.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})}}),zX=P("$ZodCheckGreaterThan",(Y,J)=>{w0.init(Y,J);let X=vG[typeof J.value];Y._zod.onattach.push((Q)=>{let $=Q._zod.bag,G=(J.inclusive?$.minimum:$.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(J.value>G)if(J.inclusive)$.minimum=J.value;else $.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})}}),hG=P("$ZodCheckMultipleOf",(Y,J)=>{w0.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):tJ(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})}}),gG=P("$ZodCheckNumberFormat",(Y,J)=>{w0.init(Y,J),J.format=J.format||"float64";let X=J.format?.includes("int"),Q=X?"int":"number",[$,G]=XX[J.format];Y._zod.onattach.push((W)=>{let K=W._zod.bag;if(K.format=J.format,K.minimum=$,K.maximum=G,X)K.pattern=_G}),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<$)W.issues.push({origin:"number",input:K,code:"too_small",minimum:$,inclusive:!0,inst:Y,continue:!J.abort});if(K>G)W.issues.push({origin:"number",input:K,code:"too_big",maximum:G,inst:Y})}});var yG=P("$ZodCheckMaxLength",(Y,J)=>{var X;w0.init(Y,J),(X=Y._zod.def).when??(X.when=(Q)=>{let $=Q.value;return!y9($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(J.maximum<$)Q._zod.bag.maximum=J.maximum}),Y._zod.check=(Q)=>{let $=Q.value;if($.length<=J.maximum)return;let W=m9($);Q.issues.push({origin:W,code:"too_big",maximum:J.maximum,inclusive:!0,input:$,inst:Y,continue:!J.abort})}}),fG=P("$ZodCheckMinLength",(Y,J)=>{var X;w0.init(Y,J),(X=Y._zod.def).when??(X.when=(Q)=>{let $=Q.value;return!y9($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(J.minimum>$)Q._zod.bag.minimum=J.minimum}),Y._zod.check=(Q)=>{let $=Q.value;if($.length>=J.minimum)return;let W=m9($);Q.issues.push({origin:W,code:"too_small",minimum:J.minimum,inclusive:!0,input:$,inst:Y,continue:!J.abort})}}),mG=P("$ZodCheckLengthEquals",(Y,J)=>{var X;w0.init(Y,J),(X=Y._zod.def).when??(X.when=(Q)=>{let $=Q.value;return!y9($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.minimum=J.length,$.maximum=J.length,$.length=J.length}),Y._zod.check=(Q)=>{let $=Q.value,G=$.length;if(G===J.length)return;let W=m9($),K=G>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})}}),p9=P("$ZodCheckStringFormat",(Y,J)=>{var X,Q;if(w0.init(Y,J),Y._zod.onattach.push(($)=>{let G=$._zod.bag;if(G.format=J.format,J.pattern)G.patterns??(G.patterns=new Set),G.patterns.add(J.pattern)}),J.pattern)(X=Y._zod).check??(X.check=($)=>{if(J.pattern.lastIndex=0,J.pattern.test($.value))return;$.issues.push({origin:"string",code:"invalid_format",format:J.format,input:$.value,...J.pattern?{pattern:J.pattern.toString()}:{},inst:Y,continue:!J.abort})});else(Q=Y._zod).check??(Q.check=()=>{})}),cG=P("$ZodCheckRegex",(Y,J)=>{p9.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})}}),uG=P("$ZodCheckLowerCase",(Y,J)=>{J.pattern??(J.pattern=xG),p9.init(Y,J)}),pG=P("$ZodCheckUpperCase",(Y,J)=>{J.pattern??(J.pattern=bG),p9.init(Y,J)}),lG=P("$ZodCheckIncludes",(Y,J)=>{w0.init(Y,J);let X=j1(J.includes),Q=new RegExp(typeof J.position==="number"?`^.{${J.position}}${X}`:X);J.pattern=Q,Y._zod.onattach.push(($)=>{let G=$._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(Q)}),Y._zod.check=($)=>{if($.value.includes(J.includes,J.position))return;$.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:J.includes,input:$.value,inst:Y,continue:!J.abort})}}),dG=P("$ZodCheckStartsWith",(Y,J)=>{w0.init(Y,J);let X=new RegExp(`^${j1(J.prefix)}.*`);J.pattern??(J.pattern=X),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.patterns??($.patterns=new Set),$.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})}}),iG=P("$ZodCheckEndsWith",(Y,J)=>{w0.init(Y,J);let X=new RegExp(`.*${j1(J.suffix)}$`);J.pattern??(J.pattern=X),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.patterns??($.patterns=new Set),$.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 oG=P("$ZodCheckOverwrite",(Y,J)=>{w0.init(Y,J),Y._zod.check=(X)=>{X.value=J.tx(X.value)}});class KX{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(`
|
|
72
|
-
`).filter((G)=>G),Q=Math.min(...X.map((G)=>G.length-G.trimStart().length)),$=X.map((G)=>G.slice(Q)).map((G)=>" ".repeat(this.indent*2)+G);for(let G of $)this.content.push(G)}compile(){let Y=Function,J=this?.args,Q=[...(this?.content??[""]).map(($)=>` ${$}`)];return new Y(...J,Q.join(`
|
|
73
|
-
`))}}var rG={major:4,minor:1,patch:8};var K0=P("$ZodType",(Y,J)=>{var X;Y??(Y={}),Y._zod.def=J,Y._zod.bag=Y._zod.bag||{},Y._zod.version=rG;let Q=[...Y._zod.def.checks??[]];if(Y._zod.traits.has("$ZodCheck"))Q.unshift(Y);for(let $ of Q)for(let G of $._zod.onattach)G(Y);if(Q.length===0)(X=Y._zod).deferred??(X.deferred=[]),Y._zod.deferred?.push(()=>{Y._zod.run=Y._zod.parse});else{let $=(W,K,Z)=>{let U=I1(W),L;for(let j of K){if(j._zod.def.when){if(!j._zod.def.when(W))continue}else if(U)continue;let N=W.issues.length,V=j._zod.check(W);if(V instanceof Promise&&Z?.async===!1)throw new F1;if(L||V instanceof Promise)L=(L??Promise.resolve()).then(async()=>{if(await V,W.issues.length===N)return;if(!U)U=I1(W,N)});else{if(W.issues.length===N)continue;if(!U)U=I1(W,N)}}if(L)return L.then(()=>{return W});return W},G=(W,K,Z)=>{if(I1(W))return W.aborted=!0,W;let U=$(K,Q,Z);if(U instanceof Promise){if(Z.async===!1)throw new F1;return U.then((L)=>Y._zod.parse(L,Z))}return Y._zod.parse(U,Z)};Y._zod.run=(W,K)=>{if(K.skipChecks)return Y._zod.parse(W,K);if(K.direction==="backward"){let U=Y._zod.parse({value:W.value,issues:[]},{...K,skipChecks:!0});if(U instanceof Promise)return U.then((L)=>{return G(L,W,K)});return G(U,W,K)}let Z=Y._zod.parse(W,K);if(Z instanceof Promise){if(K.async===!1)throw new F1;return Z.then((U)=>$(U,Q,K))}return $(Z,Q,K)}}Y["~standard"]={validate:($)=>{try{let G=s$(Y,$);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return a$(Y,$).then((W)=>W.success?{value:W.data}:{issues:W.error?.issues})}},vendor:"zod",version:1}}),pY=P("$ZodString",(Y,J)=>{K0.init(Y,J),Y._zod.pattern=[...Y?._zod.bag?.patterns??[]].pop()??CG(Y._zod.bag),Y._zod.parse=(X,Q)=>{if(J.coerce)try{X.value=String(X.value)}catch($){}if(typeof X.value==="string")return X;return X.issues.push({expected:"string",code:"invalid_type",input:X.value,inst:Y}),X}}),Z0=P("$ZodStringFormat",(Y,J)=>{p9.init(Y,J),pY.init(Y,J)}),$2=P("$ZodGUID",(Y,J)=>{J.pattern??(J.pattern=VG),Z0.init(Y,J)}),G2=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=$X(Q))}else J.pattern??(J.pattern=$X());Z0.init(Y,J)}),W2=P("$ZodEmail",(Y,J)=>{J.pattern??(J.pattern=NG),Z0.init(Y,J)}),z2=P("$ZodURL",(Y,J)=>{Z0.init(Y,J),Y._zod.check=(X)=>{try{let Q=X.value.trim(),$=new URL(Q);if(J.hostname){if(J.hostname.lastIndex=0,!J.hostname.test($.hostname))X.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:PG.source,input:X.value,inst:Y,continue:!J.abort})}if(J.protocol){if(J.protocol.lastIndex=0,!J.protocol.test($.protocol.endsWith(":")?$.protocol.slice(0,-1):$.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=$.href;else X.value=Q;return}catch(Q){X.issues.push({code:"invalid_format",format:"url",input:X.value,inst:Y,continue:!J.abort})}}}),K2=P("$ZodEmoji",(Y,J)=>{J.pattern??(J.pattern=BG()),Z0.init(Y,J)}),U2=P("$ZodNanoID",(Y,J)=>{J.pattern??(J.pattern=LG),Z0.init(Y,J)}),Z2=P("$ZodCUID",(Y,J)=>{J.pattern??(J.pattern=WG),Z0.init(Y,J)}),L2=P("$ZodCUID2",(Y,J)=>{J.pattern??(J.pattern=zG),Z0.init(Y,J)}),H2=P("$ZodULID",(Y,J)=>{J.pattern??(J.pattern=KG),Z0.init(Y,J)}),V2=P("$ZodXID",(Y,J)=>{J.pattern??(J.pattern=UG),Z0.init(Y,J)}),N2=P("$ZodKSUID",(Y,J)=>{J.pattern??(J.pattern=ZG),Z0.init(Y,J)}),B2=P("$ZodISODateTime",(Y,J)=>{J.pattern??(J.pattern=TG(J)),Z0.init(Y,J)}),F2=P("$ZodISODate",(Y,J)=>{J.pattern??(J.pattern=wG),Z0.init(Y,J)}),j2=P("$ZodISOTime",(Y,J)=>{J.pattern??(J.pattern=RG(J)),Z0.init(Y,J)}),O2=P("$ZodISODuration",(Y,J)=>{J.pattern??(J.pattern=HG),Z0.init(Y,J)}),q2=P("$ZodIPv4",(Y,J)=>{J.pattern??(J.pattern=FG),Z0.init(Y,J),Y._zod.onattach.push((X)=>{let Q=X._zod.bag;Q.format="ipv4"})}),D2=P("$ZodIPv6",(Y,J)=>{J.pattern??(J.pattern=jG),Z0.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})}}}),P2=P("$ZodCIDRv4",(Y,J)=>{J.pattern??(J.pattern=OG),Z0.init(Y,J)}),E2=P("$ZodCIDRv6",(Y,J)=>{J.pattern??(J.pattern=qG),Z0.init(Y,J),Y._zod.check=(X)=>{let Q=X.value.split("/");try{if(Q.length!==2)throw Error();let[$,G]=Q;if(!G)throw Error();let W=Number(G);if(`${W}`!==G)throw Error();if(W<0||W>128)throw Error();new URL(`http://[${$}]`)}catch{X.issues.push({code:"invalid_format",format:"cidrv6",input:X.value,inst:Y,continue:!J.abort})}}});function M2(Y){if(Y==="")return!0;if(Y.length%4!==0)return!1;try{return atob(Y),!0}catch{return!1}}var w2=P("$ZodBase64",(Y,J)=>{J.pattern??(J.pattern=DG),Z0.init(Y,J),Y._zod.onattach.push((X)=>{X._zod.bag.contentEncoding="base64"}),Y._zod.check=(X)=>{if(M2(X.value))return;X.issues.push({code:"invalid_format",format:"base64",input:X.value,inst:Y,continue:!J.abort})}});function UH(Y){if(!GX.test(Y))return!1;let J=Y.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),X=J.padEnd(Math.ceil(J.length/4)*4,"=");return M2(X)}var A2=P("$ZodBase64URL",(Y,J)=>{J.pattern??(J.pattern=GX),Z0.init(Y,J),Y._zod.onattach.push((X)=>{X._zod.bag.contentEncoding="base64url"}),Y._zod.check=(X)=>{if(UH(X.value))return;X.issues.push({code:"invalid_format",format:"base64url",input:X.value,inst:Y,continue:!J.abort})}}),R2=P("$ZodE164",(Y,J)=>{J.pattern??(J.pattern=EG),Z0.init(Y,J)});function ZH(Y,J=null){try{let X=Y.split(".");if(X.length!==3)return!1;let[Q]=X;if(!Q)return!1;let $=JSON.parse(atob(Q));if("typ"in $&&$?.typ!=="JWT")return!1;if(!$.alg)return!1;if(J&&(!("alg"in $)||$.alg!==J))return!1;return!0}catch{return!1}}var T2=P("$ZodJWT",(Y,J)=>{Z0.init(Y,J),Y._zod.check=(X)=>{if(ZH(X.value,J.alg))return;X.issues.push({code:"invalid_format",format:"jwt",input:X.value,inst:Y,continue:!J.abort})}});var ZX=P("$ZodNumber",(Y,J)=>{K0.init(Y,J),Y._zod.pattern=Y._zod.bag.pattern??IG,Y._zod.parse=(X,Q)=>{if(J.coerce)try{X.value=Number(X.value)}catch(W){}let $=X.value;if(typeof $==="number"&&!Number.isNaN($)&&Number.isFinite($))return X;let G=typeof $==="number"?Number.isNaN($)?"NaN":!Number.isFinite($)?"Infinity":void 0:void 0;return X.issues.push({expected:"number",code:"invalid_type",input:$,inst:Y,...G?{received:G}:{}}),X}}),C2=P("$ZodNumber",(Y,J)=>{gG.init(Y,J),ZX.init(Y,J)}),_2=P("$ZodBoolean",(Y,J)=>{K0.init(Y,J),Y._zod.pattern=SG,Y._zod.parse=(X,Q)=>{if(J.coerce)try{X.value=Boolean(X.value)}catch(G){}let $=X.value;if(typeof $==="boolean")return X;return X.issues.push({expected:"boolean",code:"invalid_type",input:$,inst:Y}),X}});var I2=P("$ZodNull",(Y,J)=>{K0.init(Y,J),Y._zod.pattern=kG,Y._zod.values=new Set([null]),Y._zod.parse=(X,Q)=>{let $=X.value;if($===null)return X;return X.issues.push({expected:"null",code:"invalid_type",input:$,inst:Y}),X}});var S2=P("$ZodUnknown",(Y,J)=>{K0.init(Y,J),Y._zod.parse=(X)=>X}),k2=P("$ZodNever",(Y,J)=>{K0.init(Y,J),Y._zod.parse=(X,Q)=>{return X.issues.push({expected:"never",code:"invalid_type",input:X.value,inst:Y}),X}});function sG(Y,J,X){if(Y.issues.length)J.issues.push(...O1(X,Y.issues));J.value[X]=Y.value}var x2=P("$ZodArray",(Y,J)=>{K0.init(Y,J),Y._zod.parse=(X,Q)=>{let $=X.value;if(!Array.isArray($))return X.issues.push({expected:"array",code:"invalid_type",input:$,inst:Y}),X;X.value=Array($.length);let G=[];for(let W=0;W<$.length;W++){let K=$[W],Z=J.element._zod.run({value:K,issues:[]},Q);if(Z instanceof Promise)G.push(Z.then((U)=>sG(U,X,W)));else sG(Z,X,W)}if(G.length)return Promise.all(G).then(()=>X);return X}});function uY(Y,J,X,Q){if(Y.issues.length)J.issues.push(...O1(X,Y.issues));if(Y.value===void 0){if(X in Q)J.value[X]=void 0}else J.value[X]=Y.value}function b2(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=JX(Y.shape);return{...Y,keys:J,keySet:new Set(J),numKeys:J.length,optionalKeys:new Set(X)}}function v2(Y,J,X,Q,$,G){let W=[],K=$.keySet,Z=$.catchall._zod,U=Z.def.type;for(let L of Object.keys(J)){if(K.has(L))continue;if(U==="never"){W.push(L);continue}let j=Z.run({value:J[L],issues:[]},Q);if(j instanceof Promise)Y.push(j.then((N)=>uY(N,X,L,J)));else uY(j,X,L,J)}if(W.length)X.issues.push({code:"unrecognized_keys",keys:W,input:J,inst:G});if(!Y.length)return X;return Promise.all(Y).then(()=>{return X})}var LH=P("$ZodObject",(Y,J)=>{K0.init(Y,J);let X=U9(()=>b2(J));J0(Y._zod,"propValues",()=>{let W=J.shape,K={};for(let Z in W){let U=W[Z]._zod;if(U.values){K[Z]??(K[Z]=new Set);for(let L of U.values)K[Z].add(L)}}return K});let Q=l1,$=J.catchall,G;Y._zod.parse=(W,K)=>{G??(G=X.value);let Z=W.value;if(!Q(Z))return W.issues.push({expected:"object",code:"invalid_type",input:Z,inst:Y}),W;W.value={};let U=[],L=G.shape;for(let j of G.keys){let V=L[j]._zod.run({value:Z[j],issues:[]},K);if(V instanceof Promise)U.push(V.then((q)=>uY(q,W,j,Z)));else uY(V,W,j,Z)}if(!$)return U.length?Promise.all(U).then(()=>W):W;return v2(U,Z,W,K,X.value,Y)}}),h2=P("$ZodObjectJIT",(Y,J)=>{LH.init(Y,J);let X=Y._zod.parse,Q=U9(()=>b2(J)),$=(N)=>{let V=new KX(["shape","payload","ctx"]),q=Q.value,T=(E)=>{let b=vY(E);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`};V.write("const input = payload.value;");let S=Object.create(null),c=0;for(let E of q.keys)S[E]=`key_${c++}`;V.write("const newResult = {};");for(let E of q.keys){let b=S[E],f=vY(E);V.write(`const ${b} = ${T(E)};`),V.write(`
|
|
74
|
-
if (${b}.issues.length) {
|
|
75
|
-
payload.issues = payload.issues.concat(${b}.issues.map(iss => ({
|
|
51
|
+
Warming limited to **${`${String(H).padStart(2,"0")}-${String(U).padStart(2,"0")}`}** local hours.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:Z?.sustain??$?.cachekeep?.sustain===!0,window:{startHour:H,endHour:U},running:Z?.running??!1,tracked:Z?.tracked??0,generatedAt:Z?.generatedAt??Date.now(),maxIdleWarmMs:Z?.maxIdleWarmMs??3600000,maxSubagentIdleMs:Z?.maxSubagentIdleMs??1800000}}}return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep`, `/openai-cachekeep on`, `/openai-cachekeep off`, `/openai-cachekeep sustain on`, `/openai-cachekeep sustain off`, `/openai-cachekeep HH-HH`, `/openai-cachekeep window clear`, `/openai-cachekeep subagents on`, `/openai-cachekeep subagents off`",knobs:{}}}var hU={"openai-killswitch":SU,"openai-dump":kU,"openai-logging":xU,"openai-cachekeep":vU};function DX(Y,X,J){return qX(Y,X,J,hU)}var gU=300000,yU=30000,fU=240000,mU="bg-quota-refresh",cU=120000;function uU(Y,X){return L1({name:mU,ttlMs:cU,path:Y,renew:!0,...X})}function LQ(Y,X=E1,J=()=>uU(Y.paths.configPath)){return pU(Y,X,J)}async function pU(Y,X,J){let Q;try{Q=await J()}catch{Q=void 0}if(Q===null)return[];try{return await X({...Y,respectBackoff:!0,skipFresherThanMs:fU})}finally{await Q?.release().catch(()=>{})}}class PX{setIntervalFn;clearIntervalFn;random;onError;run;timer;tickPromise;stopped=!1;constructor(Y={}){this.setIntervalFn=Y.setIntervalFn??setInterval,this.clearIntervalFn=Y.clearIntervalFn??clearInterval,this.random=Y.random??Math.random,this.onError=Y.onError}start(Y,X=this.onError){if(this.run=Y,this.onError=X,this.stopped=!1,this.timer)return;let J=Math.round((this.random()*2-1)*yU);if(this.timer=this.setIntervalFn(()=>{let Q=this.run;if(this.stopped||!Q||this.tickPromise)return;let $=Q().catch((G)=>{try{this.onError?.(G)}catch{}}).finally(()=>{if(this.tickPromise===$)this.tickPromise=void 0});this.tickPromise=$},gU+J),"unref"in this.timer)this.timer.unref()}stop(){if(this.stopped=!0,this.run=void 0,!this.timer)return;this.clearIntervalFn(this.timer),this.timer=void 0}isStopped(){return this.stopped}}function EX(Y){if(typeof Y!=="string")return!1;try{let X=JSON.parse(Y);return i(X)&&i(X.client_metadata)&&X.client_metadata.ws_request_header_x_openai_internal_codex_responses_lite==="true"}catch{return!1}}function MX(Y){if(typeof Y!=="string")return Y;try{let X=JSON.parse(Y);if(!i(X)||!i(X.client_metadata))return Y;if(!(("x-codex-turn-metadata"in X.client_metadata)||("x-codex-ws-stream-request-start-ms"in X.client_metadata)||("ws_request_header_x_openai_internal_codex_responses_lite"in X.client_metadata)))return Y;let J={...X.client_metadata};return delete J["x-codex-turn-metadata"],delete J["x-codex-ws-stream-request-start-ms"],delete J.ws_request_header_x_openai_internal_codex_responses_lite,JSON.stringify({...X,client_metadata:J})}catch{return Y}}function _Y(Y){if(Y?.method?.toUpperCase()!=="POST")return Y;let X=new Headers(Y.headers);if(X.set("accept","text/event-stream"),X.set("content-type","application/json"),EX(Y.body))X.set("x-openai-internal-codex-responses-lite","true");return{...Y,headers:X,body:MX(Y.body)}}function OQ(Y){if(!Y.enabled||typeof Y.body!=="string")return;let X=Y.headers.has("x-parent-session-id");if(X&&!Y.includeSubagents)return;let J=Y.headers.get("session-id")??Y.headers.get("x-opencode-session")??Y.headers.get("x-session-affinity")??void 0;if(!J)return;let Q={};for(let $ of["session-id","x-session-affinity","x-parent-session-id","user-agent","version","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-client-request-id","thread-id","x-openai-internal-codex-responses-lite"]){let G=Y.headers.get($);if(G)Q[$]=G}return{sessionKey:J,bodyText:Y.body,replayHeaders:Q,isSubagent:X}}function jQ(Y){let X=Number(Y?.cachekeep?.startHour),J=Number(Y?.cachekeep?.endHour);if(!Number.isInteger(X)||!Number.isInteger(J)||X<0||X>23||J<0||J>23||X===J)return;return{startHour:X,endHour:J}}function VQ(Y,X=new Date){if(!Y)return!1;let J=X.getHours();if(Y.startHour<Y.endHour)return J>=Y.startHour&&J<Y.endHour;return J>=Y.startHour||J<Y.endHour}var lU=300000,qQ=1800000,NQ=2*qQ+900000,dU=3600000,BQ=1800000,FQ=60000,iU=32,nU=8388608,wX=600000;function DQ(Y){try{let J=JSON.parse(Y).model;if(typeof J!=="string")return!1;return J==="gpt-5.6"||J.startsWith("gpt-5.6-")}catch{return!1}}function oU(Y){let J=JSON.parse(Y);return J.store=!1,delete J.max_output_tokens,delete J.max_tokens,delete J.max_completion_tokens,JSON.stringify(J)}function rU(Y,X){return DQ(Y)?qQ:X}function AX(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function PQ(Y){if(!Y||typeof Y!=="object")return AX();let X=Y,J=Number(X.input_tokens)||Number(X.prompt_tokens)||0,Q=Number(X.output_tokens)||Number(X.completion_tokens)||0,$=X.input_tokens_details??X.prompt_tokens_details,G=Number($?.cached_tokens)||Number(X.cached_tokens)||0,W=J>0?G/J:null;return{input_tokens:J,output_tokens:Q,cached_tokens:G,hit_rate:W}}function sU(Y){try{let X=JSON.parse(Y);return PQ(X.usage)}catch{return AX()}}function aU(Y){let X,J=[],Q,$=()=>{if(!J.length)return;let G=J.join(`
|
|
52
|
+
`).trim();J=[];let W=X;if(X=void 0,!G||G==="[DONE]")return;try{let K=JSON.parse(G),H=K.type??W;if(H!=="response.completed"&&H!=="response.done")return;let U=K.response;Q=PQ(U?.usage??K.usage)}catch{}};for(let G of Y.split(/\r?\n/)){if(G===""){$();continue}if(G.startsWith("event:")){X=G.slice(6).trim();continue}if(G.startsWith("data:"))J.push(G.slice(5).trim())}return $(),Q??AX()}class RX{targets=new Map;fetchImpl;getMainToken;refreshFallback;codexResponsesUrl;log;now;ttlMs;leadMs;maxIdleWarmMs;maxSubagentIdleMs;tickIntervalMs;maxTargets;maxBytes;getWindow;getSustain;timer=null;startedAt=null;totalBytes=0;tickInFlight=!1;disposed=!1;abortController=new AbortController;logPayload(Y={}){return{pid:process.pid,...Y}}constructor(Y){this.fetchImpl=Y.fetchImpl,this.getMainToken=Y.getMainToken,this.refreshFallback=Y.refreshFallback,this.codexResponsesUrl=Y.codexResponsesUrl,this.log=Y.logger,this.now=Y.now,this.ttlMs=Y.ttlMs??lU,this.tickIntervalMs=Y.tickIntervalMs??FQ,this.leadMs=Y.leadMs??this.tickIntervalMs+15000;let X=Y.maxIdleWarmMs??Y.maxDurationMs;this.maxIdleWarmMs=typeof X==="number"&&Number.isFinite(X)&&X>0?X:dU;let J=Y.maxSubagentIdleMs??BQ;this.maxSubagentIdleMs=typeof J==="number"&&Number.isFinite(J)&&J>0?J:BQ,this.tickIntervalMs=Y.tickIntervalMs??FQ,this.maxTargets=Y.maxTargets??iU,this.maxBytes=Y.maxBytes??nU,this.getWindow=Y.getWindow,this.getSustain=Y.getSustain}track(Y,X,J,Q,$={},G=!1){this.pruneStale();let W=X.length;if(W>this.maxBytes){this.log.debug("cachekeep track skipped (body exceeds maxBytes)",this.logPayload({sessionKey:Y,bodyBytes:W,maxBytes:this.maxBytes}));return}let K=this.getWindow?.();if(K&&!VQ(K,new Date(this.now()))){this.log.debug("cachekeep track skipped (outside window)",this.logPayload({sessionKey:Y,startHour:K.startHour,endHour:K.endHour}));return}if(this.targets.has(Y)){let Z=this.targets.get(Y);if(Z)this.totalBytes-=Z.bodyText.length;this.targets.delete(Y)}else this.log.debug("cachekeep captured target",this.logPayload({sessionKey:Y,accountId:J}));while(this.targets.size>=this.maxTargets||this.totalBytes+W>this.maxBytes&&this.targets.size>0){let Z,F=Number.POSITIVE_INFINITY;for(let[V,q]of this.targets){let R=Math.max(q.lastRealRequestAt,q.lastWarmedAt??0);if(R<F)Z=V,F=R}if(Z===void 0)break;let N=this.targets.get(Z);if(N)this.totalBytes-=N.bodyText.length;this.targets.delete(Z)}let H=rU(X,this.ttlMs),U={bodyText:X,accountId:J||void 0,chatgptAccountId:Q,route:"main",ttlMs:H,cacheExpiresAt:this.now()+H,warmCount:0,lastRealRequestAt:this.now(),replayHeaders:$,isSubagent:G,is56:DQ(X)};this.targets.set(Y,U),this.totalBytes+=W,this.start()}isGpt56Subagent(Y){return Y.isSubagent===!0&&Y.is56}pruneStale(){let Y=this.now(),X=Y-this.maxIdleWarmMs,J=Y-this.maxSubagentIdleMs,Q=Y-NQ;for(let[$,G]of this.targets){let W,K;if(this.isGpt56Subagent(G))W=Q,K=NQ;else W=G.isSubagent?J:X,K=G.isSubagent?this.maxSubagentIdleMs:this.maxIdleWarmMs;if(!(G.isSubagent!==!0&&this.getSustain?.()===!0)&&G.lastRealRequestAt<W)this.log.debug("cachekeep pruned idle target",this.logPayload({sessionKey:$,accountId:G.accountId??"main",lastRealRequestAt:G.lastRealRequestAt,maxIdleWarmMs:K})),this.totalBytes-=G.bodyText.length,this.targets.delete($)}}start(){if(this.disposed=!1,this.timer)return;if(this.startedAt=this.now(),this.log.debug("cachekeep started",this.logPayload({ttlMs:this.ttlMs,leadMs:this.leadMs,maxIdleWarmMs:this.maxIdleWarmMs})),this.timer=setInterval(()=>{this.tick().catch(()=>{})},this.tickIntervalMs),"unref"in this.timer)this.timer.unref()}stop(){if(this.disposed=!0,this.abortController.abort(),this.abortController=new AbortController,this.timer)clearInterval(this.timer),this.timer=null;this.startedAt=null,this.targets.clear(),this.totalBytes=0,this.log.debug("cachekeep stopped",this.logPayload())}remove(Y){let X=this.targets.get(Y);if(X)this.totalBytes-=X.bodyText.length,this.targets.delete(Y),this.log.debug("cachekeep removed target",this.logPayload({sessionKey:Y}))}status(){let Y=this.now(),X=Array.from(this.targets.entries()).map(([J,Q])=>({sessionKey:J,accountId:Q.accountId,route:Q.route,cacheExpiresAt:Q.cacheExpiresAt,lastRealRequestAt:Q.lastRealRequestAt,lastWarmedAt:Q.lastWarmedAt,backoffUntil:Q.backoffUntil,bodyBytes:Q.bodyText.length}));return{running:this.timer!=null,tracked:this.targets.size,generatedAt:Y,startedAt:this.startedAt,maxIdleWarmMs:this.maxIdleWarmMs,maxSubagentIdleMs:this.maxSubagentIdleMs,ttlMs:this.ttlMs,leadMs:this.leadMs,sustain:this.getSustain?.()===!0,window:this.getWindow?.(),targets:X}}async tick(){if(this.tickInFlight)return;this.tickInFlight=!0;try{this.pruneStale();let Y=this.getWindow?.();if(Y&&!VQ(Y,new Date(this.now())))return;let X=this.now(),J=X+this.leadMs;for(let[Q,$]of this.targets)if($.backoffUntil&&X>=$.backoffUntil&&$.cacheExpiresAt<=J)await this.prewarm(Q,$);for(let[Q,$]of this.targets){if($.backoffUntil&&X<$.backoffUntil)continue;if($.cacheExpiresAt<=J)await this.prewarm(Q,$)}}finally{this.tickInFlight=!1}}async prewarm(Y,X){let J,Q;try{if(X.accountId&&X.accountId!=="main"){let G=await this.refreshFallback(X.accountId);if(typeof G==="string")J=G;else J=G.token,Q=G.onAuthFailure}else J=await this.getMainToken()}catch(G){if(!this.disposed&&this.targets.get(Y)===X)X.backoffUntil=this.now()+wX;this.log.debug("cachekeep skip (no token)",this.logPayload({sessionKey:Y,accountId:X.accountId??"main",error:G instanceof Error?G.message:String(G)}));return}if(this.disposed||this.targets.get(Y)!==X)return;let $={...X.replayHeaders,authorization:`Bearer ${J}`,"content-type":"application/json"};if(X.chatgptAccountId)$["ChatGPT-Account-Id"]=X.chatgptAccountId;else delete $["ChatGPT-Account-Id"];try{let G=oU(X.bodyText),W;try{let k=JSON.parse(G);W={warmBodyKeys:Object.keys(k),stream:k.stream,max_output_tokens:k.max_output_tokens,store:k.store,has_stream_options:"stream_options"in k,has_max_tokens:"max_tokens"in k,model:k.model}}catch{}this.log.debug("cachekeep warm request",this.logPayload({...W,headerKeys:Object.keys($),hasChatGptAccountId:"ChatGPT-Account-Id"in $}));let K=_Y({method:"POST",headers:$,body:G,signal:AbortSignal.any([AbortSignal.timeout(30000),this.abortController.signal])}),H=await this.fetchImpl(this.codexResponsesUrl,K),U="";try{U=await H.text()}catch{}if(this.disposed||this.targets.get(Y)!==X)return;if(!H.ok){if(X.backoffUntil=this.now()+wX,H.status===401)await Q?.(H.status);this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",status:H.status,error:`HTTP ${H.status}`,responseBody:U.slice(0,600)}));return}let Z=H.headers.get("content-type")??"",F=Z.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(U.slice(0,200));this.log.debug("cachekeep warm response",this.logPayload({status:H.status,contentType:Z,bodyLen:U.length,isSse:F}));let N=F?aU(U):sU(U),V=Q9(H.headers),q=V.primary?.usedPercent??null,R=V.secondary?.usedPercent??null;if(this.log.debug("cachekeep fired",this.logPayload({session:Y,accountId:X.accountId??"main",input_tokens:N.input_tokens,cached_tokens:N.cached_tokens,hit_rate:N.hit_rate,output_tokens:N.output_tokens,quota_primary_pct:q,quota_secondary_pct:R})),X.cacheExpiresAt=this.now()+X.ttlMs,X.lastWarmedAt=this.now(),X.backoffUntil=void 0,X.warmCount+=1,this.isGpt56Subagent(X)&&X.warmCount>=2){if(this.targets.get(Y)===X)this.totalBytes-=X.bodyText.length,this.targets.delete(Y);return}}catch(G){if(this.disposed||this.targets.get(Y)!==X)return;X.backoffUntil=this.now()+wX,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",error:G instanceof Error?G.message:String(G)}))}}}import{createHash as YH}from"node:crypto";import{isAbsolute as tU,join as EQ}from"node:path";var eU=j0("custody"),MQ=new Set;function TX(Y=process.env){let X=Y.CLAUSTRUM_OPENCODE_HANDLES;if(X&&tU(X))return X;if(X&&!MQ.has(X))MQ.add(X),eU.warn("ignoring non-absolute CLAUSTRUM_OPENCODE_HANDLES",{configuredPath:X});let J=Y.XDG_CONFIG_HOME||(Y.HOME?EQ(Y.HOME,".config"):".config");return EQ(J,"cortexkit","opencode-handles.json")}function e0(Y=TX(),X={}){return wQ(Y,X)}var CX="openai",AQ=250,IQ=new Set;function SQ(Y){if(typeof Y.access!=="string"||typeof Y.refresh!=="string")return;let X=Buffer.from(Y.access),J=Buffer.from(Y.refresh),Q=($)=>{let G=Buffer.alloc(4);return G.writeUInt32BE($.length),G};return YH("sha256").update(Q(X)).update(X).update(Q(J)).update(J).digest("hex")}function kQ(Y){let X=SQ(Y);if(X)IQ.add(X)}function XH(Y){let X=SQ(Y);return X!==void 0&&IQ.has(X)}function xQ(Y){if(!Y||typeof Y!=="object")return;let X=Y;if(X.type!=="oauth")return;return{type:"oauth",...typeof X.access==="string"?{access:X.access}:{},...typeof X.refresh==="string"?{refresh:X.refresh}:{},...typeof X.expires==="number"?{expires:X.expires}:{}}}function SY(Y){let X=xQ(Y);if(typeof X?.access!=="string"||typeof X.refresh!=="string")return;return{access:X.access,refresh:X.refresh,...typeof X.expires==="number"?{expires:X.expires}:{}}}function IY(Y){let X=xQ(Y);if(!X)return{kind:"indeterminate"};if(!b0({id:"main",type:"oauth",access:X.access??"",refresh:X.refresh??"",expires:X.expires??0,addedAt:0},CX))return{kind:"real",oauth:X};let J=V1(CX);if(X.access===J.access&&X.expires===J.expires)return{kind:"tombstone",oauth:X};return{kind:"empty",oauth:X}}async function RQ(Y){if(!Y.auth.get)return;return Y.auth.get({path:{id:CX}})}async function TQ(Y){if(!Y.auth.all)return!1;return Object.keys(await Y.auth.all()).length>0}async function JH(Y){let X=await RQ(Y.client);if(X!==void 0)return IY(X);let J=await TQ(Y.client),Q=Y.now();if(await Y.sleep(AQ),Y.now()-Q<AQ)return{kind:"indeterminate"};let $=await RQ(Y.client);if($!==void 0)return IY($);let G=await TQ(Y.client);return J&&G?{kind:"slot-absent"}:{kind:"indeterminate"}}function QH(Y){if(Y.ok)return"present";return Y.reason==="absent"?"absent":"unreadable"}function x9(Y){let X=W1(Y);return X?z1(X):void 0}async function CQ(Y){let X=f0(Y.manifest).get("main");if(!X)return"no_handle";if(!Y.getCredential)return"cold";try{let J=await Y.getCredential(X),Q=x9(J.access);if(Y.mainAccountId&&Q&&Q!==Y.mainAccountId)return"identity_mismatch";return"serves"}catch{return Y.isReauth?.(X)?"needs_reauth":"cold"}}function _Q(Y){return Y.kind==="real"&&XH(Y.oauth)}async function bQ(Y){let X=await JH(Y);if(X.kind==="indeterminate")return;let J=QH(Y.manifest);if(X.kind==="slot-absent"){let $=await CQ(Y);return k9({mode:Y.mode,manifest:J,local:X.kind,verifiedInProcessLogin:_Q(X),vault:()=>$==="no_handle"||$==="identity_mismatch"?$:"serves"})}let Q=await CQ(Y);return k9({mode:Y.mode,manifest:J,local:X.kind,verifiedInProcessLogin:_Q(X),vault:()=>Q})}import{createHash as $H}from"node:crypto";var cQ="claustrum-mode",u1="main-refresh",vQ=Promise.resolve();async function IX(){let Y,X=new Promise(($)=>{Y=$}),J=vQ;vQ=J.then(()=>X),await J;let Q=!1;return{async release(){if(Q)return;Q=!0,Y()}}}async function uQ(Y){let X=Y.now()+5000;while(Y.now()<X){try{let J=await Y.getAuth();if(J?.access===Y.accessToken&&J.refresh===Y.refreshToken){await Y.onObserved?.({access:J.access,refresh:J.refresh}),await Y.release();return}}catch{}await Y.sleep(Math.max(0,Math.min(100,X-Y.now())))}Y.warn("host write not observed within 5s; lease released"),await Y.release()}function hQ(Y){return Y.accounts.filter((X)=>O0(X)&&X.enabled!==!1)}function _X(Y,X){return Y<X?-1:Y>X?1:0}function gQ(Y,X){return[{id:"main",accountId:X?.mainAccountId,kind:"main"},...Y.map((J)=>({id:J,accountId:X?.accounts.find((Q)=>Q.id===J)?.accountId,kind:"fallback"}))].sort((J,Q)=>_X(J.id,Q.id))}function GH(Y){return Y.kind==="main"?u1:M1(Y.id)}function yQ(Y){return Y.access?$9(Y.access,Y.refresh):void 0}function fQ(Y){return Object.values(Y).some((X)=>X==="new-local-family-under-claustrum"||X==="torn-read-deferred"||X.startsWith("aborted:"))}async function pQ(Y){let X=await IX(),J=[],Q={},$=!1,G=async(W)=>{await Y.onStep?.(W)};try{if(await G("mutex-acquired"),Y.accountIds.includes("main")||new Set(Y.accountIds).size!==Y.accountIds.length)return{status:"aborted",outcomes:Q,reason:"duplicate-account-lock"};let W=await Y.acquireLock({name:cQ,renew:!0});if(!W)return{status:"aborted",outcomes:Q,reason:"mode-lock-unavailable"};J.push(W),Y.warn?.(`transition deps: ${JSON.stringify({acquireLock:typeof Y.acquireLock,withStoreTransaction:typeof Y.withStoreTransaction,readManifest:typeof Y.readManifest,preflight:typeof Y.preflight,auth:typeof Y.auth,authAll:typeof Y.auth?.all,authGet:typeof Y.auth?.get,authSet:typeof Y.auth?.set,accountIds:Y.accountIds?.length})}`);let K=gQ(Y.accountIds);Y.warn?.(`transition participants: ${K.map((H)=>H.id).join(",")}`);for(let H of K){let U=await Y.acquireLock({name:GH(H),renew:!0});if(!U)return{status:"aborted",outcomes:Q,reason:`account-lock-unavailable:${H.id}`};J.push(U)}return await Y.withStoreTransaction(async(H)=>{let U=await H.read(),Z=gQ(Y.accountIds,U),F=hQ(U).map((E)=>E.id).sort(_X),N=[...Y.accountIds].sort(_X);if(F.length!==N.length||F.some((E,S)=>E!==N[S]))return{status:"aborted",outcomes:Q,reason:"account-roster-changed"};let V=await Y.readManifest();if(!V.ok)return{status:"aborted",outcomes:Q,reason:`manifest-${V.reason}`};let q=f0(V),R=U.claustrum?.mode==="claustrum"?U.claustrum?.transition:void 0,k=R?R.fingerprints:{fallbacks:{}},u=R?.storeGeneration??mQ(U);if(!R){Y.warn?.(`capturing main slot fingerprint; auth.get is ${typeof Y.auth?.get}`);let E=SY(await Y.auth.get({path:{id:"openai"}}));if(Y.warn?.(`main slot captured: ${E?"complete":"absent"}`),E)k.main=$9(E.access,E.refresh);for(let S of hQ(U)){let c=yQ(S);if(c)k.fallbacks[S.id]=c}}await G("captured"),Y.warn?.(`handles resolved: isMap=${q instanceof Map} size=${q instanceof Map?q.size:"n/a"}`);for(let E of Z){let S=q.get(E.id);if(Y.warn?.(`participant ${E.id}: handle=${S?"yes":"NO"}`),!S){Q[E.id]="no-handle";continue}let c=await Y.preflight({id:E.id,accountId:E.accountId,handle:S});Q[E.id]=c}if(await G("preflight"),Object.values(Q).some((E)=>E!=="ready"))return{status:"aborted",outcomes:Q,reason:"preflight-failed"};if(!R){let E=await Y.readManifest(),S=await H.read();if(!E.ok||E.revision!==V.revision)return{status:"aborted",outcomes:Q,reason:"manifest-revision-changed"};if(mQ(S)!==u)return{status:"aborted",outcomes:Q,reason:"store-generation-changed"};await G("revalidated"),await H.writeMode("claustrum",{manifestRevision:V.revision,storeGeneration:u,fingerprints:k}),await G("mode-written")}let C=!1;for(let E of K){if(E.kind==="main")continue;let S=await H.read(),c=S.accounts.find((K0)=>K0.id===E.id&&K0.type==="oauth");if(c&&b0(c,"openai")){Q[E.id]="tombstoned";continue}let o=k.fallbacks[E.id];if(!c||!o||yQ(c)!==o){Q[E.id]="new-local-family-under-claustrum";continue}let J0=structuredClone(S),L0=J0.accounts.find((K0)=>K0.id===E.id&&K0.type==="oauth");if(!L0){Q[E.id]="new-local-family-under-claustrum";continue}Object.assign(L0,V1("openai"));try{await H.write(J0);let K0=(await H.read()).accounts.find((B0)=>B0.id===E.id&&B0.type==="oauth");Q[E.id]=K0&&b0(K0,"openai")?"tombstoned":"aborted:post-write-readback"}catch{Q[E.id]="aborted:write-failed",C=!0;break}}if(C)return await G("material-written"),{status:"incomplete",outcomes:Q};if(Q.main=k.main?await SX(k.main,{auth:Y.auth,warn:(E)=>{if($)return;$=!0,Y.warn?.(E)}}):"new-local-family-under-claustrum",await G("material-written"),!fQ(Q))await H.writeMode("claustrum");return{status:fQ(Q)?"incomplete":"completed",outcomes:Q}})}finally{for(let W of J.reverse())await W.release().catch(()=>{});await X.release(),await G("mutex-released").catch(()=>{})}}async function SX(Y,X){let J=SY(await X.auth.get({path:{id:"openai"}}));if(J&&b0({id:"main",type:"oauth",access:J.access,refresh:J.refresh,expires:J.expires??0},"openai"))return"tombstoned";if(!J||$9(J.access,J.refresh)!==Y)return"new-local-family-under-claustrum";let Q=await X.auth.all();if(Object.keys(Q).length===0)return X.warn?.("host auth store read empty; refusing to write — possible torn read"),"torn-read-deferred";try{let $=V1("openai");await X.auth.set.bind(X.auth)({path:{id:"openai"},body:$});let W=SY(await X.auth.get({path:{id:"openai"}}));return W&&W.access===$.access&&W.refresh===$.refresh&&W.expires===$.expires?"tombstoned":"new-local-family-under-claustrum"}catch{return"aborted:write-failed"}}async function lQ(Y){let X=await Y.acquireLock({name:cQ,renew:!0});if(!X)throw Error("Claustrum mode lock unavailable");try{await Y.withStoreTransaction(async(J)=>{return await J.writeMode("local"),{status:"completed",outcomes:{}}})}finally{await X.release()}}function mQ(Y){let X=Y.accounts.filter((J)=>J.type==="oauth").map((J)=>({id:J.id,enabled:J.enabled!==!1,accountId:J.accountId??"",access:J.access??"",refresh:J.refresh,expires:J.expires??null})).sort((J,Q)=>J.id<Q.id?-1:J.id>Q.id?1:0);return $H("sha256").update(JSON.stringify(X)).digest("hex")}var rQ=900000,WH=0.016666666666666666,dQ=0.000001;function xX(Y,X){for(let J of[Y?.primary?.checkedAt,Y?.checkedAt,X])if(typeof J==="number"&&Number.isFinite(J))return J;return}function bX(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let X=xX(Y.quota,Y.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||Y.now-X>rQ)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let J=kX(Y.quota).sort(($,G)=>{let W=$.windowMs,K=G.windowMs,H=typeof W==="number"&&Number.isFinite(W),U=typeof K==="number"&&Number.isFinite(K);if(H!==U)return H?-1:1;if(H&&U)return K-W;return 0});for(let{key:$,window:G}of J)if(Number.isFinite(G.remainingPercent)&&G.remainingPercent<=0)return{action:"migrate",reason:"exhausted",windowKey:$,...typeof G.resetsAt==="string"?{resetsAt:G.resetsAt}:{}};let Q=oQ(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 iQ(Y,X,J){let Q=Math.max(0,Y.remainingPercent-X);if(Q<=0)return 0;if(!Y.resetsAt)return Q;let $=Date.parse(Y.resetsAt);if(!Number.isFinite($)||$<=J)return Q;let G=Math.max(($-J)/3600000,WH);return Q/G}function nQ(Y,X){if(Y<X)return-1;if(Y>X)return 1;return 0}function zH(Y,X){if(!Y.quota)return;let J=xX(Y.quota,Y.quotaCheckedAt);if(J===void 0||X-J>rQ)return;let Q=kX(Y.quota).map(({key:W,window:K})=>{return iQ(K,Y.reservePercent[W]??0,X)}),$=Y.quota.spendControl;if($&&Number.isFinite($.remainingPercent))Q.push(iQ($,0,X));let G=Q.length>0?Math.min(...Q):0;return G>0?{candidate:Y,quotaCheckedAt:J,weight:G}:void 0}function sQ(Y){let X=Y.candidates.filter(($)=>$.killswitchPasses!==!1);if(Y.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if(X.length===0)return;let J=X.map(($)=>zH($,Y.now)).filter(($)=>$!==void 0);if(J.length>0){J.sort((G,W)=>{let K=((Y.pendingBytes.get(G.candidate.accountId)??0)+Y.requestBytes)/Math.max(G.weight,dQ),H=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,dQ);return K-H||G.candidate.configuredOrder-W.candidate.configuredOrder||nQ(G.candidate.accountId,W.candidate.accountId)});let $=J[0];if($)return{accountId:$.candidate.accountId,quotaCheckedAt:$.quotaCheckedAt,source:"weighted"}}Y.onEmptyWeightedSet?.();let Q=[...X].sort(($,G)=>{let W=($.resetCreditsApplicable??0)>0?1:0;return((G.resetCreditsApplicable??0)>0?1:0)-W||$.configuredOrder-G.configuredOrder||nQ($.accountId,G.accountId)})[0];if(!Q)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Q.accountId,quotaCheckedAt:xX(Q.quota,Q.quotaCheckedAt),source:"mode-fallback"}}import{createHash as KH}from"node:crypto";import{chmod as UH,mkdir as HH,readdir as ZH,readFile as LH,writeFile as vX}from"node:fs/promises";import{join as Y5}from"node:path";var fX=j0("dump"),w1="x-cortexkit-openai-auth-dump-session",VH=["http","prewarm","main"],aQ=0,G9=new Map,NH=100;function hX(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function X5(Y){let X=Y.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!X)return"session-unknown";return X.length<=80?X:X.slice(0,80)}function J5(Y){return KH("sha256").update(Y).digest("hex")}function gX(Y){return J5(JSON.stringify(Y))}function Q5(Y){try{let X=JSON.parse(Y);return X!=null&&typeof X==="object"&&!Array.isArray(X)?X:void 0}catch{return}}function BH(Y,X){if(Y===void 0)return null;if(Y===X)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:Y.length,currentBytes:X.length};let J=0;while(J<Y.length&&J<X.length&&Y[J]===X[J])J++;let Q=Y.length-1,$=X.length-1;while(Q>=J&&$>=J&&Y[Q]===X[$])Q--,$--;return{changed:!0,firstByte:J,lastPreviousByte:Q,lastCurrentByte:$,changedPreviousBytes:Q-J+1,changedCurrentBytes:$-J+1,previousBytes:Y.length,currentBytes:X.length}}function FH(Y,X){if(!G9.has(Y))while(G9.size>=NH){let J=G9.keys().next().value;if(J===void 0)break;G9.delete(J)}G9.set(Y,X)}var tQ=new Set;async function OH(Y,X,J){let Q=X5(X),$=VH.map((G)=>`-${Q}-${J}-${G}.body.json`);try{let W=(await ZH(Y)).filter((K)=>$.some((H)=>K.endsWith(H))).sort().pop();if(!W)return;return await LH(Y5(Y,W),"utf8")}catch{return}}function jH(Y){if(Y===void 0)return;return Object.fromEntries(new Headers(Y).entries())}function mX(Y){if(Array.isArray(Y))return Y.map(mX);if(Y==null||typeof Y!=="object")return Y;let X={};for(let[J,Q]of Object.entries(Y)){let $=J.toLowerCase();if($==="authorization"||$==="chatgpt-account-id"||$==="cookie"||$==="set-cookie"){X[J]="[redacted]";continue}X[J]=mX(Q)}return X}function qH(Y){let X=Q5(Y);if(X===void 0)return Y;let J=DH(X),Q=JSON.stringify(J);if(Q===void 0)return Y;return JSON.stringify(X)===Q?Y:Q}function DH(Y){if(!i(Y))return yX(Y);let X={};for(let[J,Q]of Object.entries(Y))X[J]=J==="tools"?eQ(Q):yX({[J]:Q})[J];return X}function PH(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function EH(Y){let X=Q5(Y);if(!X)return{parseable:!1};let J=Array.isArray(X.input)?X.input:[],Q=Array.isArray(X.tools)?X.tools:[],$=Q.map(PH),G=X.client_metadata!=null&&typeof X.client_metadata==="object"&&!Array.isArray(X.client_metadata)?X.client_metadata:void 0;return{parseable:!0,model:typeof X.model==="string"?X.model:void 0,stream:X.stream,generate:X.generate,store:X.store,previousResponseID:typeof X.previous_response_id==="string"?X.previous_response_id:void 0,promptCacheKey:typeof X.prompt_cache_key==="string"?X.prompt_cache_key:void 0,reasoning:X.reasoning,inputCount:J.length,inputHash:gX(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:gX(J[0]),toolsCount:Q.length,toolTypes:$,toolsHash:gX(Q),clientMetadataKeys:G?Object.keys(G).sort():[]}}async function W9(Y){let X=s0();if(!X.dump)return;aQ++;let J=Y.sessionID?.trim()||"session-unknown",Q=`${new Date().toISOString().replace(/[:.]/g,"-")}-${process.pid}-${String(aQ).padStart(5,"0")}-${X5(J)}-${Y.transport}-${Y.phase}`,$=Y5(X.dumpDir,Q),G={body:`${$}.body.json`,metadata:`${$}.meta.json`,request:`${$}.request.json`},W=`${Y.transport}:${J}`,K=G9.get(W),H=K?"memory":void 0;if(K===void 0&&!tQ.has(W)){if(tQ.add(W),K=await OH(X.dumpDir,J,Y.transport),K!==void 0)H="disk"}try{await HH(X.dumpDir,{recursive:!0,mode:448}),await UH(X.dumpDir,448).catch(()=>{});let U=qH(Y.bodyText),Z={id:Q,createdAt:new Date().toISOString(),session:hX(J),transport:Y.transport,phase:Y.phase,accountId:Y.accountId,status:Y.status,error:Y.error,bodyBytes:Y.bodyText.length,bodyHash:J5(Y.bodyText),diff:BH(K,U),baselineSource:H,body:EH(Y.bodyText),files:G};await Promise.all([vX(G.body,U,{encoding:"utf8",mode:384}),vX(G.metadata,`${JSON.stringify(Z,null,2)}
|
|
53
|
+
`,{encoding:"utf8",mode:384}),vX(G.request,`${JSON.stringify(mX({url:Y.url,method:Y.method,accountId:Y.accountId,headers:jH(Y.headers)}),null,2)}
|
|
54
|
+
`,{encoding:"utf8",mode:384})]),fX.debug("dumped request",{id:Q,session:hX(J),body:G.body,meta:G.metadata}),FH(W,U)}catch(U){fX.warn("request dump failed",{session:hX(J),error:U instanceof Error?U.message:String(U)})}}async function p1(Y){if(!s0().dump)return;fX.debug("diagnostic",Y)}import{readFile as MH}from"node:fs/promises";import{homedir as wH}from"node:os";import{join as $5}from"node:path";var AH="https://models.dev/api.json",RH="OPENCODE_OPENAI_AUTH_MODELS_CACHE",TH="OPENCODE_MODELS_PATH",CH="OPENCODE_DISABLE_MODELS_FETCH",_H=1e4,IH=300000;function A1(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function G5(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function cX(Y){let{input:X,output:J}=Y;if(typeof X!=="number"||!Number.isFinite(X)||X<0)return null;if(typeof J!=="number"||!Number.isFinite(J)||J<0)return null;let Q=G5(Y.cache_read),$=G5(Y.cache_write);if(Q===null||$===null)return null;return{input:X,output:J,cache:{read:Q,write:$}}}function SH(Y){let X=A1(Y);if(!X)return null;let J=cX(X);if(!J)return null;let Q=J;if(Array.isArray(X.tiers)){let W=[];for(let K of X.tiers){let H=A1(K);if(!H)continue;let U=A1(H.tier),Z=U?.size;if(U?.type!=="context")continue;if(typeof Z!=="number"||!Number.isFinite(Z)||Z<=0)continue;let F=cX(H);if(!F)continue;W.push({...F,tier:{type:"context",size:Z}})}if(W.length>0)Q.tiers=W}let $=A1(X.context_over_200k),G=$?cX($):null;if(G)Q.experimentalOver200K=G;return Q}function W5(Y){let X=A1(Y),J=A1(X?.openai),Q=A1(J?.models);if(!Q)return null;let $={};for(let[G,W]of Object.entries(Q)){let K=A1(W),H=SH(K?.cost);if(H)$[G]=H}return Object.keys($).length>0?$:null}function kH(){let Y=process.env[RH]?.trim();if(Y)return Y;let X=process.env[TH]?.trim();if(X)return X;let J=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||$5(wH(),".cache");return $5(J,"opencode","models.json")}function xH(){let Y=process.env[CH]?.toLowerCase();return Y==="true"||Y==="1"}async function bH(){try{let Y=W5(JSON.parse(await MH(kH(),"utf8")));if(Y)return Y}catch{}if(xH())return null;try{let Y=await fetch(AH,{signal:AbortSignal.timeout(_H)});if(!Y.ok)return null;return W5(await Y.json())}catch{return null}}var z9;function z5(){let Y=Date.now();if(z9&&z9.expiresAt>Y)return z9.promise;let X={expiresAt:Y+IH,promise:bH()};return z9=X,X.promise.then((J)=>{if(J===null&&z9===X)z9=void 0}),X.promise}function K9(Y){return typeof Y==="object"&&Y!==null}function vH(Y){if(Array.isArray(Y))return Y;if(K9(Y)&&Array.isArray(Y.data))return Y.data;return[]}function hH(Y){if(!K9(Y)||!K9(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function K5(Y){if(!K9(Y)||!K9(Y.info))return null;let X=Y.info,J=K9(X.model)?X.model:void 0,Q=typeof X.agent==="string"?X.agent:void 0,$=typeof J?.providerID==="string"?J.providerID:typeof X.providerID==="string"?X.providerID:void 0,G=typeof J?.modelID==="string"?J.modelID:typeof X.modelID==="string"?X.modelID:void 0,W=typeof J?.variant==="string"?J.variant:typeof X.variant==="string"?X.variant:void 0;if(!Q&&(!$||!G)&&!W)return null;let K={};if(Q)K.agent=Q;if($&&G)K.model={providerID:$,modelID:G};if(W)K.variant=W;return K}function U5(Y,X){return{agent:Y.agent??X.agent,model:Y.model??X.model,variant:Y.variant??X.variant}}function H5(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function Z5(Y,X){if(!Y||!X)return null;let J=Y;if(typeof J.session?.messages!=="function")return null;let Q=[];try{Q=vH(await Promise.resolve(J.session.messages({path:{id:X},query:{limit:100}})))}catch{return null}if(Q.length===0)return null;let $={};for(let G=Q.length-1;G>=0;G--){if(hH(Q[G])!=="assistant")continue;let W=K5(Q[G]);if(!W)continue;if($=U5($,W),H5($))return $}for(let G=Q.length-1;G>=0;G--){let W=K5(Q[G]);if(!W)continue;if($=U5($,W),H5($))return $}if(!$.agent&&!$.model&&!$.variant)return null;return $}var R1=[],gH=1,L5=new Map;function uX(Y,X){if(R1.push({id:gH++,type:"open-dialog",payload:Y,sessionId:X}),R1.length>100)R1=R1.slice(R1.length-100)}function V5(Y=0,X){let J=Date.now();if(X!==void 0)L5.set(X,J);let Q=($)=>X===void 0||$.sessionId===void 0||$.sessionId===X;if(Y>0)R1=R1.filter(($)=>{if($.id>Y)return!0;if(X===void 0)return!0;return $.sessionId!==X});return R1.filter(($)=>$.id>Y&&Q($))}function N5(Y){let X=Date.now(),J=L5.get(Y)??0;return J>0&&X-J<3000}import{randomBytes as yH,timingSafeEqual as fH}from"node:crypto";import{readFile as mH,unlink as cH}from"node:fs/promises";import{createServer as uH}from"node:http";import{join as pH}from"node:path";var pX=j0("rpc");function lH(Y){return new Promise((X,J)=>{let Q=[],$=0;Y.on("data",(G)=>{if($+=G.length,$>1e6){Y.destroy(),J(Error("body too large"));return}Q.push(G)}),Y.on("end",()=>X(Buffer.concat(Q).toString("utf8"))),Y.on("error",J)})}function dH(Y,X){if(!Y?.startsWith("Bearer "))return!1;let J=Buffer.from(Y.slice(7)),Q=Buffer.from(X);return J.length===Q.length&&fH(J,Q)}async function O5(Y){let X=yH(32).toString("hex"),J=Y.timeoutMs??90000,Q=Y.receiptTimeoutMs??2000,$=!1,G=uH((H,U)=>{H.setTimeout(J,()=>{H.socket.destroy()}),W(H,U)});G.requestTimeout=Q,G.headersTimeout=Q;async function W(H,U){let Z=(F,N)=>{if(U.headersSent||U.writableEnded||U.destroyed)return;U.writeHead(F,{"content-type":"application/json"}),U.end(JSON.stringify(N))};try{let F=H.url??"";if(H.method==="GET"&&F==="/health")return Z(200,{ok:!0});if(H.method!=="POST"||!F.startsWith("/rpc/"))return Z(404,{error:"not found"});if(!dH(H.headers.authorization,X))return Z(401,{error:"unauthorized"});let N=F.slice(5),V=await lH(H),q=JSON.parse(V||"{}");if(N==="pending-notifications"){let R=typeof q.sessionId==="string"?q.sessionId:void 0;if(R===void 0&&!$)$=!0,pX.warn("rpc notification drain missing session id",{pid:process.pid});let k=Y.drain(Number(q.lastReceivedId??0),R);return Z(200,{messages:k})}if(N==="apply"){let R=await Y.apply(q);return Z(200,R)}return Z(404,{error:"unknown method"})}catch(F){Z(500,{error:F instanceof Error?F.message:String(F)})}}let K=await new Promise((H,U)=>{G.on("error",U),G.listen(0,"127.0.0.1",()=>{let Z=G.address();if(Z&&typeof Z==="object")H(Z.port);else U(Error("no port"))})});if(G.unref(),Y.sweepRoot)try{await F5(Y.sweepRoot,Y.dir)}catch(H){pX.warn("rpc state sweep failed",{pid:process.pid,error:H instanceof Error?H.message:String(H)})}try{await B5(Y.dir,{port:K,token:X,pid:process.pid},{secureDir:Y.secureDir}),pX.debug("rpc server pid",{pid:process.pid,rpcPort:K})}catch(H){throw await new Promise((U)=>G.close(()=>U())),H}return{port:K,token:X,async stop(){await new Promise((Z)=>G.close(()=>Z()));let H=pH(Y.dir,`port-${process.pid}.json`),U=await mH(H,"utf8").then((Z)=>JSON.parse(Z)).catch(()=>{return});if(U?.port===K&&U.token===X)await cH(H).catch(()=>{})}}}function N1(Y){return JSON.stringify(lX(Y))??"undefined"}function lX(Y){if(Array.isArray(Y))return Y.map(lX);if(!i(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((X)=>[X,lX(Y[X])]))}function l1(){let Y=crypto.getRandomValues(new Uint8Array(16)),X=Date.now();Y[0]=X/1099511627776&255,Y[1]=X/4294967296&255,Y[2]=X/16777216&255,Y[3]=X/65536&255,Y[4]=X/256&255,Y[5]=X&255,Y[6]=(Y[6]??0)&15|112,Y[8]=(Y[8]??0)&63|128;let J=Array.from(Y,(Q)=>Q.toString(16).padStart(2,"0")).join("");return`${J.slice(0,8)}-${J.slice(8,12)}-${J.slice(12,16)}-${J.slice(16,20)}-${J.slice(20)}`}var b1={};nX(b1,{withoutInternalHeaders:()=>Y4,sanitizeHttpFallbackBody:()=>MX,orderCodexBody:()=>e9,hasWebSocketResponsesLiteMetadata:()=>EX,createWebSocketFetch:()=>rB,applyTurnId:()=>sK,advanceTurn:()=>iJ,TITLE_HEADER:()=>dJ,QUOTA_ACCOUNT_HEADER:()=>GX,OpenAIWebSocketPool:()=>b1,CODEX_BODY_KEY_ORDER:()=>oK});import{createHash as lB}from"node:crypto";var s5="vercel.ai.error",iH=Symbol.for(s5),j5,q5,A=class Y extends(q5=Error,j5=iH,q5){constructor({name:X,message:J,cause:Q}){super(J);this[j5]=!0,this.name=X,this.cause=Q}static isInstance(X){return Y.hasMarker(X,s5)}static hasMarker(X,J){let Q=Symbol.for(J);return X!=null&&typeof X==="object"&&Q in X&&typeof X[Q]==="boolean"&&X[Q]===!0}},a5="AI_APICallError",t5=`vercel.ai.error.${a5}`,nH=Symbol.for(t5),D5,P5,b9=class extends(P5=A,D5=nH,P5){constructor({message:Y,url:X,requestBodyValues:J,statusCode:Q,responseHeaders:$,responseBody:G,cause:W,isRetryable:K=Q!=null&&(Q===408||Q===409||Q===429||Q>=500),data:H}){super({name:a5,message:Y,cause:W});this[D5]=!0,this.url=X,this.requestBodyValues=J,this.statusCode=Q,this.responseHeaders=$,this.responseBody=G,this.isRetryable=K,this.data=H}static isInstance(Y){return A.hasMarker(Y,t5)}},e5="AI_EmptyResponseBodyError",Y$=`vercel.ai.error.${e5}`,oH=Symbol.for(Y$),E5,M5,rH=class extends(M5=A,E5=oH,M5){constructor({message:Y="Empty response body"}={}){super({name:e5,message:Y});this[E5]=!0}static isInstance(Y){return A.hasMarker(Y,Y$)}},X$="AI_EvaluationUnsupportedQuestionTypeError",J$=`vercel.ai.error.${X$}`,sH=Symbol.for(J$),w5,A5,aH=class extends(A5=A,w5=sH,A5){constructor({questionId:Y,questionType:X,provider:J,modelId:Q,message:$=`Question "${Y}" has type "${X}", which is not supported by provider "${J}" and model "${Q}".`}){super({name:X$,message:$});this[w5]=!0,this.questionId=Y,this.questionType=X,this.provider=J,this.modelId=Q}static isInstance(Y){return A.hasMarker(Y,J$)}};function d1(Y){if(Y==null)return"unknown error";if(typeof Y==="string")return Y;if(Y instanceof Error)return Y.toString();return JSON.stringify(Y)}var Q$="AI_InvalidArgumentError",$$=`vercel.ai.error.${Q$}`,tH=Symbol.for($$),R5,T5,G$=class extends(T5=A,R5=tH,T5){constructor({message:Y,cause:X,argument:J}){super({name:Q$,message:Y,cause:X});this[R5]=!0,this.argument=J}static isInstance(Y){return A.hasMarker(Y,$$)}},W$="AI_InvalidPromptError",z$=`vercel.ai.error.${W$}`,eH=Symbol.for(z$),C5,_5,YZ=class extends(_5=A,C5=eH,_5){constructor({prompt:Y,message:X,cause:J}){super({name:W$,message:`Invalid prompt: ${X}`,cause:J});this[C5]=!0,this.prompt=Y}static isInstance(Y){return A.hasMarker(Y,z$)}},K$="AI_InvalidResponseDataError",U$=`vercel.ai.error.${K$}`,XZ=Symbol.for(U$),I5,S5,JZ=class extends(S5=A,I5=XZ,S5){constructor({data:Y,message:X=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:K$,message:X});this[I5]=!0,this.data=Y}static isInstance(Y){return A.hasMarker(Y,U$)}},H$="AI_JSONParseError",Z$=`vercel.ai.error.${H$}`,QZ=Symbol.for(Z$),k5,x5,kY=class extends(x5=A,k5=QZ,x5){constructor({text:Y,cause:X}){super({name:H$,message:`JSON parsing failed: Text: ${Y}.
|
|
55
|
+
Error message: ${d1(X)}`,cause:X});this[k5]=!0,this.text=Y}static isInstance(Y){return A.hasMarker(Y,Z$)}},L$="AI_LoadAPIKeyError",V$=`vercel.ai.error.${L$}`,$Z=Symbol.for(V$),b5,v5,GZ=class extends(v5=A,b5=$Z,v5){constructor({message:Y}){super({name:L$,message:Y});this[b5]=!0}static isInstance(Y){return A.hasMarker(Y,V$)}},N$="AI_LoadSettingError",B$=`vercel.ai.error.${N$}`,WZ=Symbol.for(B$),h5,g5,zZ=class extends(g5=A,h5=WZ,g5){constructor({message:Y}){super({name:N$,message:Y});this[h5]=!0}static isInstance(Y){return A.hasMarker(Y,B$)}},F$="AI_NoContentGeneratedError",O$=`vercel.ai.error.${F$}`,KZ=Symbol.for(O$),y5,f5,UZ=class extends(f5=A,y5=KZ,f5){constructor({message:Y="No content generated."}={}){super({name:F$,message:Y});this[y5]=!0}static isInstance(Y){return A.hasMarker(Y,O$)}},j$="AI_NoSuchModelError",q$=`vercel.ai.error.${j$}`,HZ=Symbol.for(q$),m5,c5,dX=class extends(c5=A,m5=HZ,c5){constructor({errorName:Y=j$,modelId:X,modelType:J,message:Q=`No such ${J}: ${X}`}){super({name:Y,message:Q});this[m5]=!0,this.modelId=X,this.modelType=J}static isInstance(Y){return A.hasMarker(Y,q$)}},D$="AI_NoSuchProviderReferenceError",P$=`vercel.ai.error.${D$}`,ZZ=Symbol.for(P$),u5,p5,LZ=class extends(p5=A,u5=ZZ,p5){constructor({provider:Y,reference:X,message:J=`No provider reference found for provider '${Y}'. Available providers: ${Object.keys(X).join(", ")}`}){super({name:D$,message:J});this[u5]=!0,this.provider=Y,this.reference=X}static isInstance(Y){return A.hasMarker(Y,P$)}},E$="AI_TooManyEmbeddingValuesForCallError",M$=`vercel.ai.error.${E$}`,VZ=Symbol.for(M$),l5,d5,NZ=class extends(d5=A,l5=VZ,d5){constructor(Y){super({name:E$,message:`Too many values for a single embedding call. The ${Y.provider} model "${Y.modelId}" can only embed up to ${Y.maxEmbeddingsPerCall} values per call, but ${Y.values.length} values were provided.`});this[l5]=!0,this.provider=Y.provider,this.modelId=Y.modelId,this.maxEmbeddingsPerCall=Y.maxEmbeddingsPerCall,this.values=Y.values}static isInstance(Y){return A.hasMarker(Y,M$)}},w$="AI_TypeValidationError",A$=`vercel.ai.error.${w$}`,BZ=Symbol.for(A$),i5,n5,t0=class Y extends(n5=A,i5=BZ,n5){constructor({value:X,cause:J,context:Q}){let $="Type validation failed";if(Q==null?void 0:Q.field)$+=` for ${Q.field}`;if((Q==null?void 0:Q.entityName)||(Q==null?void 0:Q.entityId)){$+=" (";let G=[];if(Q.entityName)G.push(Q.entityName);if(Q.entityId)G.push(`id: "${Q.entityId}"`);$+=G.join(", "),$+=")"}super({name:w$,message:`${$}: Value: ${JSON.stringify(X)}.
|
|
56
|
+
Error message: ${d1(J)}`,cause:J});this[i5]=!0,this.value=X,this.context=Q}static isInstance(X){return A.hasMarker(X,A$)}static wrap({value:X,cause:J,context:Q}){var $,G,W;if(Y.isInstance(J)&&J.value===X&&(($=J.context)==null?void 0:$.field)===(Q==null?void 0:Q.field)&&((G=J.context)==null?void 0:G.entityName)===(Q==null?void 0:Q.entityName)&&((W=J.context)==null?void 0:W.entityId)===(Q==null?void 0:Q.entityId))return J;return new Y({value:X,cause:J,context:Q})}},R$="AI_UnsupportedFunctionalityError",T$=`vercel.ai.error.${R$}`,FZ=Symbol.for(T$),o5,r5,OZ=class extends(r5=A,o5=FZ,r5){constructor({functionality:Y,message:X=`'${Y}' functionality not supported.`}){super({name:R$,message:X});this[o5]=!0,this.functionality=Y}static isInstance(Y){return A.hasMarker(Y,T$)}};var Qq=Object.freeze({status:"aborted"});function D(Y,X,J){function Q(K,H){var U;Object.defineProperty(K,"_zod",{value:K._zod??{},enumerable:!1}),(U=K._zod).traits??(U.traits=new Set),K._zod.traits.add(Y),X(K,H);for(let Z in W.prototype)if(!(Z in K))Object.defineProperty(K,Z,{value:W.prototype[Z].bind(K)});K._zod.constr=W,K._zod.def=H}let $=J?.Parent??Object;class G extends ${}Object.defineProperty(G,"name",{value:Y});function W(K){var H;let U=J?.Parent?new G:this;Q(U,K),(H=U._zod).deferred??(H.deferred=[]);for(let Z of U._zod.deferred)Z();return U}return Object.defineProperty(W,"init",{value:Q}),Object.defineProperty(W,Symbol.hasInstance,{value:(K)=>{if(J?.Parent&&K instanceof J.Parent)return!0;return K?._zod?.traits?.has(Y)}}),Object.defineProperty(W,"name",{value:Y}),W}var $q=Symbol("zod_brand");class B1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class v9 extends Error{constructor(Y){super(`Encountered unidirectional transform during encode: ${Y}`);this.name="ZodEncodeError"}}var xY={};function K1(Y){if(Y)Object.assign(xY,Y);return xY}var a={};nX(a,{unwrapMessage:()=>h9,uint8ArrayToHex:()=>pZ,uint8ArrayToBase64url:()=>cZ,uint8ArrayToBase64:()=>v$,stringifyPrimitive:()=>S$,shallowClone:()=>_$,safeExtend:()=>vZ,required:()=>yZ,randomString:()=>CZ,propertyKeyTypes:()=>sX,promiseAllObject:()=>TZ,primitiveTypes:()=>I$,prefixIssues:()=>O1,pick:()=>kZ,partial:()=>gZ,optionalKeys:()=>aX,omit:()=>xZ,objectClone:()=>wZ,numKeys:()=>_Z,nullish:()=>y9,normalizeParams:()=>n,mergeDefs:()=>C1,merge:()=>hZ,jsonStringifyReplacer:()=>U9,joinValues:()=>MZ,issue:()=>Z9,isPlainObject:()=>_1,isObject:()=>i1,hexToUint8Array:()=>uZ,getSizableOrigin:()=>x$,getParsedType:()=>IZ,getLengthableOrigin:()=>m9,getEnumValues:()=>g9,getElementAtPath:()=>RZ,floatSafeRemainder:()=>oX,finalizeIssue:()=>X1,extend:()=>bZ,escapeRegex:()=>F1,esc:()=>bY,defineLazy:()=>X0,createTransparentProxy:()=>SZ,cloneDef:()=>AZ,clone:()=>Y1,cleanRegex:()=>f9,cleanEnum:()=>fZ,captureStackTrace:()=>vY,cached:()=>H9,base64urlToUint8Array:()=>mZ,base64ToUint8Array:()=>b$,assignProp:()=>T1,assertNotEqual:()=>qZ,assertNever:()=>PZ,assertIs:()=>DZ,assertEqual:()=>jZ,assert:()=>EZ,allowsEval:()=>rX,aborted:()=>I1,NUMBER_FORMAT_RANGES:()=>tX,Class:()=>h$,BIGINT_FORMAT_RANGES:()=>k$});function jZ(Y){return Y}function qZ(Y){return Y}function DZ(Y){}function PZ(Y){throw Error()}function EZ(Y){}function g9(Y){let X=Object.values(Y).filter((Q)=>typeof Q==="number");return Object.entries(Y).filter(([Q,$])=>X.indexOf(+Q)===-1).map(([Q,$])=>$)}function MZ(Y,X="|"){return Y.map((J)=>S$(J)).join(X)}function U9(Y,X){if(typeof X==="bigint")return X.toString();return X}function H9(Y){return{get value(){{let J=Y();return Object.defineProperty(this,"value",{value:J}),J}throw Error("cached value already set")}}}function y9(Y){return Y===null||Y===void 0}function f9(Y){let X=Y.startsWith("^")?1:0,J=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(X,J)}function oX(Y,X){let J=(Y.toString().split(".")[1]||"").length,Q=X.toString(),$=(Q.split(".")[1]||"").length;if($===0&&/\d?e-\d?/.test(Q)){let H=Q.match(/\d?e-(\d?)/);if(H?.[1])$=Number.parseInt(H[1])}let G=J>$?J:$,W=Number.parseInt(Y.toFixed(G).replace(".","")),K=Number.parseInt(X.toFixed(G).replace(".",""));return W%K/10**G}var C$=Symbol("evaluating");function X0(Y,X,J){let Q=void 0;Object.defineProperty(Y,X,{get(){if(Q===C$)return;if(Q===void 0)Q=C$,Q=J();return Q},set($){Object.defineProperty(Y,X,{value:$})},configurable:!0})}function wZ(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function T1(Y,X,J){Object.defineProperty(Y,X,{value:J,writable:!0,enumerable:!0,configurable:!0})}function C1(...Y){let X={};for(let J of Y){let Q=Object.getOwnPropertyDescriptors(J);Object.assign(X,Q)}return Object.defineProperties({},X)}function AZ(Y){return C1(Y._zod.def)}function RZ(Y,X){if(!X)return Y;return X.reduce((J,Q)=>J?.[Q],Y)}function TZ(Y){let X=Object.keys(Y),J=X.map((Q)=>Y[Q]);return Promise.all(J).then((Q)=>{let $={};for(let G=0;G<X.length;G++)$[X[G]]=Q[G];return $})}function CZ(Y=10){let J="";for(let Q=0;Q<Y;Q++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function bY(Y){return JSON.stringify(Y)}var vY="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function i1(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var rX=H9(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function _1(Y){if(i1(Y)===!1)return!1;let X=Y.constructor;if(X===void 0)return!0;let J=X.prototype;if(i1(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function _$(Y){if(_1(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function _Z(Y){let X=0;for(let J in Y)if(Object.prototype.hasOwnProperty.call(Y,J))X++;return X}var IZ=(Y)=>{let X=typeof Y;switch(X){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(Y)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(Y))return"array";if(Y===null)return"null";if(Y.then&&typeof Y.then==="function"&&Y.catch&&typeof Y.catch==="function")return"promise";if(typeof Map<"u"&&Y instanceof Map)return"map";if(typeof Set<"u"&&Y instanceof Set)return"set";if(typeof Date<"u"&&Y instanceof Date)return"date";if(typeof File<"u"&&Y instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${X}`)}},sX=new Set(["string","number","symbol"]),I$=new Set(["string","number","bigint","boolean","symbol","undefined"]);function F1(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Y1(Y,X,J){let Q=new Y._zod.constr(X??Y._zod.def);if(!X||J?.parent)Q._zod.parent=Y;return Q}function n(Y){let X=Y;if(!X)return{};if(typeof X==="string")return{error:()=>X};if(X?.message!==void 0){if(X?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");X.error=X.message}if(delete X.message,typeof X.error==="string")return{...X,error:()=>X.error};return X}function SZ(Y){let X;return new Proxy({},{get(J,Q,$){return X??(X=Y()),Reflect.get(X,Q,$)},set(J,Q,$,G){return X??(X=Y()),Reflect.set(X,Q,$,G)},has(J,Q){return X??(X=Y()),Reflect.has(X,Q)},deleteProperty(J,Q){return X??(X=Y()),Reflect.deleteProperty(X,Q)},ownKeys(J){return X??(X=Y()),Reflect.ownKeys(X)},getOwnPropertyDescriptor(J,Q){return X??(X=Y()),Reflect.getOwnPropertyDescriptor(X,Q)},defineProperty(J,Q,$){return X??(X=Y()),Reflect.defineProperty(X,Q,$)}})}function S$(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function aX(Y){return Object.keys(Y).filter((X)=>{return Y[X]._zod.optin==="optional"&&Y[X]._zod.optout==="optional"})}var tX={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]},k$={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function kZ(Y,X){let J=Y._zod.def,Q=C1(Y._zod.def,{get shape(){let $={};for(let G in X){if(!(G in J.shape))throw Error(`Unrecognized key: "${G}"`);if(!X[G])continue;$[G]=J.shape[G]}return T1(this,"shape",$),$},checks:[]});return Y1(Y,Q)}function xZ(Y,X){let J=Y._zod.def,Q=C1(Y._zod.def,{get shape(){let $={...Y._zod.def.shape};for(let G in X){if(!(G in J.shape))throw Error(`Unrecognized key: "${G}"`);if(!X[G])continue;delete $[G]}return T1(this,"shape",$),$},checks:[]});return Y1(Y,Q)}function bZ(Y,X){if(!_1(X))throw Error("Invalid input to extend: expected a plain object");let J=Y._zod.def.checks;if(J&&J.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let $=C1(Y._zod.def,{get shape(){let G={...Y._zod.def.shape,...X};return T1(this,"shape",G),G},checks:[]});return Y1(Y,$)}function vZ(Y,X){if(!_1(X))throw Error("Invalid input to safeExtend: expected a plain object");let J={...Y._zod.def,get shape(){let Q={...Y._zod.def.shape,...X};return T1(this,"shape",Q),Q},checks:Y._zod.def.checks};return Y1(Y,J)}function hZ(Y,X){let J=C1(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape,...X._zod.def.shape};return T1(this,"shape",Q),Q},get catchall(){return X._zod.def.catchall},checks:[]});return Y1(Y,J)}function gZ(Y,X,J){let Q=C1(X._zod.def,{get shape(){let $=X._zod.def.shape,G={...$};if(J)for(let W in J){if(!(W in $))throw Error(`Unrecognized key: "${W}"`);if(!J[W])continue;G[W]=Y?new Y({type:"optional",innerType:$[W]}):$[W]}else for(let W in $)G[W]=Y?new Y({type:"optional",innerType:$[W]}):$[W];return T1(this,"shape",G),G},checks:[]});return Y1(X,Q)}function yZ(Y,X,J){let Q=C1(X._zod.def,{get shape(){let $=X._zod.def.shape,G={...$};if(J)for(let W in J){if(!(W in G))throw Error(`Unrecognized key: "${W}"`);if(!J[W])continue;G[W]=new Y({type:"nonoptional",innerType:$[W]})}else for(let W in $)G[W]=new Y({type:"nonoptional",innerType:$[W]});return T1(this,"shape",G),G},checks:[]});return Y1(X,Q)}function I1(Y,X=0){if(Y.aborted===!0)return!0;for(let J=X;J<Y.issues.length;J++)if(Y.issues[J]?.continue!==!0)return!0;return!1}function O1(Y,X){return X.map((J)=>{var Q;return(Q=J).path??(Q.path=[]),J.path.unshift(Y),J})}function h9(Y){return typeof Y==="string"?Y:Y?.message}function X1(Y,X,J){let Q={...Y,path:Y.path??[]};if(!Y.message){let $=h9(Y.inst?._zod.def?.error?.(Y))??h9(X?.error?.(Y))??h9(J.customError?.(Y))??h9(J.localeError?.(Y))??"Invalid input";Q.message=$}if(delete Q.inst,delete Q.continue,!X?.reportInput)delete Q.input;return Q}function x$(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function m9(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function Z9(...Y){let[X,J,Q]=Y;if(typeof X==="string")return{message:X,code:"custom",input:J,inst:Q};return{...X}}function fZ(Y){return Object.entries(Y).filter(([X,J])=>{return Number.isNaN(Number.parseInt(X,10))}).map((X)=>X[1])}function b$(Y){let X=atob(Y),J=new Uint8Array(X.length);for(let Q=0;Q<X.length;Q++)J[Q]=X.charCodeAt(Q);return J}function v$(Y){let X="";for(let J=0;J<Y.length;J++)X+=String.fromCharCode(Y[J]);return btoa(X)}function mZ(Y){let X=Y.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-X.length%4)%4);return b$(X+J)}function cZ(Y){return v$(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function uZ(Y){let X=Y.replace(/^0x/,"");if(X.length%2!==0)throw Error("Invalid hex string length");let J=new Uint8Array(X.length/2);for(let Q=0;Q<X.length;Q+=2)J[Q/2]=Number.parseInt(X.slice(Q,Q+2),16);return J}function pZ(Y){return Array.from(Y).map((X)=>X.toString(16).padStart(2,"0")).join("")}class h${constructor(...Y){}}var g$=(Y,X)=>{Y.name="$ZodError",Object.defineProperty(Y,"_zod",{value:Y._zod,enumerable:!1}),Object.defineProperty(Y,"issues",{value:X,enumerable:!1}),Y.message=JSON.stringify(X,U9,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},hY=D("$ZodError",g$),eX=D("$ZodError",g$,{Parent:Error});function y$(Y,X=(J)=>J.message){let J={},Q=[];for(let $ of Y.issues)if($.path.length>0)J[$.path[0]]=J[$.path[0]]||[],J[$.path[0]].push(X($));else Q.push(X($));return{formErrors:Q,fieldErrors:J}}function f$(Y,X){let J=X||function(G){return G.message},Q={_errors:[]},$=(G)=>{for(let W of G.issues)if(W.code==="invalid_union"&&W.errors.length)W.errors.map((K)=>$({issues:K}));else if(W.code==="invalid_key")$({issues:W.issues});else if(W.code==="invalid_element")$({issues:W.issues});else if(W.path.length===0)Q._errors.push(J(W));else{let K=Q,H=0;while(H<W.path.length){let U=W.path[H];if(H!==W.path.length-1)K[U]=K[U]||{_errors:[]};else K[U]=K[U]||{_errors:[]},K[U]._errors.push(J(W));K=K[U],H++}}};return $(Y),Q}var gY=(Y)=>(X,J,Q,$)=>{let G=Q?Object.assign(Q,{async:!1}):{async:!1},W=X._zod.run({value:J,issues:[]},G);if(W instanceof Promise)throw new B1;if(W.issues.length){let K=new($?.Err??Y)(W.issues.map((H)=>X1(H,G,K1())));throw vY(K,$?.callee),K}return W.value};var yY=(Y)=>async(X,J,Q,$)=>{let G=Q?Object.assign(Q,{async:!0}):{async:!0},W=X._zod.run({value:J,issues:[]},G);if(W instanceof Promise)W=await W;if(W.issues.length){let K=new($?.Err??Y)(W.issues.map((H)=>X1(H,G,K1())));throw vY(K,$?.callee),K}return W.value};var c9=(Y)=>(X,J,Q)=>{let $=Q?{...Q,async:!1}:{async:!1},G=X._zod.run({value:J,issues:[]},$);if(G instanceof Promise)throw new B1;return G.issues.length?{success:!1,error:new(Y??hY)(G.issues.map((W)=>X1(W,$,K1())))}:{success:!0,data:G.value}},m$=c9(eX),u9=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{async:!0}):{async:!0},G=X._zod.run({value:J,issues:[]},$);if(G instanceof Promise)G=await G;return G.issues.length?{success:!1,error:new Y(G.issues.map((W)=>X1(W,$,K1())))}:{success:!0,data:G.value}},c$=u9(eX),u$=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return gY(Y)(X,J,$)};var p$=(Y)=>(X,J,Q)=>{return gY(Y)(X,J,Q)};var l$=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return yY(Y)(X,J,$)};var d$=(Y)=>async(X,J,Q)=>{return yY(Y)(X,J,Q)};var i$=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return c9(Y)(X,J,$)};var n$=(Y)=>(X,J,Q)=>{return c9(Y)(X,J,Q)};var o$=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return u9(Y)(X,J,$)};var r$=(Y)=>async(X,J,Q)=>{return u9(Y)(X,J,Q)};var s$=/^[cC][^\s-]{8,}$/,a$=/^[0-9a-z]+$/,t$=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,e$=/^[0-9a-vA-V]{20}$/,YG=/^[A-Za-z0-9]{27}$/,XG=/^[a-zA-Z0-9_-]{21}$/,JG=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var QG=/^([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})$/,YJ=(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 $G=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function GG(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var WG=/^(?:(?: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])$/,zG=/^(([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}|:))$/,KG=/^((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])$/,UG=/^(([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])$/,HG=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,XJ=/^[A-Za-z0-9_-]*$/,ZG=/^(?=.{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 LG=/^\+(?:[0-9]){6,14}[0-9]$/,VG="(?:(?:\\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])))",NG=new RegExp(`^${VG}$`);function BG(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 FG(Y){return new RegExp(`^${BG(Y)}$`)}function OG(Y){let X=BG({precision:Y.precision}),J=["Z"];if(Y.local)J.push("");if(Y.offset)J.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let Q=`${X}(?:${J.join("|")})`;return new RegExp(`^${VG}T(?:${Q})$`)}var jG=(Y)=>{let X=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${X}$`)};var qG=/^-?\d+$/,DG=/^-?\d+(?:\.\d+)?/,PG=/^(?:true|false)$/i,EG=/^null$/i;var MG=/^[^A-Z]*$/,wG=/^[^a-z]*$/;var T0=D("$ZodCheck",(Y,X)=>{var J;Y._zod??(Y._zod={}),Y._zod.def=X,(J=Y._zod).onattach??(J.onattach=[])}),AG={number:"number",bigint:"bigint",object:"date"},JJ=D("$ZodCheckLessThan",(Y,X)=>{T0.init(Y,X);let J=AG[typeof X.value];Y._zod.onattach.push((Q)=>{let $=Q._zod.bag,G=(X.inclusive?$.maximum:$.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(X.value<G)if(X.inclusive)$.maximum=X.value;else $.exclusiveMaximum=X.value}),Y._zod.check=(Q)=>{if(X.inclusive?Q.value<=X.value:Q.value<X.value)return;Q.issues.push({origin:J,code:"too_big",maximum:X.value,input:Q.value,inclusive:X.inclusive,inst:Y,continue:!X.abort})}}),QJ=D("$ZodCheckGreaterThan",(Y,X)=>{T0.init(Y,X);let J=AG[typeof X.value];Y._zod.onattach.push((Q)=>{let $=Q._zod.bag,G=(X.inclusive?$.minimum:$.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(X.value>G)if(X.inclusive)$.minimum=X.value;else $.exclusiveMinimum=X.value}),Y._zod.check=(Q)=>{if(X.inclusive?Q.value>=X.value:Q.value>X.value)return;Q.issues.push({origin:J,code:"too_small",minimum:X.value,input:Q.value,inclusive:X.inclusive,inst:Y,continue:!X.abort})}}),RG=D("$ZodCheckMultipleOf",(Y,X)=>{T0.init(Y,X),Y._zod.onattach.push((J)=>{var Q;(Q=J._zod.bag).multipleOf??(Q.multipleOf=X.value)}),Y._zod.check=(J)=>{if(typeof J.value!==typeof X.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof J.value==="bigint"?J.value%X.value===BigInt(0):oX(J.value,X.value)===0)return;J.issues.push({origin:typeof J.value,code:"not_multiple_of",divisor:X.value,input:J.value,inst:Y,continue:!X.abort})}}),TG=D("$ZodCheckNumberFormat",(Y,X)=>{T0.init(Y,X),X.format=X.format||"float64";let J=X.format?.includes("int"),Q=J?"int":"number",[$,G]=tX[X.format];Y._zod.onattach.push((W)=>{let K=W._zod.bag;if(K.format=X.format,K.minimum=$,K.maximum=G,J)K.pattern=qG}),Y._zod.check=(W)=>{let K=W.value;if(J){if(!Number.isInteger(K)){W.issues.push({expected:Q,format:X.format,code:"invalid_type",continue:!1,input:K,inst:Y});return}if(!Number.isSafeInteger(K)){if(K>0)W.issues.push({input:K,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:Q,continue:!X.abort});else W.issues.push({input:K,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:Q,continue:!X.abort});return}}if(K<$)W.issues.push({origin:"number",input:K,code:"too_small",minimum:$,inclusive:!0,inst:Y,continue:!X.abort});if(K>G)W.issues.push({origin:"number",input:K,code:"too_big",maximum:G,inst:Y})}});var CG=D("$ZodCheckMaxLength",(Y,X)=>{var J;T0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!y9($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(X.maximum<$)Q._zod.bag.maximum=X.maximum}),Y._zod.check=(Q)=>{let $=Q.value;if($.length<=X.maximum)return;let W=m9($);Q.issues.push({origin:W,code:"too_big",maximum:X.maximum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),_G=D("$ZodCheckMinLength",(Y,X)=>{var J;T0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!y9($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(X.minimum>$)Q._zod.bag.minimum=X.minimum}),Y._zod.check=(Q)=>{let $=Q.value;if($.length>=X.minimum)return;let W=m9($);Q.issues.push({origin:W,code:"too_small",minimum:X.minimum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),IG=D("$ZodCheckLengthEquals",(Y,X)=>{var J;T0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!y9($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.minimum=X.length,$.maximum=X.length,$.length=X.length}),Y._zod.check=(Q)=>{let $=Q.value,G=$.length;if(G===X.length)return;let W=m9($),K=G>X.length;Q.issues.push({origin:W,...K?{code:"too_big",maximum:X.length}:{code:"too_small",minimum:X.length},inclusive:!0,exact:!0,input:Q.value,inst:Y,continue:!X.abort})}}),p9=D("$ZodCheckStringFormat",(Y,X)=>{var J,Q;if(T0.init(Y,X),Y._zod.onattach.push(($)=>{let G=$._zod.bag;if(G.format=X.format,X.pattern)G.patterns??(G.patterns=new Set),G.patterns.add(X.pattern)}),X.pattern)(J=Y._zod).check??(J.check=($)=>{if(X.pattern.lastIndex=0,X.pattern.test($.value))return;$.issues.push({origin:"string",code:"invalid_format",format:X.format,input:$.value,...X.pattern?{pattern:X.pattern.toString()}:{},inst:Y,continue:!X.abort})});else(Q=Y._zod).check??(Q.check=()=>{})}),SG=D("$ZodCheckRegex",(Y,X)=>{p9.init(Y,X),Y._zod.check=(J)=>{if(X.pattern.lastIndex=0,X.pattern.test(J.value))return;J.issues.push({origin:"string",code:"invalid_format",format:"regex",input:J.value,pattern:X.pattern.toString(),inst:Y,continue:!X.abort})}}),kG=D("$ZodCheckLowerCase",(Y,X)=>{X.pattern??(X.pattern=MG),p9.init(Y,X)}),xG=D("$ZodCheckUpperCase",(Y,X)=>{X.pattern??(X.pattern=wG),p9.init(Y,X)}),bG=D("$ZodCheckIncludes",(Y,X)=>{T0.init(Y,X);let J=F1(X.includes),Q=new RegExp(typeof X.position==="number"?`^.{${X.position}}${J}`:J);X.pattern=Q,Y._zod.onattach.push(($)=>{let G=$._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(Q)}),Y._zod.check=($)=>{if($.value.includes(X.includes,X.position))return;$.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:X.includes,input:$.value,inst:Y,continue:!X.abort})}}),vG=D("$ZodCheckStartsWith",(Y,X)=>{T0.init(Y,X);let J=new RegExp(`^${F1(X.prefix)}.*`);X.pattern??(X.pattern=J),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(J)}),Y._zod.check=(Q)=>{if(Q.value.startsWith(X.prefix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:X.prefix,input:Q.value,inst:Y,continue:!X.abort})}}),hG=D("$ZodCheckEndsWith",(Y,X)=>{T0.init(Y,X);let J=new RegExp(`.*${F1(X.suffix)}$`);X.pattern??(X.pattern=J),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(J)}),Y._zod.check=(Q)=>{if(Q.value.endsWith(X.suffix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:X.suffix,input:Q.value,inst:Y,continue:!X.abort})}});var gG=D("$ZodCheckOverwrite",(Y,X)=>{T0.init(Y,X),Y._zod.check=(J)=>{J.value=X.tx(J.value)}});class $J{constructor(Y=[]){if(this.content=[],this.indent=0,this)this.args=Y}indented(Y){this.indent+=1,Y(this),this.indent-=1}write(Y){if(typeof Y==="function"){Y(this,{execution:"sync"}),Y(this,{execution:"async"});return}let J=Y.split(`
|
|
57
|
+
`).filter((G)=>G),Q=Math.min(...J.map((G)=>G.length-G.trimStart().length)),$=J.map((G)=>G.slice(Q)).map((G)=>" ".repeat(this.indent*2)+G);for(let G of $)this.content.push(G)}compile(){let Y=Function,X=this?.args,Q=[...(this?.content??[""]).map(($)=>` ${$}`)];return new Y(...X,Q.join(`
|
|
58
|
+
`))}}var fG={major:4,minor:1,patch:8};var U0=D("$ZodType",(Y,X)=>{var J;Y??(Y={}),Y._zod.def=X,Y._zod.bag=Y._zod.bag||{},Y._zod.version=fG;let Q=[...Y._zod.def.checks??[]];if(Y._zod.traits.has("$ZodCheck"))Q.unshift(Y);for(let $ of Q)for(let G of $._zod.onattach)G(Y);if(Q.length===0)(J=Y._zod).deferred??(J.deferred=[]),Y._zod.deferred?.push(()=>{Y._zod.run=Y._zod.parse});else{let $=(W,K,H)=>{let U=I1(W),Z;for(let F of K){if(F._zod.def.when){if(!F._zod.def.when(W))continue}else if(U)continue;let N=W.issues.length,V=F._zod.check(W);if(V instanceof Promise&&H?.async===!1)throw new B1;if(Z||V instanceof Promise)Z=(Z??Promise.resolve()).then(async()=>{if(await V,W.issues.length===N)return;if(!U)U=I1(W,N)});else{if(W.issues.length===N)continue;if(!U)U=I1(W,N)}}if(Z)return Z.then(()=>{return W});return W},G=(W,K,H)=>{if(I1(W))return W.aborted=!0,W;let U=$(K,Q,H);if(U instanceof Promise){if(H.async===!1)throw new B1;return U.then((Z)=>Y._zod.parse(Z,H))}return Y._zod.parse(U,H)};Y._zod.run=(W,K)=>{if(K.skipChecks)return Y._zod.parse(W,K);if(K.direction==="backward"){let U=Y._zod.parse({value:W.value,issues:[]},{...K,skipChecks:!0});if(U instanceof Promise)return U.then((Z)=>{return G(Z,W,K)});return G(U,W,K)}let H=Y._zod.parse(W,K);if(H instanceof Promise){if(K.async===!1)throw new B1;return H.then((U)=>$(U,Q,K))}return $(H,Q,K)}}Y["~standard"]={validate:($)=>{try{let G=m$(Y,$);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return c$(Y,$).then((W)=>W.success?{value:W.data}:{issues:W.error?.issues})}},vendor:"zod",version:1}}),uY=D("$ZodString",(Y,X)=>{U0.init(Y,X),Y._zod.pattern=[...Y?._zod.bag?.patterns??[]].pop()??jG(Y._zod.bag),Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=String(J.value)}catch($){}if(typeof J.value==="string")return J;return J.issues.push({expected:"string",code:"invalid_type",input:J.value,inst:Y}),J}}),Z0=D("$ZodStringFormat",(Y,X)=>{p9.init(Y,X),uY.init(Y,X)}),oG=D("$ZodGUID",(Y,X)=>{X.pattern??(X.pattern=QG),Z0.init(Y,X)}),rG=D("$ZodUUID",(Y,X)=>{if(X.version){let Q={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[X.version];if(Q===void 0)throw Error(`Invalid UUID version: "${X.version}"`);X.pattern??(X.pattern=YJ(Q))}else X.pattern??(X.pattern=YJ());Z0.init(Y,X)}),sG=D("$ZodEmail",(Y,X)=>{X.pattern??(X.pattern=$G),Z0.init(Y,X)}),aG=D("$ZodURL",(Y,X)=>{Z0.init(Y,X),Y._zod.check=(J)=>{try{let Q=J.value.trim(),$=new URL(Q);if(X.hostname){if(X.hostname.lastIndex=0,!X.hostname.test($.hostname))J.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:ZG.source,input:J.value,inst:Y,continue:!X.abort})}if(X.protocol){if(X.protocol.lastIndex=0,!X.protocol.test($.protocol.endsWith(":")?$.protocol.slice(0,-1):$.protocol))J.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:X.protocol.source,input:J.value,inst:Y,continue:!X.abort})}if(X.normalize)J.value=$.href;else J.value=Q;return}catch(Q){J.issues.push({code:"invalid_format",format:"url",input:J.value,inst:Y,continue:!X.abort})}}}),tG=D("$ZodEmoji",(Y,X)=>{X.pattern??(X.pattern=GG()),Z0.init(Y,X)}),eG=D("$ZodNanoID",(Y,X)=>{X.pattern??(X.pattern=XG),Z0.init(Y,X)}),Y2=D("$ZodCUID",(Y,X)=>{X.pattern??(X.pattern=s$),Z0.init(Y,X)}),X2=D("$ZodCUID2",(Y,X)=>{X.pattern??(X.pattern=a$),Z0.init(Y,X)}),J2=D("$ZodULID",(Y,X)=>{X.pattern??(X.pattern=t$),Z0.init(Y,X)}),Q2=D("$ZodXID",(Y,X)=>{X.pattern??(X.pattern=e$),Z0.init(Y,X)}),$2=D("$ZodKSUID",(Y,X)=>{X.pattern??(X.pattern=YG),Z0.init(Y,X)}),G2=D("$ZodISODateTime",(Y,X)=>{X.pattern??(X.pattern=OG(X)),Z0.init(Y,X)}),W2=D("$ZodISODate",(Y,X)=>{X.pattern??(X.pattern=NG),Z0.init(Y,X)}),z2=D("$ZodISOTime",(Y,X)=>{X.pattern??(X.pattern=FG(X)),Z0.init(Y,X)}),K2=D("$ZodISODuration",(Y,X)=>{X.pattern??(X.pattern=JG),Z0.init(Y,X)}),U2=D("$ZodIPv4",(Y,X)=>{X.pattern??(X.pattern=WG),Z0.init(Y,X),Y._zod.onattach.push((J)=>{let Q=J._zod.bag;Q.format="ipv4"})}),H2=D("$ZodIPv6",(Y,X)=>{X.pattern??(X.pattern=zG),Z0.init(Y,X),Y._zod.onattach.push((J)=>{let Q=J._zod.bag;Q.format="ipv6"}),Y._zod.check=(J)=>{try{new URL(`http://[${J.value}]`)}catch{J.issues.push({code:"invalid_format",format:"ipv6",input:J.value,inst:Y,continue:!X.abort})}}}),Z2=D("$ZodCIDRv4",(Y,X)=>{X.pattern??(X.pattern=KG),Z0.init(Y,X)}),L2=D("$ZodCIDRv6",(Y,X)=>{X.pattern??(X.pattern=UG),Z0.init(Y,X),Y._zod.check=(J)=>{let Q=J.value.split("/");try{if(Q.length!==2)throw Error();let[$,G]=Q;if(!G)throw Error();let W=Number(G);if(`${W}`!==G)throw Error();if(W<0||W>128)throw Error();new URL(`http://[${$}]`)}catch{J.issues.push({code:"invalid_format",format:"cidrv6",input:J.value,inst:Y,continue:!X.abort})}}});function V2(Y){if(Y==="")return!0;if(Y.length%4!==0)return!1;try{return atob(Y),!0}catch{return!1}}var N2=D("$ZodBase64",(Y,X)=>{X.pattern??(X.pattern=HG),Z0.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64"}),Y._zod.check=(J)=>{if(V2(J.value))return;J.issues.push({code:"invalid_format",format:"base64",input:J.value,inst:Y,continue:!X.abort})}});function dZ(Y){if(!XJ.test(Y))return!1;let X=Y.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),J=X.padEnd(Math.ceil(X.length/4)*4,"=");return V2(J)}var B2=D("$ZodBase64URL",(Y,X)=>{X.pattern??(X.pattern=XJ),Z0.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64url"}),Y._zod.check=(J)=>{if(dZ(J.value))return;J.issues.push({code:"invalid_format",format:"base64url",input:J.value,inst:Y,continue:!X.abort})}}),F2=D("$ZodE164",(Y,X)=>{X.pattern??(X.pattern=LG),Z0.init(Y,X)});function iZ(Y,X=null){try{let J=Y.split(".");if(J.length!==3)return!1;let[Q]=J;if(!Q)return!1;let $=JSON.parse(atob(Q));if("typ"in $&&$?.typ!=="JWT")return!1;if(!$.alg)return!1;if(X&&(!("alg"in $)||$.alg!==X))return!1;return!0}catch{return!1}}var O2=D("$ZodJWT",(Y,X)=>{Z0.init(Y,X),Y._zod.check=(J)=>{if(iZ(J.value,X.alg))return;J.issues.push({code:"invalid_format",format:"jwt",input:J.value,inst:Y,continue:!X.abort})}});var WJ=D("$ZodNumber",(Y,X)=>{U0.init(Y,X),Y._zod.pattern=Y._zod.bag.pattern??DG,Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=Number(J.value)}catch(W){}let $=J.value;if(typeof $==="number"&&!Number.isNaN($)&&Number.isFinite($))return J;let G=typeof $==="number"?Number.isNaN($)?"NaN":!Number.isFinite($)?"Infinity":void 0:void 0;return J.issues.push({expected:"number",code:"invalid_type",input:$,inst:Y,...G?{received:G}:{}}),J}}),j2=D("$ZodNumber",(Y,X)=>{TG.init(Y,X),WJ.init(Y,X)}),q2=D("$ZodBoolean",(Y,X)=>{U0.init(Y,X),Y._zod.pattern=PG,Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=Boolean(J.value)}catch(G){}let $=J.value;if(typeof $==="boolean")return J;return J.issues.push({expected:"boolean",code:"invalid_type",input:$,inst:Y}),J}});var D2=D("$ZodNull",(Y,X)=>{U0.init(Y,X),Y._zod.pattern=EG,Y._zod.values=new Set([null]),Y._zod.parse=(J,Q)=>{let $=J.value;if($===null)return J;return J.issues.push({expected:"null",code:"invalid_type",input:$,inst:Y}),J}});var P2=D("$ZodUnknown",(Y,X)=>{U0.init(Y,X),Y._zod.parse=(J)=>J}),E2=D("$ZodNever",(Y,X)=>{U0.init(Y,X),Y._zod.parse=(J,Q)=>{return J.issues.push({expected:"never",code:"invalid_type",input:J.value,inst:Y}),J}});function mG(Y,X,J){if(Y.issues.length)X.issues.push(...O1(J,Y.issues));X.value[J]=Y.value}var M2=D("$ZodArray",(Y,X)=>{U0.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value;if(!Array.isArray($))return J.issues.push({expected:"array",code:"invalid_type",input:$,inst:Y}),J;J.value=Array($.length);let G=[];for(let W=0;W<$.length;W++){let K=$[W],H=X.element._zod.run({value:K,issues:[]},Q);if(H instanceof Promise)G.push(H.then((U)=>mG(U,J,W)));else mG(H,J,W)}if(G.length)return Promise.all(G).then(()=>J);return J}});function cY(Y,X,J,Q){if(Y.issues.length)X.issues.push(...O1(J,Y.issues));if(Y.value===void 0){if(J in Q)X.value[J]=void 0}else X.value[J]=Y.value}function w2(Y){let X=Object.keys(Y.shape);for(let Q of X)if(!Y.shape?.[Q]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${Q}": expected a Zod schema`);let J=aX(Y.shape);return{...Y,keys:X,keySet:new Set(X),numKeys:X.length,optionalKeys:new Set(J)}}function A2(Y,X,J,Q,$,G){let W=[],K=$.keySet,H=$.catchall._zod,U=H.def.type;for(let Z of Object.keys(X)){if(K.has(Z))continue;if(U==="never"){W.push(Z);continue}let F=H.run({value:X[Z],issues:[]},Q);if(F instanceof Promise)Y.push(F.then((N)=>cY(N,J,Z,X)));else cY(F,J,Z,X)}if(W.length)J.issues.push({code:"unrecognized_keys",keys:W,input:X,inst:G});if(!Y.length)return J;return Promise.all(Y).then(()=>{return J})}var nZ=D("$ZodObject",(Y,X)=>{U0.init(Y,X);let J=H9(()=>w2(X));X0(Y._zod,"propValues",()=>{let W=X.shape,K={};for(let H in W){let U=W[H]._zod;if(U.values){K[H]??(K[H]=new Set);for(let Z of U.values)K[H].add(Z)}}return K});let Q=i1,$=X.catchall,G;Y._zod.parse=(W,K)=>{G??(G=J.value);let H=W.value;if(!Q(H))return W.issues.push({expected:"object",code:"invalid_type",input:H,inst:Y}),W;W.value={};let U=[],Z=G.shape;for(let F of G.keys){let V=Z[F]._zod.run({value:H[F],issues:[]},K);if(V instanceof Promise)U.push(V.then((q)=>cY(q,W,F,H)));else cY(V,W,F,H)}if(!$)return U.length?Promise.all(U).then(()=>W):W;return A2(U,H,W,K,J.value,Y)}}),R2=D("$ZodObjectJIT",(Y,X)=>{nZ.init(Y,X);let J=Y._zod.parse,Q=H9(()=>w2(X)),$=(N)=>{let V=new $J(["shape","payload","ctx"]),q=Q.value,R=(E)=>{let S=bY(E);return`shape[${S}]._zod.run({ value: input[${S}], issues: [] }, ctx)`};V.write("const input = payload.value;");let k=Object.create(null),u=0;for(let E of q.keys)k[E]=`key_${u++}`;V.write("const newResult = {};");for(let E of q.keys){let S=k[E],c=bY(E);V.write(`const ${S} = ${R(E)};`),V.write(`
|
|
59
|
+
if (${S}.issues.length) {
|
|
60
|
+
payload.issues = payload.issues.concat(${S}.issues.map(iss => ({
|
|
76
61
|
...iss,
|
|
77
|
-
path: iss.path ? [${
|
|
62
|
+
path: iss.path ? [${c}, ...iss.path] : [${c}]
|
|
78
63
|
})));
|
|
79
64
|
}
|
|
80
65
|
|
|
81
66
|
|
|
82
|
-
if (${
|
|
83
|
-
if (${
|
|
84
|
-
newResult[${
|
|
67
|
+
if (${S}.value === undefined) {
|
|
68
|
+
if (${c} in input) {
|
|
69
|
+
newResult[${c}] = undefined;
|
|
85
70
|
}
|
|
86
71
|
} else {
|
|
87
|
-
newResult[${
|
|
72
|
+
newResult[${c}] = ${S}.value;
|
|
88
73
|
}
|
|
89
74
|
|
|
90
|
-
`)}V.write("payload.value = newResult;"),V.write("return payload;");let _=V.compile();return(E,b)=>_(N,E,b)},G,W=l1,K=!bY.jitless,U=K&&eJ.value,L=J.catchall,j;Y._zod.parse=(N,V)=>{j??(j=Q.value);let q=N.value;if(!W(q))return N.issues.push({expected:"object",code:"invalid_type",input:q,inst:Y}),N;if(K&&U&&V?.async===!1&&V.jitless!==!0){if(!G)G=$(J.shape);if(N=G(N,V),!L)return N;return v2([],q,N,V,j,Y)}return X(N,V)}});function aG(Y,J,X,Q){for(let G of Y)if(G.issues.length===0)return J.value=G.value,J;let $=Y.filter((G)=>!I1(G));if($.length===1)return J.value=$[0].value,$[0];return J.issues.push({code:"invalid_union",input:J.value,inst:X,errors:Y.map((G)=>G.issues.map((W)=>t0(W,Q,G1())))}),J}var LX=P("$ZodUnion",(Y,J)=>{K0.init(Y,J),J0(Y._zod,"optin",()=>J.options.some(($)=>$._zod.optin==="optional")?"optional":void 0),J0(Y._zod,"optout",()=>J.options.some(($)=>$._zod.optout==="optional")?"optional":void 0),J0(Y._zod,"values",()=>{if(J.options.every(($)=>$._zod.values))return new Set(J.options.flatMap(($)=>Array.from($._zod.values)));return}),J0(Y._zod,"pattern",()=>{if(J.options.every(($)=>$._zod.pattern)){let $=J.options.map((G)=>G._zod.pattern);return new RegExp(`^(${$.map((G)=>f9(G.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 Z of J.options){let U=Z._zod.run({value:$.value,issues:[]},G);if(U instanceof Promise)K.push(U),W=!0;else{if(U.issues.length===0)return U;K.push(U)}}if(!W)return aG(K,$,Y,G);return Promise.all(K).then((Z)=>{return aG(Z,$,Y,G)})}}),g2=P("$ZodDiscriminatedUnion",(Y,J)=>{LX.init(Y,J);let X=Y._zod.parse;J0(Y._zod,"propValues",()=>{let $={};for(let G of J.options){let W=G._zod.propValues;if(!W||Object.keys(W).length===0)throw Error(`Invalid discriminated union option at index "${J.options.indexOf(G)}"`);for(let[K,Z]of Object.entries(W)){if(!$[K])$[K]=new Set;for(let U of Z)$[K].add(U)}}return $});let Q=U9(()=>{let $=J.options,G=new Map;for(let W of $){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 Z of K){if(G.has(Z))throw Error(`Duplicate discriminator value "${String(Z)}"`);G.set(Z,W)}}return G});Y._zod.parse=($,G)=>{let W=$.value;if(!l1(W))return $.issues.push({code:"invalid_type",expected:"object",input:W,inst:Y}),$;let K=Q.value.get(W?.[J.discriminator]);if(K)return K._zod.run($,G);if(J.unionFallback)return X($,G);return $.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:J.discriminator,input:W,path:[J.discriminator],inst:Y}),$}}),y2=P("$ZodIntersection",(Y,J)=>{K0.init(Y,J),Y._zod.parse=(X,Q)=>{let $=X.value,G=J.left._zod.run({value:$,issues:[]},Q),W=J.right._zod.run({value:$,issues:[]},Q);if(G instanceof Promise||W instanceof Promise)return Promise.all([G,W]).then(([Z,U])=>{return tG(X,Z,U)});return tG(X,G,W)}});function UX(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(_1(Y)&&_1(J)){let X=Object.keys(J),Q=Object.keys(Y).filter((G)=>X.indexOf(G)!==-1),$={...Y,...J};for(let G of Q){let W=UX(Y[G],J[G]);if(!W.valid)return{valid:!1,mergeErrorPath:[G,...W.mergeErrorPath]};$[G]=W.data}return{valid:!0,data:$}}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 $=Y[Q],G=J[Q],W=UX($,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 tG(Y,J,X){if(J.issues.length)Y.issues.push(...J.issues);if(X.issues.length)Y.issues.push(...X.issues);if(I1(Y))return Y;let Q=UX(J.value,X.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return Y.value=Q.data,Y}var f2=P("$ZodRecord",(Y,J)=>{K0.init(Y,J),Y._zod.parse=(X,Q)=>{let $=X.value;if(!_1($))return X.issues.push({expected:"record",code:"invalid_type",input:$,inst:Y}),X;let G=[];if(J.keyType._zod.values){let W=J.keyType._zod.values;X.value={};for(let Z of W)if(typeof Z==="string"||typeof Z==="number"||typeof Z==="symbol"){let U=J.valueType._zod.run({value:$[Z],issues:[]},Q);if(U instanceof Promise)G.push(U.then((L)=>{if(L.issues.length)X.issues.push(...O1(Z,L.issues));X.value[Z]=L.value}));else{if(U.issues.length)X.issues.push(...O1(Z,U.issues));X.value[Z]=U.value}}let K;for(let Z in $)if(!W.has(Z))K=K??[],K.push(Z);if(K&&K.length>0)X.issues.push({code:"unrecognized_keys",input:$,inst:Y,keys:K})}else{X.value={};for(let W of Reflect.ownKeys($)){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((U)=>t0(U,Q,G1())),input:W,path:[W],inst:Y}),X.value[K.value]=K.value;continue}let Z=J.valueType._zod.run({value:$[W],issues:[]},Q);if(Z instanceof Promise)G.push(Z.then((U)=>{if(U.issues.length)X.issues.push(...O1(W,U.issues));X.value[K.value]=U.value}));else{if(Z.issues.length)X.issues.push(...O1(W,Z.issues));X.value[K.value]=Z.value}}}if(G.length)return Promise.all(G).then(()=>X);return X}});var m2=P("$ZodEnum",(Y,J)=>{K0.init(Y,J);let X=g9(J.entries),Q=new Set(X);Y._zod.values=Q,Y._zod.pattern=new RegExp(`^(${X.filter(($)=>YX.has(typeof $)).map(($)=>typeof $==="string"?j1($):$.toString()).join("|")})$`),Y._zod.parse=($,G)=>{let W=$.value;if(Q.has(W))return $;return $.issues.push({code:"invalid_value",values:X,input:W,inst:Y}),$}}),c2=P("$ZodLiteral",(Y,J)=>{if(K0.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"?j1(X):X?j1(X.toString()):String(X)).join("|")})$`),Y._zod.parse=(X,Q)=>{let $=X.value;if(Y._zod.values.has($))return X;return X.issues.push({code:"invalid_value",values:J.values,input:$,inst:Y}),X}});var u2=P("$ZodTransform",(Y,J)=>{K0.init(Y,J),Y._zod.parse=(X,Q)=>{if(Q.direction==="backward")throw new v9(Y.constructor.name);let $=J.transform(X.value,X);if(Q.async)return($ instanceof Promise?$:Promise.resolve($)).then((W)=>{return X.value=W,X});if($ instanceof Promise)throw new F1;return X.value=$,X}});function eG(Y,J){if(Y.issues.length&&J===void 0)return{issues:[],value:void 0};return Y}var p2=P("$ZodOptional",(Y,J)=>{K0.init(Y,J),Y._zod.optin="optional",Y._zod.optout="optional",J0(Y._zod,"values",()=>{return J.innerType._zod.values?new Set([...J.innerType._zod.values,void 0]):void 0}),J0(Y._zod,"pattern",()=>{let X=J.innerType._zod.pattern;return X?new RegExp(`^(${f9(X.source)})?$`):void 0}),Y._zod.parse=(X,Q)=>{if(J.innerType._zod.optin==="optional"){let $=J.innerType._zod.run(X,Q);if($ instanceof Promise)return $.then((G)=>eG(G,X.value));return eG($,X.value)}if(X.value===void 0)return X;return J.innerType._zod.run(X,Q)}}),l2=P("$ZodNullable",(Y,J)=>{K0.init(Y,J),J0(Y._zod,"optin",()=>J.innerType._zod.optin),J0(Y._zod,"optout",()=>J.innerType._zod.optout),J0(Y._zod,"pattern",()=>{let X=J.innerType._zod.pattern;return X?new RegExp(`^(${f9(X.source)}|null)$`):void 0}),J0(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)}}),d2=P("$ZodDefault",(Y,J)=>{K0.init(Y,J),Y._zod.optin="optional",J0(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 $=J.innerType._zod.run(X,Q);if($ instanceof Promise)return $.then((G)=>Y2(G,J));return Y2($,J)}});function Y2(Y,J){if(Y.value===void 0)Y.value=J.defaultValue;return Y}var i2=P("$ZodPrefault",(Y,J)=>{K0.init(Y,J),Y._zod.optin="optional",J0(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)}}),o2=P("$ZodNonOptional",(Y,J)=>{K0.init(Y,J),J0(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 $=J.innerType._zod.run(X,Q);if($ instanceof Promise)return $.then((G)=>J2(G,Y));return J2($,Y)}});function J2(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 n2=P("$ZodCatch",(Y,J)=>{K0.init(Y,J),J0(Y._zod,"optin",()=>J.innerType._zod.optin),J0(Y._zod,"optout",()=>J.innerType._zod.optout),J0(Y._zod,"values",()=>J.innerType._zod.values),Y._zod.parse=(X,Q)=>{if(Q.direction==="backward")return J.innerType._zod.run(X,Q);let $=J.innerType._zod.run(X,Q);if($ instanceof Promise)return $.then((G)=>{if(X.value=G.value,G.issues.length)X.value=J.catchValue({...X,error:{issues:G.issues.map((W)=>t0(W,Q,G1()))},input:X.value}),X.issues=[];return X});if(X.value=$.value,$.issues.length)X.value=J.catchValue({...X,error:{issues:$.issues.map((G)=>t0(G,Q,G1()))},input:X.value}),X.issues=[];return X}});var r2=P("$ZodPipe",(Y,J)=>{K0.init(Y,J),J0(Y._zod,"values",()=>J.in._zod.values),J0(Y._zod,"optin",()=>J.in._zod.optin),J0(Y._zod,"optout",()=>J.out._zod.optout),J0(Y._zod,"propValues",()=>J.in._zod.propValues),Y._zod.parse=(X,Q)=>{if(Q.direction==="backward"){let G=J.out._zod.run(X,Q);if(G instanceof Promise)return G.then((W)=>cY(W,J.in,Q));return cY(G,J.in,Q)}let $=J.in._zod.run(X,Q);if($ instanceof Promise)return $.then((G)=>cY(G,J.out,Q));return cY($,J.out,Q)}});function cY(Y,J,X){if(Y.issues.length)return Y.aborted=!0,Y;return J._zod.run({value:Y.value,issues:Y.issues},X)}var s2=P("$ZodReadonly",(Y,J)=>{K0.init(Y,J),J0(Y._zod,"propValues",()=>J.innerType._zod.propValues),J0(Y._zod,"values",()=>J.innerType._zod.values),J0(Y._zod,"optin",()=>J.innerType._zod.optin),J0(Y._zod,"optout",()=>J.innerType._zod.optout),Y._zod.parse=(X,Q)=>{if(Q.direction==="backward")return J.innerType._zod.run(X,Q);let $=J.innerType._zod.run(X,Q);if($ instanceof Promise)return $.then(X2);return X2($)}});function X2(Y){return Y.value=Object.freeze(Y.value),Y}var a2=P("$ZodLazy",(Y,J)=>{K0.init(Y,J),J0(Y._zod,"innerType",()=>J.getter()),J0(Y._zod,"pattern",()=>Y._zod.innerType._zod.pattern),J0(Y._zod,"propValues",()=>Y._zod.innerType._zod.propValues),J0(Y._zod,"optin",()=>Y._zod.innerType._zod.optin??void 0),J0(Y._zod,"optout",()=>Y._zod.innerType._zod.optout??void 0),Y._zod.parse=(X,Q)=>{return Y._zod.innerType._zod.run(X,Q)}}),t2=P("$ZodCustom",(Y,J)=>{w0.init(Y,J),K0.init(Y,J),Y._zod.parse=(X,Q)=>{return X},Y._zod.check=(X)=>{let Q=X.value,$=J.fn(Q);if($ instanceof Promise)return $.then((G)=>Q2(G,X,Q,Y));Q2($,X,Q,Y);return}});function Q2(Y,J,X,Q){if(!Y){let $={code:"custom",input:X,inst:Q,path:[...Q._zod.def.path??[]],continue:!Q._zod.def.abort};if(Q._zod.def.params)$.params=Q._zod.def.params;J.issues.push(Z9($))}}var pq=Symbol("ZodOutput"),lq=Symbol("ZodInput");class lY{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 HH(){return new lY}var d1=HH();function e2(Y,J){return new Y({type:"string",...i(J)})}function Y7(Y,J){return new Y({type:"string",format:"email",check:"string_format",abort:!1,...i(J)})}function HX(Y,J){return new Y({type:"string",format:"guid",check:"string_format",abort:!1,...i(J)})}function J7(Y,J){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...i(J)})}function X7(Y,J){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...i(J)})}function Q7(Y,J){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...i(J)})}function $7(Y,J){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...i(J)})}function G7(Y,J){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...i(J)})}function W7(Y,J){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...i(J)})}function z7(Y,J){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...i(J)})}function K7(Y,J){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...i(J)})}function U7(Y,J){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...i(J)})}function Z7(Y,J){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...i(J)})}function L7(Y,J){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...i(J)})}function H7(Y,J){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...i(J)})}function V7(Y,J){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...i(J)})}function N7(Y,J){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...i(J)})}function B7(Y,J){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...i(J)})}function F7(Y,J){return new Y({type:"string",format:"cidrv6",check:"string_format",abort:!1,...i(J)})}function j7(Y,J){return new Y({type:"string",format:"base64",check:"string_format",abort:!1,...i(J)})}function O7(Y,J){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...i(J)})}function q7(Y,J){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...i(J)})}function D7(Y,J){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...i(J)})}function P7(Y,J){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...i(J)})}function E7(Y,J){return new Y({type:"string",format:"date",check:"string_format",...i(J)})}function M7(Y,J){return new Y({type:"string",format:"time",check:"string_format",precision:null,...i(J)})}function w7(Y,J){return new Y({type:"string",format:"duration",check:"string_format",...i(J)})}function A7(Y,J){return new Y({type:"number",checks:[],...i(J)})}function R7(Y,J){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...i(J)})}function T7(Y,J){return new Y({type:"boolean",...i(J)})}function C7(Y,J){return new Y({type:"null",...i(J)})}function _7(Y){return new Y({type:"unknown"})}function I7(Y,J){return new Y({type:"never",...i(J)})}function dY(Y,J){return new WX({check:"less_than",...i(J),value:Y,inclusive:!1})}function l9(Y,J){return new WX({check:"less_than",...i(J),value:Y,inclusive:!0})}function iY(Y,J){return new zX({check:"greater_than",...i(J),value:Y,inclusive:!1})}function d9(Y,J){return new zX({check:"greater_than",...i(J),value:Y,inclusive:!0})}function oY(Y,J){return new hG({check:"multiple_of",...i(J),value:Y})}function nY(Y,J){return new yG({check:"max_length",...i(J),maximum:Y})}function L9(Y,J){return new fG({check:"min_length",...i(J),minimum:Y})}function rY(Y,J){return new mG({check:"length_equals",...i(J),length:Y})}function VX(Y,J){return new cG({check:"string_format",format:"regex",...i(J),pattern:Y})}function NX(Y){return new uG({check:"string_format",format:"lowercase",...i(Y)})}function BX(Y){return new pG({check:"string_format",format:"uppercase",...i(Y)})}function FX(Y,J){return new lG({check:"string_format",format:"includes",...i(J),includes:Y})}function jX(Y,J){return new dG({check:"string_format",format:"starts_with",...i(J),prefix:Y})}function OX(Y,J){return new iG({check:"string_format",format:"ends_with",...i(J),suffix:Y})}function i1(Y){return new oG({check:"overwrite",tx:Y})}function qX(Y){return i1((J)=>J.normalize(Y))}function DX(){return i1((Y)=>Y.trim())}function PX(){return i1((Y)=>Y.toLowerCase())}function EX(){return i1((Y)=>Y.toUpperCase())}function S7(Y,J,X){return new Y({type:"array",element:J,...i(X)})}function k7(Y,J,X){let Q=i(X);return Q.abort??(Q.abort=!0),new Y({type:"custom",check:"custom",fn:J,...Q})}function x7(Y,J,X){return new Y({type:"custom",check:"custom",fn:J,...i(X)})}function b7(Y){let J=VH((X)=>{return X.addIssue=(Q)=>{if(typeof Q==="string")X.issues.push(Z9(Q,X.value,J._zod.def));else{let $=Q;if($.fatal)$.continue=!1;$.code??($.code="custom"),$.input??($.input=X.value),$.inst??($.inst=J),$.continue??($.continue=!J._zod.def.abort),X.issues.push(Z9($))}},Y(X.value,X)});return J}function VH(Y,J){let X=new w0({check:"custom",...i(J)});return X._zod.check=Y,X}class MX{constructor(Y){this.counter=0,this.metadataRegistry=Y?.metadata??d1,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,$={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},G=this.seen.get(Y);if(G){if(G.count++,J.schemaPath.includes(Y))G.cycle=J.path;return G.schema}let 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 L={...J,schemaPath:[...J.schemaPath,Y],path:J.path},j=Y._zod.parent;if(j)W.ref=j,this.process(j,L),this.seen.get(j).isParent=!0;else{let N=W.schema;switch(Q.type){case"string":{let V=N;V.type="string";let{minimum:q,maximum:T,format:S,patterns:c,contentEncoding:_}=Y._zod.bag;if(typeof q==="number")V.minLength=q;if(typeof T==="number")V.maxLength=T;if(S){if(V.format=$[S]??S,V.format==="")delete V.format}if(_)V.contentEncoding=_;if(c&&c.size>0){let E=[...c];if(E.length===1)V.pattern=E[0].source;else if(E.length>1)W.schema.allOf=[...E.map((b)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:b.source}))]}break}case"number":{let V=N,{minimum:q,maximum:T,format:S,multipleOf:c,exclusiveMaximum:_,exclusiveMinimum:E}=Y._zod.bag;if(typeof S==="string"&&S.includes("int"))V.type="integer";else V.type="number";if(typeof E==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")V.minimum=E,V.exclusiveMinimum=!0;else V.exclusiveMinimum=E;if(typeof q==="number"){if(V.minimum=q,typeof E==="number"&&this.target!=="draft-4")if(E>=q)delete V.minimum;else delete V.exclusiveMinimum}if(typeof _==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")V.maximum=_,V.exclusiveMaximum=!0;else V.exclusiveMaximum=_;if(typeof T==="number"){if(V.maximum=T,typeof _==="number"&&this.target!=="draft-4")if(_<=T)delete V.maximum;else delete V.exclusiveMaximum}if(typeof c==="number")V.multipleOf=c;break}case"boolean":{let V=N;V.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema");break}case"null":{if(this.target==="openapi-3.0")N.type="string",N.nullable=!0,N.enum=[null];else N.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema");break}case"never":{N.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let V=N,{minimum:q,maximum:T}=Y._zod.bag;if(typeof q==="number")V.minItems=q;if(typeof T==="number")V.maxItems=T;V.type="array",V.items=this.process(Q.element,{...L,path:[...L.path,"items"]});break}case"object":{let V=N;V.type="object",V.properties={};let q=Q.shape;for(let c in q)V.properties[c]=this.process(q[c],{...L,path:[...L.path,"properties",c]});let T=new Set(Object.keys(q)),S=new Set([...T].filter((c)=>{let _=Q.shape[c]._zod;if(this.io==="input")return _.optin===void 0;else return _.optout===void 0}));if(S.size>0)V.required=Array.from(S);if(Q.catchall?._zod.def.type==="never")V.additionalProperties=!1;else if(!Q.catchall){if(this.io==="output")V.additionalProperties=!1}else if(Q.catchall)V.additionalProperties=this.process(Q.catchall,{...L,path:[...L.path,"additionalProperties"]});break}case"union":{let V=N,q=Q.options.map((T,S)=>this.process(T,{...L,path:[...L.path,"anyOf",S]}));V.anyOf=q;break}case"intersection":{let V=N,q=this.process(Q.left,{...L,path:[...L.path,"allOf",0]}),T=this.process(Q.right,{...L,path:[...L.path,"allOf",1]}),S=(_)=>("allOf"in _)&&Object.keys(_).length===1,c=[...S(q)?q.allOf:[q],...S(T)?T.allOf:[T]];V.allOf=c;break}case"tuple":{let V=N;V.type="array";let q=this.target==="draft-2020-12"?"prefixItems":"items",T=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",S=Q.items.map((b,f)=>this.process(b,{...L,path:[...L.path,q,f]})),c=Q.rest?this.process(Q.rest,{...L,path:[...L.path,T,...this.target==="openapi-3.0"?[Q.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(V.prefixItems=S,c)V.items=c}else if(this.target==="openapi-3.0"){if(V.items={anyOf:S},c)V.items.anyOf.push(c);if(V.minItems=S.length,!c)V.maxItems=S.length}else if(V.items=S,c)V.additionalItems=c;let{minimum:_,maximum:E}=Y._zod.bag;if(typeof _==="number")V.minItems=_;if(typeof E==="number")V.maxItems=E;break}case"record":{let V=N;if(V.type="object",this.target==="draft-7"||this.target==="draft-2020-12")V.propertyNames=this.process(Q.keyType,{...L,path:[...L.path,"propertyNames"]});V.additionalProperties=this.process(Q.valueType,{...L,path:[...L.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let V=N,q=g9(Q.entries);if(q.every((T)=>typeof T==="number"))V.type="number";if(q.every((T)=>typeof T==="string"))V.type="string";V.enum=q;break}case"literal":{let V=N,q=[];for(let T of Q.values)if(T===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof T==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else q.push(Number(T));else q.push(T);if(q.length===0);else if(q.length===1){let T=q[0];if(V.type=T===null?"null":typeof T,this.target==="draft-4"||this.target==="openapi-3.0")V.enum=[T];else V.const=T}else{if(q.every((T)=>typeof T==="number"))V.type="number";if(q.every((T)=>typeof T==="string"))V.type="string";if(q.every((T)=>typeof T==="boolean"))V.type="string";if(q.every((T)=>T===null))V.type="null";V.enum=q}break}case"file":{let V=N,q={type:"string",format:"binary",contentEncoding:"binary"},{minimum:T,maximum:S,mime:c}=Y._zod.bag;if(T!==void 0)q.minLength=T;if(S!==void 0)q.maxLength=S;if(c)if(c.length===1)q.contentMediaType=c[0],Object.assign(V,q);else V.anyOf=c.map((_)=>{return{...q,contentMediaType:_}});else Object.assign(V,q);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let V=this.process(Q.innerType,L);if(this.target==="openapi-3.0")W.ref=Q.innerType,N.nullable=!0;else N.anyOf=[V,{type:"null"}];break}case"nonoptional":{this.process(Q.innerType,L),W.ref=Q.innerType;break}case"success":{let V=N;V.type="boolean";break}case"default":{this.process(Q.innerType,L),W.ref=Q.innerType,N.default=JSON.parse(JSON.stringify(Q.defaultValue));break}case"prefault":{if(this.process(Q.innerType,L),W.ref=Q.innerType,this.io==="input")N._prefault=JSON.parse(JSON.stringify(Q.defaultValue));break}case"catch":{this.process(Q.innerType,L),W.ref=Q.innerType;let V;try{V=Q.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}N.default=V;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let V=N,q=Y._zod.pattern;if(!q)throw Error("Pattern not found in template literal");V.type="string",V.pattern=q.source;break}case"pipe":{let V=this.io==="input"?Q.in._zod.def.type==="transform"?Q.out:Q.in:Q.out;this.process(V,L),W.ref=V;break}case"readonly":{this.process(Q.innerType,L),W.ref=Q.innerType,N.readOnly=!0;break}case"promise":{this.process(Q.innerType,L),W.ref=Q.innerType;break}case"optional":{this.process(Q.innerType,L),W.ref=Q.innerType;break}case"lazy":{let V=Y._zod.innerType;this.process(V,L),W.ref=V;break}case"custom":{if(this.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema");break}case"function":{if(this.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema");break}default:}}}let Z=this.metadataRegistry.get(Y);if(Z)Object.assign(W.schema,Z);if(this.io==="input"&&D0(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 $=(U)=>{let L=this.target==="draft-2020-12"?"$defs":"definitions";if(X.external){let q=X.external.registry.get(U[0])?.id,T=X.external.uri??((c)=>c);if(q)return{ref:T(q)};let S=U[1].defId??U[1].schema.id??`schema${this.counter++}`;return U[1].defId=S,{defId:S,ref:`${T("__shared")}#/${L}/${S}`}}if(U[1]===Q)return{ref:"#"};let N=`${"#"}/${L}/`,V=U[1].schema.id??`__schema${this.counter++}`;return{defId:V,ref:N+V}},G=(U)=>{if(U[1].schema.$ref)return;let L=U[1],{ref:j,defId:N}=$(U);if(L.def={...L.schema},N)L.defId=N;let V=L.schema;for(let q in V)delete V[q];V.$ref=j};if(X.cycles==="throw")for(let U of this.seen.entries()){let L=U[1];if(L.cycle)throw Error(`Cycle detected: #/${L.cycle?.join("/")}/<root>
|
|
75
|
+
`)}V.write("payload.value = newResult;"),V.write("return payload;");let C=V.compile();return(E,S)=>C(N,E,S)},G,W=i1,K=!xY.jitless,U=K&&rX.value,Z=X.catchall,F;Y._zod.parse=(N,V)=>{F??(F=Q.value);let q=N.value;if(!W(q))return N.issues.push({expected:"object",code:"invalid_type",input:q,inst:Y}),N;if(K&&U&&V?.async===!1&&V.jitless!==!0){if(!G)G=$(X.shape);if(N=G(N,V),!Z)return N;return A2([],q,N,V,F,Y)}return J(N,V)}});function cG(Y,X,J,Q){for(let G of Y)if(G.issues.length===0)return X.value=G.value,X;let $=Y.filter((G)=>!I1(G));if($.length===1)return X.value=$[0].value,$[0];return X.issues.push({code:"invalid_union",input:X.value,inst:J,errors:Y.map((G)=>G.issues.map((W)=>X1(W,Q,K1())))}),X}var zJ=D("$ZodUnion",(Y,X)=>{U0.init(Y,X),X0(Y._zod,"optin",()=>X.options.some(($)=>$._zod.optin==="optional")?"optional":void 0),X0(Y._zod,"optout",()=>X.options.some(($)=>$._zod.optout==="optional")?"optional":void 0),X0(Y._zod,"values",()=>{if(X.options.every(($)=>$._zod.values))return new Set(X.options.flatMap(($)=>Array.from($._zod.values)));return}),X0(Y._zod,"pattern",()=>{if(X.options.every(($)=>$._zod.pattern)){let $=X.options.map((G)=>G._zod.pattern);return new RegExp(`^(${$.map((G)=>f9(G.source)).join("|")})$`)}return});let J=X.options.length===1,Q=X.options[0]._zod.run;Y._zod.parse=($,G)=>{if(J)return Q($,G);let W=!1,K=[];for(let H of X.options){let U=H._zod.run({value:$.value,issues:[]},G);if(U instanceof Promise)K.push(U),W=!0;else{if(U.issues.length===0)return U;K.push(U)}}if(!W)return cG(K,$,Y,G);return Promise.all(K).then((H)=>{return cG(H,$,Y,G)})}}),T2=D("$ZodDiscriminatedUnion",(Y,X)=>{zJ.init(Y,X);let J=Y._zod.parse;X0(Y._zod,"propValues",()=>{let $={};for(let G of X.options){let W=G._zod.propValues;if(!W||Object.keys(W).length===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf(G)}"`);for(let[K,H]of Object.entries(W)){if(!$[K])$[K]=new Set;for(let U of H)$[K].add(U)}}return $});let Q=H9(()=>{let $=X.options,G=new Map;for(let W of $){let K=W._zod.propValues?.[X.discriminator];if(!K||K.size===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf(W)}"`);for(let H of K){if(G.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);G.set(H,W)}}return G});Y._zod.parse=($,G)=>{let W=$.value;if(!i1(W))return $.issues.push({code:"invalid_type",expected:"object",input:W,inst:Y}),$;let K=Q.value.get(W?.[X.discriminator]);if(K)return K._zod.run($,G);if(X.unionFallback)return J($,G);return $.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:X.discriminator,input:W,path:[X.discriminator],inst:Y}),$}}),C2=D("$ZodIntersection",(Y,X)=>{U0.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value,G=X.left._zod.run({value:$,issues:[]},Q),W=X.right._zod.run({value:$,issues:[]},Q);if(G instanceof Promise||W instanceof Promise)return Promise.all([G,W]).then(([H,U])=>{return uG(J,H,U)});return uG(J,G,W)}});function GJ(Y,X){if(Y===X)return{valid:!0,data:Y};if(Y instanceof Date&&X instanceof Date&&+Y===+X)return{valid:!0,data:Y};if(_1(Y)&&_1(X)){let J=Object.keys(X),Q=Object.keys(Y).filter((G)=>J.indexOf(G)!==-1),$={...Y,...X};for(let G of Q){let W=GJ(Y[G],X[G]);if(!W.valid)return{valid:!1,mergeErrorPath:[G,...W.mergeErrorPath]};$[G]=W.data}return{valid:!0,data:$}}if(Array.isArray(Y)&&Array.isArray(X)){if(Y.length!==X.length)return{valid:!1,mergeErrorPath:[]};let J=[];for(let Q=0;Q<Y.length;Q++){let $=Y[Q],G=X[Q],W=GJ($,G);if(!W.valid)return{valid:!1,mergeErrorPath:[Q,...W.mergeErrorPath]};J.push(W.data)}return{valid:!0,data:J}}return{valid:!1,mergeErrorPath:[]}}function uG(Y,X,J){if(X.issues.length)Y.issues.push(...X.issues);if(J.issues.length)Y.issues.push(...J.issues);if(I1(Y))return Y;let Q=GJ(X.value,J.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return Y.value=Q.data,Y}var _2=D("$ZodRecord",(Y,X)=>{U0.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value;if(!_1($))return J.issues.push({expected:"record",code:"invalid_type",input:$,inst:Y}),J;let G=[];if(X.keyType._zod.values){let W=X.keyType._zod.values;J.value={};for(let H of W)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let U=X.valueType._zod.run({value:$[H],issues:[]},Q);if(U instanceof Promise)G.push(U.then((Z)=>{if(Z.issues.length)J.issues.push(...O1(H,Z.issues));J.value[H]=Z.value}));else{if(U.issues.length)J.issues.push(...O1(H,U.issues));J.value[H]=U.value}}let K;for(let H in $)if(!W.has(H))K=K??[],K.push(H);if(K&&K.length>0)J.issues.push({code:"unrecognized_keys",input:$,inst:Y,keys:K})}else{J.value={};for(let W of Reflect.ownKeys($)){if(W==="__proto__")continue;let K=X.keyType._zod.run({value:W,issues:[]},Q);if(K instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(K.issues.length){J.issues.push({code:"invalid_key",origin:"record",issues:K.issues.map((U)=>X1(U,Q,K1())),input:W,path:[W],inst:Y}),J.value[K.value]=K.value;continue}let H=X.valueType._zod.run({value:$[W],issues:[]},Q);if(H instanceof Promise)G.push(H.then((U)=>{if(U.issues.length)J.issues.push(...O1(W,U.issues));J.value[K.value]=U.value}));else{if(H.issues.length)J.issues.push(...O1(W,H.issues));J.value[K.value]=H.value}}}if(G.length)return Promise.all(G).then(()=>J);return J}});var I2=D("$ZodEnum",(Y,X)=>{U0.init(Y,X);let J=g9(X.entries),Q=new Set(J);Y._zod.values=Q,Y._zod.pattern=new RegExp(`^(${J.filter(($)=>sX.has(typeof $)).map(($)=>typeof $==="string"?F1($):$.toString()).join("|")})$`),Y._zod.parse=($,G)=>{let W=$.value;if(Q.has(W))return $;return $.issues.push({code:"invalid_value",values:J,input:W,inst:Y}),$}}),S2=D("$ZodLiteral",(Y,X)=>{if(U0.init(Y,X),X.values.length===0)throw Error("Cannot create literal schema with no valid values");Y._zod.values=new Set(X.values),Y._zod.pattern=new RegExp(`^(${X.values.map((J)=>typeof J==="string"?F1(J):J?F1(J.toString()):String(J)).join("|")})$`),Y._zod.parse=(J,Q)=>{let $=J.value;if(Y._zod.values.has($))return J;return J.issues.push({code:"invalid_value",values:X.values,input:$,inst:Y}),J}});var k2=D("$ZodTransform",(Y,X)=>{U0.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new v9(Y.constructor.name);let $=X.transform(J.value,J);if(Q.async)return($ instanceof Promise?$:Promise.resolve($)).then((W)=>{return J.value=W,J});if($ instanceof Promise)throw new B1;return J.value=$,J}});function pG(Y,X){if(Y.issues.length&&X===void 0)return{issues:[],value:void 0};return Y}var x2=D("$ZodOptional",(Y,X)=>{U0.init(Y,X),Y._zod.optin="optional",Y._zod.optout="optional",X0(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,void 0]):void 0}),X0(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${f9(J.source)})?$`):void 0}),Y._zod.parse=(J,Q)=>{if(X.innerType._zod.optin==="optional"){let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>pG(G,J.value));return pG($,J.value)}if(J.value===void 0)return J;return X.innerType._zod.run(J,Q)}}),b2=D("$ZodNullable",(Y,X)=>{U0.init(Y,X),X0(Y._zod,"optin",()=>X.innerType._zod.optin),X0(Y._zod,"optout",()=>X.innerType._zod.optout),X0(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${f9(J.source)}|null)$`):void 0}),X0(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,null]):void 0}),Y._zod.parse=(J,Q)=>{if(J.value===null)return J;return X.innerType._zod.run(J,Q)}}),v2=D("$ZodDefault",(Y,X)=>{U0.init(Y,X),Y._zod.optin="optional",X0(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);if(J.value===void 0)return J.value=X.defaultValue,J;let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>lG(G,X));return lG($,X)}});function lG(Y,X){if(Y.value===void 0)Y.value=X.defaultValue;return Y}var h2=D("$ZodPrefault",(Y,X)=>{U0.init(Y,X),Y._zod.optin="optional",X0(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);if(J.value===void 0)J.value=X.defaultValue;return X.innerType._zod.run(J,Q)}}),g2=D("$ZodNonOptional",(Y,X)=>{U0.init(Y,X),X0(Y._zod,"values",()=>{let J=X.innerType._zod.values;return J?new Set([...J].filter((Q)=>Q!==void 0)):void 0}),Y._zod.parse=(J,Q)=>{let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>dG(G,Y));return dG($,Y)}});function dG(Y,X){if(!Y.issues.length&&Y.value===void 0)Y.issues.push({code:"invalid_type",expected:"nonoptional",input:Y.value,inst:X});return Y}var y2=D("$ZodCatch",(Y,X)=>{U0.init(Y,X),X0(Y._zod,"optin",()=>X.innerType._zod.optin),X0(Y._zod,"optout",()=>X.innerType._zod.optout),X0(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>{if(J.value=G.value,G.issues.length)J.value=X.catchValue({...J,error:{issues:G.issues.map((W)=>X1(W,Q,K1()))},input:J.value}),J.issues=[];return J});if(J.value=$.value,$.issues.length)J.value=X.catchValue({...J,error:{issues:$.issues.map((G)=>X1(G,Q,K1()))},input:J.value}),J.issues=[];return J}});var f2=D("$ZodPipe",(Y,X)=>{U0.init(Y,X),X0(Y._zod,"values",()=>X.in._zod.values),X0(Y._zod,"optin",()=>X.in._zod.optin),X0(Y._zod,"optout",()=>X.out._zod.optout),X0(Y._zod,"propValues",()=>X.in._zod.propValues),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward"){let G=X.out._zod.run(J,Q);if(G instanceof Promise)return G.then((W)=>mY(W,X.in,Q));return mY(G,X.in,Q)}let $=X.in._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>mY(G,X.out,Q));return mY($,X.out,Q)}});function mY(Y,X,J){if(Y.issues.length)return Y.aborted=!0,Y;return X._zod.run({value:Y.value,issues:Y.issues},J)}var m2=D("$ZodReadonly",(Y,X)=>{U0.init(Y,X),X0(Y._zod,"propValues",()=>X.innerType._zod.propValues),X0(Y._zod,"values",()=>X.innerType._zod.values),X0(Y._zod,"optin",()=>X.innerType._zod.optin),X0(Y._zod,"optout",()=>X.innerType._zod.optout),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then(iG);return iG($)}});function iG(Y){return Y.value=Object.freeze(Y.value),Y}var c2=D("$ZodLazy",(Y,X)=>{U0.init(Y,X),X0(Y._zod,"innerType",()=>X.getter()),X0(Y._zod,"pattern",()=>Y._zod.innerType._zod.pattern),X0(Y._zod,"propValues",()=>Y._zod.innerType._zod.propValues),X0(Y._zod,"optin",()=>Y._zod.innerType._zod.optin??void 0),X0(Y._zod,"optout",()=>Y._zod.innerType._zod.optout??void 0),Y._zod.parse=(J,Q)=>{return Y._zod.innerType._zod.run(J,Q)}}),u2=D("$ZodCustom",(Y,X)=>{T0.init(Y,X),U0.init(Y,X),Y._zod.parse=(J,Q)=>{return J},Y._zod.check=(J)=>{let Q=J.value,$=X.fn(Q);if($ instanceof Promise)return $.then((G)=>nG(G,J,Q,Y));nG($,J,Q,Y);return}});function nG(Y,X,J,Q){if(!Y){let $={code:"custom",input:J,inst:Q,path:[...Q._zod.def.path??[]],continue:!Q._zod.def.abort};if(Q._zod.def.params)$.params=Q._zod.def.params;X.issues.push(Z9($))}}var qq=Symbol("ZodOutput"),Dq=Symbol("ZodInput");class pY{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Y,...X){let J=X[0];if(this._map.set(Y,J),J&&typeof J==="object"&&"id"in J){if(this._idmap.has(J.id))throw Error(`ID ${J.id} already exists in the registry`);this._idmap.set(J.id,Y)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Y){let X=this._map.get(Y);if(X&&typeof X==="object"&&"id"in X)this._idmap.delete(X.id);return this._map.delete(Y),this}get(Y){let X=Y._zod.parent;if(X){let J={...this.get(X)??{}};delete J.id;let Q={...J,...this._map.get(Y)};return Object.keys(Q).length?Q:void 0}return this._map.get(Y)}has(Y){return this._map.has(Y)}}function oZ(){return new pY}var n1=oZ();function p2(Y,X){return new Y({type:"string",...n(X)})}function l2(Y,X){return new Y({type:"string",format:"email",check:"string_format",abort:!1,...n(X)})}function KJ(Y,X){return new Y({type:"string",format:"guid",check:"string_format",abort:!1,...n(X)})}function d2(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...n(X)})}function i2(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...n(X)})}function n2(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...n(X)})}function o2(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...n(X)})}function r2(Y,X){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...n(X)})}function s2(Y,X){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...n(X)})}function a2(Y,X){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...n(X)})}function t2(Y,X){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...n(X)})}function e2(Y,X){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...n(X)})}function Y7(Y,X){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...n(X)})}function X7(Y,X){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...n(X)})}function J7(Y,X){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...n(X)})}function Q7(Y,X){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...n(X)})}function $7(Y,X){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...n(X)})}function G7(Y,X){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...n(X)})}function W7(Y,X){return new Y({type:"string",format:"cidrv6",check:"string_format",abort:!1,...n(X)})}function z7(Y,X){return new Y({type:"string",format:"base64",check:"string_format",abort:!1,...n(X)})}function K7(Y,X){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...n(X)})}function U7(Y,X){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...n(X)})}function H7(Y,X){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...n(X)})}function Z7(Y,X){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...n(X)})}function L7(Y,X){return new Y({type:"string",format:"date",check:"string_format",...n(X)})}function V7(Y,X){return new Y({type:"string",format:"time",check:"string_format",precision:null,...n(X)})}function N7(Y,X){return new Y({type:"string",format:"duration",check:"string_format",...n(X)})}function B7(Y,X){return new Y({type:"number",checks:[],...n(X)})}function F7(Y,X){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...n(X)})}function O7(Y,X){return new Y({type:"boolean",...n(X)})}function j7(Y,X){return new Y({type:"null",...n(X)})}function q7(Y){return new Y({type:"unknown"})}function D7(Y,X){return new Y({type:"never",...n(X)})}function lY(Y,X){return new JJ({check:"less_than",...n(X),value:Y,inclusive:!1})}function l9(Y,X){return new JJ({check:"less_than",...n(X),value:Y,inclusive:!0})}function dY(Y,X){return new QJ({check:"greater_than",...n(X),value:Y,inclusive:!1})}function d9(Y,X){return new QJ({check:"greater_than",...n(X),value:Y,inclusive:!0})}function iY(Y,X){return new RG({check:"multiple_of",...n(X),value:Y})}function nY(Y,X){return new CG({check:"max_length",...n(X),maximum:Y})}function L9(Y,X){return new _G({check:"min_length",...n(X),minimum:Y})}function oY(Y,X){return new IG({check:"length_equals",...n(X),length:Y})}function UJ(Y,X){return new SG({check:"string_format",format:"regex",...n(X),pattern:Y})}function HJ(Y){return new kG({check:"string_format",format:"lowercase",...n(Y)})}function ZJ(Y){return new xG({check:"string_format",format:"uppercase",...n(Y)})}function LJ(Y,X){return new bG({check:"string_format",format:"includes",...n(X),includes:Y})}function VJ(Y,X){return new vG({check:"string_format",format:"starts_with",...n(X),prefix:Y})}function NJ(Y,X){return new hG({check:"string_format",format:"ends_with",...n(X),suffix:Y})}function o1(Y){return new gG({check:"overwrite",tx:Y})}function BJ(Y){return o1((X)=>X.normalize(Y))}function FJ(){return o1((Y)=>Y.trim())}function OJ(){return o1((Y)=>Y.toLowerCase())}function jJ(){return o1((Y)=>Y.toUpperCase())}function P7(Y,X,J){return new Y({type:"array",element:X,...n(J)})}function E7(Y,X,J){let Q=n(J);return Q.abort??(Q.abort=!0),new Y({type:"custom",check:"custom",fn:X,...Q})}function M7(Y,X,J){return new Y({type:"custom",check:"custom",fn:X,...n(J)})}function w7(Y){let X=rZ((J)=>{return J.addIssue=(Q)=>{if(typeof Q==="string")J.issues.push(Z9(Q,J.value,X._zod.def));else{let $=Q;if($.fatal)$.continue=!1;$.code??($.code="custom"),$.input??($.input=J.value),$.inst??($.inst=X),$.continue??($.continue=!X._zod.def.abort),J.issues.push(Z9($))}},Y(J.value,J)});return X}function rZ(Y,X){let J=new T0({check:"custom",...n(X)});return J._zod.check=Y,J}class qJ{constructor(Y){this.counter=0,this.metadataRegistry=Y?.metadata??n1,this.target=Y?.target??"draft-2020-12",this.unrepresentable=Y?.unrepresentable??"throw",this.override=Y?.override??(()=>{}),this.io=Y?.io??"output",this.seen=new Map}process(Y,X={path:[],schemaPath:[]}){var J;let Q=Y._zod.def,$={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},G=this.seen.get(Y);if(G){if(G.count++,X.schemaPath.includes(Y))G.cycle=X.path;return G.schema}let W={schema:{},count:1,cycle:void 0,path:X.path};this.seen.set(Y,W);let K=Y._zod.toJSONSchema?.();if(K)W.schema=K;else{let Z={...X,schemaPath:[...X.schemaPath,Y],path:X.path},F=Y._zod.parent;if(F)W.ref=F,this.process(F,Z),this.seen.get(F).isParent=!0;else{let N=W.schema;switch(Q.type){case"string":{let V=N;V.type="string";let{minimum:q,maximum:R,format:k,patterns:u,contentEncoding:C}=Y._zod.bag;if(typeof q==="number")V.minLength=q;if(typeof R==="number")V.maxLength=R;if(k){if(V.format=$[k]??k,V.format==="")delete V.format}if(C)V.contentEncoding=C;if(u&&u.size>0){let E=[...u];if(E.length===1)V.pattern=E[0].source;else if(E.length>1)W.schema.allOf=[...E.map((S)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:S.source}))]}break}case"number":{let V=N,{minimum:q,maximum:R,format:k,multipleOf:u,exclusiveMaximum:C,exclusiveMinimum:E}=Y._zod.bag;if(typeof k==="string"&&k.includes("int"))V.type="integer";else V.type="number";if(typeof E==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")V.minimum=E,V.exclusiveMinimum=!0;else V.exclusiveMinimum=E;if(typeof q==="number"){if(V.minimum=q,typeof E==="number"&&this.target!=="draft-4")if(E>=q)delete V.minimum;else delete V.exclusiveMinimum}if(typeof C==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")V.maximum=C,V.exclusiveMaximum=!0;else V.exclusiveMaximum=C;if(typeof R==="number"){if(V.maximum=R,typeof C==="number"&&this.target!=="draft-4")if(C<=R)delete V.maximum;else delete V.exclusiveMaximum}if(typeof u==="number")V.multipleOf=u;break}case"boolean":{let V=N;V.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema");break}case"null":{if(this.target==="openapi-3.0")N.type="string",N.nullable=!0,N.enum=[null];else N.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema");break}case"never":{N.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let V=N,{minimum:q,maximum:R}=Y._zod.bag;if(typeof q==="number")V.minItems=q;if(typeof R==="number")V.maxItems=R;V.type="array",V.items=this.process(Q.element,{...Z,path:[...Z.path,"items"]});break}case"object":{let V=N;V.type="object",V.properties={};let q=Q.shape;for(let u in q)V.properties[u]=this.process(q[u],{...Z,path:[...Z.path,"properties",u]});let R=new Set(Object.keys(q)),k=new Set([...R].filter((u)=>{let C=Q.shape[u]._zod;if(this.io==="input")return C.optin===void 0;else return C.optout===void 0}));if(k.size>0)V.required=Array.from(k);if(Q.catchall?._zod.def.type==="never")V.additionalProperties=!1;else if(!Q.catchall){if(this.io==="output")V.additionalProperties=!1}else if(Q.catchall)V.additionalProperties=this.process(Q.catchall,{...Z,path:[...Z.path,"additionalProperties"]});break}case"union":{let V=N,q=Q.options.map((R,k)=>this.process(R,{...Z,path:[...Z.path,"anyOf",k]}));V.anyOf=q;break}case"intersection":{let V=N,q=this.process(Q.left,{...Z,path:[...Z.path,"allOf",0]}),R=this.process(Q.right,{...Z,path:[...Z.path,"allOf",1]}),k=(C)=>("allOf"in C)&&Object.keys(C).length===1,u=[...k(q)?q.allOf:[q],...k(R)?R.allOf:[R]];V.allOf=u;break}case"tuple":{let V=N;V.type="array";let q=this.target==="draft-2020-12"?"prefixItems":"items",R=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",k=Q.items.map((S,c)=>this.process(S,{...Z,path:[...Z.path,q,c]})),u=Q.rest?this.process(Q.rest,{...Z,path:[...Z.path,R,...this.target==="openapi-3.0"?[Q.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(V.prefixItems=k,u)V.items=u}else if(this.target==="openapi-3.0"){if(V.items={anyOf:k},u)V.items.anyOf.push(u);if(V.minItems=k.length,!u)V.maxItems=k.length}else if(V.items=k,u)V.additionalItems=u;let{minimum:C,maximum:E}=Y._zod.bag;if(typeof C==="number")V.minItems=C;if(typeof E==="number")V.maxItems=E;break}case"record":{let V=N;if(V.type="object",this.target==="draft-7"||this.target==="draft-2020-12")V.propertyNames=this.process(Q.keyType,{...Z,path:[...Z.path,"propertyNames"]});V.additionalProperties=this.process(Q.valueType,{...Z,path:[...Z.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let V=N,q=g9(Q.entries);if(q.every((R)=>typeof R==="number"))V.type="number";if(q.every((R)=>typeof R==="string"))V.type="string";V.enum=q;break}case"literal":{let V=N,q=[];for(let R of Q.values)if(R===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof R==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else q.push(Number(R));else q.push(R);if(q.length===0);else if(q.length===1){let R=q[0];if(V.type=R===null?"null":typeof R,this.target==="draft-4"||this.target==="openapi-3.0")V.enum=[R];else V.const=R}else{if(q.every((R)=>typeof R==="number"))V.type="number";if(q.every((R)=>typeof R==="string"))V.type="string";if(q.every((R)=>typeof R==="boolean"))V.type="string";if(q.every((R)=>R===null))V.type="null";V.enum=q}break}case"file":{let V=N,q={type:"string",format:"binary",contentEncoding:"binary"},{minimum:R,maximum:k,mime:u}=Y._zod.bag;if(R!==void 0)q.minLength=R;if(k!==void 0)q.maxLength=k;if(u)if(u.length===1)q.contentMediaType=u[0],Object.assign(V,q);else V.anyOf=u.map((C)=>{return{...q,contentMediaType:C}});else Object.assign(V,q);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let V=this.process(Q.innerType,Z);if(this.target==="openapi-3.0")W.ref=Q.innerType,N.nullable=!0;else N.anyOf=[V,{type:"null"}];break}case"nonoptional":{this.process(Q.innerType,Z),W.ref=Q.innerType;break}case"success":{let V=N;V.type="boolean";break}case"default":{this.process(Q.innerType,Z),W.ref=Q.innerType,N.default=JSON.parse(JSON.stringify(Q.defaultValue));break}case"prefault":{if(this.process(Q.innerType,Z),W.ref=Q.innerType,this.io==="input")N._prefault=JSON.parse(JSON.stringify(Q.defaultValue));break}case"catch":{this.process(Q.innerType,Z),W.ref=Q.innerType;let V;try{V=Q.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}N.default=V;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let V=N,q=Y._zod.pattern;if(!q)throw Error("Pattern not found in template literal");V.type="string",V.pattern=q.source;break}case"pipe":{let V=this.io==="input"?Q.in._zod.def.type==="transform"?Q.out:Q.in:Q.out;this.process(V,Z),W.ref=V;break}case"readonly":{this.process(Q.innerType,Z),W.ref=Q.innerType,N.readOnly=!0;break}case"promise":{this.process(Q.innerType,Z),W.ref=Q.innerType;break}case"optional":{this.process(Q.innerType,Z),W.ref=Q.innerType;break}case"lazy":{let V=Y._zod.innerType;this.process(V,Z),W.ref=V;break}case"custom":{if(this.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema");break}case"function":{if(this.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema");break}default:}}}let H=this.metadataRegistry.get(Y);if(H)Object.assign(W.schema,H);if(this.io==="input"&&M0(Y))delete W.schema.examples,delete W.schema.default;if(this.io==="input"&&W.schema._prefault)(J=W.schema).default??(J.default=W.schema._prefault);return delete W.schema._prefault,this.seen.get(Y).schema}emit(Y,X){let J={cycles:X?.cycles??"ref",reused:X?.reused??"inline",external:X?.external??void 0},Q=this.seen.get(Y);if(!Q)throw Error("Unprocessed schema. This is a bug in Zod.");let $=(U)=>{let Z=this.target==="draft-2020-12"?"$defs":"definitions";if(J.external){let q=J.external.registry.get(U[0])?.id,R=J.external.uri??((u)=>u);if(q)return{ref:R(q)};let k=U[1].defId??U[1].schema.id??`schema${this.counter++}`;return U[1].defId=k,{defId:k,ref:`${R("__shared")}#/${Z}/${k}`}}if(U[1]===Q)return{ref:"#"};let N=`${"#"}/${Z}/`,V=U[1].schema.id??`__schema${this.counter++}`;return{defId:V,ref:N+V}},G=(U)=>{if(U[1].schema.$ref)return;let Z=U[1],{ref:F,defId:N}=$(U);if(Z.def={...Z.schema},N)Z.defId=N;let V=Z.schema;for(let q in V)delete V[q];V.$ref=F};if(J.cycles==="throw")for(let U of this.seen.entries()){let Z=U[1];if(Z.cycle)throw Error(`Cycle detected: #/${Z.cycle?.join("/")}/<root>
|
|
91
76
|
|
|
92
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let U of this.seen.entries()){let L=U[1];if(Y===U[0]){G(U);continue}if(X.external){let N=X.external.registry.get(U[0])?.id;if(Y!==U[0]&&N){G(U);continue}}if(this.metadataRegistry.get(U[0])?.id){G(U);continue}if(L.cycle){G(U);continue}if(L.count>1){if(X.reused==="ref"){G(U);continue}}}let W=(U,L)=>{let j=this.seen.get(U),N=j.def??j.schema,V={...N};if(j.ref===null)return;let q=j.ref;if(j.ref=null,q){W(q,L);let T=this.seen.get(q).schema;if(T.$ref&&(L.target==="draft-7"||L.target==="draft-4"||L.target==="openapi-3.0"))N.allOf=N.allOf??[],N.allOf.push(T);else Object.assign(N,T),Object.assign(N,V)}if(!j.isParent)this.override({zodSchema:U,jsonSchema:N,path:j.path??[]})};for(let U of[...this.seen.entries()].reverse())W(U[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 U=X.external.registry.get(Y)?.id;if(!U)throw Error("Schema is missing an `id` property");K.$id=X.external.uri(U)}Object.assign(K,Q.def);let Z=X.external?.defs??{};for(let U of this.seen.entries()){let L=U[1];if(L.def&&L.defId)Z[L.defId]=L.def}if(X.external);else if(Object.keys(Z).length>0)if(this.target==="draft-2020-12")K.$defs=Z;else K.definitions=Z;try{return JSON.parse(JSON.stringify(K))}catch(U){throw Error("Error converting schema to JSON.")}}}function v7(Y,J){if(Y instanceof lY){let Q=new MX(J),$={};for(let K of Y._idmap.entries()){let[Z,U]=K;Q.process(U)}let G={},W={registry:Y,uri:J?.uri,defs:$};for(let K of Y._idmap.entries()){let[Z,U]=K;G[Z]=Q.emit(U,{...J,external:W})}if(Object.keys($).length>0){let K=Q.target==="draft-2020-12"?"$defs":"definitions";G.__shared={[K]:$}}return{schemas:G}}let X=new MX(J);return X.process(Y),X.emit(Y,J)}function D0(Y,J){let X=J??{seen:new Set};if(X.seen.has(Y))return!1;X.seen.add(Y);let $=Y._zod.def;switch($.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 D0($.element,X);case"object":{for(let G in $.shape)if(D0($.shape[G],X))return!0;return!1}case"union":{for(let G of $.options)if(D0(G,X))return!0;return!1}case"intersection":return D0($.left,X)||D0($.right,X);case"tuple":{for(let G of $.items)if(D0(G,X))return!0;if($.rest&&D0($.rest,X))return!0;return!1}case"record":return D0($.keyType,X)||D0($.valueType,X);case"map":return D0($.keyType,X)||D0($.valueType,X);case"set":return D0($.valueType,X);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return D0($.innerType,X);case"lazy":return D0($.getter(),X);case"default":return D0($.innerType,X);case"prefault":return D0($.innerType,X);case"custom":return!1;case"transform":return!0;case"pipe":return D0($.in,X)||D0($.out,X);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${$.type}`)}var qH=P("ZodISODateTime",(Y,J)=>{B2.init(Y,J),L0.init(Y,J)});function h7(Y){return P7(qH,Y)}var DH=P("ZodISODate",(Y,J)=>{F2.init(Y,J),L0.init(Y,J)});function g7(Y){return E7(DH,Y)}var PH=P("ZodISOTime",(Y,J)=>{j2.init(Y,J),L0.init(Y,J)});function y7(Y){return M7(PH,Y)}var EH=P("ZodISODuration",(Y,J)=>{O2.init(Y,J),L0.init(Y,J)});function f7(Y){return w7(EH,Y)}var m7=(Y,J)=>{gY.init(Y,J),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(X)=>r$(Y,X)},flatten:{value:(X)=>n$(Y,X)},addIssue:{value:(X)=>{Y.issues.push(X),Y.message=JSON.stringify(Y.issues,K9,2)}},addIssues:{value:(X)=>{Y.issues.push(...X),Y.message=JSON.stringify(Y.issues,K9,2)}},isEmpty:{get(){return Y.issues.length===0}}})},D6=P("ZodError",m7),d0=P("ZodError",m7,{Parent:Error});var c7=yY(d0),u7=fY(d0),p7=c9(d0),aY=u9(d0),l7=t$(d0),d7=e$(d0),i7=YG(d0),o7=JG(d0),n7=XG(d0),r7=QG(d0),s7=$G(d0),a7=GG(d0);var H0=P("ZodType",(Y,J)=>{return K0.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)=>a0(Y,X,Q),Y.brand=()=>Y,Y.register=(X,Q)=>{return X.add(Y,Q),Y},Y.parse=(X,Q)=>c7(Y,X,Q,{callee:Y.parse}),Y.safeParse=(X,Q)=>p7(Y,X,Q),Y.parseAsync=async(X,Q)=>u7(Y,X,Q,{callee:Y.parseAsync}),Y.safeParseAsync=async(X,Q)=>aY(Y,X,Q),Y.spa=Y.safeParseAsync,Y.encode=(X,Q)=>l7(Y,X,Q),Y.decode=(X,Q)=>d7(Y,X,Q),Y.encodeAsync=async(X,Q)=>i7(Y,X,Q),Y.decodeAsync=async(X,Q)=>o7(Y,X,Q),Y.safeEncode=(X,Q)=>n7(Y,X,Q),Y.safeDecode=(X,Q)=>r7(Y,X,Q),Y.safeEncodeAsync=async(X,Q)=>s7(Y,X,Q),Y.safeDecodeAsync=async(X,Q)=>a7(Y,X,Q),Y.refine=(X,Q)=>Y.check(BV(X,Q)),Y.superRefine=(X)=>Y.check(FV(X)),Y.overwrite=(X)=>Y.check(i1(X)),Y.optional=()=>YW(Y),Y.nullable=()=>JW(Y),Y.nullish=()=>YW(JW(Y)),Y.nonoptional=(X)=>KV(Y,X),Y.array=()=>RX(Y),Y.or=(X)=>TX([Y,X]),Y.and=(X)=>tH(Y,X),Y.transform=(X)=>XW(Y,XV(X)),Y.default=(X)=>GV(Y,X),Y.prefault=(X)=>zV(Y,X),Y.catch=(X)=>ZV(Y,X),Y.pipe=(X)=>XW(Y,X),Y.readonly=()=>VV(Y),Y.describe=(X)=>{let Q=Y.clone();return d1.add(Q,{description:X}),Q},Object.defineProperty(Y,"description",{get(){return d1.get(Y)?.description},configurable:!0}),Y.meta=(...X)=>{if(X.length===0)return d1.get(Y);let Q=Y.clone();return d1.add(Q,X[0]),Q},Y.isOptional=()=>Y.safeParse(void 0).success,Y.isNullable=()=>Y.safeParse(null).success,Y}),QW=P("_ZodString",(Y,J)=>{pY.init(Y,J),H0.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(VX(...Q)),Y.includes=(...Q)=>Y.check(FX(...Q)),Y.startsWith=(...Q)=>Y.check(jX(...Q)),Y.endsWith=(...Q)=>Y.check(OX(...Q)),Y.min=(...Q)=>Y.check(L9(...Q)),Y.max=(...Q)=>Y.check(nY(...Q)),Y.length=(...Q)=>Y.check(rY(...Q)),Y.nonempty=(...Q)=>Y.check(L9(1,...Q)),Y.lowercase=(Q)=>Y.check(NX(Q)),Y.uppercase=(Q)=>Y.check(BX(Q)),Y.trim=()=>Y.check(DX()),Y.normalize=(...Q)=>Y.check(qX(...Q)),Y.toLowerCase=()=>Y.check(PX()),Y.toUpperCase=()=>Y.check(EX())}),RH=P("ZodString",(Y,J)=>{pY.init(Y,J),QW.init(Y,J),Y.email=(X)=>Y.check(Y7(TH,X)),Y.url=(X)=>Y.check(G7(CH,X)),Y.jwt=(X)=>Y.check(D7(pH,X)),Y.emoji=(X)=>Y.check(W7(_H,X)),Y.guid=(X)=>Y.check(HX(t7,X)),Y.uuid=(X)=>Y.check(J7(tY,X)),Y.uuidv4=(X)=>Y.check(X7(tY,X)),Y.uuidv6=(X)=>Y.check(Q7(tY,X)),Y.uuidv7=(X)=>Y.check($7(tY,X)),Y.nanoid=(X)=>Y.check(z7(IH,X)),Y.guid=(X)=>Y.check(HX(t7,X)),Y.cuid=(X)=>Y.check(K7(SH,X)),Y.cuid2=(X)=>Y.check(U7(kH,X)),Y.ulid=(X)=>Y.check(Z7(xH,X)),Y.base64=(X)=>Y.check(j7(mH,X)),Y.base64url=(X)=>Y.check(O7(cH,X)),Y.xid=(X)=>Y.check(L7(bH,X)),Y.ksuid=(X)=>Y.check(H7(vH,X)),Y.ipv4=(X)=>Y.check(V7(hH,X)),Y.ipv6=(X)=>Y.check(N7(gH,X)),Y.cidrv4=(X)=>Y.check(B7(yH,X)),Y.cidrv6=(X)=>Y.check(F7(fH,X)),Y.e164=(X)=>Y.check(q7(uH,X)),Y.datetime=(X)=>Y.check(h7(X)),Y.date=(X)=>Y.check(g7(X)),Y.time=(X)=>Y.check(y7(X)),Y.duration=(X)=>Y.check(f7(X))});function $W(Y){return e2(RH,Y)}var L0=P("ZodStringFormat",(Y,J)=>{Z0.init(Y,J),QW.init(Y,J)}),TH=P("ZodEmail",(Y,J)=>{W2.init(Y,J),L0.init(Y,J)});var t7=P("ZodGUID",(Y,J)=>{$2.init(Y,J),L0.init(Y,J)});var tY=P("ZodUUID",(Y,J)=>{G2.init(Y,J),L0.init(Y,J)});var CH=P("ZodURL",(Y,J)=>{z2.init(Y,J),L0.init(Y,J)});var _H=P("ZodEmoji",(Y,J)=>{K2.init(Y,J),L0.init(Y,J)});var IH=P("ZodNanoID",(Y,J)=>{U2.init(Y,J),L0.init(Y,J)});var SH=P("ZodCUID",(Y,J)=>{Z2.init(Y,J),L0.init(Y,J)});var kH=P("ZodCUID2",(Y,J)=>{L2.init(Y,J),L0.init(Y,J)});var xH=P("ZodULID",(Y,J)=>{H2.init(Y,J),L0.init(Y,J)});var bH=P("ZodXID",(Y,J)=>{V2.init(Y,J),L0.init(Y,J)});var vH=P("ZodKSUID",(Y,J)=>{N2.init(Y,J),L0.init(Y,J)});var hH=P("ZodIPv4",(Y,J)=>{q2.init(Y,J),L0.init(Y,J)});var gH=P("ZodIPv6",(Y,J)=>{D2.init(Y,J),L0.init(Y,J)});var yH=P("ZodCIDRv4",(Y,J)=>{P2.init(Y,J),L0.init(Y,J)});var fH=P("ZodCIDRv6",(Y,J)=>{E2.init(Y,J),L0.init(Y,J)});var mH=P("ZodBase64",(Y,J)=>{w2.init(Y,J),L0.init(Y,J)});var cH=P("ZodBase64URL",(Y,J)=>{A2.init(Y,J),L0.init(Y,J)});var uH=P("ZodE164",(Y,J)=>{R2.init(Y,J),L0.init(Y,J)});var pH=P("ZodJWT",(Y,J)=>{T2.init(Y,J),L0.init(Y,J)});var GW=P("ZodNumber",(Y,J)=>{ZX.init(Y,J),H0.init(Y,J),Y.gt=(Q,$)=>Y.check(iY(Q,$)),Y.gte=(Q,$)=>Y.check(d9(Q,$)),Y.min=(Q,$)=>Y.check(d9(Q,$)),Y.lt=(Q,$)=>Y.check(dY(Q,$)),Y.lte=(Q,$)=>Y.check(l9(Q,$)),Y.max=(Q,$)=>Y.check(l9(Q,$)),Y.int=(Q)=>Y.check(e7(Q)),Y.safe=(Q)=>Y.check(e7(Q)),Y.positive=(Q)=>Y.check(iY(0,Q)),Y.nonnegative=(Q)=>Y.check(d9(0,Q)),Y.negative=(Q)=>Y.check(dY(0,Q)),Y.nonpositive=(Q)=>Y.check(l9(0,Q)),Y.multipleOf=(Q,$)=>Y.check(oY(Q,$)),Y.step=(Q,$)=>Y.check(oY(Q,$)),Y.finite=()=>Y;let X=Y._zod.bag;Y.minValue=Math.max(X.minimum??Number.NEGATIVE_INFINITY,X.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Y.maxValue=Math.min(X.maximum??Number.POSITIVE_INFINITY,X.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Y.isInt=(X.format??"").includes("int")||Number.isSafeInteger(X.multipleOf??0.5),Y.isFinite=!0,Y.format=X.format??null});function WW(Y){return A7(GW,Y)}var lH=P("ZodNumberFormat",(Y,J)=>{C2.init(Y,J),GW.init(Y,J)});function e7(Y){return R7(lH,Y)}var dH=P("ZodBoolean",(Y,J)=>{_2.init(Y,J),H0.init(Y,J)});function zW(Y){return T7(dH,Y)}var iH=P("ZodNull",(Y,J)=>{I2.init(Y,J),H0.init(Y,J)});function KW(Y){return C7(iH,Y)}var oH=P("ZodUnknown",(Y,J)=>{S2.init(Y,J),H0.init(Y,J)});function i9(){return _7(oH)}var nH=P("ZodNever",(Y,J)=>{k2.init(Y,J),H0.init(Y,J)});function AX(Y){return I7(nH,Y)}var rH=P("ZodArray",(Y,J)=>{x2.init(Y,J),H0.init(Y,J),Y.element=J.element,Y.min=(X,Q)=>Y.check(L9(X,Q)),Y.nonempty=(X)=>Y.check(L9(1,X)),Y.max=(X,Q)=>Y.check(nY(X,Q)),Y.length=(X,Q)=>Y.check(rY(X,Q)),Y.unwrap=()=>Y.element});function RX(Y,J){return S7(rH,Y,J)}var UW=P("ZodObject",(Y,J)=>{h2.init(Y,J),H0.init(Y,J),a.defineLazy(Y,"shape",()=>J.shape),Y.keyof=()=>CX(Object.keys(Y._zod.def.shape)),Y.catchall=(X)=>Y.clone({...Y._zod.def,catchall:X}),Y.passthrough=()=>Y.clone({...Y._zod.def,catchall:i9()}),Y.loose=()=>Y.clone({...Y._zod.def,catchall:i9()}),Y.strict=()=>Y.clone({...Y._zod.def,catchall:AX()}),Y.strip=()=>Y.clone({...Y._zod.def,catchall:void 0}),Y.extend=(X)=>{return a.extend(Y,X)},Y.safeExtend=(X)=>{return a.safeExtend(Y,X)},Y.merge=(X)=>a.merge(Y,X),Y.pick=(X)=>a.pick(Y,X),Y.omit=(X)=>a.omit(Y,X),Y.partial=(...X)=>a.partial(FW,Y,X[0]),Y.required=(...X)=>a.required(jW,Y,X[0])});function ZW(Y,J){let X={type:"object",get shape(){return a.assignProp(this,"shape",Y?a.objectClone(Y):{}),this.shape},...a.normalizeParams(J)};return new UW(X)}function LW(Y,J){return new UW({type:"object",get shape(){return a.assignProp(this,"shape",a.objectClone(Y)),this.shape},catchall:i9(),...a.normalizeParams(J)})}var HW=P("ZodUnion",(Y,J)=>{LX.init(Y,J),H0.init(Y,J),Y.options=J.options});function TX(Y,J){return new HW({type:"union",options:Y,...a.normalizeParams(J)})}var sH=P("ZodDiscriminatedUnion",(Y,J)=>{HW.init(Y,J),g2.init(Y,J)});function VW(Y,J,X){return new sH({type:"union",options:J,discriminator:Y,...a.normalizeParams(X)})}var aH=P("ZodIntersection",(Y,J)=>{y2.init(Y,J),H0.init(Y,J)});function tH(Y,J){return new aH({type:"intersection",left:Y,right:J})}var eH=P("ZodRecord",(Y,J)=>{f2.init(Y,J),H0.init(Y,J),Y.keyType=J.keyType,Y.valueType=J.valueType});function NW(Y,J,X){return new eH({type:"record",keyType:Y,valueType:J,...a.normalizeParams(X)})}var wX=P("ZodEnum",(Y,J)=>{m2.init(Y,J),H0.init(Y,J),Y.enum=J.entries,Y.options=Object.values(J.entries);let X=new Set(Object.keys(J.entries));Y.extract=(Q,$)=>{let G={};for(let W of Q)if(X.has(W))G[W]=J.entries[W];else throw Error(`Key ${W} not found in enum`);return new wX({...J,checks:[],...a.normalizeParams($),entries:G})},Y.exclude=(Q,$)=>{let G={...J.entries};for(let W of Q)if(X.has(W))delete G[W];else throw Error(`Key ${W} not found in enum`);return new wX({...J,checks:[],...a.normalizeParams($),entries:G})}});function CX(Y,J){let X=Array.isArray(Y)?Object.fromEntries(Y.map((Q)=>[Q,Q])):Y;return new wX({type:"enum",entries:X,...a.normalizeParams(J)})}var YV=P("ZodLiteral",(Y,J)=>{c2.init(Y,J),H0.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 BW(Y,J){return new YV({type:"literal",values:Array.isArray(Y)?Y:[Y],...a.normalizeParams(J)})}var JV=P("ZodTransform",(Y,J)=>{u2.init(Y,J),H0.init(Y,J),Y._zod.parse=(X,Q)=>{if(Q.direction==="backward")throw new v9(Y.constructor.name);X.addIssue=(G)=>{if(typeof G==="string")X.issues.push(a.issue(G,X.value,J));else{let W=G;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(a.issue(W))}};let $=J.transform(X.value,X);if($ instanceof Promise)return $.then((G)=>{return X.value=G,X});return X.value=$,X}});function XV(Y){return new JV({type:"transform",transform:Y})}var FW=P("ZodOptional",(Y,J)=>{p2.init(Y,J),H0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType});function YW(Y){return new FW({type:"optional",innerType:Y})}var QV=P("ZodNullable",(Y,J)=>{l2.init(Y,J),H0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType});function JW(Y){return new QV({type:"nullable",innerType:Y})}var $V=P("ZodDefault",(Y,J)=>{d2.init(Y,J),H0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function GV(Y,J){return new $V({type:"default",innerType:Y,get defaultValue(){return typeof J==="function"?J():a.shallowClone(J)}})}var WV=P("ZodPrefault",(Y,J)=>{i2.init(Y,J),H0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType});function zV(Y,J){return new WV({type:"prefault",innerType:Y,get defaultValue(){return typeof J==="function"?J():a.shallowClone(J)}})}var jW=P("ZodNonOptional",(Y,J)=>{o2.init(Y,J),H0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType});function KV(Y,J){return new jW({type:"nonoptional",innerType:Y,...a.normalizeParams(J)})}var UV=P("ZodCatch",(Y,J)=>{n2.init(Y,J),H0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function ZV(Y,J){return new UV({type:"catch",innerType:Y,catchValue:typeof J==="function"?J:()=>J})}var LV=P("ZodPipe",(Y,J)=>{r2.init(Y,J),H0.init(Y,J),Y.in=J.in,Y.out=J.out});function XW(Y,J){return new LV({type:"pipe",in:Y,out:J})}var HV=P("ZodReadonly",(Y,J)=>{s2.init(Y,J),H0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType});function VV(Y){return new HV({type:"readonly",innerType:Y})}var NV=P("ZodLazy",(Y,J)=>{a2.init(Y,J),H0.init(Y,J),Y.unwrap=()=>Y._zod.def.getter()});function OW(Y){return new NV({type:"lazy",getter:Y})}var _X=P("ZodCustom",(Y,J)=>{t2.init(Y,J),H0.init(Y,J)});function qW(Y,J){return k7(_X,Y??(()=>!0),J)}function BV(Y,J={}){return x7(_X,Y,J)}function FV(Y){return b7(Y)}function DW(Y,J={error:`Input not instance of ${Y.name}`}){let X=new _X({type:"custom",check:"custom",fn:(Q)=>Q instanceof Y,abort:!0,...a.normalizeParams(J)});return X._zod.bag.Class=Y,X}function IW(Y=globalThis){var J,X,Q;if(Y.window)return"runtime/browser";if((J=Y.navigator)==null?void 0:J.userAgent)return`runtime/${Y.navigator.userAgent.toLowerCase()}`;if((Q=(X=Y.process)==null?void 0:X.versions)==null?void 0:Q.node)return`runtime/node.js/${Y.process.version.substring(0)}`;if(Y.EdgeRuntime)return"runtime/vercel-edge";return"runtime/unknown"}function jV(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 o1(Y,...J){let X=new Headers(jV(Y)),Q=X.get("user-agent")||"";return X.set("user-agent",[Q,...J].filter(Boolean).join(" ")),Object.fromEntries(X.entries())}var OV=[{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]}],zD=[...OV,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];var qV=12,DV=131072,KD=DV+qV;async function eY(Y){var J;try{await((J=Y.body)==null?void 0:J.cancel())}catch(X){}}var SW="AI_DownloadError",kW=`vercel.ai.error.${SW}`,PV=Symbol.for(kW),PW,EW,b0=class extends(EW=R,PW=PV,EW){constructor({url:Y,statusCode:J,statusText:X,cause:Q,message:$=Q==null?`Failed to download ${Y}: ${J} ${X}`:`Failed to download ${Y}: ${Q}`}){super({name:SW,message:$,cause:Q});this[PW]=!0,this.url=Y,this.statusCode=J,this.statusText=X}static isInstance(Y){return R.hasMarker(Y,kW)}};function EV(Y=globalThis){return Y.window!=null}function MW(Y,J){try{return new URL(Y).origin===new URL(J).origin}catch(X){return!1}}function MV(Y){let J;try{J=new URL(Y)}catch(Q){throw new b0({url:Y,message:`Invalid URL: ${Y}`})}if(J.protocol==="data:")return;if(J.protocol!=="http:"&&J.protocol!=="https:")throw new b0({url:Y,message:`URL scheme must be http, https, or data, got ${J.protocol}`});let X=J.hostname.toLowerCase().replace(/\.+$/,"");if(!X)throw new b0({url:Y,message:"URL must have a hostname"});if(X==="localhost"||X.endsWith(".local")||X.endsWith(".localhost"))throw new b0({url:Y,message:`URL with hostname ${X} is not allowed`});if(X.startsWith("[")&&X.endsWith("]")){let Q=X.slice(1,-1);if(xW(Q))throw new b0({url:Y,message:`URL with IPv6 address ${X} is not allowed`});return}if(vX(X)){if(hX(X))throw new b0({url:Y,message:`URL with IP address ${X} is not allowed`});return}}function wV({address:Y,family:J,hostname:X}){if(J===4?!vX(Y)||hX(Y):J===6?xW(Y):!0)throw new b0({url:X,message:`Hostname ${X} resolved to disallowed IP address ${Y}`})}function vX(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 hX(Y){let J=Y.split(".").map(Number),[X,Q,$]=J;if(X===0)return!0;if(X===10)return!0;if(X===100&&Q>=64&&Q<=127)return!0;if(X===127)return!0;if(X===169&&Q===254)return!0;if(X===172&&Q>=16&&Q<=31)return!0;if(X===192&&Q===0&&$===0)return!0;if(X===192&&Q===0&&$===2)return!0;if(X===192&&Q===168)return!0;if(X===198&&(Q===18||Q===19))return!0;if(X===198&&Q===51&&$===100)return!0;if(X===203&&Q===0&&$===113)return!0;if(X>=224)return!0;return!1}function AV(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 $=(W)=>{if(W==="")return[];let K=[],Z=W.split(":");for(let U=0;U<Z.length;U++){let L=Z[U];if(L.includes(".")){if(U!==Z.length-1||!vX(L))return null;let[j,N,V,q]=L.split(".").map(Number);K.push(j<<8|N,V<<8|q);continue}if(!/^[0-9a-f]{1,4}$/.test(L))return null;K.push(parseInt(L,16))}return K},G=$(Q[0]);if(G===null)return null;if(Q.length===2){let W=$(Q[1]);if(W===null)return null;let K=8-G.length-W.length;if(K<0)return null;return[...G,...Array(K).fill(0),...W]}return G.length===8?G:null}function xW(Y){let J=AV(Y);if(J===null)return!0;let X=($)=>J.slice(0,$).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){let $=J[6]>>8&255,G=J[6]&255,W=J[7]>>8&255,K=J[7]&255;return hX(`${$}.${G}.${W}.${K}`)}return!1}function RV(Y){return(J,X,Q)=>{Y(J,{...X,all:!0},($,G)=>{if($){Q($);return}try{let[W]=G;if(W==null)throw Error(`Hostname ${J} did not resolve to an address`);for(let{address:K,family:Z}of G)wV({address:K,family:Z,hostname:J});if(X.all===!0)Q(null,G);else Q(null,W.address,W.family)}catch(W){Q(W instanceof Error?W:Error(String(W)))}})}}var IX;function TV(){var Y,J,X;let Q=globalThis.process;return((Y=Q==null?void 0:Q.release)==null?void 0:Y.name)==="node"&&((J=Q.versions)==null?void 0:J.bun)==null&&((X=Q.versions)==null?void 0:X.deno)==null&&Q.title!=="workerd"&&globalThis.EdgeRuntime==null}async function CV(){if(!TV())return globalThis.fetch;return IX!=null?IX:IX=Promise.resolve().then(_V)}function _V(){let Y=wW("node:module"),{lookup:J}=wW("node:dns"),X=Y.createRequire(bW()),{Agent:Q,fetch:$}=X("undici"),G=new Q({connect:{lookup:RV(J)}});return(W,K)=>$(W,{...K,dispatcher:G})}function wW(Y){var J;let X=globalThis.process,Q=(J=X==null?void 0:X.getBuiltinModule)==null?void 0:J.call(X,Y);if(Q==null)throw Error(`Node.js built-in module ${Y} is unavailable`);return Q}function bW(){let Y=Error.prepareStackTrace;try{Error.prepareStackTrace=($,G)=>G;let J=Error("Capture current module path");Error.captureStackTrace(J,bW);let[X]=J.stack,Q=X==null?void 0:X.getFileName();if(Q==null)throw Error("Unable to determine the current module path");return Q}finally{Error.prepareStackTrace=Y}}var IV=["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 SV(Y){let J=new Headers(Y);for(let X of IV)J.delete(X);return J}var kV=10,xV=new Set([301,302,303,307,308]);async function bV(Y){return Y==null||Y===globalThis.fetch?await CV():Y}async function vW({url:Y,headers:J,abortSignal:X,maxRedirects:Q=kV,fetch:$,trustedOrigin:G}){var W;let K=J===void 0?void 0:SV(J),Z=(L)=>{let j={signal:X,redirect:L};if(K!==void 0)j.headers=new Headers(K);return j},U=Y;for(let L=0;L<=Q;L++){let j=G!==void 0&&MW(U,G);if(!j)MV(U);let N=j&&$!=null?$:j?globalThis.fetch:await bV($),V=await N(U,Z("manual"));if(V.type==="opaqueredirect"){if(!EV())throw new b0({url:Y,message:`Redirect from ${U} could not be validated and was blocked`});return await N(U,Z("follow"))}let q=(W=V.headers)==null?void 0:W.get("location");if(xV.has(V.status)&&q){eY(V);let T=new URL(q,U).toString();if(K!==void 0&&!MW(T,U)){let S=K.get("user-agent");K=new Headers(S==null?void 0:{"user-agent":S})}U=T;continue}return V}throw new b0({url:Y,message:`Too many redirects (max ${Q})`})}var gX=2147483648;async function hW({response:Y,url:J,maxBytes:X=gX}){let Q=Y.headers.get("content-length");if(Q!=null){let L=parseInt(Q,10);if(!isNaN(L)&&L>X)throw await eY(Y),new b0({url:J,message:`Download of ${J} exceeded maximum size of ${X} bytes (Content-Length: ${L}).`})}let $=Y.body;if($==null)return new Uint8Array(0);let G=$.getReader(),W=[],K=0;try{while(!0){let{done:L,value:j}=await G.read();if(L)break;if(K+=j.length,K>X)throw new b0({url:J,message:`Download of ${J} exceeded maximum size of ${X} bytes.`});W.push(j)}}finally{try{await G.cancel()}catch(L){}finally{G.releaseLock()}}let Z=new Uint8Array(K),U=0;for(let L of W)Z.set(L,U),U+=L.length;return Z}var F0=({prefix:Y,size:J=16,alphabet:X="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:Q="-"}={})=>{let $=()=>{let G=X.length,W=Array(J);for(let K=0;K<J;K++)W[K]=X[Math.random()*G|0];return W.join("")};if(Y==null)return $;if(X.includes(Q))throw new B$({argument:"separator",message:`The separator "${Q}" must not be part of the alphabet "${X}".`});return()=>`${Y}${Q}${$()}`},LD=F0();function gW(Y){var J,X;return(X=(J=globalThis.Buffer)==null?void 0:J.isBuffer(Y))!=null?X:!1}var vV=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,hV=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function AW(Y){let J=JSON.parse(Y);if(J===null||typeof J!=="object")return J;if(vV.test(Y)===!1&&hV.test(Y)===!1)return J;return gV(J)}function gV(Y){let J=[Y];while(J.length){let X=J;J=[];for(let Q of X){if(Object.prototype.hasOwnProperty.call(Q,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(Q,"constructor")&&Q.constructor!==null&&typeof Q.constructor==="object"&&Object.prototype.hasOwnProperty.call(Q.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let $ in Q){let G=Q[$];if(G&&typeof G==="object")J.push(G)}}}return Y}function yV(Y){let{stackTraceLimit:J}=Error;try{Error.stackTraceLimit=0}catch(X){return AW(Y)}try{return AW(Y)}finally{Error.stackTraceLimit=J}}function yX(Y){if(Y.type==="object"||Array.isArray(Y.type)&&Y.type.includes("object")){let{additionalProperties:X}=Y;Y.additionalProperties=X!=null&&typeof X!=="boolean"?S1(X):!1;let{properties:Q}=Y;if(Q!=null)for(let $ of Object.keys(Q))Q[$]=S1(Q[$])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(S1):S1(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(S1);if(Y.allOf!=null)Y.allOf=Y.allOf.map(S1);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(S1);let{definitions:J}=Y;if(J!=null)for(let X of Object.keys(J))J[X]=S1(J[X]);return Y}function S1(Y){if(typeof Y==="boolean")return Y;return yX(Y)}var fV=Symbol("Let zodToJsonSchema decide on which parser to use"),RW={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"},mV=(Y)=>typeof Y==="string"?{...RW,name:Y}:{...RW,...Y};function i0(){return{}}function cV(Y,J){var X,Q,$;let G={type:"array"};if(((X=Y.type)==null?void 0:X._def)&&(($=(Q=Y.type)==null?void 0:Q._def)==null?void 0:$.typeName)!=="ZodAny")G.items=G0(Y.type._def,{...J,currentPath:[...J.currentPath,"items"]});if(Y.minLength)G.minItems=Y.minLength.value;if(Y.maxLength)G.maxItems=Y.maxLength.value;if(Y.exactLength)G.minItems=Y.exactLength.value,G.maxItems=Y.exactLength.value;return G}function uV(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;break}return J}function pV(){return{type:"boolean"}}function yW(Y,J){return G0(Y.type._def,J)}var lV=(Y,J)=>{return G0(Y.innerType._def,J)};function fW(Y,J,X){let Q=X!=null?X:J.dateStrategy;if(Array.isArray(Q))return{anyOf:Q.map(($)=>fW(Y,J,$))};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 dV(Y)}}var dV=(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;break}return J};function iV(Y,J){return{...G0(Y.innerType._def,J),default:Y.defaultValue()}}function oV(Y,J){return J.effectStrategy==="input"?G0(Y.schema._def,J):i0()}function nV(Y){return{type:"string",enum:Array.from(Y.values)}}var rV=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function sV(Y,J){let X=[G0(Y.left._def,{...J,currentPath:[...J.currentPath,"allOf","0"]}),G0(Y.right._def,{...J,currentPath:[...J.currentPath,"allOf","1"]})].filter(($)=>!!$),Q=[];return X.forEach(($)=>{if(rV($))Q.push(...$.allOf);else{let G=$;if("additionalProperties"in $&&$.additionalProperties===!1){let{additionalProperties:W,...K}=$;G=K}Q.push(G)}}),Q.length?{allOf:Q}:void 0}function aV(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 SX=void 0,e0={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(SX===void 0)SX=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return SX},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 mW(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":Y1(X,"email",Q.message,J);break;case"format:idn-email":Y1(X,"idn-email",Q.message,J);break;case"pattern:zod":x0(X,e0.email,Q.message,J);break}break;case"url":Y1(X,"uri",Q.message,J);break;case"uuid":Y1(X,"uuid",Q.message,J);break;case"regex":x0(X,Q.regex,Q.message,J);break;case"cuid":x0(X,e0.cuid,Q.message,J);break;case"cuid2":x0(X,e0.cuid2,Q.message,J);break;case"startsWith":x0(X,RegExp(`^${kX(Q.value,J)}`),Q.message,J);break;case"endsWith":x0(X,RegExp(`${kX(Q.value,J)}$`),Q.message,J);break;case"datetime":Y1(X,"date-time",Q.message,J);break;case"date":Y1(X,"date",Q.message,J);break;case"time":Y1(X,"time",Q.message,J);break;case"duration":Y1(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":{x0(X,RegExp(kX(Q.value,J)),Q.message,J);break}case"ip":{if(Q.version!=="v6")Y1(X,"ipv4",Q.message,J);if(Q.version!=="v4")Y1(X,"ipv6",Q.message,J);break}case"base64url":x0(X,e0.base64url,Q.message,J);break;case"jwt":x0(X,e0.jwt,Q.message,J);break;case"cidr":{if(Q.version!=="v6")x0(X,e0.ipv4Cidr,Q.message,J);if(Q.version!=="v4")x0(X,e0.ipv6Cidr,Q.message,J);break}case"emoji":x0(X,e0.emoji(),Q.message,J);break;case"ulid":{x0(X,e0.ulid,Q.message,J);break}case"base64":{switch(J.base64Strategy){case"format:binary":{Y1(X,"binary",Q.message,J);break}case"contentEncoding:base64":{X.contentEncoding="base64";break}case"pattern:zod":{x0(X,e0.base64,Q.message,J);break}}break}case"nanoid":x0(X,e0.nanoid,Q.message,J);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return X}function kX(Y,J){return J.patternStrategy==="escape"?eV(Y):Y}var tV=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function eV(Y){let J="";for(let X=0;X<Y.length;X++){if(!tV.has(Y[X]))J+="\\";J+=Y[X]}return J}function Y1(Y,J,X,Q){var $;if(Y.format||(($=Y.anyOf)==null?void 0:$.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 x0(Y,J,X,Q){var $;if(Y.pattern||(($=Y.allOf)==null?void 0:$.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:TW(J,Q),...X&&Q.errorMessages&&{errorMessage:{pattern:X}}})}else Y.pattern=TW(J,Q)}function TW(Y,J){var X;if(!J.applyRegexFlags||!Y.flags)return Y.source;let Q={i:Y.flags.includes("i"),m:Y.flags.includes("m"),s:Y.flags.includes("s")},$=Q.i?Y.source.toLowerCase():Y.source,G="",W=!1,K=!1,Z=!1;for(let U=0;U<$.length;U++){if(W){G+=$[U],W=!1;continue}if(Q.i){if(K){if($[U].match(/[a-z]/)){if(Z)G+=$[U],G+=`${$[U-2]}-${$[U]}`.toUpperCase(),Z=!1;else if($[U+1]==="-"&&((X=$[U+2])==null?void 0:X.match(/[a-z]/)))G+=$[U],Z=!0;else G+=`${$[U]}${$[U].toUpperCase()}`;continue}}else if($[U].match(/[a-z]/)){G+=`[${$[U]}${$[U].toUpperCase()}]`;continue}}if(Q.m){if($[U]==="^"){G+=`(^|(?<=[\r
|
|
77
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let U of this.seen.entries()){let Z=U[1];if(Y===U[0]){G(U);continue}if(J.external){let N=J.external.registry.get(U[0])?.id;if(Y!==U[0]&&N){G(U);continue}}if(this.metadataRegistry.get(U[0])?.id){G(U);continue}if(Z.cycle){G(U);continue}if(Z.count>1){if(J.reused==="ref"){G(U);continue}}}let W=(U,Z)=>{let F=this.seen.get(U),N=F.def??F.schema,V={...N};if(F.ref===null)return;let q=F.ref;if(F.ref=null,q){W(q,Z);let R=this.seen.get(q).schema;if(R.$ref&&(Z.target==="draft-7"||Z.target==="draft-4"||Z.target==="openapi-3.0"))N.allOf=N.allOf??[],N.allOf.push(R);else Object.assign(N,R),Object.assign(N,V)}if(!F.isParent)this.override({zodSchema:U,jsonSchema:N,path:F.path??[]})};for(let U of[...this.seen.entries()].reverse())W(U[0],{target:this.target});let K={};if(this.target==="draft-2020-12")K.$schema="https://json-schema.org/draft/2020-12/schema";else if(this.target==="draft-7")K.$schema="http://json-schema.org/draft-07/schema#";else if(this.target==="draft-4")K.$schema="http://json-schema.org/draft-04/schema#";else if(this.target==="openapi-3.0");else console.warn(`Invalid target: ${this.target}`);if(J.external?.uri){let U=J.external.registry.get(Y)?.id;if(!U)throw Error("Schema is missing an `id` property");K.$id=J.external.uri(U)}Object.assign(K,Q.def);let H=J.external?.defs??{};for(let U of this.seen.entries()){let Z=U[1];if(Z.def&&Z.defId)H[Z.defId]=Z.def}if(J.external);else if(Object.keys(H).length>0)if(this.target==="draft-2020-12")K.$defs=H;else K.definitions=H;try{return JSON.parse(JSON.stringify(K))}catch(U){throw Error("Error converting schema to JSON.")}}}function A7(Y,X){if(Y instanceof pY){let Q=new qJ(X),$={};for(let K of Y._idmap.entries()){let[H,U]=K;Q.process(U)}let G={},W={registry:Y,uri:X?.uri,defs:$};for(let K of Y._idmap.entries()){let[H,U]=K;G[H]=Q.emit(U,{...X,external:W})}if(Object.keys($).length>0){let K=Q.target==="draft-2020-12"?"$defs":"definitions";G.__shared={[K]:$}}return{schemas:G}}let J=new qJ(X);return J.process(Y),J.emit(Y,X)}function M0(Y,X){let J=X??{seen:new Set};if(J.seen.has(Y))return!1;J.seen.add(Y);let $=Y._zod.def;switch($.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 M0($.element,J);case"object":{for(let G in $.shape)if(M0($.shape[G],J))return!0;return!1}case"union":{for(let G of $.options)if(M0(G,J))return!0;return!1}case"intersection":return M0($.left,J)||M0($.right,J);case"tuple":{for(let G of $.items)if(M0(G,J))return!0;if($.rest&&M0($.rest,J))return!0;return!1}case"record":return M0($.keyType,J)||M0($.valueType,J);case"map":return M0($.keyType,J)||M0($.valueType,J);case"set":return M0($.valueType,J);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return M0($.innerType,J);case"lazy":return M0($.getter(),J);case"default":return M0($.innerType,J);case"prefault":return M0($.innerType,J);case"custom":return!1;case"transform":return!0;case"pipe":return M0($.in,J)||M0($.out,J);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${$.type}`)}var XL=D("ZodISODateTime",(Y,X)=>{G2.init(Y,X),V0.init(Y,X)});function R7(Y){return Z7(XL,Y)}var JL=D("ZodISODate",(Y,X)=>{W2.init(Y,X),V0.init(Y,X)});function T7(Y){return L7(JL,Y)}var QL=D("ZodISOTime",(Y,X)=>{z2.init(Y,X),V0.init(Y,X)});function C7(Y){return V7(QL,Y)}var $L=D("ZodISODuration",(Y,X)=>{K2.init(Y,X),V0.init(Y,X)});function _7(Y){return N7($L,Y)}var I7=(Y,X)=>{hY.init(Y,X),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(J)=>f$(Y,J)},flatten:{value:(J)=>y$(Y,J)},addIssue:{value:(J)=>{Y.issues.push(J),Y.message=JSON.stringify(Y.issues,U9,2)}},addIssues:{value:(J)=>{Y.issues.push(...J),Y.message=JSON.stringify(Y.issues,U9,2)}},isEmpty:{get(){return Y.issues.length===0}}})},sq=D("ZodError",I7),i0=D("ZodError",I7,{Parent:Error});var S7=gY(i0),k7=yY(i0),x7=c9(i0),sY=u9(i0),b7=u$(i0),v7=p$(i0),h7=l$(i0),g7=d$(i0),y7=i$(i0),f7=n$(i0),m7=o$(i0),c7=r$(i0);var N0=D("ZodType",(Y,X)=>{return U0.init(Y,X),Y.def=X,Y.type=X.type,Object.defineProperty(Y,"_def",{value:X}),Y.check=(...J)=>{return Y.clone({...X,checks:[...X.checks??[],...J.map((Q)=>typeof Q==="function"?{_zod:{check:Q,def:{check:"custom"},onattach:[]}}:Q)]})},Y.clone=(J,Q)=>Y1(Y,J,Q),Y.brand=()=>Y,Y.register=(J,Q)=>{return J.add(Y,Q),Y},Y.parse=(J,Q)=>S7(Y,J,Q,{callee:Y.parse}),Y.safeParse=(J,Q)=>x7(Y,J,Q),Y.parseAsync=async(J,Q)=>k7(Y,J,Q,{callee:Y.parseAsync}),Y.safeParseAsync=async(J,Q)=>sY(Y,J,Q),Y.spa=Y.safeParseAsync,Y.encode=(J,Q)=>b7(Y,J,Q),Y.decode=(J,Q)=>v7(Y,J,Q),Y.encodeAsync=async(J,Q)=>h7(Y,J,Q),Y.decodeAsync=async(J,Q)=>g7(Y,J,Q),Y.safeEncode=(J,Q)=>y7(Y,J,Q),Y.safeDecode=(J,Q)=>f7(Y,J,Q),Y.safeEncodeAsync=async(J,Q)=>m7(Y,J,Q),Y.safeDecodeAsync=async(J,Q)=>c7(Y,J,Q),Y.refine=(J,Q)=>Y.check(aL(J,Q)),Y.superRefine=(J)=>Y.check(tL(J)),Y.overwrite=(J)=>Y.check(o1(J)),Y.optional=()=>l7(Y),Y.nullable=()=>d7(Y),Y.nullish=()=>l7(d7(Y)),Y.nonoptional=(J)=>lL(Y,J),Y.array=()=>EJ(Y),Y.or=(J)=>MJ([Y,J]),Y.and=(J)=>bL(Y,J),Y.transform=(J)=>i7(Y,yL(J)),Y.default=(J)=>cL(Y,J),Y.prefault=(J)=>pL(Y,J),Y.catch=(J)=>iL(Y,J),Y.pipe=(J)=>i7(Y,J),Y.readonly=()=>rL(Y),Y.describe=(J)=>{let Q=Y.clone();return n1.add(Q,{description:J}),Q},Object.defineProperty(Y,"description",{get(){return n1.get(Y)?.description},configurable:!0}),Y.meta=(...J)=>{if(J.length===0)return n1.get(Y);let Q=Y.clone();return n1.add(Q,J[0]),Q},Y.isOptional=()=>Y.safeParse(void 0).success,Y.isNullable=()=>Y.safeParse(null).success,Y}),n7=D("_ZodString",(Y,X)=>{uY.init(Y,X),N0.init(Y,X);let J=Y._zod.bag;Y.format=J.format??null,Y.minLength=J.minimum??null,Y.maxLength=J.maximum??null,Y.regex=(...Q)=>Y.check(UJ(...Q)),Y.includes=(...Q)=>Y.check(LJ(...Q)),Y.startsWith=(...Q)=>Y.check(VJ(...Q)),Y.endsWith=(...Q)=>Y.check(NJ(...Q)),Y.min=(...Q)=>Y.check(L9(...Q)),Y.max=(...Q)=>Y.check(nY(...Q)),Y.length=(...Q)=>Y.check(oY(...Q)),Y.nonempty=(...Q)=>Y.check(L9(1,...Q)),Y.lowercase=(Q)=>Y.check(HJ(Q)),Y.uppercase=(Q)=>Y.check(ZJ(Q)),Y.trim=()=>Y.check(FJ()),Y.normalize=(...Q)=>Y.check(BJ(...Q)),Y.toLowerCase=()=>Y.check(OJ()),Y.toUpperCase=()=>Y.check(jJ())}),KL=D("ZodString",(Y,X)=>{uY.init(Y,X),n7.init(Y,X),Y.email=(J)=>Y.check(l2(UL,J)),Y.url=(J)=>Y.check(r2(HL,J)),Y.jwt=(J)=>Y.check(H7(AL,J)),Y.emoji=(J)=>Y.check(s2(ZL,J)),Y.guid=(J)=>Y.check(KJ(u7,J)),Y.uuid=(J)=>Y.check(d2(aY,J)),Y.uuidv4=(J)=>Y.check(i2(aY,J)),Y.uuidv6=(J)=>Y.check(n2(aY,J)),Y.uuidv7=(J)=>Y.check(o2(aY,J)),Y.nanoid=(J)=>Y.check(a2(LL,J)),Y.guid=(J)=>Y.check(KJ(u7,J)),Y.cuid=(J)=>Y.check(t2(VL,J)),Y.cuid2=(J)=>Y.check(e2(NL,J)),Y.ulid=(J)=>Y.check(Y7(BL,J)),Y.base64=(J)=>Y.check(z7(EL,J)),Y.base64url=(J)=>Y.check(K7(ML,J)),Y.xid=(J)=>Y.check(X7(FL,J)),Y.ksuid=(J)=>Y.check(J7(OL,J)),Y.ipv4=(J)=>Y.check(Q7(jL,J)),Y.ipv6=(J)=>Y.check($7(qL,J)),Y.cidrv4=(J)=>Y.check(G7(DL,J)),Y.cidrv6=(J)=>Y.check(W7(PL,J)),Y.e164=(J)=>Y.check(U7(wL,J)),Y.datetime=(J)=>Y.check(R7(J)),Y.date=(J)=>Y.check(T7(J)),Y.time=(J)=>Y.check(C7(J)),Y.duration=(J)=>Y.check(_7(J))});function o7(Y){return p2(KL,Y)}var V0=D("ZodStringFormat",(Y,X)=>{Z0.init(Y,X),n7.init(Y,X)}),UL=D("ZodEmail",(Y,X)=>{sG.init(Y,X),V0.init(Y,X)});var u7=D("ZodGUID",(Y,X)=>{oG.init(Y,X),V0.init(Y,X)});var aY=D("ZodUUID",(Y,X)=>{rG.init(Y,X),V0.init(Y,X)});var HL=D("ZodURL",(Y,X)=>{aG.init(Y,X),V0.init(Y,X)});var ZL=D("ZodEmoji",(Y,X)=>{tG.init(Y,X),V0.init(Y,X)});var LL=D("ZodNanoID",(Y,X)=>{eG.init(Y,X),V0.init(Y,X)});var VL=D("ZodCUID",(Y,X)=>{Y2.init(Y,X),V0.init(Y,X)});var NL=D("ZodCUID2",(Y,X)=>{X2.init(Y,X),V0.init(Y,X)});var BL=D("ZodULID",(Y,X)=>{J2.init(Y,X),V0.init(Y,X)});var FL=D("ZodXID",(Y,X)=>{Q2.init(Y,X),V0.init(Y,X)});var OL=D("ZodKSUID",(Y,X)=>{$2.init(Y,X),V0.init(Y,X)});var jL=D("ZodIPv4",(Y,X)=>{U2.init(Y,X),V0.init(Y,X)});var qL=D("ZodIPv6",(Y,X)=>{H2.init(Y,X),V0.init(Y,X)});var DL=D("ZodCIDRv4",(Y,X)=>{Z2.init(Y,X),V0.init(Y,X)});var PL=D("ZodCIDRv6",(Y,X)=>{L2.init(Y,X),V0.init(Y,X)});var EL=D("ZodBase64",(Y,X)=>{N2.init(Y,X),V0.init(Y,X)});var ML=D("ZodBase64URL",(Y,X)=>{B2.init(Y,X),V0.init(Y,X)});var wL=D("ZodE164",(Y,X)=>{F2.init(Y,X),V0.init(Y,X)});var AL=D("ZodJWT",(Y,X)=>{O2.init(Y,X),V0.init(Y,X)});var r7=D("ZodNumber",(Y,X)=>{WJ.init(Y,X),N0.init(Y,X),Y.gt=(Q,$)=>Y.check(dY(Q,$)),Y.gte=(Q,$)=>Y.check(d9(Q,$)),Y.min=(Q,$)=>Y.check(d9(Q,$)),Y.lt=(Q,$)=>Y.check(lY(Q,$)),Y.lte=(Q,$)=>Y.check(l9(Q,$)),Y.max=(Q,$)=>Y.check(l9(Q,$)),Y.int=(Q)=>Y.check(p7(Q)),Y.safe=(Q)=>Y.check(p7(Q)),Y.positive=(Q)=>Y.check(dY(0,Q)),Y.nonnegative=(Q)=>Y.check(d9(0,Q)),Y.negative=(Q)=>Y.check(lY(0,Q)),Y.nonpositive=(Q)=>Y.check(l9(0,Q)),Y.multipleOf=(Q,$)=>Y.check(iY(Q,$)),Y.step=(Q,$)=>Y.check(iY(Q,$)),Y.finite=()=>Y;let J=Y._zod.bag;Y.minValue=Math.max(J.minimum??Number.NEGATIVE_INFINITY,J.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Y.maxValue=Math.min(J.maximum??Number.POSITIVE_INFINITY,J.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Y.isInt=(J.format??"").includes("int")||Number.isSafeInteger(J.multipleOf??0.5),Y.isFinite=!0,Y.format=J.format??null});function s7(Y){return B7(r7,Y)}var RL=D("ZodNumberFormat",(Y,X)=>{j2.init(Y,X),r7.init(Y,X)});function p7(Y){return F7(RL,Y)}var TL=D("ZodBoolean",(Y,X)=>{q2.init(Y,X),N0.init(Y,X)});function a7(Y){return O7(TL,Y)}var CL=D("ZodNull",(Y,X)=>{D2.init(Y,X),N0.init(Y,X)});function t7(Y){return j7(CL,Y)}var _L=D("ZodUnknown",(Y,X)=>{P2.init(Y,X),N0.init(Y,X)});function i9(){return q7(_L)}var IL=D("ZodNever",(Y,X)=>{E2.init(Y,X),N0.init(Y,X)});function PJ(Y){return D7(IL,Y)}var SL=D("ZodArray",(Y,X)=>{M2.init(Y,X),N0.init(Y,X),Y.element=X.element,Y.min=(J,Q)=>Y.check(L9(J,Q)),Y.nonempty=(J)=>Y.check(L9(1,J)),Y.max=(J,Q)=>Y.check(nY(J,Q)),Y.length=(J,Q)=>Y.check(oY(J,Q)),Y.unwrap=()=>Y.element});function EJ(Y,X){return P7(SL,Y,X)}var e7=D("ZodObject",(Y,X)=>{R2.init(Y,X),N0.init(Y,X),a.defineLazy(Y,"shape",()=>X.shape),Y.keyof=()=>wJ(Object.keys(Y._zod.def.shape)),Y.catchall=(J)=>Y.clone({...Y._zod.def,catchall:J}),Y.passthrough=()=>Y.clone({...Y._zod.def,catchall:i9()}),Y.loose=()=>Y.clone({...Y._zod.def,catchall:i9()}),Y.strict=()=>Y.clone({...Y._zod.def,catchall:PJ()}),Y.strip=()=>Y.clone({...Y._zod.def,catchall:void 0}),Y.extend=(J)=>{return a.extend(Y,J)},Y.safeExtend=(J)=>{return a.safeExtend(Y,J)},Y.merge=(J)=>a.merge(Y,J),Y.pick=(J)=>a.pick(Y,J),Y.omit=(J)=>a.omit(Y,J),Y.partial=(...J)=>a.partial(WW,Y,J[0]),Y.required=(...J)=>a.required(zW,Y,J[0])});function YW(Y,X){let J={type:"object",get shape(){return a.assignProp(this,"shape",Y?a.objectClone(Y):{}),this.shape},...a.normalizeParams(X)};return new e7(J)}function XW(Y,X){return new e7({type:"object",get shape(){return a.assignProp(this,"shape",a.objectClone(Y)),this.shape},catchall:i9(),...a.normalizeParams(X)})}var JW=D("ZodUnion",(Y,X)=>{zJ.init(Y,X),N0.init(Y,X),Y.options=X.options});function MJ(Y,X){return new JW({type:"union",options:Y,...a.normalizeParams(X)})}var kL=D("ZodDiscriminatedUnion",(Y,X)=>{JW.init(Y,X),T2.init(Y,X)});function QW(Y,X,J){return new kL({type:"union",options:X,discriminator:Y,...a.normalizeParams(J)})}var xL=D("ZodIntersection",(Y,X)=>{C2.init(Y,X),N0.init(Y,X)});function bL(Y,X){return new xL({type:"intersection",left:Y,right:X})}var vL=D("ZodRecord",(Y,X)=>{_2.init(Y,X),N0.init(Y,X),Y.keyType=X.keyType,Y.valueType=X.valueType});function $W(Y,X,J){return new vL({type:"record",keyType:Y,valueType:X,...a.normalizeParams(J)})}var DJ=D("ZodEnum",(Y,X)=>{I2.init(Y,X),N0.init(Y,X),Y.enum=X.entries,Y.options=Object.values(X.entries);let J=new Set(Object.keys(X.entries));Y.extract=(Q,$)=>{let G={};for(let W of Q)if(J.has(W))G[W]=X.entries[W];else throw Error(`Key ${W} not found in enum`);return new DJ({...X,checks:[],...a.normalizeParams($),entries:G})},Y.exclude=(Q,$)=>{let G={...X.entries};for(let W of Q)if(J.has(W))delete G[W];else throw Error(`Key ${W} not found in enum`);return new DJ({...X,checks:[],...a.normalizeParams($),entries:G})}});function wJ(Y,X){let J=Array.isArray(Y)?Object.fromEntries(Y.map((Q)=>[Q,Q])):Y;return new DJ({type:"enum",entries:J,...a.normalizeParams(X)})}var hL=D("ZodLiteral",(Y,X)=>{S2.init(Y,X),N0.init(Y,X),Y.values=new Set(X.values),Object.defineProperty(Y,"value",{get(){if(X.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return X.values[0]}})});function GW(Y,X){return new hL({type:"literal",values:Array.isArray(Y)?Y:[Y],...a.normalizeParams(X)})}var gL=D("ZodTransform",(Y,X)=>{k2.init(Y,X),N0.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new v9(Y.constructor.name);J.addIssue=(G)=>{if(typeof G==="string")J.issues.push(a.issue(G,J.value,X));else{let W=G;if(W.fatal)W.continue=!1;W.code??(W.code="custom"),W.input??(W.input=J.value),W.inst??(W.inst=Y),J.issues.push(a.issue(W))}};let $=X.transform(J.value,J);if($ instanceof Promise)return $.then((G)=>{return J.value=G,J});return J.value=$,J}});function yL(Y){return new gL({type:"transform",transform:Y})}var WW=D("ZodOptional",(Y,X)=>{x2.init(Y,X),N0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function l7(Y){return new WW({type:"optional",innerType:Y})}var fL=D("ZodNullable",(Y,X)=>{b2.init(Y,X),N0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function d7(Y){return new fL({type:"nullable",innerType:Y})}var mL=D("ZodDefault",(Y,X)=>{v2.init(Y,X),N0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function cL(Y,X){return new mL({type:"default",innerType:Y,get defaultValue(){return typeof X==="function"?X():a.shallowClone(X)}})}var uL=D("ZodPrefault",(Y,X)=>{h2.init(Y,X),N0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function pL(Y,X){return new uL({type:"prefault",innerType:Y,get defaultValue(){return typeof X==="function"?X():a.shallowClone(X)}})}var zW=D("ZodNonOptional",(Y,X)=>{g2.init(Y,X),N0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function lL(Y,X){return new zW({type:"nonoptional",innerType:Y,...a.normalizeParams(X)})}var dL=D("ZodCatch",(Y,X)=>{y2.init(Y,X),N0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function iL(Y,X){return new dL({type:"catch",innerType:Y,catchValue:typeof X==="function"?X:()=>X})}var nL=D("ZodPipe",(Y,X)=>{f2.init(Y,X),N0.init(Y,X),Y.in=X.in,Y.out=X.out});function i7(Y,X){return new nL({type:"pipe",in:Y,out:X})}var oL=D("ZodReadonly",(Y,X)=>{m2.init(Y,X),N0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function rL(Y){return new oL({type:"readonly",innerType:Y})}var sL=D("ZodLazy",(Y,X)=>{c2.init(Y,X),N0.init(Y,X),Y.unwrap=()=>Y._zod.def.getter()});function KW(Y){return new sL({type:"lazy",getter:Y})}var AJ=D("ZodCustom",(Y,X)=>{u2.init(Y,X),N0.init(Y,X)});function UW(Y,X){return E7(AJ,Y??(()=>!0),X)}function aL(Y,X={}){return M7(AJ,Y,X)}function tL(Y){return w7(Y)}function HW(Y,X={error:`Input not instance of ${Y.name}`}){let J=new AJ({type:"custom",check:"custom",fn:(Q)=>Q instanceof Y,abort:!0,...a.normalizeParams(X)});return J._zod.bag.Class=Y,J}function DW(Y=globalThis){var X,J,Q;if(Y.window)return"runtime/browser";if((X=Y.navigator)==null?void 0:X.userAgent)return`runtime/${Y.navigator.userAgent.toLowerCase()}`;if((Q=(J=Y.process)==null?void 0:J.versions)==null?void 0:Q.node)return`runtime/node.js/${Y.process.version.substring(0)}`;if(Y.EdgeRuntime)return"runtime/vercel-edge";return"runtime/unknown"}function eL(Y){if(Y==null)return{};let X={};if(Y instanceof Headers)Y.forEach((J,Q)=>{X[Q.toLowerCase()]=J});else{if(!Array.isArray(Y))Y=Object.entries(Y);for(let[J,Q]of Y)if(Q!=null)X[J.toLowerCase()]=Q}return X}function r1(Y,...X){let J=new Headers(eL(Y)),Q=J.get("user-agent")||"";return J.set("user-agent",[Q,...X].filter(Boolean).join(" ")),Object.fromEntries(J.entries())}var YV=[{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]}],g6=[...YV,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];var XV=12,JV=131072,y6=JV+XV;async function tY(Y){var X;try{await((X=Y.body)==null?void 0:X.cancel())}catch(J){}}var PW="AI_DownloadError",EW=`vercel.ai.error.${PW}`,QV=Symbol.for(EW),ZW,LW,h0=class extends(LW=A,ZW=QV,LW){constructor({url:Y,statusCode:X,statusText:J,cause:Q,message:$=Q==null?`Failed to download ${Y}: ${X} ${J}`:`Failed to download ${Y}: ${Q}`}){super({name:PW,message:$,cause:Q});this[ZW]=!0,this.url=Y,this.statusCode=X,this.statusText=J}static isInstance(Y){return A.hasMarker(Y,EW)}};function $V(Y=globalThis){return Y.window!=null}function VW(Y,X){try{return new URL(Y).origin===new URL(X).origin}catch(J){return!1}}function GV(Y){let X;try{X=new URL(Y)}catch(Q){throw new h0({url:Y,message:`Invalid URL: ${Y}`})}if(X.protocol==="data:")return;if(X.protocol!=="http:"&&X.protocol!=="https:")throw new h0({url:Y,message:`URL scheme must be http, https, or data, got ${X.protocol}`});let J=X.hostname.toLowerCase().replace(/\.+$/,"");if(!J)throw new h0({url:Y,message:"URL must have a hostname"});if(J==="localhost"||J.endsWith(".local")||J.endsWith(".localhost"))throw new h0({url:Y,message:`URL with hostname ${J} is not allowed`});if(J.startsWith("[")&&J.endsWith("]")){let Q=J.slice(1,-1);if(MW(Q))throw new h0({url:Y,message:`URL with IPv6 address ${J} is not allowed`});return}if(SJ(J)){if(kJ(J))throw new h0({url:Y,message:`URL with IP address ${J} is not allowed`});return}}function WV({address:Y,family:X,hostname:J}){if(X===4?!SJ(Y)||kJ(Y):X===6?MW(Y):!0)throw new h0({url:J,message:`Hostname ${J} resolved to disallowed IP address ${Y}`})}function SJ(Y){let X=Y.split(".");if(X.length!==4)return!1;return X.every((J)=>{let Q=Number(J);return Number.isInteger(Q)&&Q>=0&&Q<=255&&String(Q)===J})}function kJ(Y){let X=Y.split(".").map(Number),[J,Q,$]=X;if(J===0)return!0;if(J===10)return!0;if(J===100&&Q>=64&&Q<=127)return!0;if(J===127)return!0;if(J===169&&Q===254)return!0;if(J===172&&Q>=16&&Q<=31)return!0;if(J===192&&Q===0&&$===0)return!0;if(J===192&&Q===0&&$===2)return!0;if(J===192&&Q===168)return!0;if(J===198&&(Q===18||Q===19))return!0;if(J===198&&Q===51&&$===100)return!0;if(J===203&&Q===0&&$===113)return!0;if(J>=224)return!0;return!1}function zV(Y){let X=Y.toLowerCase(),J=X.indexOf("%");if(J!==-1)X=X.slice(0,J);let Q=X.split("::");if(Q.length>2)return null;let $=(W)=>{if(W==="")return[];let K=[],H=W.split(":");for(let U=0;U<H.length;U++){let Z=H[U];if(Z.includes(".")){if(U!==H.length-1||!SJ(Z))return null;let[F,N,V,q]=Z.split(".").map(Number);K.push(F<<8|N,V<<8|q);continue}if(!/^[0-9a-f]{1,4}$/.test(Z))return null;K.push(parseInt(Z,16))}return K},G=$(Q[0]);if(G===null)return null;if(Q.length===2){let W=$(Q[1]);if(W===null)return null;let K=8-G.length-W.length;if(K<0)return null;return[...G,...Array(K).fill(0),...W]}return G.length===8?G:null}function MW(Y){let X=zV(Y);if(X===null)return!0;let J=($)=>X.slice(0,$).every((G)=>G===0);if(J(7)&&(X[7]===0||X[7]===1))return!0;if((X[0]&65024)===64512)return!0;if((X[0]&65472)===65152)return!0;if((X[0]&65472)===65216)return!0;if((X[0]&65280)===65280)return!0;if(X[0]===8193&&X[1]===3512)return!0;if(X[0]===16383&&(X[1]&61440)===0)return!0;if(J(6)||J(5)&&X[5]===65535||J(4)&&X[4]===65535&&X[5]===0||X[0]===100&&X[1]===65435&&X[2]===0&&X[3]===0&&X[4]===0&&X[5]===0||X[0]===100&&X[1]===65435&&X[2]===1){let $=X[6]>>8&255,G=X[6]&255,W=X[7]>>8&255,K=X[7]&255;return kJ(`${$}.${G}.${W}.${K}`)}return!1}function KV(Y){return(X,J,Q)=>{Y(X,{...J,all:!0},($,G)=>{if($){Q($);return}try{let[W]=G;if(W==null)throw Error(`Hostname ${X} did not resolve to an address`);for(let{address:K,family:H}of G)WV({address:K,family:H,hostname:X});if(J.all===!0)Q(null,G);else Q(null,W.address,W.family)}catch(W){Q(W instanceof Error?W:Error(String(W)))}})}}var RJ;function UV(){var Y,X,J;let Q=globalThis.process;return((Y=Q==null?void 0:Q.release)==null?void 0:Y.name)==="node"&&((X=Q.versions)==null?void 0:X.bun)==null&&((J=Q.versions)==null?void 0:J.deno)==null&&Q.title!=="workerd"&&globalThis.EdgeRuntime==null}async function HV(){if(!UV())return globalThis.fetch;return RJ!=null?RJ:RJ=Promise.resolve().then(ZV)}function ZV(){let Y=NW("node:module"),{lookup:X}=NW("node:dns"),J=Y.createRequire(wW()),{Agent:Q,fetch:$}=J("undici"),G=new Q({connect:{lookup:KV(X)}});return(W,K)=>$(W,{...K,dispatcher:G})}function NW(Y){var X;let J=globalThis.process,Q=(X=J==null?void 0:J.getBuiltinModule)==null?void 0:X.call(J,Y);if(Q==null)throw Error(`Node.js built-in module ${Y} is unavailable`);return Q}function wW(){let Y=Error.prepareStackTrace;try{Error.prepareStackTrace=($,G)=>G;let X=Error("Capture current module path");Error.captureStackTrace(X,wW);let[J]=X.stack,Q=J==null?void 0:J.getFileName();if(Q==null)throw Error("Unable to determine the current module path");return Q}finally{Error.prepareStackTrace=Y}}var LV=["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 VV(Y){let X=new Headers(Y);for(let J of LV)X.delete(J);return X}var NV=10,BV=new Set([301,302,303,307,308]);async function FV(Y){return Y==null||Y===globalThis.fetch?await HV():Y}async function AW({url:Y,headers:X,abortSignal:J,maxRedirects:Q=NV,fetch:$,trustedOrigin:G}){var W;let K=X===void 0?void 0:VV(X),H=(Z)=>{let F={signal:J,redirect:Z};if(K!==void 0)F.headers=new Headers(K);return F},U=Y;for(let Z=0;Z<=Q;Z++){let F=G!==void 0&&VW(U,G);if(!F)GV(U);let N=F&&$!=null?$:F?globalThis.fetch:await FV($),V=await N(U,H("manual"));if(V.type==="opaqueredirect"){if(!$V())throw new h0({url:Y,message:`Redirect from ${U} could not be validated and was blocked`});return await N(U,H("follow"))}let q=(W=V.headers)==null?void 0:W.get("location");if(BV.has(V.status)&&q){tY(V);let R=new URL(q,U).toString();if(K!==void 0&&!VW(R,U)){let k=K.get("user-agent");K=new Headers(k==null?void 0:{"user-agent":k})}U=R;continue}return V}throw new h0({url:Y,message:`Too many redirects (max ${Q})`})}var xJ=2147483648;async function RW({response:Y,url:X,maxBytes:J=xJ}){let Q=Y.headers.get("content-length");if(Q!=null){let Z=parseInt(Q,10);if(!isNaN(Z)&&Z>J)throw await tY(Y),new h0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes (Content-Length: ${Z}).`})}let $=Y.body;if($==null)return new Uint8Array(0);let G=$.getReader(),W=[],K=0;try{while(!0){let{done:Z,value:F}=await G.read();if(Z)break;if(K+=F.length,K>J)throw new h0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes.`});W.push(F)}}finally{try{await G.cancel()}catch(Z){}finally{G.releaseLock()}}let H=new Uint8Array(K),U=0;for(let Z of W)H.set(Z,U),U+=Z.length;return H}var q0=({prefix:Y,size:X=16,alphabet:J="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:Q="-"}={})=>{let $=()=>{let G=J.length,W=Array(X);for(let K=0;K<X;K++)W[K]=J[Math.random()*G|0];return W.join("")};if(Y==null)return $;if(J.includes(Q))throw new G$({argument:"separator",message:`The separator "${Q}" must not be part of the alphabet "${J}".`});return()=>`${Y}${Q}${$()}`},c6=q0();function TW(Y){var X,J;return(J=(X=globalThis.Buffer)==null?void 0:X.isBuffer(Y))!=null?J:!1}var OV=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,jV=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function BW(Y){let X=JSON.parse(Y);if(X===null||typeof X!=="object")return X;if(OV.test(Y)===!1&&jV.test(Y)===!1)return X;return qV(X)}function qV(Y){let X=[Y];while(X.length){let J=X;X=[];for(let Q of J){if(Object.prototype.hasOwnProperty.call(Q,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(Q,"constructor")&&Q.constructor!==null&&typeof Q.constructor==="object"&&Object.prototype.hasOwnProperty.call(Q.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let $ in Q){let G=Q[$];if(G&&typeof G==="object")X.push(G)}}}return Y}function DV(Y){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(J){return BW(Y)}try{return BW(Y)}finally{Error.stackTraceLimit=X}}function bJ(Y){if(Y.type==="object"||Array.isArray(Y.type)&&Y.type.includes("object")){let{additionalProperties:J}=Y;Y.additionalProperties=J!=null&&typeof J!=="boolean"?S1(J):!1;let{properties:Q}=Y;if(Q!=null)for(let $ of Object.keys(Q))Q[$]=S1(Q[$])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(S1):S1(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(S1);if(Y.allOf!=null)Y.allOf=Y.allOf.map(S1);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(S1);let{definitions:X}=Y;if(X!=null)for(let J of Object.keys(X))X[J]=S1(X[J]);return Y}function S1(Y){if(typeof Y==="boolean")return Y;return bJ(Y)}var PV=Symbol("Let zodToJsonSchema decide on which parser to use"),FW={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"},EV=(Y)=>typeof Y==="string"?{...FW,name:Y}:{...FW,...Y};function n0(){return{}}function MV(Y,X){var J,Q,$;let G={type:"array"};if(((J=Y.type)==null?void 0:J._def)&&(($=(Q=Y.type)==null?void 0:Q._def)==null?void 0:$.typeName)!=="ZodAny")G.items=W0(Y.type._def,{...X,currentPath:[...X.currentPath,"items"]});if(Y.minLength)G.minItems=Y.minLength.value;if(Y.maxLength)G.maxItems=Y.maxLength.value;if(Y.exactLength)G.minItems=Y.exactLength.value,G.maxItems=Y.exactLength.value;return G}function wV(Y){let X={type:"integer",format:"int64"};if(!Y.checks)return X;for(let J of Y.checks)switch(J.kind){case"min":if(J.inclusive)X.minimum=J.value;else X.exclusiveMinimum=J.value;break;case"max":if(J.inclusive)X.maximum=J.value;else X.exclusiveMaximum=J.value;break;case"multipleOf":X.multipleOf=J.value;break}return X}function AV(){return{type:"boolean"}}function CW(Y,X){return W0(Y.type._def,X)}var RV=(Y,X)=>{return W0(Y.innerType._def,X)};function _W(Y,X,J){let Q=J!=null?J:X.dateStrategy;if(Array.isArray(Q))return{anyOf:Q.map(($)=>_W(Y,X,$))};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 TV(Y)}}var TV=(Y)=>{let X={type:"integer",format:"unix-time"};for(let J of Y.checks)switch(J.kind){case"min":X.minimum=J.value;break;case"max":X.maximum=J.value;break}return X};function CV(Y,X){return{...W0(Y.innerType._def,X),default:Y.defaultValue()}}function _V(Y,X){return X.effectStrategy==="input"?W0(Y.schema._def,X):n0()}function IV(Y){return{type:"string",enum:Array.from(Y.values)}}var SV=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function kV(Y,X){let J=[W0(Y.left._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),W0(Y.right._def,{...X,currentPath:[...X.currentPath,"allOf","1"]})].filter(($)=>!!$),Q=[];return J.forEach(($)=>{if(SV($))Q.push(...$.allOf);else{let G=$;if("additionalProperties"in $&&$.additionalProperties===!1){let{additionalProperties:W,...K}=$;G=K}Q.push(G)}}),Q.length?{allOf:Q}:void 0}function xV(Y){let X=typeof Y.value;if(X!=="bigint"&&X!=="number"&&X!=="boolean"&&X!=="string")return{type:Array.isArray(Y.value)?"array":"object"};return{type:X==="bigint"?"integer":X,const:Y.value}}var TJ=void 0,J1={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(TJ===void 0)TJ=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return TJ},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function IW(Y,X){let J={type:"string"};if(Y.checks)for(let Q of Y.checks)switch(Q.kind){case"min":J.minLength=typeof J.minLength==="number"?Math.max(J.minLength,Q.value):Q.value;break;case"max":J.maxLength=typeof J.maxLength==="number"?Math.min(J.maxLength,Q.value):Q.value;break;case"email":switch(X.emailStrategy){case"format:email":Q1(J,"email",Q.message,X);break;case"format:idn-email":Q1(J,"idn-email",Q.message,X);break;case"pattern:zod":v0(J,J1.email,Q.message,X);break}break;case"url":Q1(J,"uri",Q.message,X);break;case"uuid":Q1(J,"uuid",Q.message,X);break;case"regex":v0(J,Q.regex,Q.message,X);break;case"cuid":v0(J,J1.cuid,Q.message,X);break;case"cuid2":v0(J,J1.cuid2,Q.message,X);break;case"startsWith":v0(J,RegExp(`^${CJ(Q.value,X)}`),Q.message,X);break;case"endsWith":v0(J,RegExp(`${CJ(Q.value,X)}$`),Q.message,X);break;case"datetime":Q1(J,"date-time",Q.message,X);break;case"date":Q1(J,"date",Q.message,X);break;case"time":Q1(J,"time",Q.message,X);break;case"duration":Q1(J,"duration",Q.message,X);break;case"length":J.minLength=typeof J.minLength==="number"?Math.max(J.minLength,Q.value):Q.value,J.maxLength=typeof J.maxLength==="number"?Math.min(J.maxLength,Q.value):Q.value;break;case"includes":{v0(J,RegExp(CJ(Q.value,X)),Q.message,X);break}case"ip":{if(Q.version!=="v6")Q1(J,"ipv4",Q.message,X);if(Q.version!=="v4")Q1(J,"ipv6",Q.message,X);break}case"base64url":v0(J,J1.base64url,Q.message,X);break;case"jwt":v0(J,J1.jwt,Q.message,X);break;case"cidr":{if(Q.version!=="v6")v0(J,J1.ipv4Cidr,Q.message,X);if(Q.version!=="v4")v0(J,J1.ipv6Cidr,Q.message,X);break}case"emoji":v0(J,J1.emoji(),Q.message,X);break;case"ulid":{v0(J,J1.ulid,Q.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{Q1(J,"binary",Q.message,X);break}case"contentEncoding:base64":{J.contentEncoding="base64";break}case"pattern:zod":{v0(J,J1.base64,Q.message,X);break}}break}case"nanoid":v0(J,J1.nanoid,Q.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return J}function CJ(Y,X){return X.patternStrategy==="escape"?vV(Y):Y}var bV=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function vV(Y){let X="";for(let J=0;J<Y.length;J++){if(!bV.has(Y[J]))X+="\\";X+=Y[J]}return X}function Q1(Y,X,J,Q){var $;if(Y.format||(($=Y.anyOf)==null?void 0:$.some((G)=>G.format))){if(!Y.anyOf)Y.anyOf=[];if(Y.format)Y.anyOf.push({format:Y.format}),delete Y.format;Y.anyOf.push({format:X,...J&&Q.errorMessages&&{errorMessage:{format:J}}})}else Y.format=X}function v0(Y,X,J,Q){var $;if(Y.pattern||(($=Y.allOf)==null?void 0:$.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:OW(X,Q),...J&&Q.errorMessages&&{errorMessage:{pattern:J}}})}else Y.pattern=OW(X,Q)}function OW(Y,X){var J;if(!X.applyRegexFlags||!Y.flags)return Y.source;let Q={i:Y.flags.includes("i"),m:Y.flags.includes("m"),s:Y.flags.includes("s")},$=Q.i?Y.source.toLowerCase():Y.source,G="",W=!1,K=!1,H=!1;for(let U=0;U<$.length;U++){if(W){G+=$[U],W=!1;continue}if(Q.i){if(K){if($[U].match(/[a-z]/)){if(H)G+=$[U],G+=`${$[U-2]}-${$[U]}`.toUpperCase(),H=!1;else if($[U+1]==="-"&&((J=$[U+2])==null?void 0:J.match(/[a-z]/)))G+=$[U],H=!0;else G+=`${$[U]}${$[U].toUpperCase()}`;continue}}else if($[U].match(/[a-z]/)){G+=`[${$[U]}${$[U].toUpperCase()}]`;continue}}if(Q.m){if($[U]==="^"){G+=`(^|(?<=[\r
|
|
93
78
|
]))`;continue}else if($[U]==="$"){G+=`($|(?=[\r
|
|
94
79
|
]))`;continue}}if(Q.s&&$[U]==="."){G+=K?`${$[U]}\r
|
|
95
80
|
`:`[${$[U]}\r
|
|
96
|
-
]`;continue}if(G+=$[U],$[U]==="\\")W=!0;else if(K&&$[U]==="]")K=!1;else if(!K&&$[U]==="[")K=!0}try{new RegExp(G)}catch(U){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 cW(Y,J){var X,Q,$,G,W,K;let Z={type:"object",additionalProperties:(X=G0(Y.valueType._def,{...J,currentPath:[...J.currentPath,"additionalProperties"]}))!=null?X:J.allowedAdditionalProperties};if(((Q=Y.keyType)==null?void 0:Q._def.typeName)==="ZodString"&&(($=Y.keyType._def.checks)==null?void 0:$.length)){let{type:U,...L}=mW(Y.keyType._def,J);return{...Z,propertyNames:L}}else if(((G=Y.keyType)==null?void 0:G._def.typeName)==="ZodEnum")return{...Z,propertyNames:{enum:Y.keyType._def.values}};else if(((W=Y.keyType)==null?void 0:W._def.typeName)==="ZodBranded"&&Y.keyType._def.type._def.typeName==="ZodString"&&((K=Y.keyType._def.type._def.checks)==null?void 0:K.length)){let{type:U,...L}=yW(Y.keyType._def,J);return{...Z,propertyNames:L}}return Z}function YN(Y,J){if(J.mapStrategy==="record")return cW(Y,J);let X=G0(Y.keyType._def,{...J,currentPath:[...J.currentPath,"items","items","0"]})||i0(),Q=G0(Y.valueType._def,{...J,currentPath:[...J.currentPath,"items","items","1"]})||i0();return{type:"array",maxItems:125,items:{type:"array",items:[X,Q],minItems:2,maxItems:2}}}function JN(Y){let J=Y.values,Q=Object.keys(Y.values).filter((G)=>{return typeof J[J[G]]!=="number"}).map((G)=>J[G]),$=Array.from(new Set(Q.map((G)=>typeof G)));return{type:$.length===1?$[0]==="string"?"string":"number":["string","number"],enum:Q}}function XN(){return{not:i0()}}function QN(){return{type:"null"}}var xX={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function $N(Y,J){let X=Y.options instanceof Map?Array.from(Y.options.values()):Y.options;if(X.every((Q)=>(Q._def.typeName in xX)&&(!Q._def.checks||!Q._def.checks.length))){let Q=X.reduce(($,G)=>{let W=xX[G._def.typeName];return W&&!$.includes(W)?[...$,W]:$},[]);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 G._def.value;switch(W){case"string":case"number":case"boolean":return[...$,W];case"bigint":return[...$,"integer"];case"object":if(G._def.value===null)return[...$,"null"];case"symbol":case"undefined":case"function":default:return $}},[]);if(Q.length===X.length){let $=Q.filter((G,W,K)=>K.indexOf(G)===W);return{type:$.length>1?$:$[0],enum:X.reduce((G,W)=>{return G.includes(W._def.value)?G:[...G,W._def.value]},[])}}}else if(X.every((Q)=>Q._def.typeName==="ZodEnum"))return{type:"string",enum:X.reduce((Q,$)=>[...Q,...$._def.values.filter((G)=>!Q.includes(G))],[])};return GN(Y,J)}var GN=(Y,J)=>{let X=(Y.options instanceof Map?Array.from(Y.options.values()):Y.options).map((Q,$)=>G0(Q._def,{...J,currentPath:[...J.currentPath,"anyOf",`${$}`]})).filter((Q)=>!!Q&&(!J.strictUnions||typeof Q==="object"&&Object.keys(Q).length>0));return X.length?{anyOf:X}:void 0};function WN(Y,J){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Y.innerType._def.typeName)&&(!Y.innerType._def.checks||!Y.innerType._def.checks.length))return{type:[xX[Y.innerType._def.typeName],"null"]};let X=G0(Y.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","0"]});return X&&{anyOf:[X,{type:"null"}]}}function zN(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;break}return J}function KN(Y,J){let X={type:"object",properties:{}},Q=[],$=Y.shape();for(let W in $){let K=$[W];if(K===void 0||K._def===void 0)continue;let Z=ZN(K),U=G0(K._def,{...J,currentPath:[...J.currentPath,"properties",W],propertyPath:[...J.currentPath,"properties",W]});if(U===void 0)continue;if(X.properties[W]=U,!Z)Q.push(W)}if(Q.length)X.required=Q;let G=UN(Y,J);if(G!==void 0)X.additionalProperties=G;return X}function UN(Y,J){if(Y.catchall._def.typeName!=="ZodNever")return G0(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 ZN(Y){try{return Y.isOptional()}catch(J){return!0}}var LN=(Y,J)=>{var X;if(J.currentPath.toString()===((X=J.propertyPath)==null?void 0:X.toString()))return G0(Y.innerType._def,J);let Q=G0(Y.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","1"]});return Q?{anyOf:[{not:i0()},Q]}:i0()},HN=(Y,J)=>{if(J.pipeStrategy==="input")return G0(Y.in._def,J);else if(J.pipeStrategy==="output")return G0(Y.out._def,J);let X=G0(Y.in._def,{...J,currentPath:[...J.currentPath,"allOf","0"]}),Q=G0(Y.out._def,{...J,currentPath:[...J.currentPath,"allOf",X?"1":"0"]});return{allOf:[X,Q].filter(($)=>$!==void 0)}};function VN(Y,J){return G0(Y.type._def,J)}function NN(Y,J){let Q={type:"array",uniqueItems:!0,items:G0(Y.valueType._def,{...J,currentPath:[...J.currentPath,"items"]})};if(Y.minSize)Q.minItems=Y.minSize.value;if(Y.maxSize)Q.maxItems=Y.maxSize.value;return Q}function BN(Y,J){if(Y.rest)return{type:"array",minItems:Y.items.length,items:Y.items.map((X,Q)=>G0(X._def,{...J,currentPath:[...J.currentPath,"items",`${Q}`]})).reduce((X,Q)=>Q===void 0?X:[...X,Q],[]),additionalItems:G0(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)=>G0(X._def,{...J,currentPath:[...J.currentPath,"items",`${Q}`]})).reduce((X,Q)=>Q===void 0?X:[...X,Q],[])}}function FN(){return{not:i0()}}function jN(){return i0()}var ON=(Y,J)=>{return G0(Y.innerType._def,J)},qN=(Y,J,X)=>{switch(J){case"ZodString":return mW(Y,X);case"ZodNumber":return zN(Y);case"ZodObject":return KN(Y,X);case"ZodBigInt":return uV(Y);case"ZodBoolean":return pV();case"ZodDate":return fW(Y,X);case"ZodUndefined":return FN();case"ZodNull":return QN();case"ZodArray":return cV(Y,X);case"ZodUnion":case"ZodDiscriminatedUnion":return $N(Y,X);case"ZodIntersection":return sV(Y,X);case"ZodTuple":return BN(Y,X);case"ZodRecord":return cW(Y,X);case"ZodLiteral":return aV(Y);case"ZodEnum":return nV(Y);case"ZodNativeEnum":return JN(Y);case"ZodNullable":return WN(Y,X);case"ZodOptional":return LN(Y,X);case"ZodMap":return YN(Y,X);case"ZodSet":return NN(Y,X);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return VN(Y,X);case"ZodNaN":case"ZodNever":return XN();case"ZodEffects":return oV(Y,X);case"ZodAny":return i0();case"ZodUnknown":return jN();case"ZodDefault":return iV(Y,X);case"ZodBranded":return yW(Y,X);case"ZodReadonly":return ON(Y,X);case"ZodCatch":return lV(Y,X);case"ZodPipeline":return HN(Y,X);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Q)=>{return})(J)}},DN=(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 G0(Y,J,X=!1){var Q;let $=J.seen.get(Y);if(J.override){let Z=(Q=J.override)==null?void 0:Q.call(J,Y,J,$,X);if(Z!==fV)return Z}if($&&!X){let Z=PN($,J);if(Z!==void 0)return Z}let G={def:Y,path:J.currentPath,jsonSchema:void 0};J.seen.set(Y,G);let W=qN(Y,Y.typeName,J),K=typeof W==="function"?G0(W(),J):W;if(K)EN(Y,J,K);if(J.postProcess){let Z=J.postProcess(K,Y,J);return G.jsonSchema=K,Z}return G.jsonSchema=K,K}var PN=(Y,J)=>{switch(J.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:DN(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`),i0();return J.$refStrategy==="seen"?i0():void 0}}},EN=(Y,J,X)=>{if(Y.description)X.description=Y.description;return X},MN=(Y)=>{let J=mV(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,$])=>[$._def,{def:$._def,path:[...J.basePath,J.definitionPath,Q],jsonSchema:void 0}]))}},wN=(Y,J)=>{var X;let Q=MN(J),$=typeof J==="object"&&J.definitions?Object.entries(J.definitions).reduce((U,[L,j])=>{var N;return{...U,[L]:(N=G0(j._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,L]},!0))!=null?N:i0()}},{}):void 0,G=typeof J==="string"?J:(J==null?void 0:J.nameStrategy)==="title"?void 0:J==null?void 0:J.name,W=(X=G0(Y._def,G===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,G]},!1))!=null?X:i0(),K=typeof J==="object"&&J.name!==void 0&&J.nameStrategy==="title"?J.name:void 0;if(K!==void 0)W.title=K;let Z=G===void 0?$?{...W,[Q.definitionPath]:$}:W:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,G].join("/"),[Q.definitionPath]:{...$,[G]:W}};return Z.$schema="http://json-schema.org/draft-07/schema#",Z},bX=Symbol.for("vercel.ai.schema");function YJ(Y){let J;return()=>{if(J==null)J=Y();return J}}function JJ(Y,{validate:J}={}){return{[bX]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:J}}function AN(Y){return typeof Y==="object"&&Y!==null&&bX in Y&&Y[bX]===!0&&"jsonSchema"in Y&&"validate"in Y}function XJ(Y){return Y==null?JJ({type:"object",properties:{},additionalProperties:!1}):AN(Y)?Y:("~standard"in Y)?Y["~standard"].vendor==="zod"?o9(Y):RN(Y):Y()}function RN(Y){return JJ(()=>{if(!TN(Y))throw Error(`Standard schema vendor '${Y["~standard"].vendor}' does not support JSON Schema conversion.`);return yX(Y["~standard"].jsonSchema.input({target:"draft-07"}))},{validate:async(J)=>{let X=await Y["~standard"].validate(J);return"value"in X?{success:!0,value:X.value}:{success:!1,error:new r0({value:J,cause:X.issues})}}})}function TN(Y){return Y["~standard"].jsonSchema!=null}function CN(Y,J){var X;let Q=(X=J==null?void 0:J.useReferences)!=null?X:!1;return JJ(()=>wN(Y,{$refStrategy:Q?"root":"none"}),{validate:async($)=>{let G=await Y.safeParseAsync($);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function _N(Y,J){var X;let Q=(X=J==null?void 0:J.useReferences)!=null?X:!1;return JJ(()=>yX(v7(Y,{target:"draft-7",io:"input",reused:Q?"ref":"inline"})),{validate:async($)=>{let G=await aY(Y,$);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function IN(Y){return"_zod"in Y}function o9(Y,J){if(IN(Y))return _N(Y,J);else return CN(Y,J)}async function H9({value:Y,schema:J,context:X}){let Q=XJ(J);try{if(Q.validate==null)return{success:!0,value:Y,rawValue:Y};let $=await Q.validate(Y);if($.success)return{success:!0,value:$.value,rawValue:Y};return{success:!1,error:r0.wrap({value:Y,cause:$.error,context:X}),rawValue:Y}}catch($){return{success:!1,error:r0.wrap({value:Y,cause:$,context:X}),rawValue:Y}}}async function k1({text:Y,schema:J}){try{let X=yV(Y);if(J==null)return{success:!0,value:X,rawValue:X};return await H9({value:X,schema:J})}catch(X){return{success:!1,error:xY.isInstance(X)?X:new xY({text:Y,cause:X}),rawValue:void 0}}}async function fX(Y){if(typeof Y==="function")Y=Y();return Promise.resolve(Y)}var uW="AI_SerializationError",pW=`vercel.ai.error.${uW}`,SN=Symbol.for(pW),CW,_W,OD=class extends(_W=R,CW=SN,_W){constructor({message:Y="Failed to serialize value.",cause:J}={}){super({name:uW,message:Y,cause:J});this[CW]=!0}static isInstance(Y){return R.hasMarker(Y,pW)}};var bN=Object.defineProperty,vN=(Y,J)=>{for(var X in J)bN(Y,X,{get:J[X],enumerable:!0})},mz="AI_InvalidArgumentError",cz=`vercel.ai.error.${mz}`,hN=Symbol.for(cz),lW,dW,mX=class extends(dW=R,lW=hN,dW){constructor({parameter:Y,value:J,message:X}){super({name:mz,message:`Invalid argument for parameter ${Y}: ${X}`});this[lW]=!0,this.parameter=Y,this.value=J}static isInstance(Y){return R.hasMarker(Y,cz)}},uz="AI_InvalidStreamPartError",pz=`vercel.ai.error.${uz}`,gN=Symbol.for(pz),iW,oW,ID=class extends(oW=R,iW=gN,oW){constructor({chunk:Y,message:J}){super({name:uz,message:J});this[iW]=!0,this.chunk=Y}static isInstance(Y){return R.hasMarker(Y,pz)}},lz="AI_InvalidToolApprovalError",dz=`vercel.ai.error.${lz}`,yN=Symbol.for(dz),nW,rW,kD=class extends(rW=R,nW=yN,rW){constructor({approvalId:Y}){super({name:lz,message:`Tool approval response references unknown approvalId: "${Y}". No matching tool-approval-request found in message history.`});this[nW]=!0,this.approvalId=Y}static isInstance(Y){return R.hasMarker(Y,dz)}},iz="AI_InvalidToolApprovalSignatureError",oz=`vercel.ai.error.${iz}`,fN=Symbol.for(oz),sW,aW,bD=class extends(aW=R,sW=fN,aW){constructor({approvalId:Y,toolCallId:J,reason:X}){super({name:iz,message:`Tool approval signature verification failed for approval "${Y}" (tool call "${J}"): ${X}`});this[sW]=!0,this.approvalId=Y,this.toolCallId=J}static isInstance(Y){return R.hasMarker(Y,oz)}},nz="AI_InvalidToolInputError",rz=`vercel.ai.error.${nz}`,mN=Symbol.for(rz),tW,eW,hD=class extends(eW=R,tW=mN,eW){constructor({toolInput:Y,toolName:J,cause:X,message:Q=`Invalid input for tool ${J}: ${p1(X)}`}){super({name:nz,message:Q,cause:X});this[tW]=!0,this.toolInput=Y,this.toolName=J}static isInstance(Y){return R.hasMarker(Y,rz)}},sz="AI_ToolCallNotFoundForApprovalError",az=`vercel.ai.error.${sz}`,cN=Symbol.for(az),Yz,Jz,yD=class extends(Jz=R,Yz=cN,Jz){constructor({toolCallId:Y,approvalId:J}){super({name:sz,message:`Tool call "${Y}" not found for approval request "${J}".`});this[Yz]=!0,this.toolCallId=Y,this.approvalId=J}static isInstance(Y){return R.hasMarker(Y,az)}},tz="AI_MissingToolResultsError",ez=`vercel.ai.error.${tz}`,uN=Symbol.for(ez),Xz,Qz,mD=class extends(Qz=R,Xz=uN,Qz){constructor({toolCallIds:Y}){super({name:tz,message:`Tool result${Y.length>1?"s are":" is"} missing for tool call${Y.length>1?"s":""} ${Y.join(", ")}.`});this[Xz]=!0,this.toolCallIds=Y}static isInstance(Y){return R.hasMarker(Y,ez)}},YK="AI_NoImageGeneratedError",JK=`vercel.ai.error.${YK}`,pN=Symbol.for(JK),$z,Gz,uD=class extends(Gz=R,$z=pN,Gz){constructor({message:Y="No image generated.",cause:J,calls:X,responses:Q}){super({name:YK,message:Y,cause:J});this[$z]=!0,this.calls=X,this.responses=Q}static isInstance(Y){return R.hasMarker(Y,JK)}},XK="AI_NoObjectGeneratedError",QK=`vercel.ai.error.${XK}`,lN=Symbol.for(QK),Wz,zz,q1=class extends(zz=R,Wz=lN,zz){constructor({message:Y="No object generated.",cause:J,text:X,response:Q,usage:$,finishReason:G}){super({name:XK,message:Y,cause:J});this[Wz]=!0,this.text=X,this.response=Q,this.usage=$,this.finishReason=G}static isInstance(Y){return R.hasMarker(Y,QK)}},$K="AI_NoOutputGeneratedError",GK=`vercel.ai.error.${$K}`,dN=Symbol.for(GK),Kz,Uz,dD=class extends(Uz=R,Kz=dN,Uz){constructor({message:Y="No output generated.",cause:J}={}){super({name:$K,message:Y,cause:J});this[Kz]=!0}static isInstance(Y){return R.hasMarker(Y,GK)}},WK="AI_NoSpeechGeneratedError",zK=`vercel.ai.error.${WK}`,iN=Symbol.for(zK),Zz,Lz,oD=class extends(Lz=R,Zz=iN,Lz){constructor(Y){super({name:WK,message:"No speech audio generated."});this[Zz]=!0,this.responses=Y.responses}static isInstance(Y){return R.hasMarker(Y,zK)}},KK="AI_NoTranscriptGeneratedError",UK=`vercel.ai.error.${KK}`,oN=Symbol.for(UK),Hz,Vz,rD=class extends(Vz=R,Hz=oN,Vz){constructor(Y){super({name:KK,message:"No transcript generated."});this[Hz]=!0,this.responses=Y.responses}static isInstance(Y){return R.hasMarker(Y,UK)}},ZK="AI_NoTranslationGeneratedError",LK=`vercel.ai.error.${ZK}`,nN=Symbol.for(LK),Nz,Bz,aD=class extends(Bz=R,Nz=nN,Bz){constructor(Y){super({name:ZK,message:"No translation generated."});this[Nz]=!0,this.response=Y.response}static isInstance(Y){return R.hasMarker(Y,LK)}},cX="AI_NoVideoGeneratedError",HK=`vercel.ai.error.${cX}`,rN=Symbol.for(HK),Fz,jz,eD=class extends(jz=R,Fz=rN,jz){constructor({message:Y="No video generated.",cause:J,responses:X}){super({name:cX,message:Y,cause:J});this[Fz]=!0,this.responses=X}static isInstance(Y){return R.hasMarker(Y,HK)}static isNoVideoGeneratedError(Y){return Y instanceof Error&&Y.name===cX&&typeof Y.responses<"u"?!0:!1}toJSON(){return{name:this.name,message:this.message,stack:this.stack,cause:this.cause,responses:this.responses}}},VK="AI_NoSuchToolError",NK=`vercel.ai.error.${VK}`,sN=Symbol.for(NK),Oz,qz,JP=class extends(qz=R,Oz=sN,qz){constructor({toolName:Y,availableTools:J=void 0,message:X=`Model tried to call unavailable tool '${Y}'. ${J===void 0?"No tools are available.":`Available tools: ${J.join(", ")}.`}`}){super({name:VK,message:X});this[Oz]=!0,this.toolName=Y,this.availableTools=J}static isInstance(Y){return R.hasMarker(Y,NK)}},BK="AI_StreamProviderError",FK=`vercel.ai.error.${BK}`,aN=Symbol.for(FK),Dz,Pz,QP=class extends(Pz=R,Dz=aN,Pz){constructor({message:Y,type:J,code:X,statusCode:Q,isRetryable:$=tN(Q),data:G,cause:W}){super({name:BK,message:Y,cause:W});this[Dz]=!0,this.type=J,this.code=X,this.statusCode=Q,this.isRetryable=$,this.data=G}static isInstance(Y){return R.hasMarker(Y,FK)}};function tN(Y){return Y!=null&&(Y===408||Y===409||Y===429||Y>=500)}var jK="AI_ToolCallRepairError",OK=`vercel.ai.error.${jK}`,eN=Symbol.for(OK),Ez,Mz,GP=class extends(Mz=R,Ez=eN,Mz){constructor({cause:Y,originalError:J,message:X=`Error repairing tool call: ${p1(Y)}`}){super({name:jK,message:X,cause:Y});this[Ez]=!0,this.originalError=J}static isInstance(Y){return R.hasMarker(Y,OK)}},qK="AI_ToolChoiceViolationError",DK=`vercel.ai.error.${qK}`,YB=Symbol.for(DK),wz,Az,zP=class extends(Az=R,wz=YB,Az){constructor({toolChoice:Y,finishReason:J,provider:X,modelId:Q,content:$,message:G=Y.type==="required"?"Model response did not contain a tool call even though tool choice was required.":`Model response did not contain a call to the required tool '${Y.toolName}'.`}){super({name:qK,message:G});this[wz]=!0,this.toolChoice=Y,this.finishReason=J,this.provider=X,this.modelId=Q,this.content=$}static isInstance(Y){return R.hasMarker(Y,DK)}};var PK="AI_UIMessageStreamError",EK=`vercel.ai.error.${PK}`,JB=Symbol.for(EK),Rz,Tz,UP=class extends(Tz=R,Rz=JB,Tz){constructor({chunkType:Y,chunkId:J,message:X}){super({name:PK,message:X});this[Rz]=!0,this.chunkType=Y,this.chunkId=J}static isInstance(Y){return R.hasMarker(Y,EK)}},MK="AI_InvalidDataContentError",wK=`vercel.ai.error.${MK}`,XB=Symbol.for(wK),Cz,_z,LP=class extends(_z=R,Cz=XB,_z){constructor({content:Y,cause:J,message:X=`Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof Y}.`}){super({name:MK,message:X,cause:J});this[Cz]=!0,this.content=Y}static isInstance(Y){return R.hasMarker(Y,wK)}},AK="AI_InvalidMessageRoleError",RK=`vercel.ai.error.${AK}`,QB=Symbol.for(RK),Iz,Sz,VP=class extends(Sz=R,Iz=QB,Sz){constructor({role:Y,message:J=`Invalid message role: '${Y}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:AK,message:J});this[Iz]=!0,this.role=Y}static isInstance(Y){return R.hasMarker(Y,RK)}},TK="AI_MessageConversionError",CK=`vercel.ai.error.${TK}`,$B=Symbol.for(CK),kz,xz,BP=class extends(xz=R,kz=$B,xz){constructor({originalMessage:Y,message:J}){super({name:TK,message:J});this[kz]=!0,this.originalMessage=Y}static isInstance(Y){return R.hasMarker(Y,CK)}},_K="AI_RetryError",IK=`vercel.ai.error.${_K}`,GB=Symbol.for(IK),bz,vz,jP=class extends(vz=R,bz=GB,vz){constructor({message:Y,reason:J,errors:X}){super({name:_K,message:Y});this[bz]=!0,this.reason=J,this.errors=X,this.lastError=X[X.length-1]}static isInstance(Y){return R.hasMarker(Y,IK)}};var WB="7.0.111",zB=async({url:Y,maxBytes:J,abortSignal:X})=>{var Q;let $=Y.toString();try{let G=o1({},`ai-sdk/${WB}`,IW()),W=await vW({url:$,headers:G,abortSignal:X});if(!W.ok)throw await eY(W),new b0({url:$,statusCode:W.status,statusText:W.statusText});return{data:await hW({response:W,url:$,maxBytes:J!=null?J:gX}),mediaType:(Q=W.headers.get("content-type"))!=null?Q:void 0}}catch(G){if(b0.isInstance(G))throw G;throw new b0({url:$,cause:G})}};var z={array:RX,boolean:zW,custom:qW,discriminatedUnion:VW,enum:CX,instanceof:DW,lazy:OW,literal:BW,looseObject:LW,never:AX,null:KW,number:WW,object:ZW,record:NW,string:$W,union:TX,unknown:i9},n1=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),n1.optional()),z.array(n1)])),g=z.record(z.string(),z.record(z.string(),n1.optional())),r9=z.union([z.string(),z.instanceof(Uint8Array),z.instanceof(ArrayBuffer),z.custom(gW,{message:"Must be a Buffer"})]),uX=z.record(z.string(),z.string()),SK=z.object({type:z.literal("text"),text:z.string(),providerOptions:g.optional()}),KB=z.object({type:z.literal("image"),image:z.union([r9,z.instanceof(URL),uX]),mediaType:z.string().optional(),providerOptions:g.optional()}),kK=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:r9}),z.object({type:z.literal("url"),url:z.instanceof(URL)}),z.object({type:z.literal("reference"),reference:uX}),z.object({type:z.literal("text"),text:z.string()})]),UB=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:r9}),z.object({type:z.literal("url"),url:z.instanceof(URL)})]),xK=z.object({type:z.literal("file"),data:z.union([kK,r9,z.instanceof(URL),uX]),filename:z.string().optional(),mediaType:z.string(),providerOptions:g.optional()}),ZB=z.object({type:z.literal("reasoning"),text:z.string(),providerOptions:g.optional()}),LB=z.object({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerOptions:g.optional()}),HB=z.object({type:z.literal("reasoning-file"),data:z.union([UB,r9,z.instanceof(URL)]),mediaType:z.string(),providerOptions:g.optional()}),VB=z.object({type:z.literal("tool-call"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerOptions:g.optional(),providerExecuted:z.boolean().optional()}),NB=z.discriminatedUnion("type",[z.object({type:z.literal("text"),value:z.string(),providerOptions:g.optional()}),z.object({type:z.literal("json"),value:n1,providerOptions:g.optional()}),z.object({type:z.literal("execution-denied"),reason:z.string().optional(),providerOptions:g.optional()}),z.object({type:z.literal("error-text"),value:z.string(),providerOptions:g.optional()}),z.object({type:z.literal("error-json"),value:n1,providerOptions:g.optional()}),z.object({type:z.literal("content"),value:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),providerOptions:g.optional()}),z.object({type:z.literal("file"),data:kK,mediaType:z.string(),filename:z.string().optional(),providerOptions:g.optional()}),z.object({type:z.literal("file-data"),data:z.string(),mediaType:z.string(),filename:z.string().optional(),providerOptions:g.optional()}),z.object({type:z.literal("file-url"),url:z.string(),mediaType:z.string().optional(),providerOptions:g.optional()}),z.object({type:z.literal("file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:g.optional()}),z.object({type:z.literal("file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:g.optional()}),z.object({type:z.literal("image-data"),data:z.string(),mediaType:z.string(),providerOptions:g.optional()}),z.object({type:z.literal("image-url"),url:z.string(),providerOptions:g.optional()}),z.object({type:z.literal("image-file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:g.optional()}),z.object({type:z.literal("image-file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:g.optional()}),z.object({type:z.literal("custom"),providerOptions:g.optional()})]))})]),bK=z.object({type:z.literal("tool-result"),toolCallId:z.string(),toolName:z.string(),output:NB,providerOptions:g.optional()}),BB=z.object({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string(),reason:z.string().optional()}),FB=z.object({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional()}),jB=z.object({role:z.literal("system"),content:z.string(),providerOptions:g.optional()}),OB=z.object({role:z.literal("user"),content:z.union([z.string(),z.array(z.union([SK,KB,xK]))]),providerOptions:g.optional()}),qB=z.object({role:z.literal("assistant"),content:z.union([z.string(),z.array(z.union([SK,LB,xK,ZB,HB,VB,bK,BB]))]),providerOptions:g.optional()}),DB=z.object({role:z.literal("tool"),content:z.array(z.union([bK,FB])),providerOptions:g.optional()}),PP=z.union([jB,OB,qB,DB]);var PB={};vN(PB,{array:()=>AB,choice:()=>RB,json:()=>TB,object:()=>wB,text:()=>MB});function EB(Y){let J=["ROOT"],X=-1,Q=null,$=0;function G(L){return L>="0"&&L<="9"||L>="A"&&L<="F"||L>="a"&&L<="f"}function W(L,j,N){switch(L){case'"':{X=j,J.pop(),J.push(N),J.push("INSIDE_STRING");break}case"f":case"t":case"n":{X=j,Q=j,J.pop(),J.push(N),J.push("INSIDE_LITERAL");break}case"-":{J.pop(),J.push(N),J.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{X=j,J.pop(),J.push(N),J.push("INSIDE_NUMBER");break}case"{":{X=j,J.pop(),J.push(N),J.push("INSIDE_OBJECT_START");break}case"[":{X=j,J.pop(),J.push(N),J.push("INSIDE_ARRAY_START");break}}}function K(L,j){switch(L){case",":{J.pop(),J.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{X=j,J.pop();break}}}function Z(L,j){switch(L){case",":{J.pop(),J.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{X=j,J.pop();break}}}for(let L=0;L<Y.length;L++){let j=Y[L];switch(J[J.length-1]){case"ROOT":W(j,L,"FINISH");break;case"INSIDE_OBJECT_START":{switch(j){case'"':{J.pop(),J.push("INSIDE_OBJECT_KEY");break}case"}":{X=L,J.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(j){case'"':{J.pop(),J.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(j){case'"':{J.pop(),J.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(j){case":":{J.pop(),J.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{W(j,L,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{K(j,L);break}case"INSIDE_STRING":{switch(j){case'"':{J.pop(),X=L;break}case"\\":{J.push("INSIDE_STRING_ESCAPE");break}default:X=L}break}case"INSIDE_ARRAY_START":{switch(j){case"]":{X=L,J.pop();break}default:{X=L,W(j,L,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(j){case",":{J.pop(),J.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{X=L,J.pop();break}default:{X=L;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{W(j,L,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{if(J.pop(),j==="u")$=0,J.push("INSIDE_STRING_UNICODE_ESCAPE");else X=L;break}case"INSIDE_STRING_UNICODE_ESCAPE":{if(G(j)){if($++,$===4)J.pop(),X=L}break}case"INSIDE_NUMBER":{switch(j){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{X=L;break}case"e":case"E":case"-":case".":break;case",":{if(J.pop(),J[J.length-1]==="INSIDE_ARRAY_AFTER_VALUE")Z(j,L);if(J[J.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(j,L);break}case"}":{if(J.pop(),J[J.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(j,L);break}case"]":{if(J.pop(),J[J.length-1]==="INSIDE_ARRAY_AFTER_VALUE")Z(j,L);break}default:{J.pop();break}}break}case"INSIDE_LITERAL":{let V=Y.substring(Q,L+1);if(!"false".startsWith(V)&&!"true".startsWith(V)&&!"null".startsWith(V)){if(J.pop(),J[J.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(j,L);else if(J[J.length-1]==="INSIDE_ARRAY_AFTER_VALUE")Z(j,L)}else X=L;break}}}let U=Y.slice(0,X+1);for(let L=J.length-1;L>=0;L--)switch(J[L]){case"INSIDE_STRING":{U+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{U+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{U+="]";break}case"INSIDE_LITERAL":{let N=Y.substring(Q,Y.length);if("true".startsWith(N))U+="true".slice(N.length);else if("false".startsWith(N))U+="false".slice(N.length);else if("null".startsWith(N))U+="null".slice(N.length)}}return U}async function QJ(Y){if(Y===void 0)return{value:void 0,state:"undefined-input"};let J=await k1({text:Y});if(J.success)return{value:J.value,state:"successful-parse"};if(J=await k1({text:EB(Y)}),J.success)return{value:J.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var MB=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:Y}){return Y},async parsePartialOutput({text:Y}){return{partial:Y}},createElementStreamTransform(){return}}),wB=({schema:Y,name:J,description:X})=>{let Q=XJ(Y);return{name:"object",responseFormat:fX(Q.jsonSchema).then(($)=>({type:"json",schema:$,...J!=null&&{name:J},...X!=null&&{description:X}})),async parseCompleteOutput({text:$},G){let W=await k1({text:$});if(!W.success)throw new q1({message:"No object generated: could not parse the response.",cause:W.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let K=await H9({value:W.value,schema:Q});if(!K.success)throw new q1({message:"No object generated: response did not match schema.",cause:K.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});return K.value},async parsePartialOutput({text:$}){let G=await QJ($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:G.value}}},createElementStreamTransform(){return}}},AB=({element:Y,minItems:J,maxItems:X,name:Q,description:$})=>{if(hz({name:"minItems",value:J}),hz({name:"maxItems",value:X}),J!=null&&X!=null&&J>X)throw new mX({parameter:"minItems",value:J,message:"minItems must be less than or equal to maxItems"});let G=XJ(Y);return{name:"array",responseFormat:fX(G.jsonSchema).then((W)=>{let{$schema:K,definitions:Z,$defs:U,...L}=W;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",...Z!=null&&{definitions:Z},...U!=null&&{$defs:U},type:"object",properties:{elements:{type:"array",items:L,...J!=null&&{minItems:J},...X!=null&&{maxItems:X}}},required:["elements"],additionalProperties:!1},...Q!=null&&{name:Q},...$!=null&&{description:$}}}),async parseCompleteOutput({text:W},K){let Z=await k1({text:W});if(!Z.success)throw new q1({message:"No object generated: could not parse the response.",cause:Z.error,text:W,response:K.response,usage:K.usage,finishReason:K.finishReason});let U=Z.value;if(U==null||typeof U!=="object"||!("elements"in U)||!Array.isArray(U.elements))throw new q1({message:"No object generated: response did not match schema.",cause:new r0({value:U,cause:"response must be an object with an elements array"}),text:W,response:K.response,usage:K.usage,finishReason:K.finishReason});let L=gz({value:U.elements,minItems:J,maxItems:X});if(L!=null)throw new q1({message:"No object generated: response did not match schema.",cause:L,text:W,response:K.response,usage:K.usage,finishReason:K.finishReason});let j=[];for(let N of U.elements){let V=await H9({value:N,schema:G});if(!V.success)throw new q1({message:"No object generated: response did not match schema.",cause:V.error,text:W,response:K.response,usage:K.usage,finishReason:K.finishReason});j.push(V.value)}return j},async parsePartialOutput({text:W}){let K=await QJ(W);switch(K.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let Z=K.value;if(Z==null||typeof Z!=="object"||!("elements"in Z)||!Array.isArray(Z.elements))return;let U=K.state==="repaired-parse"&&Z.elements.length>0?Z.elements.slice(0,-1):Z.elements,L=[];for(let j of U){let N=await H9({value:j,schema:G});if(N.success)L.push(N.value)}return{partial:L}}}},createElementStreamTransform(){let W=0;return new TransformStream({transform({partialOutput:K},Z){if(K!=null)for(;W<K.length;W++){if(X!=null&&W>=X){Z.error(gz({value:K,maxItems:X}));return}Z.enqueue(K[W])}}})}}};function hz({name:Y,value:J}){if(J==null)return;if(!Number.isInteger(J))throw new mX({parameter:Y,value:J,message:`${Y} must be an integer`});if(J<0)throw new mX({parameter:Y,value:J,message:`${Y} must be greater than or equal to 0`})}function gz({value:Y,minItems:J,maxItems:X}){if(J!=null&&Y.length<J)return new r0({value:Y,cause:`elements array must contain at least ${J} items`});if(X!=null&&Y.length>X)return new r0({value:Y,cause:`elements array must contain at most ${X} items`});return}var RB=({options:Y,name:J,description:X})=>{return{name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:Y}},required:["result"],additionalProperties:!1},...J!=null&&{name:J},...X!=null&&{description:X}}),async parseCompleteOutput({text:Q},$){let G=await k1({text:Q});if(!G.success)throw new q1({message:"No object generated: could not parse the response.",cause:G.error,text:Q,response:$.response,usage:$.usage,finishReason:$.finishReason});let W=G.value;if(W==null||typeof W!=="object"||!("result"in W)||typeof W.result!=="string"||!Y.includes(W.result))throw new q1({message:"No object generated: response did not match schema.",cause:new r0({value:W,cause:"response must be an object that contains a choice value."}),text:Q,response:$.response,usage:$.usage,finishReason:$.finishReason});return W.result},async parsePartialOutput({text:Q}){let $=await QJ(Q);switch($.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let G=$.value;if(G==null||typeof G!=="object"||!("result"in G)||typeof G.result!=="string")return;let W=Y.filter((K)=>K.startsWith(G.result));if($.state==="successful-parse")return W.includes(G.result)?{partial:G.result}:void 0;else return W.length===1?{partial:W[0]}:void 0}}},createElementStreamTransform(){return}}},TB=({name:Y,description:J}={})=>{return{name:"json",responseFormat:Promise.resolve({type:"json",...Y!=null&&{name:Y},...J!=null&&{description:J}}),async parseCompleteOutput({text:X},Q){let $=await k1({text:X});if(!$.success)throw new q1({message:"No object generated: could not parse the response.",cause:$.error,text:X,response:Q.response,usage:Q.usage,finishReason:Q.finishReason});return $.value},async parsePartialOutput({text:X}){let Q=await QJ(X);switch(Q.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return Q.value===void 0?void 0:{partial:Q.value}}},createElementStreamTransform(){return}}};var AP=F0({prefix:"aitxt",size:24}),RP=F0({prefix:"call",size:24});var CP=class extends TransformStream{constructor(){super({transform(Y,J){J.enqueue(`data: ${JSON.stringify(Y)}
|
|
81
|
+
]`;continue}if(G+=$[U],$[U]==="\\")W=!0;else if(K&&$[U]==="]")K=!1;else if(!K&&$[U]==="[")K=!0}try{new RegExp(G)}catch(U){return console.warn(`Could not convert regex pattern at ${X.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Y.source}return G}function SW(Y,X){var J,Q,$,G,W,K;let H={type:"object",additionalProperties:(J=W0(Y.valueType._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]}))!=null?J:X.allowedAdditionalProperties};if(((Q=Y.keyType)==null?void 0:Q._def.typeName)==="ZodString"&&(($=Y.keyType._def.checks)==null?void 0:$.length)){let{type:U,...Z}=IW(Y.keyType._def,X);return{...H,propertyNames:Z}}else if(((G=Y.keyType)==null?void 0:G._def.typeName)==="ZodEnum")return{...H,propertyNames:{enum:Y.keyType._def.values}};else if(((W=Y.keyType)==null?void 0:W._def.typeName)==="ZodBranded"&&Y.keyType._def.type._def.typeName==="ZodString"&&((K=Y.keyType._def.type._def.checks)==null?void 0:K.length)){let{type:U,...Z}=CW(Y.keyType._def,X);return{...H,propertyNames:Z}}return H}function hV(Y,X){if(X.mapStrategy==="record")return SW(Y,X);let J=W0(Y.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||n0(),Q=W0(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||n0();return{type:"array",maxItems:125,items:{type:"array",items:[J,Q],minItems:2,maxItems:2}}}function gV(Y){let X=Y.values,Q=Object.keys(Y.values).filter((G)=>{return typeof X[X[G]]!=="number"}).map((G)=>X[G]),$=Array.from(new Set(Q.map((G)=>typeof G)));return{type:$.length===1?$[0]==="string"?"string":"number":["string","number"],enum:Q}}function yV(){return{not:n0()}}function fV(){return{type:"null"}}var _J={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function mV(Y,X){let J=Y.options instanceof Map?Array.from(Y.options.values()):Y.options;if(J.every((Q)=>(Q._def.typeName in _J)&&(!Q._def.checks||!Q._def.checks.length))){let Q=J.reduce(($,G)=>{let W=_J[G._def.typeName];return W&&!$.includes(W)?[...$,W]:$},[]);return{type:Q.length>1?Q:Q[0]}}else if(J.every((Q)=>Q._def.typeName==="ZodLiteral"&&!Q.description)){let Q=J.reduce(($,G)=>{let W=typeof G._def.value;switch(W){case"string":case"number":case"boolean":return[...$,W];case"bigint":return[...$,"integer"];case"object":if(G._def.value===null)return[...$,"null"];case"symbol":case"undefined":case"function":default:return $}},[]);if(Q.length===J.length){let $=Q.filter((G,W,K)=>K.indexOf(G)===W);return{type:$.length>1?$:$[0],enum:J.reduce((G,W)=>{return G.includes(W._def.value)?G:[...G,W._def.value]},[])}}}else if(J.every((Q)=>Q._def.typeName==="ZodEnum"))return{type:"string",enum:J.reduce((Q,$)=>[...Q,...$._def.values.filter((G)=>!Q.includes(G))],[])};return cV(Y,X)}var cV=(Y,X)=>{let J=(Y.options instanceof Map?Array.from(Y.options.values()):Y.options).map((Q,$)=>W0(Q._def,{...X,currentPath:[...X.currentPath,"anyOf",`${$}`]})).filter((Q)=>!!Q&&(!X.strictUnions||typeof Q==="object"&&Object.keys(Q).length>0));return J.length?{anyOf:J}:void 0};function uV(Y,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Y.innerType._def.typeName)&&(!Y.innerType._def.checks||!Y.innerType._def.checks.length))return{type:[_J[Y.innerType._def.typeName],"null"]};let J=W0(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return J&&{anyOf:[J,{type:"null"}]}}function pV(Y){let X={type:"number"};if(!Y.checks)return X;for(let J of Y.checks)switch(J.kind){case"int":X.type="integer";break;case"min":if(J.inclusive)X.minimum=J.value;else X.exclusiveMinimum=J.value;break;case"max":if(J.inclusive)X.maximum=J.value;else X.exclusiveMaximum=J.value;break;case"multipleOf":X.multipleOf=J.value;break}return X}function lV(Y,X){let J={type:"object",properties:{}},Q=[],$=Y.shape();for(let W in $){let K=$[W];if(K===void 0||K._def===void 0)continue;let H=iV(K),U=W0(K._def,{...X,currentPath:[...X.currentPath,"properties",W],propertyPath:[...X.currentPath,"properties",W]});if(U===void 0)continue;if(J.properties[W]=U,!H)Q.push(W)}if(Q.length)J.required=Q;let G=dV(Y,X);if(G!==void 0)J.additionalProperties=G;return J}function dV(Y,X){if(Y.catchall._def.typeName!=="ZodNever")return W0(Y.catchall._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]});switch(Y.unknownKeys){case"passthrough":return X.allowedAdditionalProperties;case"strict":return X.rejectedAdditionalProperties;case"strip":return X.removeAdditionalStrategy==="strict"?X.allowedAdditionalProperties:X.rejectedAdditionalProperties}}function iV(Y){try{return Y.isOptional()}catch(X){return!0}}var nV=(Y,X)=>{var J;if(X.currentPath.toString()===((J=X.propertyPath)==null?void 0:J.toString()))return W0(Y.innerType._def,X);let Q=W0(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return Q?{anyOf:[{not:n0()},Q]}:n0()},oV=(Y,X)=>{if(X.pipeStrategy==="input")return W0(Y.in._def,X);else if(X.pipeStrategy==="output")return W0(Y.out._def,X);let J=W0(Y.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),Q=W0(Y.out._def,{...X,currentPath:[...X.currentPath,"allOf",J?"1":"0"]});return{allOf:[J,Q].filter(($)=>$!==void 0)}};function rV(Y,X){return W0(Y.type._def,X)}function sV(Y,X){let Q={type:"array",uniqueItems:!0,items:W0(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items"]})};if(Y.minSize)Q.minItems=Y.minSize.value;if(Y.maxSize)Q.maxItems=Y.maxSize.value;return Q}function aV(Y,X){if(Y.rest)return{type:"array",minItems:Y.items.length,items:Y.items.map((J,Q)=>W0(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[]),additionalItems:W0(Y.rest._def,{...X,currentPath:[...X.currentPath,"additionalItems"]})};else return{type:"array",minItems:Y.items.length,maxItems:Y.items.length,items:Y.items.map((J,Q)=>W0(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[])}}function tV(){return{not:n0()}}function eV(){return n0()}var YN=(Y,X)=>{return W0(Y.innerType._def,X)},XN=(Y,X,J)=>{switch(X){case"ZodString":return IW(Y,J);case"ZodNumber":return pV(Y);case"ZodObject":return lV(Y,J);case"ZodBigInt":return wV(Y);case"ZodBoolean":return AV();case"ZodDate":return _W(Y,J);case"ZodUndefined":return tV();case"ZodNull":return fV();case"ZodArray":return MV(Y,J);case"ZodUnion":case"ZodDiscriminatedUnion":return mV(Y,J);case"ZodIntersection":return kV(Y,J);case"ZodTuple":return aV(Y,J);case"ZodRecord":return SW(Y,J);case"ZodLiteral":return xV(Y);case"ZodEnum":return IV(Y);case"ZodNativeEnum":return gV(Y);case"ZodNullable":return uV(Y,J);case"ZodOptional":return nV(Y,J);case"ZodMap":return hV(Y,J);case"ZodSet":return sV(Y,J);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return rV(Y,J);case"ZodNaN":case"ZodNever":return yV();case"ZodEffects":return _V(Y,J);case"ZodAny":return n0();case"ZodUnknown":return eV();case"ZodDefault":return CV(Y,J);case"ZodBranded":return CW(Y,J);case"ZodReadonly":return YN(Y,J);case"ZodCatch":return RV(Y,J);case"ZodPipeline":return oV(Y,J);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Q)=>{return})(X)}},JN=(Y,X)=>{let J=0;for(;J<Y.length&&J<X.length;J++)if(Y[J]!==X[J])break;return[(Y.length-J).toString(),...X.slice(J)].join("/")};function W0(Y,X,J=!1){var Q;let $=X.seen.get(Y);if(X.override){let H=(Q=X.override)==null?void 0:Q.call(X,Y,X,$,J);if(H!==PV)return H}if($&&!J){let H=QN($,X);if(H!==void 0)return H}let G={def:Y,path:X.currentPath,jsonSchema:void 0};X.seen.set(Y,G);let W=XN(Y,Y.typeName,X),K=typeof W==="function"?W0(W(),X):W;if(K)$N(Y,X,K);if(X.postProcess){let H=X.postProcess(K,Y,X);return G.jsonSchema=K,H}return G.jsonSchema=K,K}var QN=(Y,X)=>{switch(X.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:JN(X.currentPath,Y.path)};case"none":case"seen":{if(Y.path.length<X.currentPath.length&&Y.path.every((J,Q)=>X.currentPath[Q]===J))return console.warn(`Recursive reference detected at ${X.currentPath.join("/")}! Defaulting to any`),n0();return X.$refStrategy==="seen"?n0():void 0}}},$N=(Y,X,J)=>{if(Y.description)J.description=Y.description;return J},GN=(Y)=>{let X=EV(Y),J=X.name!==void 0?[...X.basePath,X.definitionPath,X.name]:X.basePath;return{...X,currentPath:J,propertyPath:void 0,seen:new Map(Object.entries(X.definitions).map(([Q,$])=>[$._def,{def:$._def,path:[...X.basePath,X.definitionPath,Q],jsonSchema:void 0}]))}},WN=(Y,X)=>{var J;let Q=GN(X),$=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((U,[Z,F])=>{var N;return{...U,[Z]:(N=W0(F._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,Z]},!0))!=null?N:n0()}},{}):void 0,G=typeof X==="string"?X:(X==null?void 0:X.nameStrategy)==="title"?void 0:X==null?void 0:X.name,W=(J=W0(Y._def,G===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,G]},!1))!=null?J:n0(),K=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if(K!==void 0)W.title=K;let H=G===void 0?$?{...W,[Q.definitionPath]:$}:W:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,G].join("/"),[Q.definitionPath]:{...$,[G]:W}};return H.$schema="http://json-schema.org/draft-07/schema#",H},IJ=Symbol.for("vercel.ai.schema");function eY(Y){let X;return()=>{if(X==null)X=Y();return X}}function YX(Y,{validate:X}={}){return{[IJ]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:X}}function zN(Y){return typeof Y==="object"&&Y!==null&&IJ in Y&&Y[IJ]===!0&&"jsonSchema"in Y&&"validate"in Y}function XX(Y){return Y==null?YX({type:"object",properties:{},additionalProperties:!1}):zN(Y)?Y:("~standard"in Y)?Y["~standard"].vendor==="zod"?n9(Y):KN(Y):Y()}function KN(Y){return YX(()=>{if(!UN(Y))throw Error(`Standard schema vendor '${Y["~standard"].vendor}' does not support JSON Schema conversion.`);return bJ(Y["~standard"].jsonSchema.input({target:"draft-07"}))},{validate:async(X)=>{let J=await Y["~standard"].validate(X);return"value"in J?{success:!0,value:J.value}:{success:!1,error:new t0({value:X,cause:J.issues})}}})}function UN(Y){return Y["~standard"].jsonSchema!=null}function HN(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return YX(()=>WN(Y,{$refStrategy:Q?"root":"none"}),{validate:async($)=>{let G=await Y.safeParseAsync($);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function ZN(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return YX(()=>bJ(A7(Y,{target:"draft-7",io:"input",reused:Q?"ref":"inline"})),{validate:async($)=>{let G=await sY(Y,$);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function LN(Y){return"_zod"in Y}function n9(Y,X){if(LN(Y))return ZN(Y,X);else return HN(Y,X)}async function V9({value:Y,schema:X,context:J}){let Q=XX(X);try{if(Q.validate==null)return{success:!0,value:Y,rawValue:Y};let $=await Q.validate(Y);if($.success)return{success:!0,value:$.value,rawValue:Y};return{success:!1,error:t0.wrap({value:Y,cause:$.error,context:J}),rawValue:Y}}catch($){return{success:!1,error:t0.wrap({value:Y,cause:$,context:J}),rawValue:Y}}}async function k1({text:Y,schema:X}){try{let J=DV(Y);if(X==null)return{success:!0,value:J,rawValue:J};return await V9({value:J,schema:X})}catch(J){return{success:!1,error:kY.isInstance(J)?J:new kY({text:Y,cause:J}),rawValue:void 0}}}async function vJ(Y){if(typeof Y==="function")Y=Y();return Promise.resolve(Y)}var kW="AI_SerializationError",xW=`vercel.ai.error.${kW}`,VN=Symbol.for(xW),jW,qW,o6=class extends(qW=A,jW=VN,qW){constructor({message:Y="Failed to serialize value.",cause:X}={}){super({name:kW,message:Y,cause:X});this[jW]=!0}static isInstance(Y){return A.hasMarker(Y,xW)}};var FN=Object.defineProperty,ON=(Y,X)=>{for(var J in X)FN(Y,J,{get:X[J],enumerable:!0})},Iz="AI_InvalidArgumentError",Sz=`vercel.ai.error.${Iz}`,jN=Symbol.for(Sz),bW,vW,hJ=class extends(vW=A,bW=jN,vW){constructor({parameter:Y,value:X,message:J}){super({name:Iz,message:`Invalid argument for parameter ${Y}: ${J}`});this[bW]=!0,this.parameter=Y,this.value=X}static isInstance(Y){return A.hasMarker(Y,Sz)}},kz="AI_InvalidStreamPartError",xz=`vercel.ai.error.${kz}`,qN=Symbol.for(xz),hW,gW,WD=class extends(gW=A,hW=qN,gW){constructor({chunk:Y,message:X}){super({name:kz,message:X});this[hW]=!0,this.chunk=Y}static isInstance(Y){return A.hasMarker(Y,xz)}},bz="AI_InvalidToolApprovalError",vz=`vercel.ai.error.${bz}`,DN=Symbol.for(vz),yW,fW,KD=class extends(fW=A,yW=DN,fW){constructor({approvalId:Y}){super({name:bz,message:`Tool approval response references unknown approvalId: "${Y}". No matching tool-approval-request found in message history.`});this[yW]=!0,this.approvalId=Y}static isInstance(Y){return A.hasMarker(Y,vz)}},hz="AI_InvalidToolApprovalSignatureError",gz=`vercel.ai.error.${hz}`,PN=Symbol.for(gz),mW,cW,HD=class extends(cW=A,mW=PN,cW){constructor({approvalId:Y,toolCallId:X,reason:J}){super({name:hz,message:`Tool approval signature verification failed for approval "${Y}" (tool call "${X}"): ${J}`});this[mW]=!0,this.approvalId=Y,this.toolCallId=X}static isInstance(Y){return A.hasMarker(Y,gz)}},yz="AI_InvalidToolInputError",fz=`vercel.ai.error.${yz}`,EN=Symbol.for(fz),uW,pW,LD=class extends(pW=A,uW=EN,pW){constructor({toolInput:Y,toolName:X,cause:J,message:Q=`Invalid input for tool ${X}: ${d1(J)}`}){super({name:yz,message:Q,cause:J});this[uW]=!0,this.toolInput=Y,this.toolName=X}static isInstance(Y){return A.hasMarker(Y,fz)}},mz="AI_ToolCallNotFoundForApprovalError",cz=`vercel.ai.error.${mz}`,MN=Symbol.for(cz),lW,dW,ND=class extends(dW=A,lW=MN,dW){constructor({toolCallId:Y,approvalId:X}){super({name:mz,message:`Tool call "${Y}" not found for approval request "${X}".`});this[lW]=!0,this.toolCallId=Y,this.approvalId=X}static isInstance(Y){return A.hasMarker(Y,cz)}},uz="AI_MissingToolResultsError",pz=`vercel.ai.error.${uz}`,wN=Symbol.for(pz),iW,nW,FD=class extends(nW=A,iW=wN,nW){constructor({toolCallIds:Y}){super({name:uz,message:`Tool result${Y.length>1?"s are":" is"} missing for tool call${Y.length>1?"s":""} ${Y.join(", ")}.`});this[iW]=!0,this.toolCallIds=Y}static isInstance(Y){return A.hasMarker(Y,pz)}},lz="AI_NoImageGeneratedError",dz=`vercel.ai.error.${lz}`,AN=Symbol.for(dz),oW,rW,jD=class extends(rW=A,oW=AN,rW){constructor({message:Y="No image generated.",cause:X,calls:J,responses:Q}){super({name:lz,message:Y,cause:X});this[oW]=!0,this.calls=J,this.responses=Q}static isInstance(Y){return A.hasMarker(Y,dz)}},iz="AI_NoObjectGeneratedError",nz=`vercel.ai.error.${iz}`,RN=Symbol.for(nz),sW,aW,j1=class extends(aW=A,sW=RN,aW){constructor({message:Y="No object generated.",cause:X,text:J,response:Q,usage:$,finishReason:G}){super({name:iz,message:Y,cause:X});this[sW]=!0,this.text=J,this.response=Q,this.usage=$,this.finishReason=G}static isInstance(Y){return A.hasMarker(Y,nz)}},oz="AI_NoOutputGeneratedError",rz=`vercel.ai.error.${oz}`,TN=Symbol.for(rz),tW,eW,PD=class extends(eW=A,tW=TN,eW){constructor({message:Y="No output generated.",cause:X}={}){super({name:oz,message:Y,cause:X});this[tW]=!0}static isInstance(Y){return A.hasMarker(Y,rz)}},sz="AI_NoSpeechGeneratedError",az=`vercel.ai.error.${sz}`,CN=Symbol.for(az),Yz,Xz,MD=class extends(Xz=A,Yz=CN,Xz){constructor(Y){super({name:sz,message:"No speech audio generated."});this[Yz]=!0,this.responses=Y.responses}static isInstance(Y){return A.hasMarker(Y,az)}},tz="AI_NoTranscriptGeneratedError",ez=`vercel.ai.error.${tz}`,_N=Symbol.for(ez),Jz,Qz,AD=class extends(Qz=A,Jz=_N,Qz){constructor(Y){super({name:tz,message:"No transcript generated."});this[Jz]=!0,this.responses=Y.responses}static isInstance(Y){return A.hasMarker(Y,ez)}},YK="AI_NoTranslationGeneratedError",XK=`vercel.ai.error.${YK}`,IN=Symbol.for(XK),$z,Gz,TD=class extends(Gz=A,$z=IN,Gz){constructor(Y){super({name:YK,message:"No translation generated."});this[$z]=!0,this.response=Y.response}static isInstance(Y){return A.hasMarker(Y,XK)}},gJ="AI_NoVideoGeneratedError",JK=`vercel.ai.error.${gJ}`,SN=Symbol.for(JK),Wz,zz,_D=class extends(zz=A,Wz=SN,zz){constructor({message:Y="No video generated.",cause:X,responses:J}){super({name:gJ,message:Y,cause:X});this[Wz]=!0,this.responses=J}static isInstance(Y){return A.hasMarker(Y,JK)}static isNoVideoGeneratedError(Y){return Y instanceof Error&&Y.name===gJ&&typeof Y.responses<"u"?!0:!1}toJSON(){return{name:this.name,message:this.message,stack:this.stack,cause:this.cause,responses:this.responses}}},QK="AI_NoSuchToolError",$K=`vercel.ai.error.${QK}`,kN=Symbol.for($K),Kz,Uz,SD=class extends(Uz=A,Kz=kN,Uz){constructor({toolName:Y,availableTools:X=void 0,message:J=`Model tried to call unavailable tool '${Y}'. ${X===void 0?"No tools are available.":`Available tools: ${X.join(", ")}.`}`}){super({name:QK,message:J});this[Kz]=!0,this.toolName=Y,this.availableTools=X}static isInstance(Y){return A.hasMarker(Y,$K)}},GK="AI_StreamProviderError",WK=`vercel.ai.error.${GK}`,xN=Symbol.for(WK),Hz,Zz,xD=class extends(Zz=A,Hz=xN,Zz){constructor({message:Y,type:X,code:J,statusCode:Q,isRetryable:$=bN(Q),data:G,cause:W}){super({name:GK,message:Y,cause:W});this[Hz]=!0,this.type=X,this.code=J,this.statusCode=Q,this.isRetryable=$,this.data=G}static isInstance(Y){return A.hasMarker(Y,WK)}};function bN(Y){return Y!=null&&(Y===408||Y===409||Y===429||Y>=500)}var zK="AI_ToolCallRepairError",KK=`vercel.ai.error.${zK}`,vN=Symbol.for(KK),Lz,Vz,vD=class extends(Vz=A,Lz=vN,Vz){constructor({cause:Y,originalError:X,message:J=`Error repairing tool call: ${d1(Y)}`}){super({name:zK,message:J,cause:Y});this[Lz]=!0,this.originalError=X}static isInstance(Y){return A.hasMarker(Y,KK)}},UK="AI_ToolChoiceViolationError",HK=`vercel.ai.error.${UK}`,hN=Symbol.for(HK),Nz,Bz,gD=class extends(Bz=A,Nz=hN,Bz){constructor({toolChoice:Y,finishReason:X,provider:J,modelId:Q,content:$,message:G=Y.type==="required"?"Model response did not contain a tool call even though tool choice was required.":`Model response did not contain a call to the required tool '${Y.toolName}'.`}){super({name:UK,message:G});this[Nz]=!0,this.toolChoice=Y,this.finishReason=X,this.provider=J,this.modelId=Q,this.content=$}static isInstance(Y){return A.hasMarker(Y,HK)}};var ZK="AI_UIMessageStreamError",LK=`vercel.ai.error.${ZK}`,gN=Symbol.for(LK),Fz,Oz,fD=class extends(Oz=A,Fz=gN,Oz){constructor({chunkType:Y,chunkId:X,message:J}){super({name:ZK,message:J});this[Fz]=!0,this.chunkType=Y,this.chunkId=X}static isInstance(Y){return A.hasMarker(Y,LK)}},VK="AI_InvalidDataContentError",NK=`vercel.ai.error.${VK}`,yN=Symbol.for(NK),jz,qz,cD=class extends(qz=A,jz=yN,qz){constructor({content:Y,cause:X,message:J=`Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof Y}.`}){super({name:VK,message:J,cause:X});this[jz]=!0,this.content=Y}static isInstance(Y){return A.hasMarker(Y,NK)}},BK="AI_InvalidMessageRoleError",FK=`vercel.ai.error.${BK}`,fN=Symbol.for(FK),Dz,Pz,pD=class extends(Pz=A,Dz=fN,Pz){constructor({role:Y,message:X=`Invalid message role: '${Y}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:BK,message:X});this[Dz]=!0,this.role=Y}static isInstance(Y){return A.hasMarker(Y,FK)}},OK="AI_MessageConversionError",jK=`vercel.ai.error.${OK}`,mN=Symbol.for(jK),Ez,Mz,dD=class extends(Mz=A,Ez=mN,Mz){constructor({originalMessage:Y,message:X}){super({name:OK,message:X});this[Ez]=!0,this.originalMessage=Y}static isInstance(Y){return A.hasMarker(Y,jK)}},qK="AI_RetryError",DK=`vercel.ai.error.${qK}`,cN=Symbol.for(DK),wz,Az,nD=class extends(Az=A,wz=cN,Az){constructor({message:Y,reason:X,errors:J}){super({name:qK,message:Y});this[wz]=!0,this.reason=X,this.errors=J,this.lastError=J[J.length-1]}static isInstance(Y){return A.hasMarker(Y,DK)}};var uN="7.0.111",pN=async({url:Y,maxBytes:X,abortSignal:J})=>{var Q;let $=Y.toString();try{let G=r1({},`ai-sdk/${uN}`,DW()),W=await AW({url:$,headers:G,abortSignal:J});if(!W.ok)throw await tY(W),new h0({url:$,statusCode:W.status,statusText:W.statusText});return{data:await RW({response:W,url:$,maxBytes:X!=null?X:xJ}),mediaType:(Q=W.headers.get("content-type"))!=null?Q:void 0}}catch(G){if(h0.isInstance(G))throw G;throw new h0({url:$,cause:G})}};var z={array:EJ,boolean:a7,custom:UW,discriminatedUnion:QW,enum:wJ,instanceof:HW,lazy:KW,literal:GW,looseObject:XW,never:PJ,null:t7,number:s7,object:YW,record:$W,string:o7,union:MJ,unknown:i9},s1=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),s1.optional()),z.array(s1)])),f=z.record(z.string(),z.record(z.string(),s1.optional())),r9=z.union([z.string(),z.instanceof(Uint8Array),z.instanceof(ArrayBuffer),z.custom(TW,{message:"Must be a Buffer"})]),yJ=z.record(z.string(),z.string()),PK=z.object({type:z.literal("text"),text:z.string(),providerOptions:f.optional()}),lN=z.object({type:z.literal("image"),image:z.union([r9,z.instanceof(URL),yJ]),mediaType:z.string().optional(),providerOptions:f.optional()}),EK=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:r9}),z.object({type:z.literal("url"),url:z.instanceof(URL)}),z.object({type:z.literal("reference"),reference:yJ}),z.object({type:z.literal("text"),text:z.string()})]),dN=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:r9}),z.object({type:z.literal("url"),url:z.instanceof(URL)})]),MK=z.object({type:z.literal("file"),data:z.union([EK,r9,z.instanceof(URL),yJ]),filename:z.string().optional(),mediaType:z.string(),providerOptions:f.optional()}),iN=z.object({type:z.literal("reasoning"),text:z.string(),providerOptions:f.optional()}),nN=z.object({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerOptions:f.optional()}),oN=z.object({type:z.literal("reasoning-file"),data:z.union([dN,r9,z.instanceof(URL)]),mediaType:z.string(),providerOptions:f.optional()}),rN=z.object({type:z.literal("tool-call"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerOptions:f.optional(),providerExecuted:z.boolean().optional()}),sN=z.discriminatedUnion("type",[z.object({type:z.literal("text"),value:z.string(),providerOptions:f.optional()}),z.object({type:z.literal("json"),value:s1,providerOptions:f.optional()}),z.object({type:z.literal("execution-denied"),reason:z.string().optional(),providerOptions:f.optional()}),z.object({type:z.literal("error-text"),value:z.string(),providerOptions:f.optional()}),z.object({type:z.literal("error-json"),value:s1,providerOptions:f.optional()}),z.object({type:z.literal("content"),value:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),providerOptions:f.optional()}),z.object({type:z.literal("file"),data:EK,mediaType:z.string(),filename:z.string().optional(),providerOptions:f.optional()}),z.object({type:z.literal("file-data"),data:z.string(),mediaType:z.string(),filename:z.string().optional(),providerOptions:f.optional()}),z.object({type:z.literal("file-url"),url:z.string(),mediaType:z.string().optional(),providerOptions:f.optional()}),z.object({type:z.literal("file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:f.optional()}),z.object({type:z.literal("file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:f.optional()}),z.object({type:z.literal("image-data"),data:z.string(),mediaType:z.string(),providerOptions:f.optional()}),z.object({type:z.literal("image-url"),url:z.string(),providerOptions:f.optional()}),z.object({type:z.literal("image-file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:f.optional()}),z.object({type:z.literal("image-file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:f.optional()}),z.object({type:z.literal("custom"),providerOptions:f.optional()})]))})]),wK=z.object({type:z.literal("tool-result"),toolCallId:z.string(),toolName:z.string(),output:sN,providerOptions:f.optional()}),aN=z.object({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string(),reason:z.string().optional()}),tN=z.object({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional()}),eN=z.object({role:z.literal("system"),content:z.string(),providerOptions:f.optional()}),YB=z.object({role:z.literal("user"),content:z.union([z.string(),z.array(z.union([PK,lN,MK]))]),providerOptions:f.optional()}),XB=z.object({role:z.literal("assistant"),content:z.union([z.string(),z.array(z.union([PK,nN,MK,iN,oN,rN,wK,aN]))]),providerOptions:f.optional()}),JB=z.object({role:z.literal("tool"),content:z.array(z.union([wK,tN])),providerOptions:f.optional()}),aD=z.union([eN,YB,XB,JB]);var QB={};ON(QB,{array:()=>zB,choice:()=>KB,json:()=>UB,object:()=>WB,text:()=>GB});function $B(Y){let X=["ROOT"],J=-1,Q=null,$=0;function G(Z){return Z>="0"&&Z<="9"||Z>="A"&&Z<="F"||Z>="a"&&Z<="f"}function W(Z,F,N){switch(Z){case'"':{J=F,X.pop(),X.push(N),X.push("INSIDE_STRING");break}case"f":case"t":case"n":{J=F,Q=F,X.pop(),X.push(N),X.push("INSIDE_LITERAL");break}case"-":{X.pop(),X.push(N),X.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=F,X.pop(),X.push(N),X.push("INSIDE_NUMBER");break}case"{":{J=F,X.pop(),X.push(N),X.push("INSIDE_OBJECT_START");break}case"[":{J=F,X.pop(),X.push(N),X.push("INSIDE_ARRAY_START");break}}}function K(Z,F){switch(Z){case",":{X.pop(),X.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{J=F,X.pop();break}}}function H(Z,F){switch(Z){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=F,X.pop();break}}}for(let Z=0;Z<Y.length;Z++){let F=Y[Z];switch(X[X.length-1]){case"ROOT":W(F,Z,"FINISH");break;case"INSIDE_OBJECT_START":{switch(F){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}case"}":{J=Z,X.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(F){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(F){case'"':{X.pop(),X.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(F){case":":{X.pop(),X.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{W(F,Z,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{K(F,Z);break}case"INSIDE_STRING":{switch(F){case'"':{X.pop(),J=Z;break}case"\\":{X.push("INSIDE_STRING_ESCAPE");break}default:J=Z}break}case"INSIDE_ARRAY_START":{switch(F){case"]":{J=Z,X.pop();break}default:{J=Z,W(F,Z,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(F){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=Z,X.pop();break}default:{J=Z;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{W(F,Z,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{if(X.pop(),F==="u")$=0,X.push("INSIDE_STRING_UNICODE_ESCAPE");else J=Z;break}case"INSIDE_STRING_UNICODE_ESCAPE":{if(G(F)){if($++,$===4)X.pop(),J=Z}break}case"INSIDE_NUMBER":{switch(F){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=Z;break}case"e":case"E":case"-":case".":break;case",":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")H(F,Z);if(X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(F,Z);break}case"}":{if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(F,Z);break}case"]":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")H(F,Z);break}default:{X.pop();break}}break}case"INSIDE_LITERAL":{let V=Y.substring(Q,Z+1);if(!"false".startsWith(V)&&!"true".startsWith(V)&&!"null".startsWith(V)){if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(F,Z);else if(X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")H(F,Z)}else J=Z;break}}}let U=Y.slice(0,J+1);for(let Z=X.length-1;Z>=0;Z--)switch(X[Z]){case"INSIDE_STRING":{U+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{U+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{U+="]";break}case"INSIDE_LITERAL":{let N=Y.substring(Q,Y.length);if("true".startsWith(N))U+="true".slice(N.length);else if("false".startsWith(N))U+="false".slice(N.length);else if("null".startsWith(N))U+="null".slice(N.length)}}return U}async function JX(Y){if(Y===void 0)return{value:void 0,state:"undefined-input"};let X=await k1({text:Y});if(X.success)return{value:X.value,state:"successful-parse"};if(X=await k1({text:$B(Y)}),X.success)return{value:X.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var GB=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:Y}){return Y},async parsePartialOutput({text:Y}){return{partial:Y}},createElementStreamTransform(){return}}),WB=({schema:Y,name:X,description:J})=>{let Q=XX(Y);return{name:"object",responseFormat:vJ(Q.jsonSchema).then(($)=>({type:"json",schema:$,...X!=null&&{name:X},...J!=null&&{description:J}})),async parseCompleteOutput({text:$},G){let W=await k1({text:$});if(!W.success)throw new j1({message:"No object generated: could not parse the response.",cause:W.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let K=await V9({value:W.value,schema:Q});if(!K.success)throw new j1({message:"No object generated: response did not match schema.",cause:K.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});return K.value},async parsePartialOutput({text:$}){let G=await JX($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:G.value}}},createElementStreamTransform(){return}}},zB=({element:Y,minItems:X,maxItems:J,name:Q,description:$})=>{if(Rz({name:"minItems",value:X}),Rz({name:"maxItems",value:J}),X!=null&&J!=null&&X>J)throw new hJ({parameter:"minItems",value:X,message:"minItems must be less than or equal to maxItems"});let G=XX(Y);return{name:"array",responseFormat:vJ(G.jsonSchema).then((W)=>{let{$schema:K,definitions:H,$defs:U,...Z}=W;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",...H!=null&&{definitions:H},...U!=null&&{$defs:U},type:"object",properties:{elements:{type:"array",items:Z,...X!=null&&{minItems:X},...J!=null&&{maxItems:J}}},required:["elements"],additionalProperties:!1},...Q!=null&&{name:Q},...$!=null&&{description:$}}}),async parseCompleteOutput({text:W},K){let H=await k1({text:W});if(!H.success)throw new j1({message:"No object generated: could not parse the response.",cause:H.error,text:W,response:K.response,usage:K.usage,finishReason:K.finishReason});let U=H.value;if(U==null||typeof U!=="object"||!("elements"in U)||!Array.isArray(U.elements))throw new j1({message:"No object generated: response did not match schema.",cause:new t0({value:U,cause:"response must be an object with an elements array"}),text:W,response:K.response,usage:K.usage,finishReason:K.finishReason});let Z=Tz({value:U.elements,minItems:X,maxItems:J});if(Z!=null)throw new j1({message:"No object generated: response did not match schema.",cause:Z,text:W,response:K.response,usage:K.usage,finishReason:K.finishReason});let F=[];for(let N of U.elements){let V=await V9({value:N,schema:G});if(!V.success)throw new j1({message:"No object generated: response did not match schema.",cause:V.error,text:W,response:K.response,usage:K.usage,finishReason:K.finishReason});F.push(V.value)}return F},async parsePartialOutput({text:W}){let K=await JX(W);switch(K.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let H=K.value;if(H==null||typeof H!=="object"||!("elements"in H)||!Array.isArray(H.elements))return;let U=K.state==="repaired-parse"&&H.elements.length>0?H.elements.slice(0,-1):H.elements,Z=[];for(let F of U){let N=await V9({value:F,schema:G});if(N.success)Z.push(N.value)}return{partial:Z}}}},createElementStreamTransform(){let W=0;return new TransformStream({transform({partialOutput:K},H){if(K!=null)for(;W<K.length;W++){if(J!=null&&W>=J){H.error(Tz({value:K,maxItems:J}));return}H.enqueue(K[W])}}})}}};function Rz({name:Y,value:X}){if(X==null)return;if(!Number.isInteger(X))throw new hJ({parameter:Y,value:X,message:`${Y} must be an integer`});if(X<0)throw new hJ({parameter:Y,value:X,message:`${Y} must be greater than or equal to 0`})}function Tz({value:Y,minItems:X,maxItems:J}){if(X!=null&&Y.length<X)return new t0({value:Y,cause:`elements array must contain at least ${X} items`});if(J!=null&&Y.length>J)return new t0({value:Y,cause:`elements array must contain at most ${J} items`});return}var KB=({options:Y,name:X,description:J})=>{return{name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:Y}},required:["result"],additionalProperties:!1},...X!=null&&{name:X},...J!=null&&{description:J}}),async parseCompleteOutput({text:Q},$){let G=await k1({text:Q});if(!G.success)throw new j1({message:"No object generated: could not parse the response.",cause:G.error,text:Q,response:$.response,usage:$.usage,finishReason:$.finishReason});let W=G.value;if(W==null||typeof W!=="object"||!("result"in W)||typeof W.result!=="string"||!Y.includes(W.result))throw new j1({message:"No object generated: response did not match schema.",cause:new t0({value:W,cause:"response must be an object that contains a choice value."}),text:Q,response:$.response,usage:$.usage,finishReason:$.finishReason});return W.result},async parsePartialOutput({text:Q}){let $=await JX(Q);switch($.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let G=$.value;if(G==null||typeof G!=="object"||!("result"in G)||typeof G.result!=="string")return;let W=Y.filter((K)=>K.startsWith(G.result));if($.state==="successful-parse")return W.includes(G.result)?{partial:G.result}:void 0;else return W.length===1?{partial:W[0]}:void 0}}},createElementStreamTransform(){return}}},UB=({name:Y,description:X}={})=>{return{name:"json",responseFormat:Promise.resolve({type:"json",...Y!=null&&{name:Y},...X!=null&&{description:X}}),async parseCompleteOutput({text:J},Q){let $=await k1({text:J});if(!$.success)throw new j1({message:"No object generated: could not parse the response.",cause:$.error,text:J,response:Q.response,usage:Q.usage,finishReason:Q.finishReason});return $.value},async parsePartialOutput({text:J}){let Q=await JX(J);switch(Q.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return Q.value===void 0?void 0:{partial:Q.value}}},createElementStreamTransform(){return}}};var XP=q0({prefix:"aitxt",size:24}),JP=q0({prefix:"call",size:24});var $P=class extends TransformStream{constructor(){super({transform(Y,X){X.enqueue(`data: ${JSON.stringify(Y)}
|
|
97
82
|
|
|
98
83
|
`)},flush(Y){Y.enqueue(`data: [DONE]
|
|
99
84
|
|
|
100
|
-
`)}})}};var n9=z.record(z.string(),n1.optional()),IP=YJ(()=>o9(z.union([z.looseObject({type:z.literal("text-start"),id:z.string(),providerMetadata:g.optional()}),z.looseObject({type:z.literal("text-delta"),id:z.string(),delta:z.string(),providerMetadata:g.optional()}),z.looseObject({type:z.literal("text-end"),id:z.string(),providerMetadata:g.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:g.optional(),toolMetadata:n9.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:g.optional(),toolMetadata:n9.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:g.optional(),toolMetadata:n9.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(),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:g.optional()}),z.looseObject({type:z.literal("tool-output-available"),toolCallId:z.string(),output:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:g.optional(),toolMetadata:n9.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:g.optional(),toolMetadata:n9.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:g.optional()}),z.looseObject({type:z.literal("reasoning-delta"),id:z.string(),delta:z.string(),providerMetadata:g.optional()}),z.looseObject({type:z.literal("reasoning-end"),id:z.string(),providerMetadata:g.optional()}),z.looseObject({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerMetadata:g.optional()}),z.looseObject({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:g.optional()}),z.looseObject({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:g.optional()}),z.looseObject({type:z.literal("file"),url:z.string(),mediaType:z.string(),providerMetadata:g.optional()}),z.looseObject({type:z.literal("reasoning-file"),url:z.string(),mediaType:z.string(),providerMetadata:g.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 kP=F0({prefix:"aitxt",size:24}),xP=F0({prefix:"call",size:24});var bP=F0({prefix:"aitxt",size:24}),vP=F0({prefix:"call",size:24});var f0=z.record(z.string(),n1.optional()),CB=z.record(z.string(),z.string());var gP=YJ(()=>o9(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(),state:z.enum(["streaming","done"]).optional(),providerMetadata:g.optional()}),z.object({type:z.literal("reasoning"),id:z.string().optional(),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:g.optional()}),z.object({type:z.literal("custom"),kind:z.string(),providerMetadata:g.optional()}),z.object({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:g.optional()}),z.object({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:g.optional()}),z.object({type:z.literal("file"),mediaType:z.string(),filename:z.string().optional(),url:z.string(),providerReference:CB.optional(),providerMetadata:g.optional()}),z.object({type:z.literal("reasoning-file"),mediaType:z.string(),url:z.string(),providerMetadata:g.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"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("input-streaming"),input:z.unknown().optional(),providerExecuted:z.boolean().optional(),callProviderMetadata:g.optional(),output:z.never().optional(),errorText:z.never().optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("input-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:g.optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:g.optional(),approval: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()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:g.optional(),approval:z.object({id:z.string(),approved:z.boolean(),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("output-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:g.optional(),resultProviderMetadata:g.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:f0.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:g.optional(),resultProviderMetadata:g.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("output-denied"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:g.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("input-streaming"),providerExecuted:z.boolean().optional(),callProviderMetadata:g.optional(),input:z.unknown().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:f0.optional(),state:z.literal("input-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:g.optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:g.optional(),approval: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()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:g.optional(),approval:z.object({id:z.string(),approved:z.boolean(),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("output-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:g.optional(),resultProviderMetadata:g.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:f0.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:g.optional(),resultProviderMetadata:g.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("output-denied"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:g.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})})]))}).superRefine((Y,J)=>{if(Y.role!=="assistant"&&Y.parts.length===0)J.addIssue({origin:"array",code:"too_small",minimum:1,inclusive:!0,input:Y.parts,path:["parts"],message:"Message must contain at least one part"})})).nonempty("Messages array must not be empty")));var fP=F0({prefix:"call",size:24});var cP=F0({prefix:"call",size:24});var pP=F0({prefix:"call",size:24});var dP=F0({prefix:"aiobj",size:24});function vK(Y){return({url:J,abortSignal:X})=>zB({url:J,maxBytes:Y==null?void 0:Y.maxBytes,abortSignal:X})}var oP=F0({prefix:"aiobj",size:24});var nP=vK();var rP=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(J){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 hK="AI_NoSuchProviderError",gK=`vercel.ai.error.${hK}`,_B=Symbol.for(gK),yz,fz,aP=class extends(fz=rJ,yz=_B,fz){constructor({modelId:Y,modelType:J,providerId:X,availableProviders:Q,message:$=`No such provider: ${X} (available providers: ${Q.join()})`}){super({errorName:hK,modelId:Y,modelType:J,message:$});this[yz]=!0,this.providerId=X,this.availableProviders=Q}static isInstance(Y){return R.hasMarker(Y,gK)}};var eP=F0({prefix:"call",size:24});var YE=vK();class m0 extends b9{name="ProviderResponseStreamError";constructor(Y,J){super({message:Y,url:"",requestBodyValues:void 0,cause:J?.cause,isRetryable:J?.retryable??!0})}}var I0={};aJ(I0,{toWebSocketUrl:()=>oB,streamResponsesWebSocket:()=>tB,parseRateLimitSignal:()=>a9,normalizeHeaders:()=>nB,markOversizedFrame:()=>nK,isUpgradeFailure:()=>rB,isOversizedFrame:()=>sB,isAbortError:()=>iX,connectResponsesWebSocket:()=>aB,TERMINAL_AFTER_OUTPUT_MESSAGE:()=>sK,PROTOCOL_HEADER:()=>dK,OpenAIWebSocket:()=>I0,OVERSIZED_FRAME_MESSAGE:()=>aK});function s9(Y){let J=Number(Y.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(J)?J:void 0}function $J(Y,J,X=!1){let $=Buffer.from(Y.slice(0,J)).toString("latin1").split(`\r
|
|
101
|
-
`),G=$[0]??"",W=s9(G);if(W===void 0||W===101)return;let K=Object.fromEntries($.slice(1).flatMap((V)=>{let q=V.indexOf(":");return q===-1?[]:[[V.slice(0,q).trim().toLowerCase(),V.slice(q+1).trim()]]})),
|
|
85
|
+
`)}})}};var o9=z.record(z.string(),s1.optional()),WP=eY(()=>n9(z.union([z.looseObject({type:z.literal("text-start"),id:z.string(),providerMetadata:f.optional()}),z.looseObject({type:z.literal("text-delta"),id:z.string(),delta:z.string(),providerMetadata:f.optional()}),z.looseObject({type:z.literal("text-end"),id:z.string(),providerMetadata:f.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:f.optional(),toolMetadata:o9.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:f.optional(),toolMetadata:o9.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:f.optional(),toolMetadata:o9.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(),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:f.optional()}),z.looseObject({type:z.literal("tool-output-available"),toolCallId:z.string(),output:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:f.optional(),toolMetadata:o9.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:f.optional(),toolMetadata:o9.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:f.optional()}),z.looseObject({type:z.literal("reasoning-delta"),id:z.string(),delta:z.string(),providerMetadata:f.optional()}),z.looseObject({type:z.literal("reasoning-end"),id:z.string(),providerMetadata:f.optional()}),z.looseObject({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerMetadata:f.optional()}),z.looseObject({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:f.optional()}),z.looseObject({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:f.optional()}),z.looseObject({type:z.literal("file"),url:z.string(),mediaType:z.string(),providerMetadata:f.optional()}),z.looseObject({type:z.literal("reasoning-file"),url:z.string(),mediaType:z.string(),providerMetadata:f.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 KP=q0({prefix:"aitxt",size:24}),UP=q0({prefix:"call",size:24});var HP=q0({prefix:"aitxt",size:24}),ZP=q0({prefix:"call",size:24});var m0=z.record(z.string(),s1.optional()),HB=z.record(z.string(),z.string());var VP=eY(()=>n9(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(),state:z.enum(["streaming","done"]).optional(),providerMetadata:f.optional()}),z.object({type:z.literal("reasoning"),id:z.string().optional(),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:f.optional()}),z.object({type:z.literal("custom"),kind:z.string(),providerMetadata:f.optional()}),z.object({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:f.optional()}),z.object({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:f.optional()}),z.object({type:z.literal("file"),mediaType:z.string(),filename:z.string().optional(),url:z.string(),providerReference:HB.optional(),providerMetadata:f.optional()}),z.object({type:z.literal("reasoning-file"),mediaType:z.string(),url:z.string(),providerMetadata:f.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"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("input-streaming"),input:z.unknown().optional(),providerExecuted:z.boolean().optional(),callProviderMetadata:f.optional(),output:z.never().optional(),errorText:z.never().optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("input-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:f.optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:f.optional(),approval: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()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:f.optional(),approval:z.object({id:z.string(),approved:z.boolean(),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("output-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:f.optional(),resultProviderMetadata:f.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.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:f.optional(),resultProviderMetadata:f.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("output-denied"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:f.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("input-streaming"),providerExecuted:z.boolean().optional(),callProviderMetadata:f.optional(),input:z.unknown().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:m0.optional(),state:z.literal("input-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:f.optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:f.optional(),approval: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()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:f.optional(),approval:z.object({id:z.string(),approved:z.boolean(),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("output-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:f.optional(),resultProviderMetadata:f.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.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:f.optional(),resultProviderMetadata:f.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("output-denied"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:f.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})})]))}).superRefine((Y,X)=>{if(Y.role!=="assistant"&&Y.parts.length===0)X.addIssue({origin:"array",code:"too_small",minimum:1,inclusive:!0,input:Y.parts,path:["parts"],message:"Message must contain at least one part"})})).nonempty("Messages array must not be empty")));var BP=q0({prefix:"call",size:24});var OP=q0({prefix:"call",size:24});var qP=q0({prefix:"call",size:24});var PP=q0({prefix:"aiobj",size:24});function AK(Y){return({url:X,abortSignal:J})=>pN({url:X,maxBytes:Y==null?void 0:Y.maxBytes,abortSignal:J})}var MP=q0({prefix:"aiobj",size:24});var wP=AK();var AP=z.object({token:z.string().refine((Y)=>Y.trim().length>0),url:z.string().refine((Y)=>{try{let X=new URL(Y);return(X.protocol==="ws:"||X.protocol==="wss:")&&X.hostname!==""}catch(X){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 RK="AI_NoSuchProviderError",TK=`vercel.ai.error.${RK}`,ZB=Symbol.for(TK),Cz,_z,TP=class extends(_z=dX,Cz=ZB,_z){constructor({modelId:Y,modelType:X,providerId:J,availableProviders:Q,message:$=`No such provider: ${J} (available providers: ${Q.join()})`}){super({errorName:RK,modelId:Y,modelType:X,message:$});this[Cz]=!0,this.providerId=J,this.availableProviders=Q}static isInstance(Y){return A.hasMarker(Y,TK)}};var _P=q0({prefix:"call",size:24});var IP=AK();class c0 extends b9{name="ProviderResponseStreamError";constructor(Y,X){super({message:Y,url:"",requestBodyValues:void 0,cause:X?.cause,isRetryable:X?.retryable??!0})}}var k0={};nX(k0,{toWebSocketUrl:()=>_B,streamResponsesWebSocket:()=>bB,parseRateLimitSignal:()=>a9,normalizeHeaders:()=>IB,markOversizedFrame:()=>yK,isUpgradeFailure:()=>SB,isOversizedFrame:()=>kB,isAbortError:()=>pJ,connectResponsesWebSocket:()=>xB,TERMINAL_AFTER_OUTPUT_MESSAGE:()=>uJ,PROTOCOL_HEADER:()=>vK,OpenAIWebSocket:()=>k0,OVERSIZED_FRAME_MESSAGE:()=>mK});function s9(Y){let X=Number(Y.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(X)?X:void 0}function QX(Y,X,J=!1){let $=Buffer.from(Y.slice(0,X)).toString("latin1").split(`\r
|
|
86
|
+
`),G=$[0]??"",W=s9(G);if(W===void 0||W===101)return;let K=Object.fromEntries($.slice(1).flatMap((V)=>{let q=V.indexOf(":");return q===-1?[]:[[V.slice(0,q).trim().toLowerCase(),V.slice(q+1).trim()]]})),H=Y.slice(X+4),U=K["content-length"],Z=Number(U);if(!J&&(U===void 0||Number.isFinite(Z)&&H.length<Z))return;let F=Buffer.from(H).toString("utf8"),N=(()=>{try{let V=JSON.parse(F);return i(V)?V:void 0}catch{return}})();return{message:`WS upgrade failed: ${G}`,status:W,status_code:W,headers:K,body:F,...i(N?.error)?{error:N.error}:{}}}var LB="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",CK=["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 fJ{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];writeQueue=[];constructor(Y,X,J){this.url=Y,this.sessionID=J?.sessionID,this.connect(Y,X)}addEventListener(Y,X,J){this.listeners[Y]?.add(X)}removeEventListener(Y,X){this.listeners[Y]?.delete(X)}peerClose;closeEmitted=!1;emitClose(Y,X){if(this.closeEmitted)return;this.closeEmitted=!0,this.emit("close",{code:Y,reason:X})}emit(Y,X){for(let J of[...this.listeners[Y]??[]])try{J(X)}catch{}}async connect(Y,X){let J=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),Q=J.hostname,$=J.port?Number(J.port):J.protocol==="https:"?443:80,G=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),K=Buffer.from(W).toString("base64"),H=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(K+LB));this.expectedAccept=Buffer.from(new Uint8Array(H)).toString("base64");let U={};for(let[N,V]of Object.entries(X))U[N.toLowerCase()]=V;let Z=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${K}`];for(let N of CK)if(U[N]!==void 0)Z.push(`${VB(N)}: ${U[N]}`);for(let[N,V]of Object.entries(X))if(!CK.includes(N.toLowerCase())&&N.toLowerCase()!=="content-length")Z.push(`${N}: ${V}`);let F=`${Z.join(`\r
|
|
102
87
|
`)}\r
|
|
103
88
|
\r
|
|
104
|
-
`;try{this.log("connect_start",{host:Q,port:$,tls:
|
|
89
|
+
`;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let N=globalThis.Bun?.connect;if(!N)throw Error("Bun.connect is not available");this.socket=await N({hostname:Q,port:$,tls:J.protocol==="https:"?{serverName:Q}:void 0,socket:{open:(V)=>{this.socket=V,this.enqueueWrite(new TextEncoder().encode(F))},data:(V,q)=>this.onData(q),drain:()=>this.flushWrites(),error:(V,q)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let R=q instanceof Error?q.message:String(q);this.log("socket_error",{message:R}),this.emit("error",{message:R})},close:()=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close"),this.emitClose(this.peerClose?.code??1006,this.peerClose?.reason??"socket closed")}}})}catch(N){this.readyState=3;let V=N instanceof Error?N.message:String(N);this.log("connect_exception",{message:V}),this.emit("error",{message:V})}}onData(Y){if(this.rxBuffer=NB(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
|
|
105
90
|
\r
|
|
106
|
-
`);if(
|
|
107
|
-
`)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=s9($);if(W!==101){if(W===void 0){this.readyState=3;try{this.socket?.end()}catch{}this.log("upgrade_failed",{statusLine:$}),this.emit("error",{message:`WS upgrade failed: ${$}`});return}if(!this.emitRejectedUpgrade())return;try{this.socket?.end()}catch{}return}if(!G||G[1]!==this.expectedAccept){this.readyState=3;try{this.socket?.end()}catch{}this.log("accept_mismatch",{statusLine:$}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(
|
|
91
|
+
`);if(J===-1)return;let Q=X.slice(0,J),$=Q.split(`\r
|
|
92
|
+
`)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=s9($);if(W!==101){if(W===void 0){this.readyState=3;try{this.socket?.end()}catch{}this.log("upgrade_failed",{statusLine:$}),this.emit("error",{message:`WS upgrade failed: ${$}`});return}if(!this.emitRejectedUpgrade())return;try{this.socket?.end()}catch{}return}if(!G||G[1]!==this.expectedAccept){this.readyState=3;try{this.socket?.end()}catch{}this.log("accept_mismatch",{statusLine:$}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(J+4),this.log("open",{statusLine:$}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let X=Buffer.from(this.rxBuffer).indexOf(`\r
|
|
108
93
|
\r
|
|
109
|
-
`);if(
|
|
94
|
+
`);if(X===-1)return!1;let J=QX(this.rxBuffer,X,Y);if(!J)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:J.status,partial:Y}),this.emit("error",J),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let X=Y[0],J=Y[1],Q=(X&128)!==0,$=X&15,G=(J&128)!==0,W=J&127,K=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],K=4}else if(W===127){if(Y.length<10)return;W=0;for(let U=0;U<8;U++)W=W*256+Y[2+U];K=10}if(G)K+=4;if(Y.length<K+W)return;let H=Y.slice(K,K+W);this.rxBuffer=Y.slice(K+W),this.handleFrame(Q,$,H)}}handleFrame(Y,X,J){if(X===9){this.writeFrame(10,J);return}if(X===10)return;if(X===8){let $=1005,G="";if(J.length>=2)$=J[0]<<8|J[1],G=Buffer.from(J.slice(2)).toString("utf-8");this.readyState=3,this.peerClose={code:$,reason:G};try{this.socket?.end()}catch{}this.log("close_frame",{code:$,reason:G}),this.emitClose($,G);return}if(X===1||X===2)this.fragOpcode=X,this.fragChunks=[J];else if(X===0)this.fragChunks.push(J);if(!Y)return;let Q=BB(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let $=Buffer.from(Q).toString("utf-8");this.emit("message",{data:$})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),$;if(J<126)$=[128|Y,128|J];else if(J<65536)$=[128|Y,254,J>>8&255,J&255];else{$=[128|Y,255];for(let K=7;K>=0;K--)$.push(J/2**(8*K)&255)}let G=new Uint8Array(J);for(let K=0;K<J;K++)G[K]=X[K]^Q[K%4];let W=new Uint8Array($.length+4+J);W.set($,0),W.set(Q,$.length),W.set(G,$.length+4);try{this.enqueueWrite(W)}catch{}}enqueueWrite(Y){this.writeQueue.push(Y),this.flushWrites()}flushWrites(){let Y=this.socket;if(!Y)return;while(this.writeQueue.length>0){let X=this.writeQueue[0],J=Y.write(X);if(J<X.length){this.writeQueue[0]=X.slice(J),this.log("write_backpressure",{written:J,remaining:X.length-J});return}this.writeQueue.shift()}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return p1({component:"raw-ws-bun",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function VB(Y){return Y}function NB(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function BB(Y){let X=0;for(let $ of Y)X+=$.length;let J=new Uint8Array(X),Q=0;for(let $ of Y)J.set($,Q),Q+=$.length;return J}import{connect as FB}from"node:net";import{connect as OB}from"node:tls";var jB="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",_K=["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 mJ{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];constructor(Y,X,J){this.url=Y,this.sessionID=J?.sessionID,this.connect(Y,X)}addEventListener(Y,X,J){this.listeners[Y]?.add(X)}removeEventListener(Y,X){this.listeners[Y]?.delete(X)}peerClose;closeEmitted=!1;emitClose(Y,X){if(this.closeEmitted)return;this.closeEmitted=!0,this.emit("close",{code:Y,reason:X})}emit(Y,X){for(let J of[...this.listeners[Y]??[]])try{J(X)}catch{}}async connect(Y,X){let J=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),Q=J.hostname,$=J.port?Number(J.port):J.protocol==="https:"?443:80,G=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),K=Buffer.from(W).toString("base64"),H=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(K+jB));this.expectedAccept=Buffer.from(new Uint8Array(H)).toString("base64");let U={};for(let[N,V]of Object.entries(X))U[N.toLowerCase()]=V;let Z=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${K}`];for(let N of _K)if(U[N]!==void 0)Z.push(`${qB(N)}: ${U[N]}`);for(let[N,V]of Object.entries(X))if(!_K.includes(N.toLowerCase())&&N.toLowerCase()!=="content-length")Z.push(`${N}: ${V}`);let F=`${Z.join(`\r
|
|
110
95
|
`)}\r
|
|
111
96
|
\r
|
|
112
|
-
`;try{this.log("connect_start",{host:Q,port:$,tls:
|
|
97
|
+
`;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let N=()=>{this.socket?.write(F)},V=J.protocol==="https:"?OB({host:Q,port:$,servername:Q},N):FB({host:Q,port:$},N);this.socket=V,V.on("data",(q)=>{this.onData(typeof q==="string"?Buffer.from(q,"binary"):q)}),V.on("error",(q)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let R=q instanceof Error?q.message:String(q);this.log("socket_error",{message:R}),this.emit("error",{message:R})}),V.on("close",(q)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close",{hadError:q}),this.emitClose(this.peerClose?.code??1006,this.peerClose?.reason??"socket closed")})}catch(N){this.readyState=3,this.log("connect_exception",{message:N instanceof Error?N.message:String(N)}),this.emit("error",{message:N instanceof Error?N.message:String(N)})}}onData(Y){if(this.rxBuffer=DB(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
|
|
113
98
|
\r
|
|
114
|
-
`);if(
|
|
115
|
-
`)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=s9($);if(W!==101){if(W===void 0){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:$}),this.emit("error",{message:`WS upgrade failed: ${$}`});return}if(!this.emitRejectedUpgrade())return;this.socket?.destroy?.();return}if(!G||G[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:$}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(
|
|
99
|
+
`);if(J===-1)return;let Q=X.slice(0,J),$=Q.split(`\r
|
|
100
|
+
`)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=s9($);if(W!==101){if(W===void 0){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:$}),this.emit("error",{message:`WS upgrade failed: ${$}`});return}if(!this.emitRejectedUpgrade())return;this.socket?.destroy?.();return}if(!G||G[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:$}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(J+4),this.log("open",{statusLine:$}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let X=Buffer.from(this.rxBuffer).indexOf(`\r
|
|
116
101
|
\r
|
|
117
|
-
`);if(
|
|
102
|
+
`);if(X===-1)return!1;let J=QX(this.rxBuffer,X,Y);if(!J)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:J.status,partial:Y}),this.emit("error",J),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let X=Y[0],J=Y[1],Q=(X&128)!==0,$=X&15,G=(J&128)!==0,W=J&127,K=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],K=4}else if(W===127){if(Y.length<10)return;W=0;for(let U=0;U<8;U++)W=W*256+Y[2+U];K=10}if(G)K+=4;if(Y.length<K+W)return;let H=Y.slice(K,K+W);this.rxBuffer=Y.slice(K+W),this.handleFrame(Q,$,H)}}handleFrame(Y,X,J){if(X===9){this.writeFrame(10,J);return}if(X===10)return;if(X===8){let $=1005,G="";if(J.length>=2)$=J[0]<<8|J[1],G=Buffer.from(J.slice(2)).toString("utf-8");this.readyState=3,this.peerClose={code:$,reason:G};try{this.socket?.end()}catch{}this.log("close_frame",{code:$,reason:G}),this.emitClose($,G);return}if(X===1||X===2)this.fragOpcode=X,this.fragChunks=[J];else if(X===0)this.fragChunks.push(J);if(!Y)return;let Q=PB(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let $=Buffer.from(Q).toString("utf-8");this.emit("message",{data:$})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),$;if(J<126)$=[128|Y,128|J];else if(J<65536)$=[128|Y,254,J>>8&255,J&255];else{$=[128|Y,255];for(let K=7;K>=0;K--)$.push(J/2**(8*K)&255)}let G=new Uint8Array(J);for(let K=0;K<J;K++)G[K]=X[K]^Q[K%4];let W=new Uint8Array($.length+4+J);W.set($,0),W.set(Q,$.length),W.set(G,$.length+4);try{this.socket?.write(W)}catch{}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return p1({component:"raw-ws-node",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function qB(Y){return Y}function DB(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function PB(Y){let X=0;for(let $ of Y)X+=$.length;let J=new Uint8Array(X),Q=0;for(let $ of Y)J.set($,Q),Q+=$.length;return J}function EB(){return typeof globalThis.Bun?.connect==="function"}var IK=EB()?fJ:mJ;function $X(Y){return process.env[Y]??process.env[Y.toLowerCase()]}function MB(Y){let X=$X("NO_PROXY");if(!X)return!1;let J=Y.hostname.toLowerCase(),Q=X.split(",").map(($)=>$.trim().toLowerCase()).filter(Boolean);for(let $ of Q){if($==="*")return!0;if($.startsWith(".")){if(J===$.slice(1)||J.endsWith($))return!0}else if(J===$||J.endsWith(`.${$}`))return!0}return!1}function wB(Y){let X=new URL(Y);if(MB(X))return;if(X.protocol==="http:")return $X("HTTP_PROXY");if(X.protocol==="https:")return $X("HTTPS_PROXY")??$X("HTTP_PROXY");return}var SK={getProxyForUrl:wB};var AB=j0("quota"),x1=j0("transport"),vK="responses_websockets=2026-02-06",kK=["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"],RB=new Set([w1,"x-opencode-title"]);function TB(Y){let X=new Map;for(let Q of Object.keys(Y))X.set(Q.toLowerCase(),Q);let J={};for(let Q of kK){let $=X.get(Q),G=$===void 0?void 0:Y[$];if($!==void 0&&G!==void 0)J[$]=G}for(let[Q,$]of Object.entries(Y))if(!kK.includes(Q.toLowerCase()))J[Q]=$;return J}function CB(Y){let X={};for(let[J,Q]of Object.entries(Y)){if(RB.has(J.toLowerCase()))continue;X[J]=Q}return X}function _B(Y){return Y.replace(/^http/,"ws")}function IB(Y){let X={};if(!Y)return X;if(Y instanceof Headers)return Y.forEach((J,Q)=>{X[Q.toLowerCase()]=J}),X;if(Array.isArray(Y)){for(let[J,Q]of Y)X[J.toLowerCase()]=Q;return X}for(let[J,Q]of Object.entries(Y))if(Q!=null)X[J.toLowerCase()]=String(Q);return X}function pJ(Y){return Y instanceof DOMException&&Y.name==="AbortError"}var hK=new WeakSet;function SB(Y){return typeof Y==="object"&&Y!==null&&hK.has(Y)}var gK=new WeakSet;function kB(Y){return typeof Y==="object"&&Y!==null&&gK.has(Y)}function yK(Y){return gK.add(Y),Y}function xK(Y,X){let J=Error(Y,X===void 0?void 0:{cause:X});return hK.add(J),J}function xB(Y){return new Promise((X,J)=>{if(Y.signal?.aborted){J(cJ(Y.signal));return}let Q={...Y.headers,"openai-beta":Y.headers["openai-beta"]??vK},$=Q[w1]??Q["session-id"];delete Q["content-length"],Q=TB(CB(Q));let G=typeof Bun>"u"?void 0:SK.getProxyForUrl(Y.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),W=!0,K=Y.rawWebSocket?new IK(Y.url,Q,{sessionID:$}):new globalThis.WebSocket(Y.url,{headers:Q,...G?{proxy:G}:{},perMessageDeflate:W}),H=Y.timeout?setTimeout(()=>{U(),K.close(),J(Error("WebSocket connect timed out"))},Y.timeout):void 0;function U(){if(H)clearTimeout(H);K.removeEventListener("open",Z),K.removeEventListener("error",F),K.removeEventListener("close",N),Y.signal?.removeEventListener("abort",V)}function Z(){U(),X(K)}function F(q){U(),J(xK(t9(q),q))}function N(q){U(),J(xK(cK("WebSocket closed before open",q.code,q.reason)))}function V(){U(),K.close(),J(cJ(Y.signal))}K.addEventListener("open",Z,{once:!0}),K.addEventListener("error",F,{once:!0}),K.addEventListener("close",N,{once:!0}),Y.signal?.addEventListener("abort",V,{once:!0})})}function bB(Y){let X=new TextEncoder,J=Y.socket,Q,$=()=>{},G=!1,W=0,K=!1,H=!1,U,Z=[],F=12,N=typeof Y.body.previous_response_id==="string"?Y.body.previous_response_id:void 0,V=typeof Y.body.prompt_cache_key==="string"?Y.body.prompt_cache_key:void 0,q={sessionID:Y.sessionID,codexSessionID:V},R,k=0,u,C=new Set,E={addedItemIds:new Set,finished:!1,other:!1};function S(){if(U)clearTimeout(U);$(),Y.signal?.removeEventListener("abort",j)}function c(I=J){I.close()}function o(){S(),Q?.enqueue(X.encode(`data: [DONE]
|
|
103
|
+
|
|
104
|
+
`)),Q?.close()}function J0(I){u0(I,I)}function L0(){if(!H)return"none";if(E.other)return"other";return E.finished?"finished-calls":"unfinished-calls"}function K0(){Q?.enqueue(X.encode(`data: ${JSON.stringify(uB)}
|
|
118
105
|
|
|
119
|
-
`)),
|
|
106
|
+
`)),o()}function B0(I){let y={...q,openingFrameTypes:Z,responseID:R,previousResponseID:N,hasContinuation:N!==void 0,framesSinceCreated:k,msSinceLastFrame:u===void 0?void 0:Date.now()-u},g=L0();if(g==="finished-calls"){if(G)return;x1.warn("stream failed after finished function calls only; ended as completed",{reason:I.message,emittedOutput:!0,outputShape:g,...y}),G=!0,S(),Y.onConnectionInvalid?.(I),K0();return}if(g==="other"){let s=uJ;x1.warn("stream failed after output; not retried",{reason:I.message,emittedOutput:!0,outputShape:g,...y}),u0(Error(s,{cause:I}),new c0(s,{cause:I}));return}x1.warn(g==="none"?"stream failed before output; retryable":"stream failed after unfinished function calls only; retryable",{reason:I.message,emittedOutput:g!=="none",outputShape:g,...y}),J0(I)}function u0(I,y){if(G)return;G=!0,S(),Y.onConnectionInvalid?.(y),Q?.error(I)}function o0(I){if(G)return;if(!Y.idleTimeout)return;if(U)clearTimeout(U);U=setTimeout(()=>B0(new c0(I)),Y.idleTimeout)}async function p(I){if(G)return;if(typeof I.data!=="string"){B0(new c0("Unexpected binary WebSocket frame"));return}let y=I.data,g=(()=>{try{let Y0=JSON.parse(y);return typeof Y0==="object"&&Y0!==null?Y0:void 0}catch{return}})();if(g?.type==="codex.rate_limits"){AB.debug("codex.rate_limits frame received",{pid:process.pid}),o0("idle timeout waiting for websocket");let Y0=bK(g);Y.onQuota?.(Y0);return}let s=L0(),F0=s==="none"||s==="unfinished-calls"?a9(g):void 0;if(F0&&g){G=!0,S(),Y.onRateLimitReached?.(F0.window,F0.resetAt),Y.onTerminal?.(g),Y.onFirstEvent?.(),Q?.error(new c0(`OpenAI account rate limit reached at admission (${F0.window})`));return}if(g?.type==="error"&&Y.onRetryableTerminal){if($(),U)clearTimeout(U);U=void 0;try{let Y0=await Y.onRetryableTerminal(g);if(G){if(Y0)c(Y0);return}if(Y0){x(Y0);return}}catch(Y0){B0(new c0(Y0 instanceof Error?Y0.message:String(Y0),{cause:Y0}));return}}let D0=gB(g,y);if(D0&&g){if(!K)Y.onFirstEvent?.(D0);G=!0,S(),Y.onTerminal?.(g);let Y0=new b9({message:D0.message,url:J.url,requestBodyValues:Y.body,statusCode:D0.status,responseHeaders:D0.headers,responseBody:D0.body}),z0=L0();if(z0==="none"||z0==="unfinished-calls"){if(z0==="unfinished-calls")x1.warn("protocol error after unfinished function calls only; surfaced as before output",{...q,status:D0.status,reason:D0.message,outputShape:z0,responseID:R,previousResponseID:N});Q?.error(Y0);return}if(x1.warn(z0==="finished-calls"?"protocol error after finished function calls only; ended as completed":"protocol error after output; not retried",{...q,status:D0.status,reason:D0.message,outputShape:z0,responseID:R,previousResponseID:N}),z0==="finished-calls"){K0();return}Q?.error(Error(uJ,{cause:Y0}));return}if(i(g)&&g.type==="response.failed"){let Y0=i(g.response)?g.response.failed:void 0,z0=i(Y0)?Y0.rate_limit_reached_type:void 0;if(typeof z0==="string"){G=!0,S(),Y.onRateLimitReached?.(z0),Y.onTerminal?.(g);let g0=L0();if(g0!=="none")x1.warn(g0==="other"?"rate limit reached after output; ended without retry":g0==="finished-calls"?"rate limit reached after finished function calls only; ended as completed":"rate limit reached after unfinished function calls only; retryable",{...q,outputShape:g0,responseID:R,previousResponseID:N});if(g0==="none"||g0==="unfinished-calls")Y.onFirstEvent?.(),Q?.error(new c0(`OpenAI account rate limit reached mid-stream (${z0})`));else if(g0==="finished-calls")K0();else o();return}}if(!g){if(!K)Y.onFirstEvent?.();o0("idle timeout waiting for websocket");return}if(vB(g,C),!K)Y.onFirstEvent?.();if(Q?.enqueue(X.encode(`${y.split(/\r?\n/).map((Y0)=>`data: ${Y0}`).join(`
|
|
120
107
|
`)}
|
|
121
108
|
|
|
122
|
-
`)),K=!0,c=Date.now(),T!==void 0)S++;if(L.length<j)L.push(String(n.type));if(n.type==="response.created")T=WF(n),WJ.debug("response created",{...q,responseID:T,previousResponseID:N,hasContinuation:N!==void 0});if(!zF(n.type))Z=!0;if(W0("idle timeout waiting for websocket"),!n)return;if(n.type==="response.completed"||n.type==="response.done"){G=!0,XF(n,_),Y.onComplete?.(n,_),Y.onTerminal?.(n),f();return}if(n.type==="response.failed"||n.type==="response.incomplete"||n.type==="error")G=!0,Y.onTerminal?.(n),f()}function c0(B){t(new m0(t9(B),{cause:B}))}function z1(B){if(G)return;let D=B.code===1009,w=new m0(D?aK:tK("WebSocket closed before response.completed",B.code,B.reason),{retryable:!D});if(D)WJ.warn("websocket peer refused the request size",{...q,requestBytes:W,reason:B.reason.toString()});t(D?nK(w):w)}function u(){let B=dX(Y.signal);if(G)return;G=!0,E(),b(),Y.onAbort?.(B),Q?.error(B)}function M(B){if(G)return;G=!0,E(),b(),Y.onAbort?.($F(B))}function A(B){$(),X=B,X.addEventListener("message",O0),X.addEventListener("error",c0,{once:!0}),X.addEventListener("close",z1,{once:!0}),$=()=>{X.removeEventListener("message",O0),X.removeEventListener("error",c0),X.removeEventListener("close",z1)};let{background:D,...w}=Y.body;W0("idle timeout sending websocket request");try{let m=JSON.stringify({type:"response.create",...w});W=m.length,X.send(m),W0("idle timeout waiting for websocket")}catch(m){if(G)return;o(new m0(m instanceof Error?m.message:String(m),{cause:m}))}}return new Response(new ReadableStream({start(B){if(Q=B,Y.signal?.addEventListener("abort",u,{once:!0}),Y.signal?.aborted){u();return}A(X)},cancel(B){M(B)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function eB(Y,J){if(!YF(Y))return;await N1({component:"ws",event:"provider_native_web_search_event",sessionID:J,serverEventType:Y.type,itemType:h(Y.item)?Y.item.type:void 0,serverEvent:Y})}function YF(Y){if(typeof Y.type==="string"&&(Y.type.startsWith("response.web_search_call.")||Y.type.startsWith("response.web_search_preview_call.")))return!0;if(h(Y.item)&&typeof Y.item.type==="string")return Y.item.type==="web_search_call"||Y.item.type==="web_search_preview_call";return!1}function JF(Y,J){if(Y.type!=="response.output_item.done")return;if(!h(Y.item))return;rK(Y.item,J)}function XF(Y,J){let X=Y.response;if(!h(X)||!Array.isArray(X.output))return;for(let Q of X.output)if(h(Q))rK(Q,J)}function rK(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 QF(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:h(Y.headers)?Object.fromEntries(Object.entries(Y.headers).flatMap(([Q,$])=>typeof $==="string"||typeof $==="number"||typeof $==="boolean"?[[Q,String($)]]:[])):void 0,body:J,message:h(Y.error)&&typeof Y.error.message==="string"?Y.error.message:`${X}`}}function a9(Y){if(typeof Y==="string")try{return a9(JSON.parse(Y))}catch{return}if(!h(Y))return;let J=a9(Y.cause);if(J)return J;let X=a9(Y.body);if(X)return X;let Q=h(Y.error)?Y.error:Y,$=typeof Q.type==="string"?Q.type:void 0,G=Y.status??Y.status_code;if($!=="usage_limit_reached"&&G!==429)return;let{resets_at:W,resets_in_seconds:K}=Q,Z=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:$??"primary",resetAt:Z}}function $F(Y){if(iX(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function dX(Y){let J=Y?.reason;if(iX(J))return J;if(GF(J))return J;return new DOMException(J instanceof Error?J.message:"Aborted","AbortError")}function GF(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function WF(Y){let J=Y.response;if(!h(J))return;return typeof J.id==="string"?J.id:void 0}function zF(Y){return Y==="response.created"||Y==="response.in_progress"||Y.startsWith("codex.")}var sK="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.",aK="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 tK(Y,J,X){let Q=[`code ${J}`];if(X.length>0)Q.push(X.toString());return`${Y} (${Q.join(": ")})`}var nX="x-opencode-title",zJ="x-openai-auth-quota-account",oX=new Set([nX,w1,zJ,"x-opencode-session"]),UF=15000,ZF=300000,LF=3300000,eK="websocket_connection_limit_reached";function HF(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 KF("sha256").update(Q).digest("hex").slice(0,12)}function VF(Y){let J=Y?.httpFetch??globalThis.fetch,X=new Map,Q=Y?.connectTimeout??UF,$=Y?.idleTimeout??ZF,G=Y?.maxConnectionAge??LF,W=Y?.streamRetries??5,K=Y?.firstEventGraceMs??250,Z=Y?.rawWebSocket??!1,U=Y?.onQuota,L=Y?.onRateLimitReached,j=setInterval(()=>T(),Math.min($,60000));if(typeof j==="object"&&"unref"in j&&typeof j.unref==="function")j.unref();function N(_,E,b){if(!E||!b)return b;rX(_,Y4(E));let f=new Headers(b.headers),o=f.get("x-codex-turn-metadata");if(!o)return b;let t=K4(o,_.turnID,_.turnStartedAt);if(!t)return b;return f.set("x-codex-turn-metadata",t),{...b,headers:f}}async function V(_,E){let b=_ instanceof URL?_.toString():typeof _==="string"?_:_.url,f=I0.normalizeHeaders(E?.headers),o=L4(E),t=_Y(o);if(E?.method!=="POST"||!new URL(b).pathname.endsWith("/responses"))return J(_,t);let N0=(()=>{try{if(typeof E?.body!=="string")return;let D=JSON.parse(E.body);return typeof D==="object"&&D!==null?D:void 0}catch{return}})();if(!N0?.stream)return J(_,t);if(f[nX]==="true")return J(_,t);let W0=f[w1]??f["x-session-affinity"]??f["session-id"],O0=W0;if(!W0)return J(_,t);let c0=I0.normalizeHeaders(o?.headers),z1=HF(c0),u=`${W0}:${z1}:conversation`,M=typeof f[zJ]==="string"?f[zJ]:void 0,A=L?(D,w)=>L(D,M,w):void 0,B=X.get(u)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};if(X.set(u,B),B.fallback)return J(_,N(B,N0,t));if(B.busy)return J(_,N(B,N0,t));B.busy=!0,B.lastUsedAt=Date.now();try{let D=Y4(N0),w=I0.normalizeHeaders(o?.headers),m=typeof w.authorization==="string"&&w.authorization.startsWith("Bearer ")?w.authorization.slice(7):"",p=typeof w["chatgpt-account-id"]==="string"?w["chatgpt-account-id"]:void 0,n=U?(Q0)=>U(Q0,m,M,p):void 0,z0=!B.socket&&!B.continuation?EF(w):w;if(B.socket=await jF(B,Y?.url??b,z0,Q,G,Z,E?.signal),RF(B,D))await OF(B,D,$,{signal:E?.signal??void 0,sessionID:O0,url:Y?.url??b,headers:o?.headers,onRateLimitReached:A});let r=()=>{},v0=()=>{},K1=new Promise((Q0,R0)=>{r=Q0,v0=R0}),A0=AF(B,D),a1=e9(z4(B,A0,D)),J1=typeof a1.previous_response_id==="string";await G9({sessionID:O0,transport:"websocket",phase:"main",bodyText:JSON.stringify(a1),url:Y?.url??b,method:o?.method,headers:o?.headers});let X0=I0.streamResponsesWebSocket({socket:B.socket,body:a1,sessionID:O0??void 0,idleTimeout:$,signal:E?.signal??void 0,onQuota:n,onRateLimitReached:A,onFirstEvent:(Q0)=>r(Q0??!0),onComplete:(Q0,R0)=>{let g1=Q4(Q0);N1({component:"ws-pool",event:"main_completed",sessionID:O0,responseID:X4(Q0),usage:g1}),W4(B,D,Q0,R0,J1)},onTerminal:(Q0)=>{if(B.busy=!1,B.lastUsedAt=Date.now(),B.streamFailures=0,Q0.type!=="response.completed"&&Q0.type!=="response.done")B.continuation=void 0,D1(B)},onConnectionInvalid:(Q0)=>{if(B.busy=!1,B.lastUsedAt=Date.now(),I0.isOversizedFrame(Q0))B.fallback=!0;if(!B.fallback)q(B);B.continuation=void 0,D1(B),r(!1)},onAbort:(Q0)=>{B.busy=!1,B.lastUsedAt=Date.now(),B.streamFailures=0,B.continuation=void 0,D1(B),v0(Q0)},onRetryableTerminal:async(Q0)=>{let R0=J4(Q0);if(!R0)return;throw B.fallback=!0,R0}}),o0=await NF(K1,K);if(o0!==!1){if(o0===!0||o0.status<200||o0.status>599)return X0;return new Response(o0.body,{status:o0.status,headers:{"content-type":"application/json",...o0.headers}})}let V9=()=>J(_,N(B,N0,t));if(!B.fallback)return BF(X0,V9);return V9()}catch(D){if(B.busy=!1,B.lastUsedAt=Date.now(),I0.isAbortError(D))throw B.streamFailures=0,B.continuation=void 0,D1(B),D;let w=I0.parseRateLimitSignal(D);if(w)A?.(w.window,w.resetAt);if(I0.isUpgradeFailure(D)&&!Z)B.fallback=!0;if(q(B),B.continuation=void 0,D1(B),B.fallback)return J(_,N(B,N0,t));return FF(new m0(D instanceof Error?D.message:String(D),{cause:D}))}}function q(_){if(_.streamFailures++,_.streamFailures>W)_.fallback=!0}function T(){let _=Date.now();for(let[E,b]of X){if(b.busy)continue;if(_-b.lastUsedAt<$)continue;D1(b),X.delete(E)}}function S(){clearInterval(j);for(let _ of X.values())D1(_);X.clear()}function c(_){let E=`${_}:`;for(let[b,f]of X){if(!b.startsWith(E))continue;D1(f),X.delete(b)}}return Object.assign(V,{close:S,remove:c})}function J4(Y){if(Y.type!=="error"||!h(Y.error)||Y.error.code!==eK)return;return Error(typeof Y.error.message==="string"?Y.error.message:eK)}async function NF(Y,J){if(J<=0)return!1;return new Promise((X,Q)=>{let $=setTimeout(()=>X(!1),J);Y.then((G)=>{clearTimeout($),X(G)},(G)=>{clearTimeout($),Q(G)})})}function BF(Y,J){let X=Y.body;if(!X)return Y;let Q=!1,$=new ReadableStream({async start(G){let W=X.getReader(),K=async(Z)=>{while(!0){let{done:U,value:L}=await Z.read();if(U)return;if(L&&L.length>0)Q=!0,G.enqueue(L)}};try{await K(W),G.close()}catch(Z){if(Q||!I0.isOversizedFrame(Z)){G.error(Z);return}try{let U=await J();if(!U.ok){G.error(new m0(`HTTP fallback after an oversized WebSocket frame failed with ${U.status}`));return}if(U.body)await K(U.body.getReader());G.close()}catch(U){G.error(U)}}},cancel(G){X.cancel(G)}});return new Response($,{status:Y.status,headers:Y.headers})}function FF(Y){return new Response(new ReadableStream({start(J){J.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function jF(Y,J,X,Q,$,G,W){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<$)return Y.socket;D1(Y);let K=await I0.connectResponsesWebSocket({url:I0.toWebSocketUrl(J),headers:X,timeout:Q,rawWebSocket:G,signal:W??void 0});return Y.connectedAt=Date.now(),K}function D1(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function OF(Y,J,X,Q){if(!Y.socket||!Array.isArray(J.input)||J.input.length===0)return;let $=DF(J);await G9({sessionID:Q.sessionID,transport:"websocket",phase:"prewarm",bodyText:JSON.stringify($),url:Q.url,method:"POST",headers:Q.headers});let G=I0.streamResponsesWebSocket({socket:Y.socket,body:$,sessionID:Q.sessionID,idleTimeout:X,signal:Q.signal,onRateLimitReached:Q.onRateLimitReached,onComplete:(W,K)=>{N1({component:"ws-pool",event:"prewarm_completed",sessionID:Q.sessionID,responseID:X4(W),usage:Q4(W)}),W4(Y,$,W,K,!1)},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=J4(W);if(!K)return;throw Y.fallback=!0,K}});await qF(G)}function X4(Y){let J=Y.response;if(!h(J))return;return typeof J.id==="string"?J.id:void 0}function Q4(Y){let J=Y.response;if(!h(J))return;return h(J.usage)?J.usage:void 0}async function qF(Y){let J=Y.body?.getReader();if(!J)return;while(!0)if((await J.read()).done)return}function DF(Y){return e9({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:PF(Y.client_metadata)})}function $4(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 PF(Y){if(!h(Y))return Y;if(typeof Y["x-codex-turn-metadata"]!=="string")return Y;try{let J=JSON.parse(Y["x-codex-turn-metadata"]);if(!h(J))return Y;return{...Y,"x-codex-turn-metadata":$4(J),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function EF(Y){let J=Y["x-codex-turn-metadata"];if(!J)return Y;try{let X=JSON.parse(J);if(!h(X))return Y;return{...Y,"x-codex-turn-metadata":$4(X)}}catch{return Y}}var G4=["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 Y4(Y){let J={...Y};if(Array.isArray(Y.input))J.input=Y.input.map(MF);return J}function e9(Y){let J={};for(let X of G4)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}function MF(Y){if(!h(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 W4(Y,J,X,Q,$){let G=X.response,W=h(G)&&typeof G.id==="string"?G.id:void 0;if(!W||!Array.isArray(J.input)){Y.continuation=void 0;return}let K=$?new Set(Y.continuation?.finalizedCallIds):new Set;for(let Z of Q)K.add(Z);Y.continuation={responseID:W,input:J.input,signature:sX(J),finalizedCallIds:K}}function rX(Y,J,X=J){let Q=Array.isArray(J.input)?J.input:[],$=Array.isArray(X.input)?X.input:Q,G=sX(X),W=Y.turnInput&&Y.turnSignature===G?wF(Y.turnInput,$):void 0,K=W===void 0?Q:$.slice(W);if(K.length>0&&K.some(U4)||!Y.turnID)Y.turnID=u1(),Y.turnStartedAt=Date.now();Y.turnInput=$.slice(),Y.turnSignature=G}function z4(Y,J,X=J){rX(Y,J,X);let Q=J.client_metadata;if(!h(Q)||typeof Q["x-codex-turn-metadata"]!=="string")return J;let $=K4(Q["x-codex-turn-metadata"],Y.turnID,Y.turnStartedAt);if(!$)return J;return{...J,client_metadata:{...Q,"x-codex-turn-metadata":$}}}function K4(Y,J,X){let Q;try{Q=JSON.parse(Y)}catch{return}if(!h(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 wF(Y,J){if(Y.length>J.length)return;for(let X=0;X<Y.length;X++)if(B1(Y[X])!==B1(J[X]))return;return Y.length}function AF(Y,J){let X=Array.isArray(J.input)?J.input:void 0;if(!X||!Y.continuation)return J;if(Y.continuation.signature!==sX(J))return Y.continuation=void 0,J;if(!Z4(Y.continuation.input,X))return Y.continuation=void 0,J;if(Y.continuation.input.length===0)return{...J,previous_response_id:Y.continuation.responseID};let Q=X.slice(Y.continuation.input.length),$=TF(Q,Y.continuation.finalizedCallIds);if($.length===0)return J;return{...J,previous_response_id:Y.continuation.responseID,input:$}}function RF(Y,J){let X=Array.isArray(J.input)?J.input:void 0;if(!Y.continuation)return!0;if(!X)return!1;if(!Z4(Y.continuation.input,X))return!0;return X.slice(Y.continuation.input.length).some(U4)}function U4(Y){if(!h(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function TF(Y,J){return Y.filter((X)=>{if(!h(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 sX(Y){return B1(CF(Object.fromEntries(Object.entries(Y).filter(([J])=>J!=="input"&&J!=="stream"&&J!=="background"&&J!=="previous_response_id"&&J!=="generate"))))}function CF(Y){if(!h(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 Z4(Y,J){if(Y.length>=J.length)return!1;for(let X=0;X<Y.length;X++)if(B1(Y[X])!==B1(J[X]))return!1;return!0}function L4(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let J=new Headers(Y.headers);for(let X of oX)J.delete(X);return{...Y,headers:J}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((J)=>!oX.has(J[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([J])=>!oX.has(J.toLowerCase())))}}var _F=300000,IF=30000,SF=5000,kF=100;function X8(Y){let J=Y.logger,X=Y.now??Date.now,Q=Y.manifestPath??_J(),$=Y.cacheConnector??gF(J),G=Y.detectClaustrumConnection??N4,W,K,Z,U,L,j=!1,N=new Map,V=new Set,q,S={isEnabled:()=>U?.status==="available",wasDetected:()=>U?.status==="available",getCache:()=>W,async ensureCache(){if(W)return W;return await c(),W},getTransport:()=>K,getCustodyProjection:(u,M)=>{let A=N.get(u.id);if(A)return A;return H4(u,Y.storage,M,W,q)},async boot(){if(j)return;try{U=await G()}catch(w){J.warn("custody detection failed",{error:w instanceof Error?w.message:String(w)});return}if(U.status!=="available"){if(U.status==="malformed")J.warn("custody connection malformed; disabled for this process",{reason:U.reason});else J.info("custody not configured; no client/timer created",{});return}let u=await Y.readCustodyManifest(Q);if(q=u,await E(u),Y.storage?.claustrum?.mode!=="claustrum"){J.info("custody connection available but mode is local; manifest read for the refresh gate, no client/timer",{});return}if(!await c()){O0();return}let M=W;if(!M)return;if(!u.ok&&u.reason!=="absent"){_(await Y.loadAccounts(s(Y.configPath))),O0();return}await f(),await o(u);let A=await Y.loadAccounts(s(Y.configPath));await Y.onReconcileStep?.("enabled-manifest-join");let B=aX(u,A),D=[];for(let w of tX(A)){if(A?.claustrum?.transition?.fingerprints.fallbacks[w.id])continue;if(!eX(w,u,E0)&&!(k0(w,E0)&&!w.accountId))continue;if(!B.get(w.id))continue;let p=c0(M);D.push(Y8(w,p).then((n)=>z1(w,n,u)).catch((n)=>J.warn("custody boot sweep failed",{error:n instanceof Error?n.message:String(n)})))}await Promise.all(D),await hF(B,M,A,kF),O0()},async runTick(){if(j)return;if(Y.storage?.claustrum?.mode!=="claustrum")return;let u=q?.ok?q.revision:void 0,M=Y.readCustodyManifest(Q),A=W?void 0:c(),B=await M;if(q=B,!B.ok&&B.reason!=="absent"){_(await Y.loadAccounts(s(Y.configPath)));return}let D=B.ok&&B.revision!==u?await E(B):await Y.loadAccounts(s(Y.configPath));if(!W&&!await A)return;if(B.ok&&B.revision===u){await f(),await Y.onReconcileStep?.("enabled-manifest-join");let m=aX(B,D);await b(B,m),await W0(B,m);return}await f(),await o(B),await Y.onReconcileStep?.("enabled-manifest-join");let w=aX(B,D);await b(B,w),await W0(B,w)},dispose(){if(j)return;if(j=!0,L)(Y.clearIntervalFn??clearInterval)(L),L=void 0;try{W?.close()}catch{}if(!W)try{K?.close()}catch{}W=void 0,K=void 0}};async function c(){if(j)return!1;if(W)return!0;if(Z)return Z;if(!U)return!1;let u=(async()=>{let M;try{let A=$({connectionFile:fF(U),handshakeTimeoutMs:SF});M=new j4({connector:()=>A,now:X});let B=await A;if(j)return M.close(),!1;return W=M,K=B,!0}catch(A){return M?.close(),J.warn("custody connect failed; disabled until tick reconnect",{error:A instanceof Error?A.message:String(A)}),!1}})();Z=u;try{return await u}finally{if(Z===u)Z=void 0}}function _(u){for(let M of tX(u))N.set(M.id,{state:"inert",reason:"manifest-unreadable"})}async function E(u){let M=await Y.loadAccounts(s(Y.configPath));if(!M||!u.ok)return M;for(let[A,B]of y0(u)){if(!M)break;if(A==="main")continue;if(M.accounts.some((p)=>p.id===A))continue;let D=M.claustrum?.rowHistory?.includes(A)?"row removed":"awaiting discovery",w=`${A}:${D}`;if(!V.has(w))V.add(w),J.info(`orphan-binding: ${D}`,{accountId:A});if(M.claustrum?.mode!=="claustrum")continue;let m=null;while(!m&&!j)if(m=await Y.acquireRefreshFileLock({name:M1(A),ttlMs:b1,path:Y.configPath,renew:!0}),!m)await new Promise((p)=>setTimeout(p,5));if(!m)continue;try{await Y.onReconcileStep?.("discovery-lock-acquired",A);let p=await Y.readCustodyManifest(Q),n=await Y.loadAccounts(s(Y.configPath));if(n?.claustrum?.mode!=="claustrum"||!p.ok||y0(p).get(A)!==B||n.accounts.some((z0)=>z0.id===A))continue;await Y.mutateAccounts((z0)=>{if(z0.claustrum?.mode!=="claustrum"||z0.accounts.some((r)=>r.id===A))return z0;return{...z0,claustrum:{...z0.claustrum,mode:"claustrum",rowHistory:[...new Set([...z0.claustrum?.rowHistory??[],A])]},accounts:[...z0.accounts,{id:A,...V1(E0),enabled:!0}]}},s(Y.configPath))}finally{await m.release().catch(()=>{})}M=await Y.loadAccounts(s(Y.configPath))}return M}async function b(u,M){if(!W)return;let A=await Y.loadAccounts(s(Y.configPath)),B=c0(W);for(let D of tX(A)){if(A?.claustrum?.transition?.fingerprints.fallbacks[D.id])continue;if(!eX(D,u,E0)&&!(k0(D,E0)&&!D.accountId))continue;if(!M.has(D.id))continue;let w=await Y8(D,B);z1(D,w,u)}}async function f(){let u=await Y.loadAccounts(s(Y.configPath)),M=u?.claustrum?.transition;if(u?.claustrum?.mode!=="claustrum"||!M)return;let A=!1;for(let[B,D]of Object.entries(M.fingerprints.fallbacks)){let w=await Y.acquireRefreshFileLock({name:M1(B),ttlMs:b1,path:Y.configPath,renew:!0});if(!w){A=!0;continue}try{if(!await Y.withAccountStoreTransaction(async(p)=>{let n=await p.read(),z0=n.accounts.find((A0)=>A0.id===B);if(z0?.type==="oauth"&&k0(z0,"openai"))return!0;if(!z0||!V0(z0)||!z0.access||Q9(z0.access,z0.refresh)!==D)return N.set(B,{state:"inert",reason:"new-local-family-under-claustrum"}),!1;let r=structuredClone(n),v0=r.accounts.find((A0)=>A0.id===B);if(!v0||!V0(v0))return!1;Object.assign(v0,V1(E0)),await p.write(r);let K1=(await p.read()).accounts.find((A0)=>A0.id===B);return!!(K1?.type==="oauth"&&k0(K1,"openai"))},s(Y.configPath)))A=!0}catch{A=!0}finally{await w.release().catch(()=>{})}}if(M.fingerprints.main)if(!Y.auth)A=!0;else{let B=await Y.acquireRefreshFileLock({name:c1,ttlMs:b1,path:Y.configPath,renew:!0});if(!B)A=!0;else try{if(await xJ(M.fingerprints.main,{auth:Y.auth,warn:(w)=>J.warn(w,{})})!=="tombstoned")A=!0}finally{await B.release().catch(()=>{})}}if(A)return;await Y.withAccountStoreTransaction(async(B)=>{let D=await B.read();if(D.claustrum?.mode!=="claustrum"||D.claustrum.transition?.manifestRevision!==M.manifestRevision||D.claustrum.transition?.storeGeneration!==M.storeGeneration)return;await B.writeMode("claustrum")},s(Y.configPath))}async function o(u){if(!W||!u.ok)return;let M=await Y.loadAccounts(s(Y.configPath));if(M?.claustrum?.mode!=="claustrum")return;let A=y0(u);for(let B of M.accounts){if(B.type!=="oauth"||B.corrupt!==!0)continue;let D=A.get(B.id),w=D?await t(B.id,B.accountId,D):"no_handle",m=S9({mode:"claustrum",manifest:D?"present":"absent",local:"gone",vault:()=>w,verifiedInProcessLogin:!1});if(!("installTombstone"in m)||!m.installTombstone||!D)continue;await N0(B.id,D)}}async function t(u,M,A){if(Y.resolveFallbackVaultState)return Y.resolveFallbackVaultState({accountId:u,handle:A});if(!W)return"cold";if(W.isReauth(A,X()))return"needs_reauth";try{let B=await W.get(A,v1(Y.storage),{force:!0}),D=Q1(B.payload.access),w=D?$1(D):void 0;if(M&&w&&w!==M)return"identity_mismatch";if(!w)J.warn("custody identity unverifiable; serving",{credentialId:A});return"serves"}catch{return W.isReauth(A,X())?"needs_reauth":"cold"}}async function N0(u,M){let A=await Y.acquireRefreshFileLock({name:M1(u),ttlMs:b1,path:Y.configPath,renew:!0});if(!A)return;try{let B=await Y.readCustodyManifest(Q),D=await Y.loadAccounts(s(Y.configPath)),w=D?.accounts.find((m)=>m.id===u);if(D?.claustrum?.mode!=="claustrum"||!B.ok||y0(B).get(u)!==M||w?.type!=="oauth"||w.corrupt!==!0)return;await Y.mutateAccounts((m)=>{let p=m.accounts.find((r)=>r.id===u);if(p?.type!=="oauth"||p.corrupt!==!0)return m;let{corrupt:n,...z0}=p;return{...m,accounts:m.accounts.map((r)=>r.id===u?{...z0,...V1(E0)}:r)}},s(Y.configPath))}finally{await A.release().catch(()=>{})}}async function W0(u,M){if(!W)return;for(let[A,B]of M){if(W.isReauth(B,X()))continue;let w=(await Y.loadAccounts(s(Y.configPath)))?.accounts.find((m)=>m.id===A);if(!w||!V0(w))continue;if(!F4(w,u,Y.storage??{}))continue;try{let m=await W.get(B);N.set(A,{state:"vault",recordVersion:m.recordVersion})}catch{}}}function O0(){if(j)return;let u=Y.setIntervalFn??setInterval,M=Math.floor((Math.random()*2-1)*IF),A=_F+M;if(L=u(()=>{if(j)return;S.runTick().catch((D)=>J.warn("custody tick failed",{error:D instanceof Error?D.message:String(D)}))},A),L&&typeof L==="object"&&"unref"in L)L.unref?.()}function c0(u){return{loadAccounts:Y.loadAccounts,readCustodyManifest:Y.readCustodyManifest,acquireRefreshFileLock:Y.acquireRefreshFileLock,configPath:Y.configPath,paths:s(Y.configPath),manifestPath:Q,cache:u,minTtlMs:v1(Y.storage),mutateAccounts:Y.mutateAccounts,provider:E0,now:X}}function z1(u,M,A){if(M.kind==="succeeded"){N.set(u.id,{state:"vault",recordVersion:M.recordVersion});return}if(M.kind==="failed"){let D={gone:"gone",identityMismatch:"identityMismatch",nullClaim:"nullClaim",unavailable:"unavailable"}[M.reason];N.set(u.id,{state:"inert",reason:D==="unavailable"?"takeover-incomplete/vault-unavailable":"identity-mismatch"}),bF(J,u.id,D,M.recordVersion,X());return}if(M.reason==="notEnrolling"){let B=X(),D=H4(u,Y.storage,B,W,A);if(D)N.set(u.id,D)}}return S}var xF=3600000,J8=new Map;function bF(Y,J,X,Q,$){let G=`${J}:${X}`,W=J8.get(G);if(W!==void 0&&$-W<xF)return;J8.set(G,$),Y.warn("custody enroll-completion sweep failed",{accountId:J,reason:X,...typeof Q==="number"?{recordVersion:Q}:{}})}function vF(){J8.clear()}function v1(Y){return((Y?.refresh?.refreshBeforeExpiryMinutes??240)+30)*60000}function aX(Y,J){let X=new Map;for(let[Q,$]of y0(Y)){let G=J?.accounts.find((W)=>W.id===Q);if(G?.type!=="oauth")continue;if(!KJ(G,Y,E0))continue;X.set(Q,$)}return X}function H4(Y,J,X,Q,$){let G=J??{},W=$?y0($).get(Y.id):void 0;if(!k0(Y,E0)&&!W)return;if(!k0(Y,E0))return;if(G.claustrum?.mode!=="claustrum"||!W)return YY({kind:"NEEDS_LOGIN"});return YY({kind:"INERT",reason:Q?.isReauth(W,X)?"vault-reauth":"vault-cold"})}async function hF(Y,J,X,Q,$=[]){if(Y.size===0&&$.length===0)return;let G=[...$];for(let[,W]of Y)G.push(J.get(W).then(()=>{return}).catch(()=>{}));await Promise.race([Promise.all(G),new Promise((W)=>setTimeout(W,Q))])}function tX(Y){if(!Y)return[];return Y.accounts.filter(V0)}function gF(Y){return async(J)=>{let X=await B4.connect({connectionFile:J.connectionFile,handshakeTimeoutMs:J.handshakeTimeoutMs});return yF(X,Y)}}function yF(Y,J){return{getCredential:(X,Q)=>Y.getCredential(X,Q),statusCredential:(X)=>Y.statusCredential(X),reportAuthFailure:(X)=>Y.reportAuthFailure({handle:X.handle,providerStatus:X.providerStatus,recordVersion:X.recordVersion,reporterSource:X.reporterSource}),close:()=>Y.close()}}function fF(Y){if(Y.status!=="available")return Y.path??"";return V4()}var lF=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),dF=new Set(["gpt-5.6","gpt-6"]),iF="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.",oF=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-6-astra","gpt-6-sol","gpt-6-luna"]),nF="opencode-oauth-dummy-key",rF="terminal_resize_reflow",U8="0.155.0",sF=`codex_exec/${U8} (Debian 12.0.0; aarch64) unknown (codex_exec; ${U8})`,aF="seccomp",mM=()=>c1,Q8=120000,tF=90000,eF=4000,O4=50,q4=3,Yj=25,Jj=60000,Xj="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",Z8=!1;function cM(){Z8=!1}var D4=B0("models"),P4=!1,E4=!1;class H8 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 W1 extends Error{code;constructor(Y,J){super(J);this.name="ResetTargetResolutionError",this.code=Y}}function M4(Y,J,X,Q){let $=(X?.refresh?.refreshBeforeExpiryMinutes??240)*60000;return!Y||!J||J-Q<=$}function Qj(Y){return async(J)=>{if(J==="main"){let Z=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),U=await Y.getAuth();if(U.type!=="oauth")throw new W1("non_oauth_account","Main OpenAI account is not authenticated with OAuth.");if(M4(U.access,U.expires,Z,Y.now()))U={type:"oauth",...await Y.refreshMainWithLease()};if(!U.access)throw new W1("token_unavailable","Main OpenAI account has no usable access token.");let L=Q1(U.access),j=L?$1(L):void 0,N=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath});return{accountKey:J,label:"Main account",accessToken:U.access,chatgptAccountId:j??N?.mainAccountId}}let X=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),Q=X?.accounts.find((Z)=>Z.id===J);if(!X||!Q)throw new W1("unknown_account",`Fallback account ${J} was not found.`);if(Q.enabled===!1)throw new W1("disabled_account",`Fallback account ${J} is disabled.`);if(!V0(Q))throw new W1("non_oauth_account",`Fallback account ${J} is not an OAuth account.`);let $=Q;if(!await Y.isFallbackRefreshInert?.($,X)&&M4($.access,$.expires,X,Y.now()))$=await Y.refreshFallbackAccount($,X);let G=Y.resolveFallbackAccess?await Y.resolveFallbackAccess($,X):$.access?{token:$.access,provenance:"local"}:h1;if(G===h1||G===s1)throw new W1("token_unavailable",`Fallback account ${J} has no usable access token.`);let W=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),K=W?.accounts.find((Z)=>Z.id===J);if(!W||!K)throw new W1("unknown_account",`Fallback account ${J} was not found.`);if(K.enabled===!1)throw new W1("disabled_account",`Fallback account ${J} is disabled.`);if(!V0(K))throw new W1("non_oauth_account",`Fallback account ${J} is not an OAuth account.`);return{accountKey:J,label:$.label??J,accessToken:G.token,chatgptAccountId:K.accountId,onAuthFailure:G.provenance==="local"?void 0:async(Z)=>{await Y.reportAuthFailure?.({handle:G.provenance.handle,providerStatus:Z,recordVersion:G.provenance.recordVersion})}}}}function $j(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function $8(Y){return Y instanceof H8}function w4(){throw Error(Xj)}function Gj(Y){return Math.floor(Math.random()*Y)}function Wj(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 zj(Y,J,X){let Q=Y.get(J);if(Q)return Q;let $=u1(),G={threadID:$,turnID:u1(),windowID:`${$}:0`};return Y.set(J,G),X?.(),G}function s4(){return K8(OY(),"openai-auth-sessions.json")}function Kj(){let Y=new Map;try{let J=JSON.parse(r4(s4(),"utf8"));if(!h(J.sessions))return Y;for(let[X,Q]of Object.entries(J.sessions)){if(!h(Q)||typeof Q.threadID!=="string")continue;Y.set(X,{threadID:Q.threadID,turnID:u1(),windowID:`${Q.threadID}:0`})}}catch{}return Y}function Uj(Y){let J=s4(),X=`${J}.tmp-${process.pid}`;try{mF(OY(),{recursive:!0});let Q={version:1,sessions:Object.fromEntries([...Y.entries()].map(([$,G])=>[$,{threadID:G.threadID}]))};pF(X,`${JSON.stringify(Q,null,2)}
|
|
123
|
-
`,"utf8"),cF(X,J)}catch{}}function A4(Y,J){return h(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===J}function Zj(Y,J){if(Y.length>J.length)return!1;for(let X=0;X<Y.length;X++)if(B1(Y[X])!==B1(J[X]))return!1;return!0}function Lj(Y,J){if(!Y.input)return J.length>0;if(!Zj(Y.input,J))return!0;return J.slice(Y.input.length).some((Q)=>A4(Q,"user")||A4(Q,"developer"))}function Hj(Y,J){let X=Array.isArray(J?.input)?J.input:void 0;if(X&&(Lj(Y,X)||!Y.turnID))Y.turnID=u1(),Y.turnStartedAt=Date.now();else if(!Y.turnStartedAt)Y.turnStartedAt=Date.now();if(X)Y.input=X}function Vj(Y){if(!Y.metadata)return{init:Y.init};let J=Wj(Y.init?.body);if(!Y.websocket)Hj(Y.metadata,J);else if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Date.now();if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Date.now();let X=JSON.stringify({session_id:Y.metadata.threadID,thread_id:Y.metadata.threadID,thread_source:"user",turn_id:Y.metadata.turnID,sandbox:aF,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",rF),Y.headers.set("x-codex-turn-metadata",X),Y.headers.set("user-agent",sF),Y.headers.set("version",U8),Y.dumpSessionID)Y.headers.set(w1,Y.dumpSessionID);let Q=J;if(!Q)return{init:Y.init};let $=Y.responsesLite&&typeof Q.model==="string"&&oF.has(Q.model);if($&&!Y.websocket)Y.headers.set("x-openai-internal-codex-responses-lite","true");if(Q.prompt_cache_key=Y.metadata.threadID,Q.parallel_tool_calls??=!0,Array.isArray(Q.tools))Q.tools=Q.tools.map(Ej);if(Dj(Q),Pj(Q),V5(Q),Fj(Q),Oj(Q,Y.metadata),$)qj(Q);let G={...typeof Q.client_metadata==="object"&&Q.client_metadata!==null?Q.client_metadata:{},"x-codex-installation-id":Y.installationID,"x-codex-window-id":Y.metadata.windowID};if(Y.websocket){if(G["x-codex-turn-metadata"]=X,G["x-codex-ws-stream-request-start-ms"]=String(Date.now()),$)G.ws_request_header_x_openai_internal_codex_responses_lite="true"}return Q.client_metadata=G,Y.headers.delete("content-length"),Y.headers.delete("Content-Length"),{init:{...Y.init,body:JSON.stringify(e9(Q))}}}function Nj(Y,J){return Y.find((X)=>X.enabled!==!1&&V0(X)&&(X.id===J||X.accountId===J))}function R4(Y,J){if(!J)return Y;let X={...Y};for(let Q of["resetCreditsAvailable","resetCreditsApplicable"]){let $=J[Q];if(X[Q]===void 0&&$!==void 0)X[Q]=$}if(X.spendControl===void 0&&X.spendControlCleared!==!0&&J.spendControl!==void 0)X.spendControl=J.spendControl;return X}function ZJ(Y,J){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:J}}function LJ(Y,J){return y0(Y).get(J)}function a4(Y,J,X=Date.now(),Q=J.mainAccountId,$){let G=Y.getMain(),W=G?.quota;return{main:{quota:W?{...W,checkedAt:G.checkedAt,primary:ZJ(W.primary,G.checkedAt),secondary:ZJ(W.secondary,G.checkedAt)}:null,...typeof Q==="string"?{mainAccountId:Q}:{},killed:!1,...W?.resetCreditsAvailable!==void 0?{resetCredits:W.resetCreditsAvailable}:{}},fallbacks:J.accounts.filter((K)=>K.enabled).map((K)=>{let Z=Y.getFallback(K.id),U=Z?.quota,L=$?.(K,X);return{id:K.id,label:K.label,accountId:Z?.accountId??K.accountId,quota:U?{...U,checkedAt:Z.checkedAt,primary:ZJ(U.primary,Z.checkedAt),secondary:ZJ(U.secondary,Z.checkedAt)}:null,killed:!1,enabled:!0,...U?.resetCreditsAvailable!==void 0?{resetCredits:U.resetCreditsAvailable}:{},...L?{custody:L}:{}}}),route:J.routing?.mode??"main-first",lastUpdated:X}}function pM(Y,J,X,Q=Date.now()){return{...a4(Y,J,Q),activeId:X}}function T4(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 Bj(Y,J){if(!(Y instanceof Request))return J;let X=new Request(Y,J),Q=X.method.toUpperCase(),$=Q==="GET"||Q==="HEAD"||X.body===null?void 0:await X.text();return{method:X.method,headers:new Headers(X.headers),body:$,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 C4(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}function Fj(Y){if(!g0().webSearch)return;if(!Array.isArray(Y.tools)||Y.tools.length===0)return;if(Y.tools.some((J)=>h(J)&&J.type==="web_search"))return;Y.tools=[...Y.tools,{type:"web_search",external_web_access:!1,search_content_types:["text","image"]}]}function L8(Y){if(Array.isArray(Y)){for(let J of Y)L8(J);return}if(!h(Y))return;if(Y.type==="input_image")delete Y.detail;for(let J of Object.values(Y))L8(J)}var jj=new Set(["gpt-6-astra","gpt-6-sol","gpt-6-luna"]);function Oj(Y,J){let X=typeof Y.model==="string"?Y.model:"";if(!jj.has(X))return;let Q=h(Y.reasoning)?Y.reasoning:void 0,$=typeof Q?.effort==="string"?Q.effort:void 0;if(!$)return;if(J.pinnedEffort===void 0){J.pinnedEffort=$;return}if($===J.pinnedEffort)return;let G=Array.isArray(Y.input)?Y.input:void 0;if(!G||G.length===0)return;Y.reasoning={...Q,effort:J.pinnedEffort},G.splice(G.length-1,0,{type:"configuration_update",reasoning:{effort:$}})}function qj(Y){let J=h(Y.reasoning)?{...Y.reasoning}:{};J.context="all_turns",Y.reasoning=J,Y.parallel_tool_calls=!1;let X=Array.isArray(Y.input)?Y.input:[];L8(X);let $=[{type:"additional_tools",role:"developer",tools:Array.isArray(Y.tools)?Y.tools.filter((G)=>!(h(G)&&G.type==="web_search")):[]}];if(typeof Y.instructions==="string"&&Y.instructions.length>0)$.push({type:"message",role:"developer",content:[{type:"input_text",text:Y.instructions}]});Y.input=[...$,...X],delete Y.tools,delete Y.instructions}function Dj(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((J)=>!(h(J)&&J.type==="function"&&J.name==="web_search"))}function Pj(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((J)=>!(h(J)&&J.type==="function"&&J.name==="websearch_web_search_exa"))}function Ej(Y){if(!h(Y))return Y;if(Y.type!=="function")return Y;let J=h(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:Z,...U}=Y.parameters;return U})():Y.parameters,{type:X,name:Q,description:$,strict:G,parameters:W,...K}=Y;return{type:X,name:Q,description:$,strict:G??!1,parameters:J,...K}}async function Mj(Y,J={}){let X=J.codexApiEndpoint??g0().codexApiEndpoint,Q=crypto.randomUUID(),$=Kj(),G=()=>Uj($),W=!1,K=[],Z=null,U=Y.client.auth,L=new Map,j=new Map,N,V,q,T={},S=J.custody,c=B0("custody"),_=(M,A="")=>M?async()=>{let B=await M();return{url:B.url,instructions:B.instructions??A,method:"auto",callback:async()=>{try{let D=await B.tokens;return{type:"success",refresh:D.refresh_token,access:D.access_token,expires:Date.now()+(D.expires_in??3600)*1000,accountId:J9(D)}}finally{B.cleanup?.()}}}}:void 0;function E(M,A){return X8({storage:M,configPath:e(),loadAccounts:P0,mutateAccounts:j0,withAccountStoreTransaction:VJ,readCustodyManifest:s0,acquireRefreshFileLock:H1,auth:A,...S?{detectClaustrumConnection:async()=>S.detection==="absent"?{status:"absent",path:"test"}:{status:"available",schema:1,wireVersion:1,endpoints:[]},cacheConnector:async()=>S.transport}:{},logger:{info:(B,D)=>c.info(B,D??{}),warn:(B,D)=>c.warn(B,D??{}),debug:(B,D)=>c.debug(B,D??{}),error:(B,D)=>c.error(B,D??{})},now:S?.now})}let b=await P0(s(e())),f=await s0(),o=Y.client.auth;if(o.get&&o.all){if(f1(b??{})==="claustrum")q=E(b,{all:o.all,get:o.get,set:o.set}),S?.onRuntime?.(q),await q.boot();let M=q?.getCache();if(M)T.cache=M;if(T.mainVerdict=await yQ({client:{auth:o},mode:f1(b??{}),manifest:f,mainAccountId:b?.mainAccountId,getCredential:M?async(A)=>{return{access:(await M.get(A,v1(b))).payload.access}}:void 0,isReauth:M?(A)=>M.isReauth(A):void 0,now:Date.now,sleep:(A)=>new Promise((B)=>setTimeout(B,A))}),T.mainVerdict){let A=await r1();await z8({...A,main:{...A.main,custody:YY(T.mainVerdict)}})}}let t=new MJ,N0,W0={},O0=BQ({client:Y.client,getAuth:async()=>N0?.(),fetchImpl:fetch,dependencies:{...S?.authorize?{authorizeBrowser:_(S.authorize.browser,"Complete authorization in your browser. This window will close automatically."),authorizeHeadless:_(S.authorize.headless)}:{},custodyQuotaDeps:W0}}),c0=(M)=>async(A)=>{let B=await kJ();try{let D=await M(A);if(D.method!=="auto")return await B.release(),D;return{...D,callback:async()=>{try{let w=await D.callback();if(w.type!=="success"||!("refresh"in w))return await B.release(),w;return iQ({accessToken:w.access??"",refreshToken:w.refresh,getAuth:async()=>{let m=await U.get({path:{id:"openai"}});return h(m)&&typeof m.access==="string"&&typeof m.refresh==="string"?{access:m.access,refresh:m.refresh}:void 0},onObserved:({access:m,refresh:p})=>hQ({type:"oauth",access:m,refresh:p}),release:()=>B.release(),warn:(m)=>S?.warn?.(m)??c.warn(m),now:S?.now??Date.now,sleep:S?.sleep??((m)=>Bun.sleep(m))}).catch(()=>B.release()),w}catch(w){throw await B.release(),w}}}}catch(D){throw await B.release(),D}},z1=O0.map((M)=>M.type==="oauth"?{...M,authorize:c0(M.authorize)}:M);async function u(M,A){let B=Y.client.session;if(typeof B?.promptAsync==="function"){let D=await P5(Y.client,M),w={noReply:!0,parts:[{type:"text",text:A,ignored:!0}]};if(D?.agent)w.agent=D.agent;if(D?.model)w.model=D.model;if(D?.variant)w.variant=D.variant;await B.promptAsync({path:{id:M},body:w});return}}return{async dispose(){t.stop(),q?.dispose(),N?.stopBackgroundRefresh(),N=void 0;for(let B of K)B.close();K.length=0;let M=globalThis;for(let[B,D]of L)if(M.__openaiAuthCacheKeepManagers?.get(B)===D)D.stop(),M.__openaiAuthCacheKeepManagers.delete(B);L.clear();let A=globalThis;for(let[B,D]of j)if(A.__openaiAuthRpcServers?.get(B)===D)await D.stop().catch(()=>{}),A.__openaiAuthRpcServers.delete(B);j.clear()},async event(M){if(M.event.type!=="session.deleted")return;let A=M.event.properties.info,B=$.get(A.id);if(B)Z?.cacheKeepManager?.remove(B.threadID);if($.delete(A.id))G();if(V){let D=(await P0(s(e())))?.accounts;await d4(A.id,D,V)}for(let D of K)D.remove(A.id)},provider:{id:"openai",async models(M,A){if(A.auth?.type!=="oauth")return M.models;let B=await P0(s(e())),D=!B||h4(B),w=D?null:await j5();if(!D&&w&&!P4)P4=!0,D4.debug("restoring OAuth model costs from models.dev catalog");if(!D&&!w&&!E4)E4=!0,D4.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(M.models).filter(([,m])=>{if(m.options.reasoningMode==="pro")return!1;if(lF.has(m.api.id))return!0;if(dF.has(m.api.id))return!1;let n=m.api.id.match(/^gpt-(\d+(?:\.\d+)?)/)?.[1];return n?parseFloat(n)>5.4:!1}).map(([m,p])=>[m,{...p,cost:D?{input:0,output:0,cache:{read:0,write:0}}:w?.[p.api.id]??w?.[m]??p.cost,limit:p.id.includes("gpt-5.5")?{context:400000,input:272000,output:128000}:p.id.includes("gpt-6-astra")?{context:872000,input:744000,output:128000}:p.id.includes("gpt-5.6")||p.id.includes("gpt-6-sol")||p.id.includes("gpt-6-luna")?{context:372000,input:244000,output:128000}:p.limit}]))}},tool:{web_search:L5},auth:{provider:"openai",async loader(M){N0=M;let A=await M();if(A.type!=="oauth")return{};let B=IY(A),D=B.kind==="tombstone"||B.kind==="empty",w=Y.directory?await n4(Y.directory):void 0,m=w?.dir??e();if(!D)await y4({type:"oauth",access:A.access??"",refresh:A.refresh??"",expires:A.expires??0},s(e()));let p=await P0(s(e())).catch((H)=>{let F=e();throw Error(`OpenAI auth store at ${F} is corrupt or unreadable: ${H instanceof Error?H.message:String(H)}. Fix or remove it to continue.`,{cause:H})}),n;async function z0(){let H=e();try{let F=uF(H);if(n?.path===H&&n.mtimeMs===F.mtimeMs&&n.size===F.size)return n.storage;let O=await P0(s(H));return n={path:H,mtimeMs:F.mtimeMs,size:F.size,storage:O},O}catch{return n=void 0,P0(s(H))}}function r(){n=void 0}if(p&&A.access&&!D){let H=J9({id_token:"",access_token:A.access,refresh_token:A.refresh??""});if(H&&H!==p.mainAccountId)await j0((F)=>{return F.mainAccountId=H,F},s(e())),p.mainAccountId=H,r()}let v0=p?.logging?.level;if(v0&&typeof v0==="string")CY(v0);let K1=B0("transport"),A0=B0("quota"),a1=B0("refresh"),J1=B0("accounts");K1.info("codex auth loader ready",{codexApiEndpoint:X,transport:g0().rawWebSocket?"raw-websocket":g0().webSockets?"websocket":"http",webSearch:g0().webSearch});let X0=new TY({storage:p,configPath:e(),fetchQuotaFn:void 0}),o0,V9=0,Q0=new f4({paths:s(e()),refreshFn:(H)=>HJ({refreshToken:H.refreshToken,fetchImpl:H.fetchImpl,now:H.now}),quotaManager:X0,custody:{readManifest:s0},onFallbackStorageChanged:r}),R0=q??E(p);if(!q)S?.onRuntime?.(R0),await R0.boot(),q=R0;if(D){let H=await s0(),F=LJ(H,"main"),O=R0.getCache();if(F&&O)try{let C=await O.get(F,v1(p)),I=k9(C.payload.access);if(I&&I!==p?.mainAccountId){if(await j0((k)=>{return k.mainAccountId=I,k},s(e())),p)p.mainAccountId=I;T.mainAccountId=I,r()}}catch{}}if(R0.runTick().catch((H)=>c.warn("custody first tick failed",{error:H instanceof Error?H.message:String(H)})),q=R0,p&&p.accounts.length>0)Q0.startBackgroundRefresh();let g1=R0;async function WY(H,F){let O=await s0();return KJ(H,O,E0)}async function t1(H,F){let O=await s0(),C=g1.getCache(),I=LJ(O,H.id);if(!C||!I)return G8(H,F,O);return G8(H,F,O,{cache:C,manifestHandle:I,requestPath:!0,now:S?.now??Date.now,refreshBeforeExpiryMs:(F.refresh?.refreshBeforeExpiryMinutes??240)*60000,completeEnrollmentDeps:{loadAccounts:P0,readCustodyManifest:s0,acquireRefreshFileLock:H1,configPath:e(),paths:s(e()),cache:C,minTtlMs:v1(F),mutateAccounts:j0,provider:E0,now:Date.now}})}async function V8(H){if(f1(H)!=="claustrum")return s1;let F=await s0(),O=LJ(F,"main"),C=g1.getCache(),I=(v)=>{return c.warn("custody main request refused",{reason:v}),h1};if(!O||!C)return I("no-handle");let k=(S?.now??Date.now)();if(C.isBlocked(O))return I("blocked");if(C.isReauth(O,k))return I("reauth");let x=await C.peek(O);if(!x||x.expiresAtMs<=k)return I("cache-miss");return{token:x.payload.access,provenance:{handle:O,recordVersion:x.recordVersion}}}async function N9(H){let F=g1.getCache();if(!F)return;await F.reportAuthFailure({handle:H.handle,providerStatus:H.providerStatus,recordVersion:H.recordVersion})}Object.assign(W0,{isFallbackRefreshInert:WY,resolveFallbackAccess:t1,reportCustodyAuthFailure:N9});function zY(H={}){let{readSidebarState:F,respectBackoff:O,skipFresherThanMs:C}=H;return{getAuth:M,codexRefreshFn:HJ,refreshMainWithLease:ZY,fallbackManager:Q0,quotaManager:X0,loadAccounts:P0,writeSidebarState:LY,client:Y.client,fetchImpl:fetch,now:Date.now,paths:s(e()),readSidebarState:F??(()=>r1(u0)),storageMainAccountId:p?.mainAccountId,isOAuthAccountFn:V0,whamFn:RY,isFallbackRefreshInert:WY,resolveFallbackAccess:t1,resolveMainAccess:V8,reportCustodyAuthFailure:N9,...O===void 0?{}:{respectBackoff:O},...C===void 0?{}:{skipFresherThanMs:C}}}let N8=B0("cachekeep"),B8=p?.cachekeep?.enabled===!0,F8=p?.cachekeep?.subagents===!0,j8=p?.cachekeep?.sustain===!0,O8=EQ(p),KY;async function t4(H){await new Promise((F)=>setTimeout(F,H))}async function e4(H){let F;for(let O=1;O<=q4;O++)try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:H.refresh,access:H.access,expires:H.expires}});return}catch(C){if(F=C,O<q4)await t4(Yj*O)}throw new H8(F)}async function UY(H){await j0((F)=>{return F.refresh=F.refresh??{},H(F),F},s(e())),r()}async function q8(H){let F=Date.now()+eF;while(Date.now()<F){await new Promise((I)=>setTimeout(I,O4+Gj(O4)));let O=await M();if(O.type!=="oauth"||!O.access)continue;if((O.access!==H.access||O.refresh!==H.refresh||(O.expires??0)>(H.expires??0)+60000)&&(!O.expires||O.expires>Date.now()))return a1.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:O.expires?O.expires-Date.now():void 0}),{access:O.access,refresh:O.refresh??H.refresh??"",expires:O.expires??0}}return null}async function ZY(){if(!KY)KY=(async()=>{let H=await M();if(H.type!=="oauth")throw Error("not oauth");if(k0({id:"main",type:"oauth",access:H.access??"",refresh:H.refresh??"",expires:H.expires??0,addedAt:0},E0))throw new b4(E0);if(!H.refresh)throw Error("Token refresh failed: missing refresh token");let F=_4(H.refresh),O=await P0(s(e())),C=O?.refresh?.mainLastRefreshError;if(C&&EY(C,H.refresh,Date.now()))throw Error(S4(C,Date.now()));if(O?.refresh?.mainRefreshLeaseUntil&&O.refresh.mainRefreshLeaseUntil>Date.now()&&O.refresh.mainRefreshLeaseTokenHash===F){let v=await q8(H);if(v)return v;throw Error("Codex OAuth refresh is already in progress")}let I=await H1({name:c1,ttlMs:Q8,path:e(),renew:!0});if(!I){let v=await q8(H);if(v)return v;throw Error("Codex OAuth refresh is already in progress")}let k=crypto.randomUUID(),x=F;try{await UY((l)=>{l.refresh=l.refresh??{},l.refresh.mainRefreshLeaseId=k,l.refresh.mainRefreshLeaseUntil=Date.now()+tF,l.refresh.mainRefreshLeaseTokenHash=F});let v=await P0(s(e()));if(v?.refresh?.mainRefreshLeaseId!==k||v.refresh.mainRefreshLeaseTokenHash!==F)throw Error("Codex OAuth refresh is already in progress");let y=await HJ({refreshToken:H.refresh,fetchImpl:fetch,now:Date.now});return await e4(y),await UY((l)=>{if(l.refresh=l.refresh??{},l.refresh.mainLastRefreshError=void 0,l.refresh.mainRefreshLeaseId===k)l.refresh.mainRefreshLeaseId=void 0,l.refresh.mainRefreshLeaseUntil=void 0,l.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),x=void 0,y}catch(v){if(H.refresh&&!$8(v))await UY((y)=>{y.refresh=y.refresh??{},y.refresh.mainLastRefreshError=I4({error:v,now:Date.now(),refreshToken:H.refresh??"",previous:y.refresh.mainLastRefreshError})}).catch(()=>{});throw v}finally{if(x)await UY((v)=>{if(v.refresh?.mainRefreshLeaseId===k&&v.refresh.mainRefreshLeaseTokenHash===x)v.refresh.mainRefreshLeaseId=void 0,v.refresh.mainRefreshLeaseUntil=void 0,v.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await I.release().catch(()=>{})}})().finally(()=>{KY=void 0});return KY}let D8=globalThis,BJ=D8.__openaiAuthCacheKeepManagers??new Map;D8.__openaiAuthCacheKeepManagers=BJ,BJ.get(m)?.stop();let B9=new CJ({fetchImpl:fetch,getMainToken:async()=>{let H=await M();if(H.type!=="oauth")throw Error("not oauth");if(!H.access||(H.expires??0)<Date.now())try{return(await ZY()).access}catch(F){if($8(F))throw F;if(H.access)return H.access;throw Error("main token refresh failed")}return H.access},refreshFallback:async(H)=>{let F=await z0(),O=F?Nj(F.accounts,H):void 0;if(!O)throw Error(`fallback account ${H} not found`);let C=F??{version:1,accounts:[O]},I=O;if(!await WY(O,C))I=await Q0.refreshAccount(O,C);let k=await t1(I,C);if(k===h1||k===s1)throw Error(`no access token for ${H}`);return{token:k.token,onAuthFailure:k.provenance==="local"?void 0:async(x)=>{await N9({handle:k.provenance.handle,providerStatus:x,recordVersion:k.provenance.recordVersion})}}},codexResponsesUrl:X,logger:N8,now:Date.now,getWindow:()=>O8,getSustain:()=>j8});BJ.set(m,B9),L.set(m,B9);async function F9(H,F,O,C,I=!1){if(Object.keys(H).length===0&&!I)return;let k=Date.now(),x=H,v={quota:x,refreshAfter:k+300000,checkedAt:k},y;if(O&&O!=="main"){let d=F?Q1(F):null,U0=d?$1(d):void 0,p0=X0.peekFallbackForPolicy(O)?.quota,T0=R4(x,p0);v={...v,quota:T0},X0.setFallback(O,v,F,I,U0)}else{if(y=C,!y&&F){let p0=Q1(F);y=p0?$1(p0):void 0}if(y&&o0&&y!==o0){A0.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:y,currentMainIdentity:o0});return}let d=X0.peekMainForPolicy(y)?.quota,U0=R4(x,d);v={...v,quota:U0},X0.setMain(F,v,y,I)}A0.debug("quota pushed",{pid:process.pid,accountId:O??"main",snapshot:v.quota});let l=await z0();await LY(X0,l,O&&O!=="main"?l?.mainAccountId:y)}function YU(H,F,O){let C=H==="main"?X0.peekMainForPolicy()?.quota:X0.peekFallbackForPolicy(H)?.quota;return v4(C,F,Date.now(),Jj,O)}let j9=J.experimentalWebSockets?x1.createWebSocketFetch({httpFetch:fetch,rawWebSocket:g0().rawWebSocket,onQuota:(H,F,O,C)=>{F9(H,F,O,!O||O==="main"?C:void 0,!0)},onRateLimitReached:(H,F,O)=>{if(!F)A0.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:H});let C=F??"main",I=YU(C,H,O);X0.markRateLimited(C,I),A0.debug("mid-stream rate limit mark",{pid:process.pid,accountId:C,window:H})}}):void 0;if(j9)K.push(j9),W=!0;let u0=m4();V=u0;async function LY(H,F,O=F?.mainAccountId){if(!F)return;await z8(a4(H,F,Date.now(),O,JU),u0)}function JU(H,F){if(!V0(H))return;return g1.getCustodyProjection(H,F)}async function P8(H,F,O,C,I){let k={activeId:O,route:C,updatedAt:Date.now()};if(H){if(await NJ({sessionId:H,...k},I,u0),F&&F!==H){if(C==="sticky-balanced"){let x=(await r1(u0)).stickyAssignments?.[GY(F)]?.accountId,v=I===void 0||x==="main"||I.some((y)=>y.enabled!==!1&&y.id===x);if(!x||!v)return;await NJ({sessionId:F,activeId:x,route:C,updatedAt:Date.now()},I,u0);return}await NJ({sessionId:F,...k},I,u0)}return}await l4(k,u0)}let XU=async(H,F)=>{let O=await H1({name:M1(H),ttlMs:b1,path:e(),renew:!0});if(!O)throw Error("Fallback account lock unavailable");try{return await F()}finally{await O.release()}},QU=S?.withFallbackAccountLock??XU,$U=async(H)=>{let F=await s0();if(!F.ok)return{ready:!1,reason:"manifest-unreadable"};let O=LJ(F,H.id);if(!O)return{ready:!1,reason:"no-handle"};let C=R0.getCache();if(!C)return{ready:!1,reason:"vault-cold"};if(C.isReauth(O,S?.now?.()??Date.now()))return{ready:!1,reason:"vault-reauth"};if(C.isBlocked(O))return{ready:!1,reason:"vault-cold"};try{let I=await C.get(O,v1(p)),k=k9(I.payload.access);if(!k||H.accountId&&H.accountId!==k)return{ready:!1,reason:"identity-mismatch"};return{ready:!0,accountId:k}}catch{return{ready:!1,reason:C.isReauth(O,S?.now?.()??Date.now())?"vault-reauth":"vault-cold"}}};N?.stopBackgroundRefresh(),N=Q0,Z={accountStoragePath:e(),accountStatePath:PY(e()),packageVersion:P9,quotaManager:X0,loadAccounts:P0,client:Y.client,beginAccountLogin:AY,withFallbackAccountLock:QU,checkUsableCustodyBinding:$U,enterClaustrumMode:async()=>{let H=await P0(s(e())),F=(H?.accounts??[]).filter((O)=>O.type==="oauth"&&O.enabled!==!1).map((O)=>O.id);return oQ({accountIds:F,acquireLock:({name:O,renew:C})=>H1({name:O,ttlMs:O===c1?Q8:b1,path:e(),renew:C}),withStoreTransaction:(O)=>VJ(O,s(e())),readManifest:s0,preflight:async({accountId:O,handle:C})=>{c.info("preflight probing participant",{accountId:O,hasHandle:C.length>0});let I=await R0.ensureCache(),k=I?.isBlocked(C);if(!I||k)return c.warn("preflight vault-cold",{accountId:O,hasCache:I!==void 0,blocked:k}),"vault-cold";if(I.isReauth(C,S?.now?.()??Date.now()))return"vault-reauth";try{let x=await I.get(C,v1(H)),v=k9(x.payload.access);if(!v||O&&O!==v)return"identity-mismatch";return"ready"}catch{return I.isReauth(C,S?.now?.()??Date.now())?"vault-reauth":"vault-cold"}},auth:{all:async()=>{if(typeof U.all==="function")return U.all();let O=process.env.XDG_DATA_HOME??K8(UJ.homedir(),".local","share"),C=K8(O,"opencode","auth.json");try{let I=JSON.parse(r4(C,"utf8"));return h(I)?I:{}}catch{return{}}},get:async(O)=>{if(typeof U.get==="function")return U.get(O);if(O.path.id!=="openai"||!N0){c.warn("auth.get unavailable for slot",{id:O.path.id,hasLoaderGetAuth:N0!==void 0});return}return N0()},set:async(O)=>{await U.set(O)}},warn:(O)=>c.warn(O)})},leaveClaustrumMode:()=>nQ({acquireLock:({name:H,renew:F})=>H1({name:H,ttlMs:Q8,path:e(),renew:F}),withStoreTransaction:(H)=>VJ(H,s(e()))}),resolveResetTarget:Qj({getAuth:M,refreshMainWithLease:ZY,refreshFallbackAccount:(H,F)=>Q0.refreshAccount(H,F),loadAccounts:P0,accountStoragePath:e(),accountStatePath:PY(e()),now:Date.now,isFallbackRefreshInert:WY,resolveFallbackAccess:t1,reportAuthFailure:N9}),...$j(),cacheKeepManager:B9,setCacheKeepEnabled:(H)=>{B8=H},setCacheKeepSubagents:(H)=>{F8=H},setCacheKeepSustain:(H)=>{j8=H},setCacheKeepWindow:(H)=>{O8=H},clearStickyRouting:(H)=>o4(H,u0),getStickyRouting:async(H)=>p4(await r1(u0),H),refreshSidebar:async()=>{let H=await P0(s(e()));await LY(X0,H)},refreshAllQuota:async()=>E1(zY()),refreshResetTargetQuota:async(H)=>{return(await E1(zY({respectBackoff:!1}),{accountKey:H})).find((O)=>O.account===H)??{account:H,ok:!1,error:"targeted quota refresh returned no result"}}};let FJ=null;if(w){let H=globalThis,F=H.__openaiAuthRpcServers??new Map;H.__openaiAuthRpcServers=F;let O=F.get(w.dir);if(O)await O.stop().catch(()=>{}),F.delete(w.dir);try{FJ=await T5({dir:w.dir,secureDir:w.secureDir,sweepRoot:w.sweepRoot,drain:M5,apply:async(C)=>{let I={...Z,sessionId:C.sessionId},k=await EJ(C.command,C.arguments,I);return{text:k.text,knobs:k.knobs}}}),F.set(w.dir,FJ),j.set(w.dir,FJ)}catch{}}let E8=new WeakMap;function GU(H,F){let O=E8.get(H);if(!O||F.hostname!=="chatgpt.com"||!F.pathname.startsWith("/backend-api/codex/"))return;if(H.status>=200&&H.status<300){g1.getCache()?.markVaultSuccess(O.handle);return}if(H.status!==401)return;N9({handle:O.handle,providerStatus:H.status,recordVersion:O.recordVersion}).catch(()=>{})}async function O9(H,F,O,C,I="main",k){if(!O.trim())throw K1.warn("refusing to send a request with no access token",{account:I,accountId:C,hasProvenance:Boolean(k&&k!=="local")}),Error(iF);let x=T4(H,F);if(x.delete("x-api-key"),x.delete("api-key"),x.set("authorization",`Bearer ${O}`),C)x.set("ChatGPT-Account-Id",C);x.set(x1.QUOTA_ACCOUNT_HEADER,I);let v=C4(x),y=v?zj($,v,G):void 0,l=H instanceof URL?H:new URL(typeof H==="string"?H:H.url),d=l.pathname.includes("/v1/responses")||l.pathname.includes("/chat/completions")?new URL(X):l,U0=(_0)=>{let e1=x4(_0,k,E8);return GU(e1,d),e1},T0=Vj({init:{...F,headers:x},headers:x,metadata:y,installationID:Q,websocket:Boolean(j9&&l.pathname.endsWith("/responses")),responsesLite:J.responsesLite??!1,dumpSessionID:v}).init,U1=B8,P1=new Headers(T0?.headers),l0=PQ({enabled:U1,includeSubagents:F8,headers:P1,body:T0?.body});if(U1)N8.trace("cachekeep headers",{pid:process.pid,hasParent:P1.has("x-parent-session-id"),sessionKey:l0?.sessionKey,captured:Boolean(l0),affinity:P1.get("x-session-affinity"),opencodeSession:P1.get("x-opencode-session"),sessionId:P1.get("session-id")});if(j9&&l.pathname.endsWith("/responses")){if(K1.debug("WS transport",{pid:process.pid,pathname:l.pathname,accountId:I}),l0)B9.track(l0.sessionKey,l0.bodyText,I,C,l0.replayHeaders,l0.isSubagent);return U0(await j9(d,T0))}let C0=x1.withoutInternalHeaders(T0);if(typeof C0?.body!=="string")return U0(await fetch(d,C0));if(l0)B9.track(l0.sessionKey,l0.bodyText,I,C,l0.replayHeaders,l0.isSubagent);K1.debug("HTTP transport",{pid:process.pid,pathname:l.pathname,accountId:I});try{let _0=await fetch(d,C0);return await G9({sessionID:v,transport:"http",phase:"http",bodyText:C0.body,accountId:I,url:d.toString(),method:C0.method,headers:C0.headers,status:_0.status}),U0(H5(_0))}catch(_0){throw await G9({sessionID:v,transport:"http",phase:"http",bodyText:C0.body,accountId:I,url:d.toString(),method:C0.method,headers:C0.headers,error:_0 instanceof Error?_0.message:String(_0)}),_0}}function HY(H,F){if((F?.method??(H instanceof Request?H.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof F?.body!=="string")return!1;try{let C=H instanceof URL?H.toString():typeof H==="string"?H:H.url;return new URL(C).pathname.endsWith("/responses")}catch{return!1}}function WU(H){return X0.peekMainForPolicy(H)?.quota}function M8(H,F){for(let O of[H?.primary?.checkedAt,H?.secondary?.checkedAt,H?.checkedAt,F])if(typeof O==="number"&&Number.isFinite(O))return O;return}function q9(H,F,O,C,I){let k=M8(H,F),x=M8(O),v=C===I&&O!=null&&(H===void 0||x!==void 0&&(k===void 0||x>k));return{quota:v?O:H,quotaCheckedAt:v?x:k,source:v?"file":"memory"}}function w8(H,F,O,C,I){let k=H?.quota,x=q9(k,H?.checkedAt,F,C,I),v=x.source,y=x.quota;if(!u4(y,O))return{exhausted:!1};let l=c4(y,O);if(!l)return{exhausted:!1};return{exhausted:!0,source:v,...l}}function A8(H,F){A0.debug("admission skip: exhausted account",{accountId:H,source:F.source,resetsAt:F.resetsAt})}function zU(H,F="killswitch",O){let C=Date.now(),I=X0.getMain()?.quota,k=(H?.accounts??[]).filter((d)=>d.enabled!==!1&&V0(d)).map((d)=>({accountId:d.id,quota:X0.getFallback(d.id)?.quota})),x=g4(I,k,C,H);if(F==="quota-exhausted"&&O!==void 0)x=Math.max(1,Math.ceil((O-C)/1000));else if(F==="mid-stream-rate-limit"&&O!==void 0){let d=Math.max(1,Math.ceil((O-C)/1000));x=Math.min(x,d)}let v=Math.floor(x/60),y=x%60,l=F==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${v}m ${y}s.`:F==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${v}m ${y}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${v}m ${y}s.`;return new Response(JSON.stringify({error:{message:l,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(x)}})}function R8(H){let F=H?.resetCreditsAvailable;return typeof F==="number"&&Number.isFinite(F)?F:void 0}async function KU(H){let F=QY(H.storage),O=Date.now(),C=X0.peekMainForPolicy(H.mainAccountIdentity),I=q9(C?.quota,C?.checkedAt,H.sidebarState.main.quota,H.sidebarState.main.mainAccountId,H.mainAccountIdentity),k=F?$Y(C?.quota,H.storage,void 0,O):void 0,x=H.mainCustodyRefused?[]:[{accountId:"main",wireAccountId:H.mainAccountIdentity,access:H.primaryAccess,provenance:H.primaryProvenance,keepwarmAccountKey:"main",quota:I.quota,quotaCheckedAt:I.quotaCheckedAt,reservePercent:W8(H.storage),configuredOrder:0,resetCreditsApplicable:R8(I.quota),killswitchPasses:k}],v=await Q0.getUsableFallbackAccounts(H.storage);if(!H.storage)return x;for(let y of v){let l=await t1(y,H.storage);if(l===h1||l===s1)continue;let d=H.sidebarState.fallbacks.find((U1)=>U1.id===y.id),U0=X0.peekFallbackForPolicy(y.id,y.accountId),p0=q9(U0?.quota,U0?.checkedAt,d?.quota,d?.accountId,y.accountId),T0=F?$Y(U0?.quota,H.storage,y.id,O):void 0;x.push({accountId:y.id,wireAccountId:y.accountId,access:l.token,provenance:l.provenance,keepwarmAccountKey:y.id,fallback:y,quota:p0.quota,quotaCheckedAt:p0.quotaCheckedAt,reservePercent:W8(H.storage,y.id),configuredOrder:x.length,resetCreditsApplicable:R8(p0.quota),killswitchPasses:T0})}return x}function T8(H,F,O,C,I){let k=QY(I)?H.killswitchPasses:void 0;if(H.accountId==="main"){let l=X0.peekMainForPolicy(H.wireAccountId),d=q9(l?.quota,l?.checkedAt,F.main.quota,F.main.mainAccountId,H.wireAccountId);return hJ({quota:d.quota,quotaCheckedAt:d.quotaCheckedAt,status:O,now:C,killswitchPasses:k})}let x=F.fallbacks.find((l)=>l.id===H.accountId),v=X0.peekFallbackForPolicy(H.accountId,H.wireAccountId),y=q9(v?.quota,v?.checkedAt,x?.quota,x?.accountId,H.wireAccountId);return hJ({quota:y.quota,quotaCheckedAt:y.quotaCheckedAt,status:O,now:C,killswitchPasses:k})}function UU(H){return H.accountId==="main"?"main":H.keepwarmAccountKey}function C8(H){return X0.isRateLimited(UU(H))}async function jJ(H){let F=H.candidates.filter((y)=>!C8(y)),O=new Map(F.map((y)=>[y.accountId,y])),C=Object.fromEntries(F.map((y)=>[y.accountId,y.quotaCheckedAt])),I=Object.fromEntries(F.map((y)=>[y.accountId,y.wireAccountId])),k=new Set(H.excludeAccountIds),x,v=await i4({sessionId:H.sessionId,requestBytes:H.requestBytes,now:H.now,validPinnedAccountIds:[...O.keys()],excludeAccountIds:H.excludeAccountIds,quotaCheckedAtByAccount:C,wireAccountIdByAccount:I,choose:(y)=>{let l=F.filter((U0)=>!k.has(U0.accountId));if(l.length===0)return;let d=Y5({candidates:l,pendingBytes:y,requestBytes:H.requestBytes,now:H.now,onEmptyWeightedSet:()=>{J1.debug("sticky routing: no fresh weighted candidates; using configured order")}});if(!d)return;return x={accountId:d.accountId,source:d.source,pendingBytes:y.get(d.accountId)??0},d}},u0);if(x&&v?.accountId===x.accountId)J1.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:GY(H.sessionId),accountId:x.accountId,source:x.source,requestBytes:H.requestBytes,pendingBytes:x.pendingBytes});return v?O.get(v.accountId):void 0}async function ZU(H,F){let O=await Q0.getUsableFallbackAccounts(H),C=[];if(!H)return{current:[],retained:[],skipped:[]};for(let d of O){let U0=await t1(d,H);if(U0===h1||U0===s1)continue;C.push({access:U0.token,provenance:U0.provenance,accountId:d.accountId,keepwarmAccountKey:d.id,quotaAccountId:d.id,fallback:d})}let I=C.filter((d)=>!X0.isRateLimited(d.quotaAccountId)),k=QY(H)?I.filter((d)=>$Y(X0.peekFallbackForPolicy(d.quotaAccountId,d.accountId)?.quota,H,d.quotaAccountId,Date.now())):I,x=new Map(F.fallbacks.map((d)=>[d.id,{quota:d.quota,accountId:d.accountId}])),v=[],y=[],l=Date.now();for(let d of k){let U0=x.get(d.quotaAccountId),p0=w8(X0.peekFallbackForPolicy(d.quotaAccountId,d.accountId),U0?.quota,l,U0?.accountId,d.accountId);if(p0.exhausted)y.push({candidate:d,decision:p0});else v.push(d)}return{current:k,retained:v,skipped:y}}function _8(H,F){if(H.retained.length===0&&!F)return H.current;for(let{candidate:O,decision:C}of H.skipped)A8(O.quotaAccountId,C);return H.retained}async function I8(H,F){try{let O=X9(H.headers);await F9(O,F.access,F.quotaAccountId,void 0,JY(H.headers))}catch{}}async function LU(H,F,O,C){for(let I of C){let k;try{k=await O9(H,F,I.access,I.accountId,I.keepwarmAccountKey,I.provenance)}catch(x){if(x instanceof DOMException&&x.name==="AbortError")throw x;if(F?.signal?.aborted)throw x;throw J1.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:I.quotaAccountId}),x}if(!XY(k.status,O))return Q0.markUsed(I.fallback),{response:k,accessToken:I.access,quotaAccountId:I.quotaAccountId,activeId:I.keepwarmAccountKey};await I8(k,I),k.body?.cancel().catch(()=>{})}return}async function HU(H,F,O,C,I){if(!HY(H,F))return{response:O};if(!I.length)return{response:O};let k=O,x;for(let v of I){let y;try{y=await O9(H,F,v.access,v.accountId,v.keepwarmAccountKey,v.provenance)}catch(l){if(l instanceof DOMException&&l.name==="AbortError")throw l;if(F?.signal?.aborted)throw l;return J1.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:v.quotaAccountId}),{response:k,...x}}if(k.body?.cancel().catch(()=>{}),k=y,x={accessToken:v.access,accountId:v.quotaAccountId},!XY(y.status,C))return Q0.markUsed(v.fallback),{response:y,...x};await I8(y,v)}return{response:k,...x}}if(p){let H=[];for(let F of p.accounts)if(V0(F))H.push(F);X0.seedFallbacksFromAccounts(H)}if(!Z8)Z8=!0,LY(X0,p).catch(()=>{}),E1(zY({respectBackoff:!0})).catch((H)=>A0.warn("boot quota seed failed",{pid:process.pid,error:t9(H)}));return t.start(async()=>{let F=(await FQ(zY({readSidebarState:()=>r1(u0)}))).filter((O)=>!O.ok);if(F.length>0)A0.warn("background quota refresh completed with failures",{pid:process.pid,failures:F})},(H)=>{A0.warn("background quota refresh failed",{pid:process.pid,error:H instanceof Error?H.message:String(H)})}),{apiKey:nF,async fetch(H,F){let O=T4(H,F),C=C4(O),I=O.get("x-parent-session-id")?.trim()||void 0,k=await z0(),x=await M(),v=++V9;if(x.type!=="oauth")return fetch(H,F);F=await Bj(H,F);let y=D&&f1(k)==="claustrum",l="",d,U0=!1;if(y){let $0=await V8(k);if($0===h1||$0===s1)U0=!0;else l=$0.token,d=$0.provenance==="local"?void 0:$0.provenance}else{if(!x.access||(x.expires??0)<Date.now()){a1.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(x.access),expiresInMs:x.expires?x.expires-Date.now():void 0});try{let $0=await ZY();x.access=$0.access,x.refresh=$0.refresh,x.expires=$0.expires}catch($0){if($8($0))throw $0}}l=x.access??""}let T0=x.accountId??(l?$1(Q1(l)??{}):void 0);if(v===V9)o0=T0;let U1=k?.routing?.mode??"main-first",P1,C0=await(()=>{return P1??=r1(u0),P1})();if(U1==="sticky-balanced"&&C&&HY(H,F)&&typeof F?.body==="string"){let $0=Buffer.byteLength(F.body,"utf8"),M0=await KU({storage:k,sidebarState:C0,primaryAccess:l,mainAccountIdentity:T0,mainCustodyRefused:U0,primaryProvenance:d}),q0=await jJ({sessionId:C,requestBytes:$0,candidates:M0,now:Date.now()});if(q0){let g8=C8(q0)?{action:"migrate",reason:"exhausted"}:T8(q0,C0,void 0,Date.now(),k);if(g8.action==="migrate"){let h0=await jJ({sessionId:C,requestBytes:$0,candidates:M0,excludeAccountIds:[q0.accountId],now:Date.now()});if(h0)J1.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:GY(C),fromAccountId:q0.accountId,toAccountId:h0.accountId,reason:g8.reason}),q0=h0}let X1=await O9(H,F,q0.access,q0.wireAccountId,q0.keepwarmAccountKey,q0.provenance),y8=async(h0,y1)=>{try{let VU=X9(h0.headers);await F9(VU,y1.access,y1.accountId==="main"?void 0:y1.accountId,y1.accountId==="main"?y1.wireAccountId:void 0,JY(h0.headers))}catch{}};await y8(X1,q0);let f8=T8(q0,C0,X1.status,Date.now(),k);if((X1.status===401||X1.status===403||X1.status===429)&&f8.action==="migrate"){let h0=await jJ({sessionId:C,requestBytes:$0,candidates:M0,excludeAccountIds:[q0.accountId],now:Date.now()});if(h0){J1.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:GY(C),fromAccountId:q0.accountId,toAccountId:h0.accountId,reason:f8.reason});let y1=X1;X1=await O9(H,F,h0.access,h0.wireAccountId,h0.keepwarmAccountKey,h0.provenance),y1.body?.cancel().catch(()=>{}),q0=h0,await y8(X1,q0)}}if(q0.fallback&&!XY(X1.status,k))Q0.markUsed(q0.fallback);return await P8(C,I,q0.accountId,U1,k?.accounts).catch(()=>{}),X1}}let _0=w8(X0.peekMainForPolicy(T0),C0.main.quota,Date.now(),C0.main.mainAccountId,T0),e1=QY(k)&&!$Y(WU(T0),k,void 0,Date.now()),VY=X0.isRateLimited("main"),S8,OJ=()=>{return S8??=ZU(k,C0),S8},Z1,Y9,k8=!1,NY;if(U1==="fallback-first"&&HY(H,F)){k8=!0;let $0=await OJ();NY=_8($0,!e1&&!VY&&!_0.exhausted);let M0=await LU(H,F,k,NY);if(M0)Z1=M0.response,Y9={accessToken:M0.accessToken,accountId:M0.quotaAccountId,activeId:M0.activeId}}if(!Z1){let $0=_0.exhausted&&HY(H,F)&&(await OJ()).retained.length>0;if(e1||VY||$0){let M0=e1?"killswitch":VY?"mid-stream-rate-limit":"quota-exhausted";if(M0==="quota-exhausted"&&_0.exhausted)A8("main",_0);J1.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:M0}),Z1=zU(k,M0,M0==="quota-exhausted"&&_0.exhausted?_0.resetAtMs:VY?X0.rateLimitedUntil("main"):void 0)}else Z1=U0?new Response(null,{status:401}):await O9(H,F,l,T0,"main",d)}let x8=Boolean(Y9),D9=Z1,b8=Y9?.accessToken??l,v8=Y9?.accountId,h8=Y9?.activeId??"main";if(!Y9&&!k8&&XY(Z1.status,k)){J1.debug("reactive fallback triggered",{pid:process.pid,status:Z1.status}),NY??=_8(await OJ(),!1);let $0=await HU(H,F,Z1,k,NY),M0=$0.response;if(M0!==Z1){if(x8=!0,D9=M0,b8=$0.accessToken??l,v8=$0.accountId,$0.accountId)h8=$0.accountId}}try{let $0=X9(D9.headers);if(x8)await F9($0,b8,v8,void 0,JY(D9.headers));else await F9($0,l,void 0,T0,JY(D9.headers))}catch{}return await P8(C,I,h8,U1,k?.accounts).catch(()=>{}),D9}}},methods:z1},"chat.headers":async(M,A)=>{if(M.model.providerID!=="openai")return;if(A.headers.originator="opencode",A.headers["User-Agent"]=`${k4(P9)} (${UJ.platform()} ${UJ.release()}; ${UJ.arch()})`,A.headers["session-id"]=M.sessionID,W&&M.agent==="title")A.headers[x1.TITLE_HEADER]="true"},"chat.params":async(M,A)=>{if(M.model.providerID!=="openai")return;A.maxOutputTokens=void 0},config:async(M)=>{B0("commands").info("registering commands",{existing:Object.keys(M.command??{}).length,pid:process.pid}),M.command={...M.command??{},[E9]:{template:E9,description:"Show current OpenAI Codex OAuth quota usage for all accounts."},[M9]:{template:M9,description:"Manage OpenAI accounts — add, switch, remove, or reorder."},[w9]:{template:w9,description:"Show or change OpenAI account routing between main-first, fallback-first, and sticky-balanced."},[A9]:{template:A9,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."},[R9]:{template:R9,description:"Show or toggle OpenAI Codex request dump capture for debugging."},[T9]:{template:T9,description:"Show or change the plugin log level (error, warn, info, debug, trace)."},[C9]:{template:C9,description:"Keep Codex prompt cache alive during idle by shadow-replaying the last request."},[_9]:{template:_9,description:"Spend one reset credit on an exhausted Codex account."}}},"command.execute.before":async(M)=>{if(B0("commands").info("command hook entered",{command:M.command,arguments:M.arguments,modal:I9.includes(M.command),hasCmdCtx:Z!==null,pid:process.pid}),!I9.includes(M.command))return;if(!Z)B0("commands").warn("command rejected: context not loaded",{command:M.command,pid:process.pid}),await u(M.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),w4();let A=M.command,B={...Z,sessionId:M.sessionID,notify:(w)=>{iJ(w,M.sessionID)}},D=await EJ(A,M.arguments,B);if(w5(M.sessionID))iJ(D,M.sessionID);else await u(M.sessionID,D.text);w4()}}}var wj=async(Y)=>{let J=g0();return Mj(Y,{codexApiEndpoint:J.codexApiEndpoint,experimentalWebSockets:J.webSockets,responsesLite:J.responsesLite})},lM={id:"cortexkit-openai-auth",server:wj};export{C4 as resolveSidebarSessionId,Q1 as parseJwtClaims,R4 as mergePushedQuotaMetadata,mM as getMainRefreshLockName,Nj as findCachekeepFallbackAccount,$1 as extractAccountIdFromClaims,lM as default,Qj as createResetTargetResolver,pM as buildSidebarState,a4 as buildSidebarMachineState,$j as buildResetRedemptionDeps,vF as __resetSweepFailureLogDedupeForTest,cM as __resetBootQuotaSeedForTest,X8 as __createCustodyRuntimeForTest,W1 as ResetTargetResolutionError,wj as OpenAIAuthPlugin,Q8 as MAIN_REFRESH_LOCK_TTL_MS,tF as MAIN_REFRESH_LEASE_TTL_MS,iF as EMPTY_BEARER_MESSAGE,Mj as CodexAuthPlugin,H8 as AuthPersistError};
|
|
109
|
+
`)),K=!0,u=Date.now(),R!==void 0)k++;if(Z.length<F)Z.push(String(g.type));if(g.type==="response.created")R=mB(g),x1.debug("response created",{...q,responseID:R,previousResponseID:N,hasContinuation:N!==void 0});if(!pB(g.type))H=!0,cB(g,E);if(o0("idle timeout waiting for websocket"),g.type==="response.completed"||g.type==="response.done"){G=!0,hB(g,C),Y.onComplete?.(g,C),Y.onTerminal?.(g),o();return}if(g.type==="response.failed"||g.type==="response.incomplete"||g.type==="error")G=!0,Y.onTerminal?.(g),o()}function P(I){B0(new c0(t9(I),{cause:I}))}function w(I){if(G)return;let y=I.code===1009,g=new c0(y?mK:cK("WebSocket closed before response.completed",I.code,I.reason),{retryable:!y});if(y)x1.warn("websocket peer refused the request size",{...q,requestBytes:W,reason:I.reason.toString()});B0(y?yK(g):g)}function j(){let I=cJ(Y.signal);if(G)return;G=!0,S(),c(),Y.onAbort?.(I),Q?.error(I)}function M(I){if(G)return;G=!0,S(),c(),Y.onAbort?.(yB(I))}function x(I){$(),J=I,J.addEventListener("message",p),J.addEventListener("error",P,{once:!0}),J.addEventListener("close",w,{once:!0}),$=()=>{J.removeEventListener("message",p),J.removeEventListener("error",P),J.removeEventListener("close",w)};let{background:y,...g}=Y.body;o0("idle timeout sending websocket request");try{let s=JSON.stringify({type:"response.create",...g});W=s.length,J.send(s),o0("idle timeout waiting for websocket")}catch(s){if(G)return;J0(new c0(s instanceof Error?s.message:String(s),{cause:s}))}}return new Response(new ReadableStream({start(I){if(Q=I,Y.signal?.addEventListener("abort",j,{once:!0}),Y.signal?.aborted){j();return}x(J)},cancel(I){M(I)}}),{status:200,headers:{"content-type":"text/event-stream"}})}function vB(Y,X){if(Y.type!=="response.output_item.done")return;if(!i(Y.item))return;fK(Y.item,X)}function hB(Y,X){let J=Y.response;if(!i(J)||!Array.isArray(J.output))return;for(let Q of J.output)if(i(Q))fK(Q,X)}function fK(Y,X){if(Y.type!=="function_call"&&Y.type!=="custom_tool_call")return;let J=typeof Y.call_id==="string"?Y.call_id:typeof Y.id==="string"?Y.id:void 0;if(J)X.add(J)}function gB(Y,X){if(Y?.type!=="error")return;let J=Y.status??Y.status_code;if(typeof J!=="number"||J>=200&&J<300)return;return{status:J,headers:i(Y.headers)?Object.fromEntries(Object.entries(Y.headers).flatMap(([Q,$])=>typeof $==="string"||typeof $==="number"||typeof $==="boolean"?[[Q,String($)]]:[])):void 0,body:X,message:i(Y.error)&&typeof Y.error.message==="string"?Y.error.message:`${J}`}}function a9(Y){if(typeof Y==="string")try{return a9(JSON.parse(Y))}catch{return}if(!i(Y))return;let X=a9(Y.cause);if(X)return X;let J=a9(Y.body);if(J)return J;let Q=i(Y.error)?Y.error:Y,$=typeof Q.type==="string"?Q.type:void 0,G=Y.status??Y.status_code;if($!=="usage_limit_reached"&&G!==429)return;let{resets_at:W,resets_in_seconds:K}=Q,H=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:$??"primary",resetAt:H}}function yB(Y){if(pJ(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function cJ(Y){let X=Y?.reason;if(pJ(X))return X;if(fB(X))return X;return new DOMException(X instanceof Error?X.message:"Aborted","AbortError")}function fB(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function mB(Y){let X=Y.response;if(!i(X))return;return typeof X.id==="string"?X.id:void 0}function cB(Y,X){let J=i(Y.item)?Y.item:void 0;switch(Y.type){case"response.output_item.added":if(J?.type==="function_call"&&typeof J.id==="string"){X.addedItemIds.add(J.id);return}break;case"response.function_call_arguments.delta":case"response.function_call_arguments.done":if(typeof Y.item_id==="string"&&X.addedItemIds.has(Y.item_id))return;break;case"response.output_item.done":if(J?.type==="function_call"&&J.status==="completed"&&typeof J.id==="string"&&typeof J.call_id==="string"&&typeof J.name==="string"&&typeof J.arguments==="string"){X.finished=!0;return}break}X.other=!0}var uB={type:"response.completed",response:{status:"completed",incomplete_details:null,usage:{input_tokens:0,output_tokens:0,total_tokens:0}}};function pB(Y){return Y==="response.created"||Y==="response.in_progress"||Y.startsWith("codex.")}var uJ="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.",mK="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 cK(Y,X,J){let Q=[`code ${X}`];if(J.length>0)Q.push(J.toString());return`${Y} (${Q.join(": ")})`}var dJ="x-opencode-title",GX="x-openai-auth-quota-account",lJ=new Set([dJ,w1,GX,"x-opencode-session"]),dB=15000,iB=300000,nB=3300000,uK="websocket_connection_limit_reached";function oB(Y){let X=typeof Y["chatgpt-account-id"]==="string"?Y["chatgpt-account-id"]:"",J=typeof Y.authorization==="string"&&Y.authorization.startsWith("Bearer ")?Y.authorization.slice(7):"",Q=X?`acct:${X}`:`tok:${J}`;return lB("sha256").update(Q).digest("hex").slice(0,12)}function rB(Y){let X=Y?.httpFetch??globalThis.fetch,J=new Map,Q=Y?.connectTimeout??dB,$=Y?.idleTimeout??iB,G=Y?.maxConnectionAge??nB,W=Y?.streamRetries??5,K=Y?.firstEventGraceMs??250,H=Y?.rawWebSocket??!1,U=Y?.onQuota,Z=Y?.onRateLimitReached,F=setInterval(()=>R(),Math.min($,60000));if(typeof F==="object"&&"unref"in F&&typeof F.unref==="function")F.unref();function N(C,E,S){if(!E||!S)return S;iJ(C,pK(E));let c=new Headers(S.headers),o=c.get("x-codex-turn-metadata");if(!o)return S;let J0=aK(o,C.turnID,C.turnStartedAt);if(!J0)return S;return c.set("x-codex-turn-metadata",J0),{...S,headers:c}}async function V(C,E){let S=C instanceof URL?C.toString():typeof C==="string"?C:C.url,c=k0.normalizeHeaders(E?.headers),o=Y4(E),J0=_Y(o);if(E?.method!=="POST"||!new URL(S).pathname.endsWith("/responses"))return X(C,J0);let L0=(()=>{try{if(typeof E?.body!=="string")return;let M=JSON.parse(E.body);return typeof M==="object"&&M!==null?M:void 0}catch{return}})();if(!L0?.stream)return X(C,J0);if(c[dJ]==="true")return X(C,J0);let K0=c[w1]??c["x-session-affinity"]??c["session-id"],B0=K0;if(!K0)return X(C,J0);let u0=k0.normalizeHeaders(o?.headers),o0=oB(u0),p=`${K0}:${o0}:conversation`,P=typeof c[GX]==="string"?c[GX]:void 0,w=Z?(M,x)=>Z(M,P,x):void 0,j=J.get(p)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};if(J.set(p,j),j.fallback)return X(C,N(j,L0,J0));if(j.busy)return X(C,N(j,L0,J0));j.busy=!0,j.lastUsedAt=Date.now();try{let M=pK(L0),x=k0.normalizeHeaders(o?.headers),I=typeof x.authorization==="string"&&x.authorization.startsWith("Bearer ")?x.authorization.slice(7):"",y=typeof x["chatgpt-account-id"]==="string"?x["chatgpt-account-id"]:void 0,g=U?($0)=>U($0,I,P,y):void 0,s=!j.socket&&!j.continuation?$F(x):x;if(j.socket=await eB(j,Y?.url??S,s,Q,G,H,E?.signal),KF(j,M))await YF(j,M,$,{signal:E?.signal??void 0,sessionID:B0,url:Y?.url??S,headers:o?.headers,onRateLimitReached:w});let F0=()=>{},D0=()=>{},Y0=new Promise(($0,C0)=>{F0=$0,D0=C0}),z0=zF(j,M),g0=e9(sK(j,z0,M)),$1=typeof g0.previous_response_id==="string";await W9({sessionID:B0,transport:"websocket",phase:"main",bodyText:JSON.stringify(g0),url:Y?.url??S,method:o?.method,headers:o?.headers});let Q0=k0.streamResponsesWebSocket({socket:j.socket,body:g0,sessionID:B0??void 0,idleTimeout:$,signal:E?.signal??void 0,onQuota:g,onRateLimitReached:w,onFirstEvent:($0)=>F0($0??!0),onComplete:($0,C0)=>{let y1=iK($0);p1({component:"ws-pool",event:"main_completed",sessionID:B0,responseID:dK($0),usage:y1}),rK(j,M,$0,C0,$1)},onTerminal:($0)=>{if(j.busy=!1,j.lastUsedAt=Date.now(),j.streamFailures=0,$0.type!=="response.completed"&&$0.type!=="response.done")j.continuation=void 0,q1(j)},onConnectionInvalid:($0)=>{if(j.busy=!1,j.lastUsedAt=Date.now(),k0.isOversizedFrame($0))j.fallback=!0;if(!j.fallback)q(j);j.continuation=void 0,q1(j),F0(!1)},onAbort:($0)=>{j.busy=!1,j.lastUsedAt=Date.now(),j.streamFailures=0,j.continuation=void 0,q1(j),D0($0)},onRetryableTerminal:async($0)=>{let C0=lK($0);if(!C0)return;throw j.fallback=!0,C0}}),r0=await sB(Y0,K);if(r0!==!1){if(r0===!0||r0.status<200||r0.status>599)return Q0;return new Response(r0.body,{status:r0.status,headers:{"content-type":"application/json",...r0.headers}})}let N9=()=>X(C,N(j,L0,J0));if(!j.fallback)return aB(Q0,N9);return N9()}catch(M){if(j.busy=!1,j.lastUsedAt=Date.now(),k0.isAbortError(M))throw j.streamFailures=0,j.continuation=void 0,q1(j),M;let x=k0.parseRateLimitSignal(M);if(x)w?.(x.window,x.resetAt);if(k0.isUpgradeFailure(M)&&!H)j.fallback=!0;if(q(j),j.continuation=void 0,q1(j),j.fallback)return X(C,N(j,L0,J0));return tB(new c0(M instanceof Error?M.message:String(M),{cause:M}))}}function q(C){if(C.streamFailures++,C.streamFailures>W)C.fallback=!0}function R(){let C=Date.now();for(let[E,S]of J){if(S.busy)continue;if(C-S.lastUsedAt<$)continue;q1(S),J.delete(E)}}function k(){clearInterval(F);for(let C of J.values())q1(C);J.clear()}function u(C){let E=`${C}:`;for(let[S,c]of J){if(!S.startsWith(E))continue;q1(c),J.delete(S)}}return Object.assign(V,{close:k,remove:u})}function lK(Y){if(Y.type!=="error"||!i(Y.error)||Y.error.code!==uK)return;return Error(typeof Y.error.message==="string"?Y.error.message:uK)}async function sB(Y,X){if(X<=0)return!1;return new Promise((J,Q)=>{let $=setTimeout(()=>J(!1),X);Y.then((G)=>{clearTimeout($),J(G)},(G)=>{clearTimeout($),Q(G)})})}function aB(Y,X){let J=Y.body;if(!J)return Y;let Q=!1,$=new ReadableStream({async start(G){let W=J.getReader(),K=async(H)=>{while(!0){let{done:U,value:Z}=await H.read();if(U)return;if(Z&&Z.length>0)Q=!0,G.enqueue(Z)}};try{await K(W),G.close()}catch(H){if(Q||!k0.isOversizedFrame(H)){G.error(H);return}try{let U=await X();if(!U.ok){G.error(new c0(`HTTP fallback after an oversized WebSocket frame failed with ${U.status}`));return}if(U.body)await K(U.body.getReader());G.close()}catch(U){G.error(U)}}},cancel(G){J.cancel(G)}});return new Response($,{status:Y.status,headers:Y.headers})}function tB(Y){return new Response(new ReadableStream({start(X){X.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function eB(Y,X,J,Q,$,G,W){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<$)return Y.socket;q1(Y);let K=await k0.connectResponsesWebSocket({url:k0.toWebSocketUrl(X),headers:J,timeout:Q,rawWebSocket:G,signal:W??void 0});return Y.connectedAt=Date.now(),K}function q1(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function YF(Y,X,J,Q){if(!Y.socket||!Array.isArray(X.input)||X.input.length===0)return;let $=JF(X);await W9({sessionID:Q.sessionID,transport:"websocket",phase:"prewarm",bodyText:JSON.stringify($),url:Q.url,method:"POST",headers:Q.headers});let G=k0.streamResponsesWebSocket({socket:Y.socket,body:$,sessionID:Q.sessionID,idleTimeout:J,signal:Q.signal,onRateLimitReached:Q.onRateLimitReached,onComplete:(W,K)=>{p1({component:"ws-pool",event:"prewarm_completed",sessionID:Q.sessionID,responseID:dK(W),usage:iK(W)}),rK(Y,$,W,K,!1)},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=lK(W);if(!K)return;throw Y.fallback=!0,K}});await XF(G)}function dK(Y){let X=Y.response;if(!i(X))return;return typeof X.id==="string"?X.id:void 0}function iK(Y){let X=Y.response;if(!i(X))return;return i(X.usage)?X.usage:void 0}async function XF(Y){let X=Y.body?.getReader();if(!X)return;while(!0)if((await X.read()).done)return}function JF(Y){return e9({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:QF(Y.client_metadata)})}function nK(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 QF(Y){if(!i(Y))return Y;if(typeof Y["x-codex-turn-metadata"]!=="string")return Y;try{let X=JSON.parse(Y["x-codex-turn-metadata"]);if(!i(X))return Y;return{...Y,"x-codex-turn-metadata":nK(X),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function $F(Y){let X=Y["x-codex-turn-metadata"];if(!X)return Y;try{let J=JSON.parse(X);if(!i(J))return Y;return{...Y,"x-codex-turn-metadata":nK(J)}}catch{return Y}}var oK=["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 pK(Y){let X={...Y};if(Array.isArray(Y.input))X.input=Y.input.map(GF);return X}function e9(Y){let X={};for(let J of oK)if(J in Y)X[J]=Y[J];for(let J of Object.keys(Y))if(!(J in X))X[J]=Y[J];return X}function GF(Y){if(!i(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 rK(Y,X,J,Q,$){let G=J.response,W=i(G)&&typeof G.id==="string"?G.id:void 0;if(!W||!Array.isArray(X.input)){Y.continuation=void 0;return}let K=$?new Set(Y.continuation?.finalizedCallIds):new Set;for(let H of Q)K.add(H);Y.continuation={responseID:W,input:X.input,signature:nJ(X),finalizedCallIds:K}}function iJ(Y,X,J=X){let Q=Array.isArray(X.input)?X.input:[],$=Array.isArray(J.input)?J.input:Q,G=nJ(J),W=Y.turnInput&&Y.turnSignature===G?WF(Y.turnInput,$):void 0,K=W===void 0?Q:$.slice(W);if(K.length>0&&K.some(tK)||!Y.turnID)Y.turnID=l1(),Y.turnStartedAt=Date.now();Y.turnInput=$.slice(),Y.turnSignature=G}function sK(Y,X,J=X){iJ(Y,X,J);let Q=X.client_metadata;if(!i(Q)||typeof Q["x-codex-turn-metadata"]!=="string")return X;let $=aK(Q["x-codex-turn-metadata"],Y.turnID,Y.turnStartedAt);if(!$)return X;return{...X,client_metadata:{...Q,"x-codex-turn-metadata":$}}}function aK(Y,X,J){let Q;try{Q=JSON.parse(Y)}catch{return}if(!i(Q))return;return JSON.stringify({session_id:Q.session_id,thread_id:Q.thread_id,thread_source:Q.thread_source,turn_id:X,sandbox:Q.sandbox,turn_started_at_unix_ms:J,request_kind:"turn",window_id:Q.window_id})}function WF(Y,X){if(Y.length>X.length)return;for(let J=0;J<Y.length;J++)if(N1(Y[J])!==N1(X[J]))return;return Y.length}function zF(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!J||!Y.continuation)return X;if(Y.continuation.signature!==nJ(X))return Y.continuation=void 0,X;if(!eK(Y.continuation.input,J))return Y.continuation=void 0,X;if(Y.continuation.input.length===0)return{...X,previous_response_id:Y.continuation.responseID};let Q=J.slice(Y.continuation.input.length),$=UF(Q,Y.continuation.finalizedCallIds);if($.length===0)return X;return{...X,previous_response_id:Y.continuation.responseID,input:$}}function KF(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!Y.continuation)return!0;if(!J)return!1;if(!eK(Y.continuation.input,J))return!0;return J.slice(Y.continuation.input.length).some(tK)}function tK(Y){if(!i(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function UF(Y,X){return Y.filter((J)=>{if(!i(J))return!0;if(typeof J.type==="string"&&J.type.endsWith("_output"))return!0;if(J.type==="function_call_output"||J.type==="custom_tool_call_output")return!0;if(J.type==="function_call"||J.type==="custom_tool_call"){let Q=typeof J.call_id==="string"?J.call_id:typeof J.id==="string"?J.id:void 0;return Q?!X.has(Q):!0}if(J.type==="message")return J.role!=="assistant";if(typeof J.role==="string")return J.role!=="assistant";return!1})}function nJ(Y){return N1(HF(Object.fromEntries(Object.entries(Y).filter(([X])=>X!=="input"&&X!=="stream"&&X!=="background"&&X!=="previous_response_id"&&X!=="generate"))))}function HF(Y){if(!i(Y.client_metadata))return Y;let X=Object.fromEntries(Object.entries(Y.client_metadata).filter(([J])=>J!=="x-codex-turn-metadata"&&J!=="x-codex-ws-stream-request-start-ms"));return{...Y,client_metadata:X}}function eK(Y,X){if(Y.length>=X.length)return!1;for(let J=0;J<Y.length;J++)if(N1(Y[J])!==N1(X[J]))return!1;return!0}function Y4(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let X=new Headers(Y.headers);for(let J of lJ)X.delete(J);return{...Y,headers:X}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((X)=>!lJ.has(X[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([X])=>!lJ.has(X.toLowerCase())))}}var ZF=300000,LF=30000,VF=5000,NF=100;function eJ(Y){let X=Y.logger,J=Y.now??Date.now,Q=Y.manifestPath??TX(),$=Y.cacheConnector??qF(X),G=Y.detectClaustrumConnection??Q4,W,K,H,U,Z,F=!1,N=new Map,V=new Set,q,k={isEnabled:()=>U?.status==="available",wasDetected:()=>U?.status==="available",getCache:()=>W,async ensureCache(){if(W)return W;return await u(),W},getTransport:()=>K,getCustodyProjection:(p,P)=>{let w=N.get(p.id);if(w)return w;return X4(p,Y.storage,P,W,q)},async boot(){if(F)return;try{U=await G()}catch(x){X.warn("custody detection failed",{error:x instanceof Error?x.message:String(x)});return}if(U.status!=="available"){if(U.status==="malformed")X.warn("custody connection malformed; disabled for this process",{reason:U.reason});else X.info("custody not configured; no client/timer created",{});return}let p=await Y.readCustodyManifest(Q);if(q=p,await E(p),Y.storage?.claustrum?.mode!=="claustrum"){X.info("custody connection available but mode is local; manifest read for the refresh gate, no client/timer",{});return}if(!await u()){B0();return}let P=W;if(!P)return;if(!p.ok&&p.reason!=="absent"){C(await Y.loadAccounts(r(Y.configPath))),B0();return}await c(),await o(p);let w=await Y.loadAccounts(r(Y.configPath));await Y.onReconcileStep?.("enabled-manifest-join");let j=oJ(p,w),M=[];for(let x of rJ(w)){if(w?.claustrum?.transition?.fingerprints.fallbacks[x.id])continue;if(!sJ(x,p,A0)&&!(b0(x,A0)&&!x.accountId))continue;if(!j.get(x.id))continue;let y=u0(P);M.push(aJ(x,y).then((g)=>o0(x,g,p)).catch((g)=>X.warn("custody boot sweep failed",{error:g instanceof Error?g.message:String(g)})))}await Promise.all(M),await jF(j,P,w,NF),B0()},async runTick(){if(F)return;if(Y.storage?.claustrum?.mode!=="claustrum")return;let p=q?.ok?q.revision:void 0,P=Y.readCustodyManifest(Q),w=W?void 0:u(),j=await P;if(q=j,!j.ok&&j.reason!=="absent"){C(await Y.loadAccounts(r(Y.configPath)));return}let M=j.ok&&j.revision!==p?await E(j):await Y.loadAccounts(r(Y.configPath));if(!W&&!await w)return;if(j.ok&&j.revision===p){await c(),await Y.onReconcileStep?.("enabled-manifest-join");let I=oJ(j,M);await S(j,I),await K0(j,I);return}await c(),await o(j),await Y.onReconcileStep?.("enabled-manifest-join");let x=oJ(j,M);await S(j,x),await K0(j,x)},dispose(){if(F)return;if(F=!0,Z)(Y.clearIntervalFn??clearInterval)(Z),Z=void 0;try{W?.close()}catch{}if(!W)try{K?.close()}catch{}W=void 0,K=void 0}};async function u(){if(F)return!1;if(W)return!0;if(H)return H;if(!U)return!1;let p=(async()=>{let P;try{let w=$({connectionFile:PF(U),handshakeTimeoutMs:VF});P=new W4({connector:()=>w,now:J});let j=await w;if(F)return P.close(),!1;return W=P,K=j,!0}catch(w){return P?.close(),X.warn("custody connect failed; disabled until tick reconnect",{error:w instanceof Error?w.message:String(w)}),!1}})();H=p;try{return await p}finally{if(H===p)H=void 0}}function C(p){for(let P of rJ(p))N.set(P.id,{state:"inert",reason:"manifest-unreadable"})}async function E(p){let P=await Y.loadAccounts(r(Y.configPath));if(!P||!p.ok)return P;for(let[w,j]of f0(p)){if(!P)break;if(w==="main")continue;if(P.accounts.some((y)=>y.id===w))continue;let M=P.claustrum?.rowHistory?.includes(w)?"row removed":"awaiting discovery",x=`${w}:${M}`;if(!V.has(x))V.add(x),X.info(`orphan-binding: ${M}`,{accountId:w});if(P.claustrum?.mode!=="claustrum")continue;let I=null;while(!I&&!F)if(I=await Y.acquireRefreshFileLock({name:M1(w),ttlMs:v1,path:Y.configPath,renew:!0}),!I)await new Promise((y)=>setTimeout(y,5));if(!I)continue;try{await Y.onReconcileStep?.("discovery-lock-acquired",w);let y=await Y.readCustodyManifest(Q),g=await Y.loadAccounts(r(Y.configPath));if(g?.claustrum?.mode!=="claustrum"||!y.ok||f0(y).get(w)!==j||g.accounts.some((s)=>s.id===w))continue;await Y.mutateAccounts((s)=>{if(s.claustrum?.mode!=="claustrum"||s.accounts.some((F0)=>F0.id===w))return s;return{...s,claustrum:{...s.claustrum,mode:"claustrum",rowHistory:[...new Set([...s.claustrum?.rowHistory??[],w])]},accounts:[...s.accounts,{id:w,...V1(A0),enabled:!0}]}},r(Y.configPath))}finally{await I.release().catch(()=>{})}P=await Y.loadAccounts(r(Y.configPath))}return P}async function S(p,P){if(!W)return;let w=await Y.loadAccounts(r(Y.configPath)),j=u0(W);for(let M of rJ(w)){if(w?.claustrum?.transition?.fingerprints.fallbacks[M.id])continue;if(!sJ(M,p,A0)&&!(b0(M,A0)&&!M.accountId))continue;if(!P.has(M.id))continue;let x=await aJ(M,j);o0(M,x,p)}}async function c(){let p=await Y.loadAccounts(r(Y.configPath)),P=p?.claustrum?.transition;if(p?.claustrum?.mode!=="claustrum"||!P)return;let w=!1;for(let[j,M]of Object.entries(P.fingerprints.fallbacks)){let x=await Y.acquireRefreshFileLock({name:M1(j),ttlMs:v1,path:Y.configPath,renew:!0});if(!x){w=!0;continue}try{if(!await Y.withAccountStoreTransaction(async(y)=>{let g=await y.read(),s=g.accounts.find((z0)=>z0.id===j);if(s?.type==="oauth"&&b0(s,"openai"))return!0;if(!s||!O0(s)||!s.access||$9(s.access,s.refresh)!==M)return N.set(j,{state:"inert",reason:"new-local-family-under-claustrum"}),!1;let F0=structuredClone(g),D0=F0.accounts.find((z0)=>z0.id===j);if(!D0||!O0(D0))return!1;Object.assign(D0,V1(A0)),await y.write(F0);let Y0=(await y.read()).accounts.find((z0)=>z0.id===j);return!!(Y0?.type==="oauth"&&b0(Y0,"openai"))},r(Y.configPath)))w=!0}catch{w=!0}finally{await x.release().catch(()=>{})}}if(P.fingerprints.main)if(!Y.auth)w=!0;else{let j=await Y.acquireRefreshFileLock({name:u1,ttlMs:v1,path:Y.configPath,renew:!0});if(!j)w=!0;else try{if(await SX(P.fingerprints.main,{auth:Y.auth,warn:(x)=>X.warn(x,{})})!=="tombstoned")w=!0}finally{await j.release().catch(()=>{})}}if(w)return;await Y.withAccountStoreTransaction(async(j)=>{let M=await j.read();if(M.claustrum?.mode!=="claustrum"||M.claustrum.transition?.manifestRevision!==P.manifestRevision||M.claustrum.transition?.storeGeneration!==P.storeGeneration)return;await j.writeMode("claustrum")},r(Y.configPath))}async function o(p){if(!W||!p.ok)return;let P=await Y.loadAccounts(r(Y.configPath));if(P?.claustrum?.mode!=="claustrum")return;let w=f0(p);for(let j of P.accounts){if(j.type!=="oauth"||j.corrupt!==!0)continue;let M=w.get(j.id),x=M?await J0(j.id,j.accountId,M):"no_handle",I=k9({mode:"claustrum",manifest:M?"present":"absent",local:"gone",vault:()=>x,verifiedInProcessLogin:!1});if(!("installTombstone"in I)||!I.installTombstone||!M)continue;await L0(j.id,M)}}async function J0(p,P,w){if(Y.resolveFallbackVaultState)return Y.resolveFallbackVaultState({accountId:p,handle:w});if(!W)return"cold";if(W.isReauth(w,J()))return"needs_reauth";try{let j=await W.get(w,h1(Y.storage),{force:!0}),M=W1(j.payload.access),x=M?z1(M):void 0;if(P&&x&&x!==P)return"identity_mismatch";if(!x)X.warn("custody identity unverifiable; serving",{credentialId:w});return"serves"}catch{return W.isReauth(w,J())?"needs_reauth":"cold"}}async function L0(p,P){let w=await Y.acquireRefreshFileLock({name:M1(p),ttlMs:v1,path:Y.configPath,renew:!0});if(!w)return;try{let j=await Y.readCustodyManifest(Q),M=await Y.loadAccounts(r(Y.configPath)),x=M?.accounts.find((I)=>I.id===p);if(M?.claustrum?.mode!=="claustrum"||!j.ok||f0(j).get(p)!==P||x?.type!=="oauth"||x.corrupt!==!0)return;await Y.mutateAccounts((I)=>{let y=I.accounts.find((F0)=>F0.id===p);if(y?.type!=="oauth"||y.corrupt!==!0)return I;let{corrupt:g,...s}=y;return{...I,accounts:I.accounts.map((F0)=>F0.id===p?{...s,...V1(A0)}:F0)}},r(Y.configPath))}finally{await w.release().catch(()=>{})}}async function K0(p,P){if(!W)return;for(let[w,j]of P){if(W.isReauth(j,J()))continue;let x=(await Y.loadAccounts(r(Y.configPath)))?.accounts.find((I)=>I.id===w);if(!x||!O0(x))continue;if(!G4(x,p,Y.storage??{}))continue;try{let I=await W.get(j);N.set(w,{state:"vault",recordVersion:I.recordVersion})}catch{}}}function B0(){if(F)return;let p=Y.setIntervalFn??setInterval,P=Math.floor((Math.random()*2-1)*LF),w=ZF+P;if(Z=p(()=>{if(F)return;k.runTick().catch((M)=>X.warn("custody tick failed",{error:M instanceof Error?M.message:String(M)}))},w),Z&&typeof Z==="object"&&"unref"in Z)Z.unref?.()}function u0(p){return{loadAccounts:Y.loadAccounts,readCustodyManifest:Y.readCustodyManifest,acquireRefreshFileLock:Y.acquireRefreshFileLock,configPath:Y.configPath,paths:r(Y.configPath),manifestPath:Q,cache:p,minTtlMs:h1(Y.storage),mutateAccounts:Y.mutateAccounts,provider:A0,now:J}}function o0(p,P,w){if(P.kind==="succeeded"){N.set(p.id,{state:"vault",recordVersion:P.recordVersion});return}if(P.kind==="failed"){let M={gone:"gone",identityMismatch:"identityMismatch",nullClaim:"nullClaim",unavailable:"unavailable"}[P.reason];N.set(p.id,{state:"inert",reason:M==="unavailable"?"takeover-incomplete/vault-unavailable":"identity-mismatch"}),FF(X,p.id,M,P.recordVersion,J());return}if(P.reason==="notEnrolling"){let j=J(),M=X4(p,Y.storage,j,W,w);if(M)N.set(p.id,M)}}return k}var BF=3600000,tJ=new Map;function FF(Y,X,J,Q,$){let G=`${X}:${J}`,W=tJ.get(G);if(W!==void 0&&$-W<BF)return;tJ.set(G,$),Y.warn("custody enroll-completion sweep failed",{accountId:X,reason:J,...typeof Q==="number"?{recordVersion:Q}:{}})}function OF(){tJ.clear()}function h1(Y){return((Y?.refresh?.refreshBeforeExpiryMinutes??240)+30)*60000}function oJ(Y,X){let J=new Map;for(let[Q,$]of f0(Y)){let G=X?.accounts.find((W)=>W.id===Q);if(G?.type!=="oauth")continue;if(!WX(G,Y,A0))continue;J.set(Q,$)}return J}function X4(Y,X,J,Q,$){let G=X??{},W=$?f0($).get(Y.id):void 0;if(!b0(Y,A0)&&!W)return;if(!b0(Y,A0))return;if(G.claustrum?.mode!=="claustrum"||!W)return YY({kind:"NEEDS_LOGIN"});return YY({kind:"INERT",reason:Q?.isReauth(W,J)?"vault-reauth":"vault-cold"})}async function jF(Y,X,J,Q,$=[]){if(Y.size===0&&$.length===0)return;let G=[...$];for(let[,W]of Y)G.push(X.get(W).then(()=>{return}).catch(()=>{}));await Promise.race([Promise.all(G),new Promise((W)=>setTimeout(W,Q))])}function rJ(Y){if(!Y)return[];return Y.accounts.filter(O0)}function qF(Y){return async(X)=>{let J=await $4.connect({connectionFile:X.connectionFile,handshakeTimeoutMs:X.handshakeTimeoutMs});return DF(J,Y)}}function DF(Y,X){return{getCredential:(J,Q)=>Y.getCredential(J,Q),statusCredential:(J)=>Y.statusCredential(J),reportAuthFailure:(J)=>Y.reportAuthFailure({handle:J.handle,providerStatus:J.providerStatus,recordVersion:J.recordVersion,reporterSource:J.reporterSource}),close:()=>Y.close()}}function PF(Y){if(Y.status!=="available")return Y.path??"";return J4()}var RF=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),TF=new Set(["gpt-5.6","gpt-6","gpt-6.1"]),CF="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.",_F=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"]),IF="opencode-oauth-dummy-key",SF="terminal_resize_reflow",W8="0.159.0",kF=`codex_exec/${W8} (Debian 12.0.0; aarch64) unknown (codex_exec; ${W8})`,xF="seccomp",NM=()=>u1,Y8=120000,bF=90000,vF=4000,z4=50,K4=3,hF=25,gF=60000,yF="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",z8=!1;function BM(){z8=!1}var U4=j0("models"),H4=!1,Z4=!1;class U8 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 U1 extends Error{code;constructor(Y,X){super(X);this.name="ResetTargetResolutionError",this.code=Y}}function L4(Y,X,J,Q){let $=(J?.refresh?.refreshBeforeExpiryMinutes??240)*60000;return!Y||!X||X-Q<=$}function fF(Y){return async(X)=>{if(X==="main"){let H=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),U=await Y.getAuth();if(U.type!=="oauth")throw new U1("non_oauth_account","Main OpenAI account is not authenticated with OAuth.");if(L4(U.access,U.expires,H,Y.now()))U={type:"oauth",...await Y.refreshMainWithLease()};if(!U.access)throw new U1("token_unavailable","Main OpenAI account has no usable access token.");let Z=W1(U.access),F=Z?z1(Z):void 0,N=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath});return{accountKey:X,label:"Main account",accessToken:U.access,chatgptAccountId:F??N?.mainAccountId}}let J=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),Q=J?.accounts.find((H)=>H.id===X);if(!J||!Q)throw new U1("unknown_account",`Fallback account ${X} was not found.`);if(Q.enabled===!1)throw new U1("disabled_account",`Fallback account ${X} is disabled.`);if(!O0(Q))throw new U1("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);let $=Q;if(!await Y.isFallbackRefreshInert?.($,J)&&L4($.access,$.expires,J,Y.now()))$=await Y.refreshFallbackAccount($,J);let G=Y.resolveFallbackAccess?await Y.resolveFallbackAccess($,J):$.access?{token:$.access,provenance:"local"}:g1;if(G===g1||G===t1)throw new U1("token_unavailable",`Fallback account ${X} has no usable access token.`);let W=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),K=W?.accounts.find((H)=>H.id===X);if(!W||!K)throw new U1("unknown_account",`Fallback account ${X} was not found.`);if(K.enabled===!1)throw new U1("disabled_account",`Fallback account ${X} is disabled.`);if(!O0(K))throw new U1("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);return{accountKey:X,label:$.label??X,accessToken:G.token,chatgptAccountId:K.accountId,onAuthFailure:G.provenance==="local"?void 0:async(H)=>{await Y.reportAuthFailure?.({handle:G.provenance.handle,providerStatus:H,recordVersion:G.provenance.recordVersion})}}}}function mF(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function X8(Y){return Y instanceof U8}function V4(){throw Error(yF)}function cF(Y){return Math.floor(Math.random()*Y)}function uF(Y){if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return typeof X==="object"&&X!==null&&!Array.isArray(X)?X:void 0}catch{return}}function pF(Y,X,J){let Q=Y.get(X);if(Q)return Q;let $=l1(),G={threadID:$,turnID:l1(),windowID:`${$}:0`};return Y.set(X,G),J?.(),G}function f4(){return G8(jY(),"openai-auth-sessions.json")}function lF(){let Y=new Map;try{let X=JSON.parse(y4(f4(),"utf8"));if(!i(X.sessions))return Y;for(let[J,Q]of Object.entries(X.sessions)){if(!i(Q)||typeof Q.threadID!=="string")continue;Y.set(J,{threadID:Q.threadID,turnID:l1(),windowID:`${Q.threadID}:0`})}}catch{}return Y}function dF(Y){let X=f4(),J=`${X}.tmp-${process.pid}`;try{EF(jY(),{recursive:!0});let Q={version:1,sessions:Object.fromEntries([...Y.entries()].map(([$,G])=>[$,{threadID:G.threadID}]))};AF(J,`${JSON.stringify(Q,null,2)}
|
|
110
|
+
`,"utf8"),MF(J,X)}catch{}}function N4(Y,X){return i(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===X}function iF(Y,X){if(Y.length>X.length)return!1;for(let J=0;J<Y.length;J++)if(N1(Y[J])!==N1(X[J]))return!1;return!0}function nF(Y,X){if(!Y.input)return X.length>0;if(!iF(Y.input,X))return!0;return X.slice(Y.input.length).some((Q)=>N4(Q,"user")||N4(Q,"developer"))}function oF(Y,X){let J=Array.isArray(X?.input)?X.input:void 0;if(J&&(nF(Y,J)||!Y.turnID))Y.turnID=l1(),Y.turnStartedAt=Date.now();else if(!Y.turnStartedAt)Y.turnStartedAt=Date.now();if(J)Y.input=J}function rF(Y){if(!Y.metadata)return{init:Y.init};let X=uF(Y.init?.body);if(!Y.websocket)oF(Y.metadata,X);else if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Date.now();if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Date.now();let J=JSON.stringify({session_id:Y.metadata.threadID,thread_id:Y.metadata.threadID,thread_source:"user",turn_id:Y.metadata.turnID,sandbox:xF,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",SF),Y.headers.set("x-codex-turn-metadata",J),Y.headers.set("user-agent",kF),Y.headers.set("version",W8),Y.dumpSessionID)Y.headers.set(w1,Y.dumpSessionID);let Q=X;if(!Q)return{init:Y.init};let $=Y.responsesLite&&typeof Q.model==="string"&&_F.has(Q.model);if($&&!Y.websocket)Y.headers.set("x-openai-internal-codex-responses-lite","true");if(Q.prompt_cache_key=Y.metadata.threadID,Q.parallel_tool_calls??=!0,Array.isArray(Q.tools))Q.tools=Q.tools.map(XO);if(eF(Q,Y.metadata),$)YO(Q);let G={...typeof Q.client_metadata==="object"&&Q.client_metadata!==null?Q.client_metadata:{},"x-codex-installation-id":Y.installationID,"x-codex-window-id":Y.metadata.windowID};if(Y.websocket){if(G["x-codex-turn-metadata"]=J,G["x-codex-ws-stream-request-start-ms"]=String(Date.now()),$)G.ws_request_header_x_openai_internal_codex_responses_lite="true"}return Q.client_metadata=G,Y.headers.delete("content-length"),Y.headers.delete("Content-Length"),{init:{...Y.init,body:JSON.stringify(e9(Q))}}}function sF(Y,X){return Y.find((J)=>J.enabled!==!1&&O0(J)&&(J.id===X||J.accountId===X))}function B4(Y,X){if(!X)return Y;let J={...Y};for(let Q of["resetCreditsAvailable","resetCreditsApplicable"]){let $=X[Q];if(J[Q]===void 0&&$!==void 0)J[Q]=$}if(J.spendControl===void 0&&J.spendControlCleared!==!0&&X.spendControl!==void 0)J.spendControl=X.spendControl;return J}function KX(Y,X){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:X}}function UX(Y,X){return f0(Y).get(X)}function m4(Y,X,J=Date.now(),Q=X.mainAccountId,$){let G=Y.getMain(),W=G?.quota;return{main:{quota:W?{...W,checkedAt:G.checkedAt,primary:KX(W.primary,G.checkedAt),secondary:KX(W.secondary,G.checkedAt)}:null,...typeof Q==="string"?{mainAccountId:Q}:{},killed:!1,...W?.resetCreditsAvailable!==void 0?{resetCredits:W.resetCreditsAvailable}:{}},fallbacks:X.accounts.filter((K)=>K.enabled).map((K)=>{let H=Y.getFallback(K.id),U=H?.quota,Z=$?.(K,J);return{id:K.id,label:K.label,accountId:H?.accountId??K.accountId,quota:U?{...U,checkedAt:H.checkedAt,primary:KX(U.primary,H.checkedAt),secondary:KX(U.secondary,H.checkedAt)}:null,killed:!1,enabled:!0,...U?.resetCreditsAvailable!==void 0?{resetCredits:U.resetCreditsAvailable}:{},...Z?{custody:Z}:{}}}),route:X.routing?.mode??"main-first",lastUpdated:J}}function OM(Y,X,J,Q=Date.now()){return{...m4(Y,X,Q),activeId:J}}function F4(Y,X){if(X?.headers!==void 0)return new Headers(X.headers);if(Y instanceof Request)return new Headers(Y.headers);return new Headers}async function aF(Y,X){if(!(Y instanceof Request))return X;let J=new Request(Y,X),Q=J.method.toUpperCase(),$=Q==="GET"||Q==="HEAD"||J.body===null?void 0:await J.text();return{method:J.method,headers:new Headers(J.headers),body:$,signal:J.signal,cache:J.cache,credentials:J.credentials,integrity:J.integrity,keepalive:J.keepalive,mode:J.mode,redirect:J.redirect,referrer:J.referrer,referrerPolicy:J.referrerPolicy}}function O4(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}function K8(Y){if(Array.isArray(Y)){for(let X of Y)K8(X);return}if(!i(Y))return;if(Y.type==="input_image")delete Y.detail;for(let X of Object.values(Y))K8(X)}var tF=new Set(["gpt-6-astra","gpt-6-sol","gpt-6-luna","gpt-6.1-sol"]);function eF(Y,X){let J=typeof Y.model==="string"?Y.model:"";if(!tF.has(J))return;let Q=i(Y.reasoning)?Y.reasoning:void 0,$=typeof Q?.effort==="string"?Q.effort:void 0;if(!$)return;if(X.pinnedEffort===void 0){X.pinnedEffort=$;return}if($===X.pinnedEffort)return;let G=Array.isArray(Y.input)?Y.input:void 0;if(!G||G.length===0)return;Y.reasoning={...Q,effort:X.pinnedEffort},G.splice(G.length-1,0,{type:"configuration_update",reasoning:{effort:$}})}function YO(Y){let X=i(Y.reasoning)?{...Y.reasoning}:{};X.context="all_turns",Y.reasoning=X,Y.parallel_tool_calls=!1;let J=Array.isArray(Y.input)?Y.input:[];K8(J);let $=[{type:"additional_tools",role:"developer",tools:Array.isArray(Y.tools)?Y.tools.filter((G)=>!(i(G)&&G.type==="web_search")):[]}];if(typeof Y.instructions==="string"&&Y.instructions.length>0)$.push({type:"message",role:"developer",content:[{type:"input_text",text:Y.instructions}]});Y.input=[...$,...J],delete Y.tools,delete Y.instructions}function XO(Y){if(!i(Y))return Y;if(Y.type!=="function")return Y;let X=i(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:H,...U}=Y.parameters;return U})():Y.parameters,{type:J,name:Q,description:$,strict:G,parameters:W,...K}=Y;return{type:J,name:Q,description:$,strict:G??!1,parameters:X,...K}}async function JO(Y,X={}){let J=X.codexApiEndpoint??s0().codexApiEndpoint,Q=crypto.randomUUID(),$=lF(),G=()=>dF($),W=!1,K=[],H=null,U=Y.client.auth,Z=new Map,F=new Map,N,V,q,R={},k=X.custody,u=j0("custody"),C=(P,w="")=>P?async()=>{let j=await P();return{url:j.url,instructions:j.instructions??w,method:"auto",callback:async()=>{try{let M=await j.tokens;return{type:"success",refresh:M.refresh_token,access:M.access_token,expires:Date.now()+(M.expires_in??3600)*1000,accountId:J9(M)}}finally{j.cleanup?.()}}}}:void 0;function E(P,w){return eJ({storage:P,configPath:t(),loadAccounts:w0,mutateAccounts:P0,withAccountStoreTransaction:ZX,readCustodyManifest:e0,acquireRefreshFileLock:L1,auth:w,...k?{detectClaustrumConnection:async()=>k.detection==="absent"?{status:"absent",path:"test"}:{status:"available",schema:1,wireVersion:1,endpoints:[]},cacheConnector:async()=>k.transport}:{},logger:{info:(j,M)=>u.info(j,M??{}),warn:(j,M)=>u.warn(j,M??{}),debug:(j,M)=>u.debug(j,M??{}),error:(j,M)=>u.error(j,M??{})},now:k?.now})}let S=await w0(r(t())),c=await e0(),o=Y.client.auth;if(o.get&&o.all){if(m1(S??{})==="claustrum")q=E(S,{all:o.all,get:o.get,set:o.set}),k?.onRuntime?.(q),await q.boot();let P=q?.getCache();if(P)R.cache=P;if(R.mainVerdict=await bQ({client:{auth:o},mode:m1(S??{}),manifest:c,mainAccountId:S?.mainAccountId,getCredential:P?async(w)=>{return{access:(await P.get(w,h1(S))).payload.access}}:void 0,isReauth:P?(w)=>P.isReauth(w):void 0,now:Date.now,sleep:(w)=>new Promise((j)=>setTimeout(j,w))}),R.mainVerdict){let w=await a1();await $8({...w,main:{...w.main,custody:YY(R.mainVerdict)}})}}let J0=new PX,L0,K0={},B0=ZQ({client:Y.client,getAuth:async()=>L0?.(),fetchImpl:fetch,dependencies:{...k?.authorize?{authorizeBrowser:C(k.authorize.browser,"Complete authorization in your browser. This window will close automatically."),authorizeHeadless:C(k.authorize.headless)}:{},custodyQuotaDeps:K0}}),u0=(P)=>async(w)=>{let j=await IX();try{let M=await P(w);if(M.method!=="auto")return await j.release(),M;return{...M,callback:async()=>{try{let x=await M.callback();if(x.type!=="success"||!("refresh"in x))return await j.release(),x;return uQ({accessToken:x.access??"",refreshToken:x.refresh,getAuth:async()=>{let I=await U.get({path:{id:"openai"}});return i(I)&&typeof I.access==="string"&&typeof I.refresh==="string"?{access:I.access,refresh:I.refresh}:void 0},onObserved:({access:I,refresh:y})=>kQ({type:"oauth",access:I,refresh:y}),release:()=>j.release(),warn:(I)=>k?.warn?.(I)??u.warn(I),now:k?.now??Date.now,sleep:k?.sleep??((I)=>Bun.sleep(I))}).catch(()=>j.release()),x}catch(x){throw await j.release(),x}}}}catch(M){throw await j.release(),M}},o0=B0.map((P)=>P.type==="oauth"?{...P,authorize:u0(P.authorize)}:P);async function p(P,w){let j=Y.client.session;if(typeof j?.promptAsync==="function"){let M=await Z5(Y.client,P),x={noReply:!0,parts:[{type:"text",text:w,ignored:!0}]};if(M?.agent)x.agent=M.agent;if(M?.model)x.model=M.model;if(M?.variant)x.variant=M.variant;await j.promptAsync({path:{id:P},body:x});return}}return{async dispose(){J0.stop(),q?.dispose(),N?.stopBackgroundRefresh(),N=void 0;for(let j of K)j.close();K.length=0;let P=globalThis;for(let[j,M]of Z)if(P.__openaiAuthCacheKeepManagers?.get(j)===M)M.stop(),P.__openaiAuthCacheKeepManagers.delete(j);Z.clear();let w=globalThis;for(let[j,M]of F)if(w.__openaiAuthRpcServers?.get(j)===M)await M.stop().catch(()=>{}),w.__openaiAuthRpcServers.delete(j);F.clear()},async event(P){if(P.event.type!=="session.deleted")return;let w=P.event.properties.info,j=$.get(w.id);if(j)H?.cacheKeepManager?.remove(j.threadID);if($.delete(w.id))G();if(V){let M=(await w0(r(t())))?.accounts;await b4(w.id,M,V)}for(let M of K)M.remove(w.id)},provider:{id:"openai",async models(P,w){if(w.auth?.type!=="oauth")return P.models;let j=await w0(r(t())),M=!j||A4(j),x=M?null:await z5();if(!M&&x&&!H4)H4=!0,U4.debug("restoring OAuth model costs from models.dev catalog");if(!M&&!x&&!Z4)Z4=!0,U4.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(P.models).filter(([,I])=>{if(I.options.reasoningMode==="pro")return!1;if(RF.has(I.api.id))return!0;if(TF.has(I.api.id))return!1;let g=I.api.id.match(/^gpt-(\d+(?:\.\d+)?)/)?.[1];return g?parseFloat(g)>5.4:!1}).map(([I,y])=>[I,{...y,cost:M?{input:0,output:0,cache:{read:0,write:0}}:x?.[y.api.id]??x?.[I]??y.cost,limit:y.id.includes("gpt-5.5")?{context:400000,input:272000,output:128000}:y.id.includes("gpt-6-astra")?{context:872000,input:744000,output:128000}:y.id.includes("gpt-5.6")||y.id.includes("gpt-6-sol")||y.id.includes("gpt-6-luna")||y.id.includes("gpt-6.1-sol")?{context:372000,input:244000,output:128000}:y.limit}]))}},auth:{provider:"openai",async loader(P){L0=P;let w=await P();if(w.type!=="oauth")return{};let j=IY(w),M=j.kind==="tombstone"||j.kind==="empty",x=Y.directory?await g4(Y.directory):void 0,I=x?.dir??t();if(!M)await T4({type:"oauth",access:w.access??"",refresh:w.refresh??"",expires:w.expires??0},r(t()));let y=await w0(r(t())).catch((L)=>{let B=t();throw Error(`OpenAI auth store at ${B} is corrupt or unreadable: ${L instanceof Error?L.message:String(L)}. Fix or remove it to continue.`,{cause:L})}),g;async function s(){let L=t();try{let B=wF(L);if(g?.path===L&&g.mtimeMs===B.mtimeMs&&g.size===B.size)return g.storage;let O=await w0(r(L));return g={path:L,mtimeMs:B.mtimeMs,size:B.size,storage:O},O}catch{return g=void 0,w0(r(L))}}function F0(){g=void 0}if(y&&w.access&&!M){let L=J9({id_token:"",access_token:w.access,refresh_token:w.refresh??""});if(L&&L!==y.mainAccountId)await P0((B)=>{return B.mainAccountId=L,B},r(t())),y.mainAccountId=L,F0()}let D0=y?.logging?.level;if(D0&&typeof D0==="string")CY(D0);let Y0=j0("transport"),z0=j0("quota"),g0=j0("refresh"),$1=j0("accounts");Y0.info("codex auth loader ready",{codexApiEndpoint:J,transport:s0().rawWebSocket?"raw-websocket":s0().webSockets?"websocket":"http"});let Q0=new TY({storage:y,configPath:t(),fetchQuotaFn:void 0}),r0,N9=0,$0=new C4({paths:r(t()),refreshFn:(L)=>HX({refreshToken:L.refreshToken,fetchImpl:L.fetchImpl,now:L.now}),quotaManager:Q0,custody:{readManifest:e0},onFallbackStorageChanged:F0}),C0=q??E(y);if(!q)k?.onRuntime?.(C0),await C0.boot(),q=C0;if(M){let L=await e0(),B=UX(L,"main"),O=C0.getCache();if(B&&O)try{let T=await O.get(B,h1(y)),_=x9(T.payload.access);if(_&&_!==y?.mainAccountId){if(await P0((b)=>{return b.mainAccountId=_,b},r(t())),y)y.mainAccountId=_;R.mainAccountId=_,F0()}}catch{}}if(C0.runTick().catch((L)=>u.warn("custody first tick failed",{error:L instanceof Error?L.message:String(L)})),q=C0,y&&y.accounts.length>0)$0.startBackgroundRefresh();let y1=C0;async function WY(L,B){let O=await e0();return WX(L,O,A0)}async function e1(L,B){let O=await e0(),T=y1.getCache(),_=UX(O,L.id);if(!T||!_)return J8(L,B,O);return J8(L,B,O,{cache:T,manifestHandle:_,requestPath:!0,now:k?.now??Date.now,refreshBeforeExpiryMs:(B.refresh?.refreshBeforeExpiryMinutes??240)*60000,completeEnrollmentDeps:{loadAccounts:w0,readCustodyManifest:e0,acquireRefreshFileLock:L1,configPath:t(),paths:r(t()),cache:T,minTtlMs:h1(B),mutateAccounts:P0,provider:A0,now:Date.now}})}async function H8(L){if(m1(L)!=="claustrum")return t1;let B=await e0(),O=UX(B,"main"),T=y1.getCache(),_=(h)=>{return u.warn("custody main request refused",{reason:h}),g1};if(!O||!T)return _("no-handle");let b=(k?.now??Date.now)();if(T.isBlocked(O))return _("blocked");if(T.isReauth(O,b))return _("reauth");let v=await T.peek(O);if(!v||v.expiresAtMs<=b)return _("cache-miss");return{token:v.payload.access,provenance:{handle:O,recordVersion:v.recordVersion}}}async function B9(L){let B=y1.getCache();if(!B)return;await B.reportAuthFailure({handle:L.handle,providerStatus:L.providerStatus,recordVersion:L.recordVersion})}Object.assign(K0,{isFallbackRefreshInert:WY,resolveFallbackAccess:e1,reportCustodyAuthFailure:B9});function zY(L={}){let{readSidebarState:B,respectBackoff:O,skipFresherThanMs:T}=L;return{getAuth:P,codexRefreshFn:HX,refreshMainWithLease:HY,fallbackManager:$0,quotaManager:Q0,loadAccounts:w0,writeSidebarState:ZY,client:Y.client,fetchImpl:fetch,now:Date.now,paths:r(t()),readSidebarState:B??(()=>a1(p0)),storageMainAccountId:y?.mainAccountId,isOAuthAccountFn:O0,whamFn:RY,isFallbackRefreshInert:WY,resolveFallbackAccess:e1,resolveMainAccess:H8,reportCustodyAuthFailure:B9,...O===void 0?{}:{respectBackoff:O},...T===void 0?{}:{skipFresherThanMs:T}}}let Z8=j0("cachekeep"),L8=y?.cachekeep?.enabled===!0,V8=y?.cachekeep?.subagents===!0,N8=y?.cachekeep?.sustain===!0,B8=jQ(y),KY;async function c4(L){await new Promise((B)=>setTimeout(B,L))}async function u4(L){let B;for(let O=1;O<=K4;O++)try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:L.refresh,access:L.access,expires:L.expires}});return}catch(T){if(B=T,O<K4)await c4(hF*O)}throw new U8(B)}async function UY(L){await P0((B)=>{return B.refresh=B.refresh??{},L(B),B},r(t())),F0()}async function F8(L){let B=Date.now()+vF;while(Date.now()<B){await new Promise((_)=>setTimeout(_,z4+cF(z4)));let O=await P();if(O.type!=="oauth"||!O.access)continue;if((O.access!==L.access||O.refresh!==L.refresh||(O.expires??0)>(L.expires??0)+60000)&&(!O.expires||O.expires>Date.now()))return g0.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:O.expires?O.expires-Date.now():void 0}),{access:O.access,refresh:O.refresh??L.refresh??"",expires:O.expires??0}}return null}async function HY(){if(!KY)KY=(async()=>{let L=await P();if(L.type!=="oauth")throw Error("not oauth");if(b0({id:"main",type:"oauth",access:L.access??"",refresh:L.refresh??"",expires:L.expires??0,addedAt:0},A0))throw new M4(A0);if(!L.refresh)throw Error("Token refresh failed: missing refresh token");let B=j4(L.refresh),O=await w0(r(t())),T=O?.refresh?.mainLastRefreshError;if(T&&EY(T,L.refresh,Date.now()))throw Error(D4(T,Date.now()));if(O?.refresh?.mainRefreshLeaseUntil&&O.refresh.mainRefreshLeaseUntil>Date.now()&&O.refresh.mainRefreshLeaseTokenHash===B){let h=await F8(L);if(h)return h;throw Error("Codex OAuth refresh is already in progress")}let _=await L1({name:u1,ttlMs:Y8,path:t(),renew:!0});if(!_){let h=await F8(L);if(h)return h;throw Error("Codex OAuth refresh is already in progress")}let b=crypto.randomUUID(),v=B;try{await UY((l)=>{l.refresh=l.refresh??{},l.refresh.mainRefreshLeaseId=b,l.refresh.mainRefreshLeaseUntil=Date.now()+bF,l.refresh.mainRefreshLeaseTokenHash=B});let h=await w0(r(t()));if(h?.refresh?.mainRefreshLeaseId!==b||h.refresh.mainRefreshLeaseTokenHash!==B)throw Error("Codex OAuth refresh is already in progress");let m=await HX({refreshToken:L.refresh,fetchImpl:fetch,now:Date.now});return await u4(m),await UY((l)=>{if(l.refresh=l.refresh??{},l.refresh.mainLastRefreshError=void 0,l.refresh.mainRefreshLeaseId===b)l.refresh.mainRefreshLeaseId=void 0,l.refresh.mainRefreshLeaseUntil=void 0,l.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),v=void 0,m}catch(h){if(L.refresh&&!X8(h))await UY((m)=>{m.refresh=m.refresh??{},m.refresh.mainLastRefreshError=q4({error:h,now:Date.now(),refreshToken:L.refresh??"",previous:m.refresh.mainLastRefreshError})}).catch(()=>{});throw h}finally{if(v)await UY((h)=>{if(h.refresh?.mainRefreshLeaseId===b&&h.refresh.mainRefreshLeaseTokenHash===v)h.refresh.mainRefreshLeaseId=void 0,h.refresh.mainRefreshLeaseUntil=void 0,h.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await _.release().catch(()=>{})}})().finally(()=>{KY=void 0});return KY}let O8=globalThis,VX=O8.__openaiAuthCacheKeepManagers??new Map;O8.__openaiAuthCacheKeepManagers=VX,VX.get(I)?.stop();let F9=new RX({fetchImpl:fetch,getMainToken:async()=>{let L=await P();if(L.type!=="oauth")throw Error("not oauth");if(!L.access||(L.expires??0)<Date.now())try{return(await HY()).access}catch(B){if(X8(B))throw B;if(L.access)return L.access;throw Error("main token refresh failed")}return L.access},refreshFallback:async(L)=>{let B=await s(),O=B?sF(B.accounts,L):void 0;if(!O)throw Error(`fallback account ${L} not found`);let T=B??{version:1,accounts:[O]},_=O;if(!await WY(O,T))_=await $0.refreshAccount(O,T);let b=await e1(_,T);if(b===g1||b===t1)throw Error(`no access token for ${L}`);return{token:b.token,onAuthFailure:b.provenance==="local"?void 0:async(v)=>{await B9({handle:b.provenance.handle,providerStatus:v,recordVersion:b.provenance.recordVersion})}}},codexResponsesUrl:J,logger:Z8,now:Date.now,getWindow:()=>B8,getSustain:()=>N8});VX.set(I,F9),Z.set(I,F9);async function O9(L,B,O,T,_=!1){if(Object.keys(L).length===0&&!_)return;let b=Date.now(),v=L,h={quota:v,refreshAfter:b+300000,checkedAt:b},m;if(O&&O!=="main"){let d=B?W1(B):null,H0=d?z1(d):void 0,l0=Q0.peekFallbackForPolicy(O)?.quota,_0=B4(v,l0);h={...h,quota:_0},Q0.setFallback(O,h,B,_,H0)}else{if(m=T,!m&&B){let l0=W1(B);m=l0?z1(l0):void 0}if(m&&r0&&m!==r0){z0.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:m,currentMainIdentity:r0});return}let d=Q0.peekMainForPolicy(m)?.quota,H0=B4(v,d);h={...h,quota:H0},Q0.setMain(B,h,m,_)}z0.debug("quota pushed",{pid:process.pid,accountId:O??"main",snapshot:h.quota});let l=await s();await ZY(Q0,l,O&&O!=="main"?l?.mainAccountId:m)}function p4(L,B,O){let T=L==="main"?Q0.peekMainForPolicy()?.quota:Q0.peekFallbackForPolicy(L)?.quota;return w4(T,B,Date.now(),gF,O)}let j9=X.experimentalWebSockets?b1.createWebSocketFetch({httpFetch:fetch,rawWebSocket:s0().rawWebSocket,onQuota:(L,B,O,T)=>{O9(L,B,O,!O||O==="main"?T:void 0,!0)},onRateLimitReached:(L,B,O)=>{if(!B)z0.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:L});let T=B??"main",_=p4(T,L,O);Q0.markRateLimited(T,_),z0.debug("mid-stream rate limit mark",{pid:process.pid,accountId:T,window:L})}}):void 0;if(j9)K.push(j9),W=!0;let p0=_4();V=p0;async function ZY(L,B,O=B?.mainAccountId){if(!B)return;await $8(m4(L,B,Date.now(),O,l4),p0)}function l4(L,B){if(!O0(L))return;return y1.getCustodyProjection(L,B)}async function j8(L,B,O,T,_){let b={activeId:O,route:T,updatedAt:Date.now()};if(L){if(await LX({sessionId:L,...b},_,p0),B&&B!==L){if(T==="sticky-balanced"){let v=(await a1(p0)).stickyAssignments?.[GY(B)]?.accountId,h=_===void 0||v==="main"||_.some((m)=>m.enabled!==!1&&m.id===v);if(!v||!h)return;await LX({sessionId:B,activeId:v,route:T,updatedAt:Date.now()},_,p0);return}await LX({sessionId:B,...b},_,p0)}return}await x4(b,p0)}let d4=async(L,B)=>{let O=await L1({name:M1(L),ttlMs:v1,path:t(),renew:!0});if(!O)throw Error("Fallback account lock unavailable");try{return await B()}finally{await O.release()}},i4=k?.withFallbackAccountLock??d4,n4=async(L)=>{let B=await e0();if(!B.ok)return{ready:!1,reason:"manifest-unreadable"};let O=UX(B,L.id);if(!O)return{ready:!1,reason:"no-handle"};let T=C0.getCache();if(!T)return{ready:!1,reason:"vault-cold"};if(T.isReauth(O,k?.now?.()??Date.now()))return{ready:!1,reason:"vault-reauth"};if(T.isBlocked(O))return{ready:!1,reason:"vault-cold"};try{let _=await T.get(O,h1(y)),b=x9(_.payload.access);if(!b||L.accountId&&L.accountId!==b)return{ready:!1,reason:"identity-mismatch"};return{ready:!0,accountId:b}}catch{return{ready:!1,reason:T.isReauth(O,k?.now?.()??Date.now())?"vault-reauth":"vault-cold"}}};N?.stopBackgroundRefresh(),N=$0,H={accountStoragePath:t(),accountStatePath:PY(t()),packageVersion:E9,quotaManager:Q0,loadAccounts:w0,client:Y.client,beginAccountLogin:AY,withFallbackAccountLock:i4,checkUsableCustodyBinding:n4,enterClaustrumMode:async()=>{let L=await w0(r(t())),B=(L?.accounts??[]).filter((O)=>O.type==="oauth"&&O.enabled!==!1).map((O)=>O.id);return pQ({accountIds:B,acquireLock:({name:O,renew:T})=>L1({name:O,ttlMs:O===u1?Y8:v1,path:t(),renew:T}),withStoreTransaction:(O)=>ZX(O,r(t())),readManifest:e0,preflight:async({accountId:O,handle:T})=>{u.info("preflight probing participant",{accountId:O,hasHandle:T.length>0});let _=await C0.ensureCache(),b=_?.isBlocked(T);if(!_||b)return u.warn("preflight vault-cold",{accountId:O,hasCache:_!==void 0,blocked:b}),"vault-cold";if(_.isReauth(T,k?.now?.()??Date.now()))return"vault-reauth";try{let v=await _.get(T,h1(L)),h=x9(v.payload.access);if(!h||O&&O!==h)return"identity-mismatch";return"ready"}catch{return _.isReauth(T,k?.now?.()??Date.now())?"vault-reauth":"vault-cold"}},auth:{all:async()=>{if(typeof U.all==="function")return U.all();let O=process.env.XDG_DATA_HOME??G8(zX.homedir(),".local","share"),T=G8(O,"opencode","auth.json");try{let _=JSON.parse(y4(T,"utf8"));return i(_)?_:{}}catch{return{}}},get:async(O)=>{if(typeof U.get==="function")return U.get(O);if(O.path.id!=="openai"||!L0){u.warn("auth.get unavailable for slot",{id:O.path.id,hasLoaderGetAuth:L0!==void 0});return}return L0()},set:async(O)=>{await U.set(O)}},warn:(O)=>u.warn(O)})},leaveClaustrumMode:()=>lQ({acquireLock:({name:L,renew:B})=>L1({name:L,ttlMs:Y8,path:t(),renew:B}),withStoreTransaction:(L)=>ZX(L,r(t()))}),resolveResetTarget:fF({getAuth:P,refreshMainWithLease:HY,refreshFallbackAccount:(L,B)=>$0.refreshAccount(L,B),loadAccounts:w0,accountStoragePath:t(),accountStatePath:PY(t()),now:Date.now,isFallbackRefreshInert:WY,resolveFallbackAccess:e1,reportAuthFailure:B9}),...mF(),cacheKeepManager:F9,setCacheKeepEnabled:(L)=>{L8=L},setCacheKeepSubagents:(L)=>{V8=L},setCacheKeepSustain:(L)=>{N8=L},setCacheKeepWindow:(L)=>{B8=L},clearStickyRouting:(L)=>h4(L,p0),getStickyRouting:async(L)=>k4(await a1(p0),L),refreshSidebar:async()=>{let L=await w0(r(t()));await ZY(Q0,L)},refreshAllQuota:async()=>E1(zY()),refreshResetTargetQuota:async(L)=>{return(await E1(zY({respectBackoff:!1}),{accountKey:L})).find((O)=>O.account===L)??{account:L,ok:!1,error:"targeted quota refresh returned no result"}}};let NX=null;if(x){let L=globalThis,B=L.__openaiAuthRpcServers??new Map;L.__openaiAuthRpcServers=B;let O=B.get(x.dir);if(O)await O.stop().catch(()=>{}),B.delete(x.dir);try{NX=await O5({dir:x.dir,secureDir:x.secureDir,sweepRoot:x.sweepRoot,drain:V5,apply:async(T)=>{let _={...H,sessionId:T.sessionId},b=await DX(T.command,T.arguments,_);return{text:b.text,knobs:b.knobs}}}),B.set(x.dir,NX),F.set(x.dir,NX)}catch{}}let q8=new WeakMap;function o4(L,B){let O=q8.get(L);if(!O||B.hostname!=="chatgpt.com"||!B.pathname.startsWith("/backend-api/codex/"))return;if(L.status>=200&&L.status<300){y1.getCache()?.markVaultSuccess(O.handle);return}if(L.status!==401)return;B9({handle:O.handle,providerStatus:L.status,recordVersion:O.recordVersion}).catch(()=>{})}async function q9(L,B,O,T,_="main",b){if(!O.trim())throw Y0.warn("refusing to send a request with no access token",{account:_,accountId:T,hasProvenance:Boolean(b&&b!=="local")}),Error(CF);let v=F4(L,B);if(v.delete("x-api-key"),v.delete("api-key"),v.set("authorization",`Bearer ${O}`),T)v.set("ChatGPT-Account-Id",T);v.set(b1.QUOTA_ACCOUNT_HEADER,_);let h=O4(v),m=h?pF($,h,G):void 0,l=L instanceof URL?L:new URL(typeof L==="string"?L:L.url),d=l.pathname.includes("/v1/responses")||l.pathname.includes("/chat/completions")?new URL(J):l,H0=(S0)=>{let Y9=E4(S0,b,q8);return o4(Y9,d),Y9},_0=rF({init:{...B,headers:v},headers:v,metadata:m,installationID:Q,websocket:Boolean(j9&&l.pathname.endsWith("/responses")),responsesLite:X.responsesLite??!1,dumpSessionID:h}).init,H1=L8,D1=new Headers(_0?.headers),d0=OQ({enabled:H1,includeSubagents:V8,headers:D1,body:_0?.body});if(H1)Z8.trace("cachekeep headers",{pid:process.pid,hasParent:D1.has("x-parent-session-id"),sessionKey:d0?.sessionKey,captured:Boolean(d0),affinity:D1.get("x-session-affinity"),opencodeSession:D1.get("x-opencode-session"),sessionId:D1.get("session-id")});if(j9&&l.pathname.endsWith("/responses")){if(Y0.debug("WS transport",{pid:process.pid,pathname:l.pathname,accountId:_}),d0)F9.track(d0.sessionKey,d0.bodyText,_,T,d0.replayHeaders,d0.isSubagent);return H0(await j9(d,_0))}let I0=b1.withoutInternalHeaders(_0);if(typeof I0?.body!=="string")return H0(await fetch(d,I0));if(d0)F9.track(d0.sessionKey,d0.bodyText,_,T,d0.replayHeaders,d0.isSubagent);Y0.debug("HTTP transport",{pid:process.pid,pathname:l.pathname,accountId:_});try{let S0=await fetch(d,I0);return await W9({sessionID:h,transport:"http",phase:"http",bodyText:I0.body,accountId:_,url:d.toString(),method:I0.method,headers:I0.headers,status:S0.status}),H0(S0)}catch(S0){throw await W9({sessionID:h,transport:"http",phase:"http",bodyText:I0.body,accountId:_,url:d.toString(),method:I0.method,headers:I0.headers,error:S0 instanceof Error?S0.message:String(S0)}),S0}}function LY(L,B){if((B?.method??(L instanceof Request?L.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof B?.body!=="string")return!1;try{let T=L instanceof URL?L.toString():typeof L==="string"?L:L.url;return new URL(T).pathname.endsWith("/responses")}catch{return!1}}function r4(L){return Q0.peekMainForPolicy(L)?.quota}function D8(L,B){for(let O of[L?.primary?.checkedAt,L?.secondary?.checkedAt,L?.checkedAt,B])if(typeof O==="number"&&Number.isFinite(O))return O;return}function D9(L,B,O,T,_){let b=D8(L,B),v=D8(O),h=T===_&&O!=null&&(L===void 0||v!==void 0&&(b===void 0||v>b));return{quota:h?O:L,quotaCheckedAt:h?v:b,source:h?"file":"memory"}}function P8(L,B,O,T,_){let b=L?.quota,v=D9(b,L?.checkedAt,B,T,_),h=v.source,m=v.quota;if(!S4(m,O))return{exhausted:!1};let l=I4(m,O);if(!l)return{exhausted:!1};return{exhausted:!0,source:h,...l}}function E8(L,B){z0.debug("admission skip: exhausted account",{accountId:L,source:B.source,resetsAt:B.resetsAt})}function s4(L,B="killswitch",O){let T=Date.now(),_=Q0.getMain()?.quota,b=(L?.accounts??[]).filter((d)=>d.enabled!==!1&&O0(d)).map((d)=>({accountId:d.id,quota:Q0.getFallback(d.id)?.quota})),v=R4(_,b,T,L);if(B==="quota-exhausted"&&O!==void 0)v=Math.max(1,Math.ceil((O-T)/1000));else if(B==="mid-stream-rate-limit"&&O!==void 0){let d=Math.max(1,Math.ceil((O-T)/1000));v=Math.min(v,d)}let h=Math.floor(v/60),m=v%60,l=B==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${h}m ${m}s.`:B==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${h}m ${m}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${h}m ${m}s.`;return new Response(JSON.stringify({error:{message:l,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(v)}})}function M8(L){let B=L?.resetCreditsAvailable;return typeof B==="number"&&Number.isFinite(B)?B:void 0}async function a4(L){let B=QY(L.storage),O=Date.now(),T=Q0.peekMainForPolicy(L.mainAccountIdentity),_=D9(T?.quota,T?.checkedAt,L.sidebarState.main.quota,L.sidebarState.main.mainAccountId,L.mainAccountIdentity),b=B?$Y(T?.quota,L.storage,void 0,O):void 0,v=L.mainCustodyRefused?[]:[{accountId:"main",wireAccountId:L.mainAccountIdentity,access:L.primaryAccess,provenance:L.primaryProvenance,keepwarmAccountKey:"main",quota:_.quota,quotaCheckedAt:_.quotaCheckedAt,reservePercent:Q8(L.storage),configuredOrder:0,resetCreditsApplicable:M8(_.quota),killswitchPasses:b}],h=await $0.getUsableFallbackAccounts(L.storage);if(!L.storage)return v;for(let m of h){let l=await e1(m,L.storage);if(l===g1||l===t1)continue;let d=L.sidebarState.fallbacks.find((H1)=>H1.id===m.id),H0=Q0.peekFallbackForPolicy(m.id,m.accountId),l0=D9(H0?.quota,H0?.checkedAt,d?.quota,d?.accountId,m.accountId),_0=B?$Y(H0?.quota,L.storage,m.id,O):void 0;v.push({accountId:m.id,wireAccountId:m.accountId,access:l.token,provenance:l.provenance,keepwarmAccountKey:m.id,fallback:m,quota:l0.quota,quotaCheckedAt:l0.quotaCheckedAt,reservePercent:Q8(L.storage,m.id),configuredOrder:v.length,resetCreditsApplicable:M8(l0.quota),killswitchPasses:_0})}return v}function w8(L,B,O,T,_){let b=QY(_)?L.killswitchPasses:void 0;if(L.accountId==="main"){let l=Q0.peekMainForPolicy(L.wireAccountId),d=D9(l?.quota,l?.checkedAt,B.main.quota,B.main.mainAccountId,L.wireAccountId);return bX({quota:d.quota,quotaCheckedAt:d.quotaCheckedAt,status:O,now:T,killswitchPasses:b})}let v=B.fallbacks.find((l)=>l.id===L.accountId),h=Q0.peekFallbackForPolicy(L.accountId,L.wireAccountId),m=D9(h?.quota,h?.checkedAt,v?.quota,v?.accountId,L.wireAccountId);return bX({quota:m.quota,quotaCheckedAt:m.quotaCheckedAt,status:O,now:T,killswitchPasses:b})}function t4(L){return L.accountId==="main"?"main":L.keepwarmAccountKey}function A8(L){return Q0.isRateLimited(t4(L))}async function BX(L){let B=L.candidates.filter((m)=>!A8(m)),O=new Map(B.map((m)=>[m.accountId,m])),T=Object.fromEntries(B.map((m)=>[m.accountId,m.quotaCheckedAt])),_=Object.fromEntries(B.map((m)=>[m.accountId,m.wireAccountId])),b=new Set(L.excludeAccountIds),v,h=await v4({sessionId:L.sessionId,requestBytes:L.requestBytes,now:L.now,validPinnedAccountIds:[...O.keys()],excludeAccountIds:L.excludeAccountIds,quotaCheckedAtByAccount:T,wireAccountIdByAccount:_,choose:(m)=>{let l=B.filter((H0)=>!b.has(H0.accountId));if(l.length===0)return;let d=sQ({candidates:l,pendingBytes:m,requestBytes:L.requestBytes,now:L.now,onEmptyWeightedSet:()=>{$1.debug("sticky routing: no fresh weighted candidates; using configured order")}});if(!d)return;return v={accountId:d.accountId,source:d.source,pendingBytes:m.get(d.accountId)??0},d}},p0);if(v&&h?.accountId===v.accountId)$1.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:GY(L.sessionId),accountId:v.accountId,source:v.source,requestBytes:L.requestBytes,pendingBytes:v.pendingBytes});return h?O.get(h.accountId):void 0}async function e4(L,B){let O=await $0.getUsableFallbackAccounts(L),T=[];if(!L)return{current:[],retained:[],skipped:[]};for(let d of O){let H0=await e1(d,L);if(H0===g1||H0===t1)continue;T.push({access:H0.token,provenance:H0.provenance,accountId:d.accountId,keepwarmAccountKey:d.id,quotaAccountId:d.id,fallback:d})}let _=T.filter((d)=>!Q0.isRateLimited(d.quotaAccountId)),b=QY(L)?_.filter((d)=>$Y(Q0.peekFallbackForPolicy(d.quotaAccountId,d.accountId)?.quota,L,d.quotaAccountId,Date.now())):_,v=new Map(B.fallbacks.map((d)=>[d.id,{quota:d.quota,accountId:d.accountId}])),h=[],m=[],l=Date.now();for(let d of b){let H0=v.get(d.quotaAccountId),l0=P8(Q0.peekFallbackForPolicy(d.quotaAccountId,d.accountId),H0?.quota,l,H0?.accountId,d.accountId);if(l0.exhausted)m.push({candidate:d,decision:l0});else h.push(d)}return{current:b,retained:h,skipped:m}}function R8(L,B){if(L.retained.length===0&&!B)return L.current;for(let{candidate:O,decision:T}of L.skipped)E8(O.quotaAccountId,T);return L.retained}async function T8(L,B){try{let O=Q9(L.headers);await O9(O,B.access,B.quotaAccountId,void 0,XY(L.headers))}catch{}}async function YU(L,B,O,T){for(let _ of T){let b;try{b=await q9(L,B,_.access,_.accountId,_.keepwarmAccountKey,_.provenance)}catch(v){if(v instanceof DOMException&&v.name==="AbortError")throw v;if(B?.signal?.aborted)throw v;throw $1.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:_.quotaAccountId}),v}if(!JY(b.status,O))return $0.markUsed(_.fallback),{response:b,accessToken:_.access,quotaAccountId:_.quotaAccountId,activeId:_.keepwarmAccountKey};await T8(b,_),b.body?.cancel().catch(()=>{})}return}async function XU(L,B,O,T,_){if(!LY(L,B))return{response:O};if(!_.length)return{response:O};let b=O,v;for(let h of _){let m;try{m=await q9(L,B,h.access,h.accountId,h.keepwarmAccountKey,h.provenance)}catch(l){if(l instanceof DOMException&&l.name==="AbortError")throw l;if(B?.signal?.aborted)throw l;return $1.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:h.quotaAccountId}),{response:b,...v}}if(b.body?.cancel().catch(()=>{}),b=m,v={accessToken:h.access,accountId:h.quotaAccountId},!JY(m.status,T))return $0.markUsed(h.fallback),{response:m,...v};await T8(m,h)}return{response:b,...v}}if(y){let L=[];for(let B of y.accounts)if(O0(B))L.push(B);Q0.seedFallbacksFromAccounts(L)}if(!z8)z8=!0,ZY(Q0,y).catch(()=>{}),E1(zY({respectBackoff:!0})).catch((L)=>z0.warn("boot quota seed failed",{pid:process.pid,error:t9(L)}));return J0.start(async()=>{let B=(await LQ(zY({readSidebarState:()=>a1(p0)}))).filter((O)=>!O.ok);if(B.length>0)z0.warn("background quota refresh completed with failures",{pid:process.pid,failures:B})},(L)=>{z0.warn("background quota refresh failed",{pid:process.pid,error:L instanceof Error?L.message:String(L)})}),{apiKey:IF,async fetch(L,B){let O=F4(L,B),T=O4(O),_=O.get("x-parent-session-id")?.trim()||void 0,b=await s(),v=await P(),h=++N9;if(v.type!=="oauth")return fetch(L,B);B=await aF(L,B);let m=M&&m1(b)==="claustrum",l="",d,H0=!1;if(m){let G0=await H8(b);if(G0===g1||G0===t1)H0=!0;else l=G0.token,d=G0.provenance==="local"?void 0:G0.provenance}else{if(!v.access||(v.expires??0)<Date.now()){g0.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(v.access),expiresInMs:v.expires?v.expires-Date.now():void 0});try{let G0=await HY();v.access=G0.access,v.refresh=G0.refresh,v.expires=G0.expires}catch(G0){if(X8(G0))throw G0}}l=v.access??""}let _0=v.accountId??(l?z1(W1(l)??{}):void 0);if(h===N9)r0=_0;let H1=b?.routing?.mode??"main-first",D1,I0=await(()=>{return D1??=a1(p0),D1})();if(H1==="sticky-balanced"&&T&&LY(L,B)&&typeof B?.body==="string"){let G0=Buffer.byteLength(B.body,"utf8"),R0=await a4({storage:b,sidebarState:I0,primaryAccess:l,mainAccountIdentity:_0,mainCustodyRefused:H0,primaryProvenance:d}),E0=await BX({sessionId:T,requestBytes:G0,candidates:R0,now:Date.now()});if(E0){let b8=A8(E0)?{action:"migrate",reason:"exhausted"}:w8(E0,I0,void 0,Date.now(),b);if(b8.action==="migrate"){let y0=await BX({sessionId:T,requestBytes:G0,candidates:R0,excludeAccountIds:[E0.accountId],now:Date.now()});if(y0)$1.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:GY(T),fromAccountId:E0.accountId,toAccountId:y0.accountId,reason:b8.reason}),E0=y0}let G1=await q9(L,B,E0.access,E0.wireAccountId,E0.keepwarmAccountKey,E0.provenance),v8=async(y0,f1)=>{try{let JU=Q9(y0.headers);await O9(JU,f1.access,f1.accountId==="main"?void 0:f1.accountId,f1.accountId==="main"?f1.wireAccountId:void 0,XY(y0.headers))}catch{}};await v8(G1,E0);let h8=w8(E0,I0,G1.status,Date.now(),b);if((G1.status===401||G1.status===403||G1.status===429)&&h8.action==="migrate"){let y0=await BX({sessionId:T,requestBytes:G0,candidates:R0,excludeAccountIds:[E0.accountId],now:Date.now()});if(y0){$1.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:GY(T),fromAccountId:E0.accountId,toAccountId:y0.accountId,reason:h8.reason});let f1=G1;G1=await q9(L,B,y0.access,y0.wireAccountId,y0.keepwarmAccountKey,y0.provenance),f1.body?.cancel().catch(()=>{}),E0=y0,await v8(G1,E0)}}if(E0.fallback&&!JY(G1.status,b))$0.markUsed(E0.fallback);return await j8(T,_,E0.accountId,H1,b?.accounts).catch(()=>{}),G1}}let S0=P8(Q0.peekMainForPolicy(_0),I0.main.quota,Date.now(),I0.main.mainAccountId,_0),Y9=QY(b)&&!$Y(r4(_0),b,void 0,Date.now()),VY=Q0.isRateLimited("main"),C8,FX=()=>{return C8??=e4(b,I0),C8},Z1,X9,_8=!1,NY;if(H1==="fallback-first"&&LY(L,B)){_8=!0;let G0=await FX();NY=R8(G0,!Y9&&!VY&&!S0.exhausted);let R0=await YU(L,B,b,NY);if(R0)Z1=R0.response,X9={accessToken:R0.accessToken,accountId:R0.quotaAccountId,activeId:R0.activeId}}if(!Z1){let G0=S0.exhausted&&LY(L,B)&&(await FX()).retained.length>0;if(Y9||VY||G0){let R0=Y9?"killswitch":VY?"mid-stream-rate-limit":"quota-exhausted";if(R0==="quota-exhausted"&&S0.exhausted)E8("main",S0);$1.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:R0}),Z1=s4(b,R0,R0==="quota-exhausted"&&S0.exhausted?S0.resetAtMs:VY?Q0.rateLimitedUntil("main"):void 0)}else Z1=H0?new Response(null,{status:401}):await q9(L,B,l,_0,"main",d)}let I8=Boolean(X9),P9=Z1,S8=X9?.accessToken??l,k8=X9?.accountId,x8=X9?.activeId??"main";if(!X9&&!_8&&JY(Z1.status,b)){$1.debug("reactive fallback triggered",{pid:process.pid,status:Z1.status}),NY??=R8(await FX(),!1);let G0=await XU(L,B,Z1,b,NY),R0=G0.response;if(R0!==Z1){if(I8=!0,P9=R0,S8=G0.accessToken??l,k8=G0.accountId,G0.accountId)x8=G0.accountId}}try{let G0=Q9(P9.headers);if(I8)await O9(G0,S8,k8,void 0,XY(P9.headers));else await O9(G0,l,void 0,_0,XY(P9.headers))}catch{}return await j8(T,_,x8,H1,b?.accounts).catch(()=>{}),P9}}},methods:o0},"chat.headers":async(P,w)=>{if(P.model.providerID!=="openai")return;if(w.headers.originator="opencode",w.headers["User-Agent"]=`${P4(E9)} (${zX.platform()} ${zX.release()}; ${zX.arch()})`,w.headers["session-id"]=P.sessionID,W&&P.agent==="title")w.headers[b1.TITLE_HEADER]="true"},"chat.params":async(P,w)=>{if(P.model.providerID!=="openai")return;w.maxOutputTokens=void 0},config:async(P)=>{j0("commands").info("registering commands",{existing:Object.keys(P.command??{}).length,pid:process.pid}),P.command={...P.command??{},[M9]:{template:M9,description:"Show current OpenAI Codex OAuth quota usage for all accounts."},[w9]:{template:w9,description:"Manage OpenAI accounts — add, switch, remove, or reorder."},[A9]:{template:A9,description:"Show or change OpenAI account routing between main-first, fallback-first, and sticky-balanced."},[R9]:{template:R9,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."},[T9]:{template:T9,description:"Show or toggle OpenAI Codex request dump capture for debugging."},[C9]:{template:C9,description:"Show or change the plugin log level (error, warn, info, debug, trace)."},[_9]:{template:_9,description:"Keep Codex prompt cache alive during idle by shadow-replaying the last request."},[I9]:{template:I9,description:"Spend one reset credit on an exhausted Codex account."}}},"command.execute.before":async(P)=>{if(j0("commands").info("command hook entered",{command:P.command,arguments:P.arguments,modal:S9.includes(P.command),hasCmdCtx:H!==null,pid:process.pid}),!S9.includes(P.command))return;if(!H)j0("commands").warn("command rejected: context not loaded",{command:P.command,pid:process.pid}),await p(P.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),V4();let w=P.command,j={...H,sessionId:P.sessionID,notify:(x)=>{uX(x,P.sessionID)}},M=await DX(w,P.arguments,j);if(N5(P.sessionID))uX(M,P.sessionID);else await p(P.sessionID,M.text);V4()}}}var QO=async(Y)=>{let X=s0();return JO(Y,{codexApiEndpoint:X.codexApiEndpoint,experimentalWebSockets:X.webSockets,responsesLite:X.responsesLite})},jM={id:"cortexkit-openai-auth",server:QO};export{O4 as resolveSidebarSessionId,W1 as parseJwtClaims,B4 as mergePushedQuotaMetadata,NM as getMainRefreshLockName,sF as findCachekeepFallbackAccount,z1 as extractAccountIdFromClaims,jM as default,fF as createResetTargetResolver,OM as buildSidebarState,m4 as buildSidebarMachineState,mF as buildResetRedemptionDeps,OF as __resetSweepFailureLogDedupeForTest,BM as __resetBootQuotaSeedForTest,eJ as __createCustodyRuntimeForTest,U1 as ResetTargetResolutionError,QO as OpenAIAuthPlugin,Y8 as MAIN_REFRESH_LOCK_TTL_MS,bF as MAIN_REFRESH_LEASE_TTL_MS,CF as EMPTY_BEARER_MESSAGE,JO as CodexAuthPlugin,U8 as AuthPersistError};
|