@cortexkit/opencode-openai-auth 0.5.1 → 0.6.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 +2 -1
- package/dist/cli.js +1 -1
- package/dist/commands.d.ts +16 -0
- package/dist/core/accounts.d.ts +22 -0
- package/dist/core/oauth.d.ts +1 -1
- package/dist/core/refresh-all-quota.d.ts +3 -0
- package/dist/core/reset-credits.d.ts +114 -0
- package/dist/index-87145jkw.js +2 -0
- package/dist/{index-rfgyxxxq.js → index-dz9a4xwy.js} +1 -1
- package/dist/{index-zkzb0twr.js → index-e08r33g5.js} +2 -2
- package/dist/{index-s5fbqqwx.js → index-hxpv25e8.js} +1 -1
- package/dist/index-meg0ng0z.js +2 -0
- package/dist/{index-vrdc90yd.js → index-n00ybbbq.js} +1 -1
- package/dist/{index-6rnw2cgs.js → index-nwy7ec7p.js} +1 -1
- package/dist/{index-wpd7mg3p.js → index-s2vhsb2v.js} +1 -1
- package/dist/index-zddpw2sa.js +89 -0
- package/dist/index.d.ts +30 -1
- package/dist/index.js +123 -73
- package/dist/quota-normalize-vf2pj6n7.js +1 -0
- package/dist/quota-normalize.d.ts +1 -0
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.d.ts +1 -1
- package/dist/rpc/rpc-client.d.ts +2 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/rpc/rpc-server.d.ts +1 -0
- package/dist/sidebar-state.d.ts +2 -0
- package/dist/sidebar-state.js +1 -1
- package/dist/{token-5hdnazxp.js → token-esc14v6e.js} +1 -1
- package/dist/token-util-qkpkvy5t.js +1 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/ws-pool.d.ts +1 -0
- package/package.json +3 -3
- package/src/rpc/protocol.ts +1 -0
- package/src/rpc/rpc-client.ts +7 -3
- package/src/rpc/rpc-server.ts +24 -4
- package/src/sidebar-state.ts +62 -3
- package/src/tui/command-dialogs.tsx +245 -0
- package/src/tui-compiled/rpc/protocol.ts +1 -0
- package/src/tui-compiled/rpc/rpc-client.ts +7 -3
- package/src/tui-compiled/sidebar-state.ts +62 -3
- package/src/tui-compiled/tui/command-dialogs.tsx +162 -1
- package/src/tui-compiled/tui.tsx +1 -1
- package/src/tui-compiled/util/error.ts +9 -0
- package/src/tui.tsx +4 -1
- package/dist/index-2ng03cby.js +0 -2
- package/dist/index-j1364eag.js +0 -89
- package/dist/index-wnxfzjfr.js +0 -2
- package/dist/quota-normalize-n02dfdx0.js +0 -1
- package/dist/token-util-3d2nj45d.js +0 -1
package/dist/index.js
CHANGED
|
@@ -1,168 +1,218 @@
|
|
|
1
|
-
import{d as E1,e as WY,f as DG}from"./index-2ng03cby.js";import{A as o0,B as b1,C as Y8,D as GW,E as WW,G as q1,H as zW,I as H1,J as A0,K as X0,L as zY,M as KY,N as h9,O as UY,P as KW,Q as UW,R as HW,h as iG,i as nG,j as oG,k as rG,l as sG,m as aG,n as tG,o as LY,p as NY,q as eY,s as eG,t as YW,u as XW,v as JW,w as QW,x as $W,y as GX,z as WX}from"./index-j1364eag.js";import{T as P8,W as HY,X as LW,_ as L1,ca as NW,da as VW,ea as BW,ja as ZW,ka as X8,la as OW,ma as FW,na as qW,oa as jW}from"./index-wnxfzjfr.js";import{ta as PY}from"./index-vrdc90yd.js";import{ua as lX,va as dX}from"./index-zkzb0twr.js";import{xa as DY,ya as EX,za as L0}from"./index-s5fbqqwx.js";import{Ca as DW}from"./index-rfgyxxxq.js";import{Fa as g8}from"./index-wpd7mg3p.js";import{mkdirSync as wN,readFileSync as EN,renameSync as MN,statSync as AN,writeFileSync as RN}from"node:fs";import x9 from"node:os";import{join as TN}from"node:path";import{readFileSync as SW}from"node:fs";import{homedir as kW,tmpdir as bW}from"node:os";import{join as qY}from"node:path";var xW="https://chatgpt.com/backend-api/codex/responses",vW="openai-auth.json",m0={noWebSearch:"CORTEXKIT_OPENAI_AUTH_NO_WEB_SEARCH",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[m0.configDir]?.trim();if(Y)return Y;return qY(process.env.XDG_CONFIG_HOME||qY(kW(),".config"),"opencode")}function U0(){return process.env[m0.configFile]?.trim()||qY(jY(),vW)}function hW(){try{let Y=JSON.parse(SW(U0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function QX(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 FY(Y,X,J){let Q=QX(Y);if(Q!==void 0)return Q;if(typeof X==="boolean")return X;return J}function gW(){let Y=hW(),X=QX(m0.noWebSearch),J=X!==void 0?!X:typeof Y.webSearch==="boolean"?Y.webSearch:!0,Q;if(Y.dump!==void 0&&Y.dump!==null){if(typeof Y.dump==="object")Q=Y.dump.enabled;else if(typeof Y.dump==="boolean")Q=Y.dump}return{webSearch:J,webSockets:FY(m0.webSockets,Y.webSockets,!1),rawWebSocket:FY(m0.rawWebSocket,Y.rawWebSocket,!1),responsesLite:FY(m0.responsesLite,Y.responsesLite,!1),dump:FY(m0.dump,Q,!1),dumpDir:process.env[m0.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():qY(bW(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[m0.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():xW)}}var W8;function w0(){if(!W8)W8=gW();return W8}var z8="openai-quota",K8="openai-account",U8="openai-routing",H8="openai-killswitch",L8="openai-dump",N8="openai-logging",V8="openai-cachekeep",zX=["openai-quota","openai-account","openai-routing","openai-killswitch","openai-dump","openai-logging","openai-cachekeep"],G0=L0("commands");function $X(Y){if(Y==="fallback-first")return"Try usable fallback accounts before the main account.";if(Y==="sticky-balanced")return"Keep each session on its assigned account while balancing new sessions.";return"Try the main account first. Use fallback accounts only when required."}async function yW(Y){let X=await Y.refreshAllQuota?.(),J=Y.quotaManager.getMain(),Q=["## OpenAI Quota",""];if(J?.quota){let W=J.quota;Q.push("### Main account");for(let K of["primary","secondary"]){let H=W[K];if(H){let U=Math.round(H.usedPercent),N="█".repeat(Math.max(0,Math.min(Math.round(U/10),10)))+"░".repeat(Math.max(0,10-Math.min(Math.round(U/10),10)));Q.push(`- ${K}: ${N} ${U}% used (${Math.round(H.remainingPercent)}% remaining)`)}}if(W.resetCreditsAvailable!==void 0)Q.push(`- resets: ${W.resetCreditsAvailable}`)}else Q.push("No main quota snapshot available. Send a request first.");let G=[...Y.quotaManager.getAllFallbacks().entries()].filter(([,W])=>W);if(G.length>0){Q.push(""),Q.push("### Fallback accounts");for(let[W,K]of G){if(!K?.quota)continue;Q.push(`**${W}**`);for(let H of["primary","secondary"]){let U=K.quota[H];if(U){let N=Math.round(U.usedPercent);Q.push(` - ${H}: ${N}% used (${Math.round(U.remainingPercent)}% remaining)`)}}if(K.quota.resetCreditsAvailable!==void 0)Q.push(` - resets: ${K.quota.resetCreditsAvailable}`)}}if(X?.length){let W=X.filter((K)=>!K.ok);if(W.length>0){Q.push("");for(let K of W)Q.push(`- ${K.account}: fetch failed — Refresh to retry`)}}return{command:"openai-quota",text:Q.join(`
|
|
2
|
-
`),knobs:{}}}async function
|
|
3
|
-
`),knobs:{accounts:$}}}if(J[0]==="remove"&&J[1]){let G=J[1],W=!1,
|
|
1
|
+
import{d as b1,e as qY,f as eG}from"./index-87145jkw.js";import{A as $1,B as R1,C as Q1,D as uW,E as pW,G as u0,H as lW,I as F1,J as y0,K as q0,L as J0,M as FY,N as jY,O as e9,P as DY,Q as dW,R as iW,S as nW,h as _W,i as IW,j as SW,k as kW,l as bW,m as xW,n as vW,o as p1,p as l1,q as L8,s as hW,t as gW,u as yW,v as fW,w as mW,x as cW,y as gX,z as yX}from"./index-zddpw2sa.js";import{$ as D1,U as g8,X as PY,Y as oW,da as rW,ea as sW,fa as aW,ka as tW,la as V8,ma as eW,na as Y5,oa as X5,pa as J5}from"./index-meg0ng0z.js";import{ua as kY}from"./index-n00ybbbq.js";import{va as wJ,wa as EJ}from"./index-e08r33g5.js";import{Aa as L0,ya as SY,za as JJ}from"./index-hxpv25e8.js";import{Da as Q5}from"./index-dz9a4xwy.js";import{Ga as e8}from"./index-s2vhsb2v.js";import{mkdirSync as MB,readFileSync as wB,renameSync as EB,statSync as AB,writeFileSync as TB}from"node:fs";import a9 from"node:os";import{join as RB}from"node:path";import{readFileSync as Z5}from"node:fs";import{homedir as K5,tmpdir as O5}from"node:os";import{join as TY}from"node:path";var q5="https://chatgpt.com/backend-api/codex/responses",F5="openai-auth.json",o0={noWebSearch:"CORTEXKIT_OPENAI_AUTH_NO_WEB_SEARCH",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 RY(){let Y=process.env[o0.configDir]?.trim();if(Y)return Y;return TY(process.env.XDG_CONFIG_HOME||TY(K5(),".config"),"opencode")}function $0(){return process.env[o0.configFile]?.trim()||TY(RY(),F5)}function j5(){try{let Y=JSON.parse(Z5($0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function DX(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 AY(Y,X,J){let Q=DX(Y);if(Q!==void 0)return Q;if(typeof X==="boolean")return X;return J}function D5(){let Y=j5(),X=DX(o0.noWebSearch),J=X!==void 0?!X:typeof Y.webSearch==="boolean"?Y.webSearch:!0,Q;if(Y.dump!==void 0&&Y.dump!==null){if(typeof Y.dump==="object")Q=Y.dump.enabled;else if(typeof Y.dump==="boolean")Q=Y.dump}return{webSearch:J,webSockets:AY(o0.webSockets,Y.webSockets,!1),rawWebSocket:AY(o0.rawWebSocket,Y.rawWebSocket,!1),responsesLite:AY(o0.responsesLite,Y.responsesLite,!1),dump:AY(o0.dump,Q,!1),dumpDir:process.env[o0.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():TY(O5(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[o0.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():q5)}}var O8;function M0(){if(!O8)O8=D5();return O8}var q8="/backend-api/wham/rate-limit-reset-credits",P5=`https://chatgpt.com${q8}`,AX=`${q8}/consume`,M5=`https://chatgpt.com${AX}`,w5=300000,E5=60000,A5=15000,T5=60000;class _0 extends Error{kind;cooldownUntil;constructor(Y,X,J){super(X);this.name="ResetRedemptionError",this.kind=Y,this.cooldownUntil=J}}class q1 extends Error{kind;status;constructor(Y,X,J){super(X);this.name="ResetCreditError",this.kind=Y,this.status=J}}function TX(Y,X,J){return{authorization:`Bearer ${Y}`,...J?{"chatgpt-account-id":J}:{},"oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":X}}function CY(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}function RX(Y){if(!Y)return;return{...Y.inFlight?{inFlight:{...Y.inFlight}}:{},...Y.lastOutcome?{lastOutcome:{...Y.lastOutcome}}:{},...Y.cooldownUntil!==void 0?{cooldownUntil:Y.cooldownUntil}:{}}}function F8(Y){if(!CY(Y)||typeof Y.redeemRequestId!=="string"||Y.redeemRequestId.length===0||typeof Y.creditId!=="string"||Y.creditId.length===0||typeof Y.startedAt!=="number"||!Number.isFinite(Y.startedAt))return;return{redeemRequestId:Y.redeemRequestId,creditId:Y.creditId,startedAt:Y.startedAt}}function CX(Y){return Boolean(Y&&Object.hasOwn(Y,"inFlight"))}function _X(Y,X){return X-Y.startedAt<w5}function _Y(Y,X){if(!y0(X))return;return Y.reset?.[X]}function IX(Y){if(!Y.reset)Y.reset=Object.create(null);return Y.reset}function SX(Y,X,J){if(!y0(X))return;let Q=IX(Y),$=Q[X]??{},G=$.lastOutcome;delete $.inFlight,$.lastOutcome={code:"ambiguous_local",at:J,...G?{previousOutcome:{code:G.code,at:G.at}}:{}},Q[X]=$}function kX(Y,X){let J=RX(Y),Q=F8(Y?.inFlight);if(CX(Y)&&!Q)return{kind:"corrupt",beforeState:J};if(Y?.cooldownUntil!==void 0&&Y.cooldownUntil>X)return{kind:"cooldown",beforeState:J,cooldownUntil:Y.cooldownUntil};if(Q&&_X(Q,X))return{kind:"claim",beforeState:J,claim:{inFlight:Q,selectedCredit:{id:Q.creditId}}};if(Q)return{kind:"expired_unreconciled",beforeState:J,claim:{inFlight:Q,selectedCredit:{id:Q.creditId}}};return{kind:"fresh",beforeState:J}}async function R5(Y,X){if(!y0(X))return{kind:"fresh",beforeState:void 0};let J=await Y.loadAccountsFn(Y.configPath);return kX(J?_Y(J,X):void 0,Y.now())}async function C5(Y,X){let J;if(await Y.mutateAccountsFn((Q)=>{let $=Y.now(),G=_Y(Q,X);if(J=kX(G,$),J.kind==="corrupt")SX(Q,X,$);return Q},Y.configPath),!J)throw Error("corrupt reset state mutation did not run");return J}async function _5(Y,X,J){if(!y0(X))return{kind:"fresh",beforeState:void 0};let Q;if(await Y.mutateAccountsFn(($)=>{let G=Y.now(),W=_Y($,X),U=RX(W),L=F8(W?.inFlight);if(CX(W)&&!L)return SX($,X,G),Q={kind:"corrupt",beforeState:U},$;if(W?.cooldownUntil!==void 0&&W.cooldownUntil>G)return Q={kind:"cooldown",beforeState:U,cooldownUntil:W.cooldownUntil},$;if(L&&_X(L,G))return Q={kind:"claim",beforeState:U,claim:{inFlight:L,selectedCredit:{id:L.creditId}}},$;if(L)return Q={kind:"expired_unreconciled",beforeState:U,claim:{inFlight:L,selectedCredit:{id:L.creditId}}},$;let H=IY(J);if(!H)return Q={kind:"fresh",beforeState:U},$;let N={redeemRequestId:Y.randomUUID(),creditId:H.id,startedAt:G},O=IX($);return O[X]={...W,inFlight:N},Q={kind:"claim",beforeState:U,claim:{inFlight:N,selectedCredit:H}},$},Y.configPath),!Q)throw Error("reset claim mutation did not run");return Q}async function I5(Y,X,J,Q){if(!y0(X))return;if(!P8(Q.kind))return;await Y.mutateAccountsFn(($)=>{let G=_Y($,X),W=F8(G?.inFlight);if(!G||!W||W.redeemRequestId!==J.redeemRequestId||W.creditId!==J.creditId)return $;let U=Y.now();if(delete G.inFlight,G.lastOutcome={code:Q.kind,at:U},Q.kind==="reset"||Q.kind==="already_redeemed")G.cooldownUntil=U+T5;else delete G.cooldownUntil;return $},Y.configPath)}function r1(Y,X){if(!Y||Y.usedPercent<100)return!1;if(!Y.resetsAt)return!0;let J=Date.parse(Y.resetsAt);return!Number.isFinite(J)||J>X}function j8(Y,X,J,Q){if(!(X||r1(Y.primary,Q)||r1(Y.secondary,Q)))return{ok:!1,reason:"not exhausted"};if(J<=0)return{ok:!1,reason:"no applicable credits"};return{ok:!0}}function PX(Y,X){let J=Y[X];if(J===void 0||J===null)return;return typeof J==="string"?J:null}function S5(Y){if(!CY(Y))return;let X=PX(Y,"granted_at"),J=PX(Y,"reset_type");if(typeof Y.id!=="string"||typeof Y.status!=="string"||typeof Y.expires_at!=="string"||Number.isNaN(Date.parse(Y.expires_at))||typeof Y.is_supported_by_plan!=="boolean"||X===null||J===null)return;return{id:Y.id,status:Y.status,...X===void 0?{}:{grantedAt:X},expiresAt:Y.expires_at,...J===void 0?{}:{resetType:J},isSupportedByPlan:Y.is_supported_by_plan}}async function D8(Y,X,J){let Q;try{Q=await Y(P5,{method:"GET",headers:TX(X,q8,J),signal:AbortSignal.timeout(A5)})}catch{throw new q1("http_error","reset credit list request failed")}if(!Q.ok)throw new q1("http_error",`reset credit list request failed: ${Q.status}`,Q.status);let $;try{$=await Q.json()}catch{throw new q1("invalid_response","reset credit list response was not valid JSON",Q.status)}if(!CY($))throw new q1("invalid_response","reset credit list response was not an object",Q.status);return{credits:(Array.isArray($.credits)?$.credits:[]).flatMap((W)=>{let U=S5(W);return U===void 0?[]:[U]}),availableCount:typeof $.available_count==="number"&&Number.isFinite($.available_count)?$.available_count:void 0}}function IY(Y){return[...Y].filter((X)=>X.status==="available"&&X.isSupportedByPlan&&X.resetType==="codex_rate_limits").sort((X,J)=>Date.parse(X.expiresAt)-Date.parse(J.expiresAt))[0]}function P8(Y){return Y==="reset"||Y==="already_redeemed"||Y==="nothing_to_reset"||Y==="no_credit"}async function k5(Y,X,J,Q,$){let G;try{G=await Y(M5,{method:"POST",headers:{...TX(X,AX,J),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:$,credit_id:Q}),signal:AbortSignal.timeout(E5)})}catch(H){return{kind:"ambiguous",raw:H}}let W;try{W=await G.text()}catch(H){return G.ok?{kind:"ambiguous",raw:H}:{kind:"http_error",raw:H,status:G.status}}let U=W,L=!1;try{U=JSON.parse(W),L=!0}catch{}if(!G.ok)return{kind:"http_error",raw:U,status:G.status};if(!L||!CY(U)||!P8(U.code))return{kind:"ambiguous",raw:U};return{kind:U.code,raw:U}}function MX(Y){if(Y.kind==="cooldown")throw new _0("cooldown_active","reset credit redemption is cooling down",Y.cooldownUntil);throw Error(`unexpected reset state decision: ${Y.kind}`)}function wX(){throw new _0("expired_unreconciled","the previous reset attempt outcome is unknown")}function EX(Y,X){return{target:Y,selectedCredit:void 0,beforeState:X,outcome:{kind:"ambiguous_local",raw:{reason:"corrupt_in_flight"}},retrySafety:"No request was sent because the saved redemption identity was incomplete."}}function b5(Y){if(Y.kind==="reset"||Y.kind==="already_redeemed")return"The server returned a terminal result; cooldown blocks an immediate new redemption.";if(Y.kind==="nothing_to_reset"||Y.kind==="no_credit")return"The server returned a terminal no-op. No cooldown was set; a new attempt starts fresh and remains gated by fresh preconditions.";return"The outcome is uncertain. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing."}async function bX(Y,X){if(!y0(X.accountKey))throw new _0("invalid_account_key","the reset account key is reserved");let J=await Y.resolveTarget(X.accountKey);if(J.chatgptAccountId!==X.expectedChatgptAccountId)throw new _0("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let Q=J.accountKey==="main"?void 0:J.chatgptAccountId,$=await R5(Y,X.accountKey);if($.kind==="corrupt"){if($=await C5(Y,X.accountKey),$.kind==="corrupt")return EX(J,$.beforeState)}if($.kind==="cooldown")MX($);let G;if($.kind==="claim")G=$.claim;else if($.kind==="expired_unreconciled"){if(!X.retry)wX();G=$.claim}else{if(X.retry)throw new _0("retry_without_inflight","there is no active reset credit redemption to retry");let[L,H]=await Promise.all([Y.fetchUsage(J),D8(Y.fetchImpl,J.accessToken,Q)]),N=j8(L,Y.hasActiveRateLimitMark(X.accountKey),L.resetCreditsApplicable??0,Y.now());if(!N.ok)throw new _0(N.reason==="not exhausted"?"not_exhausted":"no_applicable_credits",N.reason);if(!IY(H.credits))throw new _0("no_eligible_credit","no eligible reset credit was returned");let O=await _5(Y,X.accountKey,H.credits);if(O.kind==="corrupt")return EX(J,O.beforeState);if(O.kind==="cooldown")MX(O);if(O.kind==="expired_unreconciled")wX();if(O.kind!=="claim")throw new _0("no_eligible_credit","no eligible reset credit was available while claiming");G=O.claim}let W=await k5(Y.fetchImpl,J.accessToken,Q,G.inFlight.creditId,G.inFlight.redeemRequestId),U=!1;try{await I5(Y,X.accountKey,G.inFlight,W)}catch{U=P8(W.kind)}return{target:J,selectedCredit:G.selectedCredit,beforeState:$.beforeState,outcome:W,retrySafety:U?"The server returned a terminal result, but the state write failed. A retry within five minutes reuses the same request and credit identifiers.":b5(W),...U?{finalizeStateWriteFailed:!0}:{}}}var w8="openai-quota",E8="openai-account",A8="openai-routing",T8="openai-killswitch",R8="openai-dump",C8="openai-logging",_8="openai-cachekeep",j1="openai-reset",fX=["openai-quota","openai-account","openai-routing","openai-killswitch","openai-dump","openai-logging","openai-cachekeep","openai-reset"],i=L0("commands");function xX(Y){if(Y==="fallback-first")return"Try usable fallback accounts before the main account.";if(Y==="sticky-balanced")return"Keep each session on its assigned account while balancing new sessions.";return"Try the main account first. Use fallback accounts only when required."}async function x5(Y){let X=await Y.refreshAllQuota?.(),J=Y.quotaManager.getMain(),Q=["## OpenAI Quota",""];if(J?.quota){let W=J.quota;Q.push("### Main account");for(let U of["primary","secondary"]){let L=W[U];if(L){let H=Math.round(L.usedPercent),N="█".repeat(Math.max(0,Math.min(Math.round(H/10),10)))+"░".repeat(Math.max(0,10-Math.min(Math.round(H/10),10)));Q.push(`- ${U}: ${N} ${H}% used (${Math.round(L.remainingPercent)}% remaining)`)}}if(W.resetCreditsAvailable!==void 0)Q.push(`- resets: ${W.resetCreditsAvailable}`)}else Q.push("No main quota snapshot available. Send a request first.");let G=[...Y.quotaManager.getAllFallbacks().entries()].filter(([,W])=>W);if(G.length>0){Q.push(""),Q.push("### Fallback accounts");for(let[W,U]of G){if(!U?.quota)continue;Q.push(`**${W}**`);for(let L of["primary","secondary"]){let H=U.quota[L];if(H){let N=Math.round(H.usedPercent);Q.push(` - ${L}: ${N}% used (${Math.round(H.remainingPercent)}% remaining)`)}}if(U.quota.resetCreditsAvailable!==void 0)Q.push(` - resets: ${U.quota.resetCreditsAvailable}`)}}if(X?.length){let W=X.filter((U)=>!U.ok);if(W.length>0){Q.push("");for(let U of W)Q.push(`- ${U.account}: fetch failed — Refresh to retry`)}}return{command:"openai-quota",text:Q.join(`
|
|
2
|
+
`),knobs:{}}}async function v5(Y,X){let J=Y.trim().split(/\s+/).filter(Boolean),Q=await X.loadAccounts(X.accountStoragePath)??{version:1,accounts:[]},$=Q.accounts??[];if(J.length===0){let G=["## OpenAI Accounts",""];if($.length===0)G.push("No accounts configured. Use `/login openai` to add your main account, or `/openai-account add` to add a fallback account.");else{let W=Q.routing?.mode??"main-first";G.push(`Routing: \`${W}\` (set with \`/openai-routing\`). Modes: main-first, fallback-first, or sticky-balanced. \`/openai-routing reset\` clears this session's pin.`),G.push("");for(let U of $){let L=U.type??"oauth";G.push(`- \`${U.id}\` (${L})`)}}return G.push(""),G.push("Commands: `/openai-account add [label]` | `/openai-account remove <id>`"),{command:"openai-account",text:G.join(`
|
|
3
|
+
`),knobs:{accounts:$}}}if(J[0]==="remove"&&J[1]){let G=J[1],W=!1,U=await J0((L)=>{let H=L.accounts.findIndex((N)=>N.id===G);if(H===-1)return L;return W=!0,L.accounts.splice(H,1),L},X.accountStoragePath);if(!W)return{command:"openai-account",text:`## Account Not Found
|
|
4
4
|
|
|
5
|
-
No account with id \`${G}\` exists.`,knobs:{accounts:
|
|
5
|
+
No account with id \`${G}\` exists.`,knobs:{accounts:U.accounts}};return i.info("account removed",{id:G}),X.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Account Removed
|
|
6
6
|
|
|
7
|
-
Removed account \`${G}\`.`,knobs:{accounts:
|
|
7
|
+
Removed account \`${G}\`.`,knobs:{accounts:U.accounts}}}if(J[0]==="order"&&J.length>=3){let G=!1,W=await J0((U)=>{let L=U.accounts.findIndex((O)=>O.id===J[1]),H=U.accounts.findIndex((O)=>O.id===J[2]);if(L===-1||H===-1)return U;G=!0;let N=U.accounts[L];return U.accounts[L]=U.accounts[H],U.accounts[H]=N,U},X.accountStoragePath);if(!G)return{command:"openai-account",text:`## Invalid Order
|
|
8
8
|
|
|
9
|
-
Both account IDs must exist.`,knobs:{accounts:W.accounts}};return
|
|
9
|
+
Both account IDs must exist.`,knobs:{accounts:W.accounts}};return i.info("accounts reordered",{a:J[1],b:J[2]}),X.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Accounts Reordered
|
|
10
10
|
|
|
11
|
-
Swapped positions of \`${J[1]}\` and \`${J[2]}\`.`,knobs:{accounts:W.accounts}}}if(J[0]==="add"){let G=J.includes("--headless"),W=J.filter((
|
|
11
|
+
Swapped positions of \`${J[1]}\` and \`${J[2]}\`.`,knobs:{accounts:W.accounts}}}if(J[0]==="add"){let G=J.includes("--headless"),W=J.filter((V)=>V!=="add"&&V!=="--headless"),U=W.length>0?W.join(" "):void 0,{url:L,instructions:H,completion:N}=await yX({label:U,headless:G}),O=X.notify,Z=X.sessionId;if(N.then(async(V)=>{let K=!1;if(await J0((j)=>{if(V.accountId&&j.mainAccountId&&V.accountId===j.mainAccountId)return K=!0,j;return gX(j.accounts,V),j},X.accountStoragePath),K){i.warn("account add rejected (main identity)",{id:V.id,sessionId:Z}),O?.({command:"openai-account",text:`## Add Failed
|
|
12
12
|
|
|
13
|
-
${"That account is already your main account — not added as a fallback."}`,knobs:{}});return}
|
|
13
|
+
${"That account is already your main account — not added as a fallback."}`,knobs:{}});return}i.info("account added",{id:V.id,label:V.label}),X.refreshSidebar?.().catch(()=>{}),O?.({command:"openai-account",text:`## Account Added
|
|
14
14
|
|
|
15
|
-
Added account \`${
|
|
15
|
+
Added account \`${V.id}\`${V.label?` ("${V.label}")`:""}.
|
|
16
16
|
|
|
17
|
-
Run \`/openai-account\` to confirm.`,knobs:{}})}).catch((
|
|
17
|
+
Run \`/openai-account\` to confirm.`,knobs:{}})}).catch((V)=>{let K=V instanceof Error?V.message:String(V??"unknown error");i.warn("account add failed",{error:K,sessionId:Z}),O?.({command:"openai-account",text:`## Add Failed
|
|
18
18
|
|
|
19
|
-
Account add failed: ${
|
|
19
|
+
Account add failed: ${K}`,knobs:{}})}),G){let V=H.match(/Enter code: (.+)/)?.[1]??H;return{command:"openai-account",text:`## Device Code
|
|
20
20
|
|
|
21
21
|
1. Open this verification URL:
|
|
22
22
|
|
|
23
|
-
${
|
|
23
|
+
${L}
|
|
24
24
|
|
|
25
|
-
2. Enter the code: **${
|
|
25
|
+
2. Enter the code: **${V}**
|
|
26
26
|
|
|
27
|
-
${
|
|
27
|
+
${H}
|
|
28
28
|
|
|
29
|
-
The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{verificationUrl:
|
|
29
|
+
The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{verificationUrl:L,userCode:V,instructions:H}}}return{command:"openai-account",text:`## Add OpenAI Account
|
|
30
30
|
|
|
31
31
|
Open this URL and complete sign-in:
|
|
32
32
|
|
|
33
|
-
${
|
|
33
|
+
${L}
|
|
34
34
|
|
|
35
|
-
${
|
|
35
|
+
${H}
|
|
36
36
|
|
|
37
|
-
The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{url:
|
|
37
|
+
The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{url:L,instructions:H}}}return{command:"openai-account",text:"## Account Commands\n\n- `/openai-account` — show accounts\n- `/openai-account add [label]` — add a new account\n- `/openai-account remove <id>` — remove\n- `/openai-account order <a> <b>` — swap fallback positions\n\nRouting modes are `main-first`, `fallback-first`, and `sticky-balanced`. `/openai-routing reset` clears the current session pin.",knobs:{accounts:$}}}async function h5(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),$=(await X.loadAccounts(X.accountStoragePath)??{version:1,accounts:[]}).routing?.mode??"main-first";if(J.length===1&&J[0]==="reset"){if(!X.sessionId)return{command:"openai-routing",text:`## OpenAI Routing Reset
|
|
38
38
|
|
|
39
39
|
No current session is available, so no pin was changed.`,knobs:{mode:$}};if(!X.clearStickyRouting)return{command:"openai-routing",text:`## OpenAI Routing Reset
|
|
40
40
|
|
|
41
|
-
This runtime cannot clear the current session pin.`,knobs:{mode:$}};return await X.clearStickyRouting(X.sessionId),
|
|
41
|
+
This runtime cannot clear the current session pin.`,knobs:{mode:$}};return await X.clearStickyRouting(X.sessionId),i.info("routing session pin cleared"),{command:"openai-routing",text:`## OpenAI Routing Reset
|
|
42
42
|
|
|
43
|
-
This session's pin was cleared. The next request may choose the same account if it remains the best selection.`,knobs:{mode:$}}}if(J.length===1&&(J[0]==="main-first"||J[0]==="fallback-first"||J[0]==="sticky-balanced")){let
|
|
43
|
+
This session's pin was cleared. The next request may choose the same account if it remains the best selection.`,knobs:{mode:$}}}if(J.length===1&&(J[0]==="main-first"||J[0]==="fallback-first"||J[0]==="sticky-balanced")){let U=J[0];return await J0((L)=>{return L.routing={...L.routing??{},mode:U},L},X.accountStoragePath),i.info("routing mode changed",{mode:U}),{command:"openai-routing",text:`## OpenAI Routing Updated
|
|
44
44
|
|
|
45
|
-
Mode: \`${
|
|
46
|
-
- ${
|
|
45
|
+
Mode: \`${U}\`
|
|
46
|
+
- ${xX(U)}
|
|
47
47
|
|
|
48
|
-
Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:
|
|
48
|
+
Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:U}}}let G=$==="sticky-balanced"&&X.sessionId?await X.getStickyRouting?.(X.sessionId):void 0,W=$==="sticky-balanced"?G?`
|
|
49
49
|
- Session pin: \`${G}\`. Use \`/openai-routing reset\` to clear it.`:`
|
|
50
50
|
- Session pin: none yet. A request will choose one when a usable account is available.`:"";return{command:"openai-routing",text:`## OpenAI Routing
|
|
51
51
|
|
|
52
52
|
- Mode: \`${$}\`
|
|
53
|
-
- ${
|
|
53
|
+
- ${xX($)}${W}
|
|
54
54
|
|
|
55
|
-
Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:$}}}async function
|
|
56
|
-
`),knobs:{config:Q,accountIds:$}}}if(G[0]==="on"){let W={...Q,enabled:!0,main:Q.main??{primary:
|
|
55
|
+
Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:$}}}async function g5(Y,X){let J=await X.loadAccounts(X.accountStoragePath)??{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,U=["## Killswitch","",`Status: **${W?"ON":"OFF"}**`];if(W){U.push(""),U.push("| Account | primary threshold | secondary threshold |"),U.push("| ------- | ------------ | ------------ |");let L=Q.main??{},H=L.primary??L["5h"]??F1.primary,N=L.secondary??L["1w"]??F1.secondary;U.push(`| main | ≥ ${H}% | ≥ ${N}% |`);for(let O of $){let Z=Q.accounts?.[O]??Q.main??{},V=Z.primary??Z["5h"]??F1.primary,K=Z.secondary??Z["1w"]??F1.secondary;U.push(`| ${O} | ≥ ${V}% | ≥ ${K}% |`)}}return U.push(""),U.push("Commands: `/openai-killswitch on` | `/openai-killswitch off` | `/openai-killswitch set <acct>:<5h>,<1w> ...`"),{command:"openai-killswitch",text:U.join(`
|
|
56
|
+
`),knobs:{config:Q,accountIds:$}}}if(G[0]==="on"){let W={...Q,enabled:!0,main:Q.main??{primary:F1.primary,secondary:F1.secondary}};return await J0((U)=>{return U.killswitch=W,U},X.accountStoragePath),i.info("killswitch enabled"),{command:"openai-killswitch",text:"## Killswitch Enabled",knobs:{config:W,accountIds:$}}}if(G[0]==="off"){let W={...Q,enabled:!1};return await J0((U)=>{return U.killswitch=W,U},X.accountStoragePath),i.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 U=1;U<G.length;U++){let L=G[U]?.match(/^([^:]+):(\d+),(\d+)$/);if(!L)continue;let[,H,N,O]=L,Z={primary:Number.parseInt(N,10),secondary:Number.parseInt(O,10)};if(H==="main")W.main=Z;else if(H==="all"){W.main=Z;for(let V of $)W.accounts[V]=Z}else W.accounts[H]=Z}return await J0((U)=>{return U.killswitch=W,U},X.accountStoragePath),i.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 y5(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),Q=M0(),$=Q.dump;if(J.length===0)return{command:"openai-dump",text:`## Request Dump
|
|
57
57
|
|
|
58
58
|
- Enabled: ${$?"ON":"OFF"}
|
|
59
59
|
- Directory: ${Q.dumpDir}
|
|
60
60
|
|
|
61
|
-
Usage: \`/openai-dump on\` or \`/openai-dump off\``,knobs:{enabled:$}};if(J[0]==="on")return await
|
|
61
|
+
Usage: \`/openai-dump on\` or \`/openai-dump off\``,knobs:{enabled:$}};if(J[0]==="on")return await J0((G)=>{return G.dump={...G.dump??{},enabled:!0},G},X.accountStoragePath),i.info("request dump enabled"),{command:"openai-dump",text:`## Request Dump Enabled
|
|
62
62
|
|
|
63
63
|
Dump directory: ${Q.dumpDir}
|
|
64
64
|
|
|
65
|
-
Warning: body dumps may contain prompt/session content. Turn this off after debugging.`,knobs:{enabled:!0}};if(J[0]==="off")return await
|
|
65
|
+
Warning: body dumps may contain prompt/session content. Turn this off after debugging.`,knobs:{enabled:!0}};if(J[0]==="off")return await J0((G)=>{return G.dump={...G.dump??{},enabled:!1},G},X.accountStoragePath),i.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 f5(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(X.accountStoragePath))?.logging?.level??"info";return{command:"openai-logging",text:`## Logging
|
|
66
66
|
|
|
67
67
|
- Level: \`${W}\`
|
|
68
68
|
|
|
69
|
-
Valid levels: ${Q.map((
|
|
69
|
+
Valid levels: ${Q.map((U)=>`\`${U}\``).join(", ")}
|
|
70
70
|
|
|
71
|
-
Usage: \`/openai-logging <level>\``,knobs:{level:W}}}let $=J[0];if($&&Q.includes($)){let G=$;return
|
|
71
|
+
Usage: \`/openai-logging <level>\``,knobs:{level:W}}}let $=J[0];if($&&Q.includes($)){let G=$;return SY(G),await J0((W)=>{return W.logging={...W.logging??{},level:G},W},X.accountStoragePath),i.info("log level changed",{level:G}),{command:"openai-logging",text:`## Logging Updated
|
|
72
72
|
|
|
73
73
|
Level set to \`${G}\`.`,knobs:{level:G}}}return{command:"openai-logging",text:`## Invalid Level
|
|
74
74
|
|
|
75
|
-
Valid levels: ${Q.map((G)=>`\`${G}\``).join(", ")}`,knobs:{level:"info"}}}function
|
|
75
|
+
Valid levels: ${Q.map((G)=>`\`${G}\``).join(", ")}`,knobs:{level:"info"}}}function m5(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 c5(Y,X){let J=X.cacheKeepManager,Q=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),$=await X.loadAccounts(X.accountStoragePath),G=$?.cachekeep?.enabled===!0;if(Q.length===0||Q[0]==="status"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
|
|
76
76
|
|
|
77
|
-
Status: **not available** (manager not wired)`,knobs:{}};let
|
|
78
|
-
`),knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:
|
|
77
|
+
Status: **not available** (manager not wired)`,knobs:{}};let U=J.status(),L=U.window,H=L?`${String(L.startHour).padStart(2,"0")}-${String(L.endHour).padStart(2,"0")}`:"always (no window)",N=["## Cachekeep","",`Status: **${G?"ON":"OFF"}**`,`Timer: **${U.running?"armed":"idle"}**`,`Subagent warming: **${$?.cachekeep?.subagents===!0?"ON":"OFF"}**`,`Idle policy: **sustain ${U.sustain?"ON":"OFF"} (main only)**`,`Window: **${H}**`];if(N.push(`Tracked sessions: **${U.tracked}**`),U.targets.length>0){N.push("");for(let Z of U.targets){let V=Z.sessionKey.length>12?`${Z.sessionKey.slice(0,12)}…`:Z.sessionKey,K=Math.ceil((Z.cacheExpiresAt-U.generatedAt)/1000);N.push(`- \`${V}\` (${Z.accountId??"main"}) — expires in ${K}s`+(Z.lastWarmedAt?`, last warm ${Math.ceil((U.generatedAt-Z.lastWarmedAt)/1000)}s ago`:"")+(Z.backoffUntil&&Z.backoffUntil>U.generatedAt?`, backoff ${Math.ceil((Z.backoffUntil-U.generatedAt)/1000)}s`:""))}}N.push(""),N.push(`TTL: ${Math.round(U.ttlMs/1000)}s | Lead: ${Math.round(U.leadMs/1000)}s | Max idle warm: ${Math.round(U.maxIdleWarmMs/60000)}min`),N.push(""),N.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 O=Math.max(0,...U.targets.map((Z)=>Z.lastWarmedAt??0));return{command:"openai-cachekeep",text:N.join(`
|
|
78
|
+
`),knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:U.sustain,window:L,running:U.running,tracked:U.tracked,lastWarmAt:O||void 0,generatedAt:U.generatedAt,maxIdleWarmMs:U.maxIdleWarmMs,maxSubagentIdleMs:U.maxSubagentIdleMs}}}if(Q[0]==="on"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
|
|
79
79
|
|
|
80
|
-
Cannot start: manager not wired.`,knobs:{}};await
|
|
80
|
+
Cannot start: manager not wired.`,knobs:{}};await J0((H)=>{return H.cachekeep={...H.cachekeep??{},enabled:!0},H},X.accountStoragePath),i.info("cachekeep enabled"),X.setCacheKeepEnabled?.(!0),J.start();let U=J.status(),L=Math.max(0,...U.targets.map((H)=>H.lastWarmedAt??0));return{command:"openai-cachekeep",text:`## Cachekeep Enabled
|
|
81
81
|
|
|
82
|
-
TTL: ${Math.round(
|
|
82
|
+
TTL: ${Math.round(U.ttlMs/1000)}s | Max idle warm ${Math.round(U.maxIdleWarmMs/60000)}min`,knobs:{enabled:!0,subagents:$?.cachekeep?.subagents===!0,sustain:U.sustain,window:U.window,running:U.running,tracked:U.tracked,lastWarmAt:L||void 0,generatedAt:U.generatedAt,maxIdleWarmMs:U.maxIdleWarmMs,maxSubagentIdleMs:U.maxSubagentIdleMs}}}if(Q[0]==="off")return await J0((U)=>{return U.cachekeep={...U.cachekeep??{},enabled:!1},U},X.accountStoragePath),i.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 U=Q[1];if(Q.length!==2||U!=="on"&&U!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep sustain on` | `/openai-cachekeep sustain off`",knobs:{}};let L=U==="on";await J0((N)=>{return N.cachekeep={...N.cachekeep??{},sustain:L},N},X.accountStoragePath),i.info(`cachekeep sustain ${L?"enabled":"disabled"}`),X.setCacheKeepSustain?.(L);let H=J?.status();return{command:"openai-cachekeep",text:L?`## Cachekeep Sustain Enabled
|
|
83
83
|
|
|
84
84
|
Sustain keeps main-agent sessions warming past the idle cap for this process. Clock windows still apply.
|
|
85
85
|
|
|
86
86
|
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
|
|
87
87
|
|
|
88
|
-
Main-agent sessions again stop warming at the configured idle cap.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:
|
|
88
|
+
Main-agent sessions again stop warming at the configured idle cap.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:L,window:H?.window,running:H?.running??!1,tracked:H?.tracked??0,generatedAt:H?.generatedAt??Date.now(),maxIdleWarmMs:H?.maxIdleWarmMs??3600000,maxSubagentIdleMs:H?.maxSubagentIdleMs??1800000}}}if(Q[0]==="subagents"){let U=Q[1];if(!U||U!=="on"&&U!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off`",knobs:{}};let L=U==="on";await J0((N)=>{return N.cachekeep={...N.cachekeep??{},subagents:L},N},X.accountStoragePath),i.info(L?"cachekeep subagent warming enabled":"cachekeep subagent warming disabled"),X.setCacheKeepSubagents?.(L);let H=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Subagent Warming
|
|
89
|
+
|
|
90
|
+
Subagent warming: **${L?"ON":"OFF"}**`,knobs:{enabled:G,subagents:L,sustain:H?.sustain??$?.cachekeep?.sustain===!0,window:H?.window,running:H?.running??!1,tracked:H?.tracked??0,generatedAt:H?.generatedAt??Date.now(),maxIdleWarmMs:H?.maxIdleWarmMs??3600000,maxSubagentIdleMs:H?.maxSubagentIdleMs??1800000}}}if(Q[0]==="window"){let U=Q[1];if(U==="clear"||U==="off"){await J0((H)=>{if(H.cachekeep)delete H.cachekeep.startHour,delete H.cachekeep.endHour;return H},X.accountStoragePath),X.setCacheKeepWindow?.(void 0),i.info("cachekeep window cleared");let L=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Cleared
|
|
91
|
+
|
|
92
|
+
Cachekeep will now warm on every tick (within idle caps).`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:L?.sustain??$?.cachekeep?.sustain===!0,window:void 0,running:L?.running??!1,tracked:L?.tracked??0,generatedAt:L?.generatedAt??Date.now(),maxIdleWarmMs:L?.maxIdleWarmMs??3600000,maxSubagentIdleMs:L?.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 U=m5(W);if(!U.ok)return{command:"openai-cachekeep",text:`## Cachekeep Window Invalid
|
|
93
|
+
|
|
94
|
+
${U.reason}`,knobs:{}};let{startHour:L,endHour:H}=U;await J0((Z)=>{return Z.cachekeep={...Z.cachekeep??{},startHour:L,endHour:H},Z},X.accountStoragePath),X.setCacheKeepWindow?.({startHour:L,endHour:H}),i.info("cachekeep window set",{startHour:L,endHour:H});let N=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Set
|
|
95
|
+
|
|
96
|
+
Warming limited to **${`${String(L).padStart(2,"0")}-${String(H).padStart(2,"0")}`}** local hours.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:N?.sustain??$?.cachekeep?.sustain===!0,window:{startHour:L,endHour:H},running:N?.running??!1,tracked:N?.tracked??0,generatedAt:N?.generatedAt??Date.now(),maxIdleWarmMs:N?.maxIdleWarmMs??3600000,maxSubagentIdleMs:N?.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:{}}}function mX(Y){let X=[Y.primary?.usedPercent,Y.secondary?.usedPercent].filter((J)=>J!==void 0);return X.length>0?Math.max(...X):void 0}function u5(Y,X){let J=[Y.primary,Y.secondary].filter(($)=>$!==void 0),Q=J.filter(($)=>r1($,X));return(Q.length>0?Q:J).sort(($,G)=>G.usedPercent-$.usedPercent)[0]?.resetsAt}function p5(Y,X){if(!Y)return!1;let J=[Y.primary,Y.secondary].filter((Q)=>Q!==void 0);if(J.length===0)return!1;return J.every((Q)=>!r1(Q,X))}function M8(Y){if(!Y)return;try{return decodeURIComponent(Y)}catch{return}}async function vX(Y,X){try{let J=await X.resolveResetTarget(Y),Q=J.accountKey==="main"?void 0:J.chatgptAccountId,[$,G]=await Promise.all([Q1({accessToken:J.accessToken,fetchImpl:X.fetchImpl,now:X.now,accountId:J.chatgptAccountId}),D8(X.fetchImpl,J.accessToken,Q)]),W=IY(G.credits),U=G.availableCount??$.resetCreditsAvailable??0,L=$.resetCreditsApplicable??0,H=j8($,X.quotaManager.isRateLimited(Y),L,X.now()),N;if(!J.chatgptAccountId)N="stable ChatGPT account identity unavailable";else if(!H.ok)N=H.reason;else if(!W)N="no eligible credit";return{accountKey:J.accountKey,label:J.label,chatgptAccountId:J.chatgptAccountId,usedPercent:mX($),resetTime:u5($,X.now()),availableCount:U,applicableAvailableCount:L,eligible:N===void 0,reason:N,selectedCreditId:W?.id,selectedCreditExpiresAt:W?.expiresAt}}catch(J){return i.warn("reset preview row failed",{accountKey:Y,error:J?.message??String(J)}),{accountKey:Y,label:Y==="main"?"Main account":Y,eligible:!1,reason:J?.message??String(J)}}}function l5(Y){let X=["## Reset credits","","Select an account to fetch a fresh confirmation preview:",""];for(let J of Y){let Q=J.usedPercent===void 0?"quota unavailable":`${J.usedPercent}% used`,$=J.availableCount===void 0?"credits unavailable":`${J.applicableAvailableCount??0}/${J.availableCount} applicable/available`,G=J.eligible?`eligible · credit ${J.selectedCreditId} expires ${J.selectedCreditExpiresAt}`:J.reason;X.push(`- **${J.label}** (\`${J.accountKey}\`) — ${Q}; ${$}; ${G}`)}return X.push(""),X.push("Command: `/openai-reset select <encodedAccountKey>`"),X.join(`
|
|
97
|
+
`)}function hX(Y){let X=["## Confirm reset credit","",`Account: **${Y.label}** (\`${Y.accountKey}\`)`,`Current quota: **${Y.usedPercent??"unknown"}% used**`,`Credit: **Spend 1 of ${Y.applicableAvailableCount??0}**`,`Credit expires: **${Y.selectedCreditExpiresAt??"unavailable"}**`,`Quota resets: **${Y.resetTime??"unavailable"}**`,""];if(Y.eligible&&Y.chatgptAccountId)X.push(`Confirm: \`/openai-reset confirm ${encodeURIComponent(Y.accountKey)} ${encodeURIComponent(Y.chatgptAccountId)}\``);else X.push(`Cannot reset: **${Y.reason??"not eligible"}**`);return X.join(`
|
|
98
|
+
`)}function w0(Y,X,J,Q={}){return{command:j1,text:J,knobs:{stage:"result",accountKey:Y,code:X,...Q}}}function d5(Y,X,J){if(X instanceof _0){let $={identity_mismatch:"The account identity changed before redemption. Reopen the reset account list.",invalid_account_key:"The selected account key is reserved. Reopen the reset account list.",cooldown_active:"This account just reset — re-checking quota. Wait for the cooldown before another redemption.",expired_unreconciled:"The previous attempt outcome is unknown — retry replays the same identifiers, or wait until quota reflects the earlier attempt.",retry_without_inflight:"There is no active reset redemption to retry. Reopen the account list.",not_exhausted:"No credit was spent: the fresh account state is not exhausted.",no_applicable_credits:"No credit was spent: no applicable credits are available.",no_eligible_credit:"No credit was spent: no eligible credit was returned."};return w0(Y,X.kind,`## Reset credit
|
|
99
|
+
|
|
100
|
+
${$[X.kind]}
|
|
101
|
+
|
|
102
|
+
Code: \`${X.kind}\``,{cooldownUntil:X.cooldownUntil,...X.kind==="expired_unreconciled"?{chatgptAccountId:J,retryGuidance:"Retry replays the same request and credit identifiers from the previous attempt."}:{}})}let Q=X?.code;if(Q==="unknown_account"||Q==="disabled_account"||Q==="non_oauth_account"||Q==="token_unavailable")return w0(Y,Q,`## Reset credit
|
|
103
|
+
|
|
104
|
+
${{unknown_account:"Account unavailable: the selected account no longer exists. Reopen the reset account list.",disabled_account:"Account unavailable: the selected account is disabled. Reopen the reset account list.",non_oauth_account:"Account unavailable: the selected account is not authenticated with OAuth. Reopen the reset account list.",token_unavailable:"Authentication problem: the selected account token is unavailable. Reauthenticate the account before retrying."}[Q]}
|
|
105
|
+
|
|
106
|
+
Code: \`${Q}\``);if(X instanceof q1)return w0(Y,X.kind,`## Reset credit
|
|
107
|
+
|
|
108
|
+
No redemption was attempted: reset credit availability could not be loaded.
|
|
109
|
+
|
|
110
|
+
Code: \`${X.kind}\``);return i.warn("reset command failed before a known result",{accountKey:Y,error:X?.message??String(X)}),w0(Y,"error",`## Reset credit
|
|
111
|
+
|
|
112
|
+
The reset request failed before a known result: internal command failure — see plugin log.`)}async function i5(Y,X,J){let{accountKey:Q}=Y.target,$=Y.outcome.kind;if(Y.finalizeStateWriteFailed)return w0(Q,$,`## Reset credit result
|
|
113
|
+
|
|
114
|
+
Account: **${Y.target.label}** (\`${Q}\`)
|
|
115
|
+
|
|
116
|
+
The server outcome recorded as \`${$}\`, but the state write failed. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing.`,{stateWriteFailed:!0,retryGuidance:Y.retrySafety,chatgptAccountId:J});if($==="reset"||$==="already_redeemed"){let W={account:Q,ok:!1,error:"targeted quota refresh did not complete"};try{W=await X.refreshResetTargetQuota(Q)}catch(V){W.error=V?.message??String(V)}let U=!W.ok&&W.error!==void 0;if(U)i.warn("reset quota re-check failed",{accountKey:Q,error:W.error});let L=Q==="main"?X.quotaManager.getMain():X.quotaManager.getFallback(Q),H=W.ok&&p5(L?.quota,X.now()),N=L?.quota.resetCreditsApplicable,O=H?"Post-verification: **window fresh**.":`Post-verification: **window not yet refreshed** (server code \`${$}\`).`,Z=U?`
|
|
117
|
+
|
|
118
|
+
quota re-check failed — see log.`:"";return w0(Q,$,`## Reset credit result
|
|
119
|
+
|
|
120
|
+
Account: **${Y.target.label}** (\`${Q}\`)
|
|
121
|
+
|
|
122
|
+
Code: \`${$}\`
|
|
123
|
+
|
|
124
|
+
${O}${Z}${N===void 0?"":`
|
|
125
|
+
|
|
126
|
+
Remaining applicable credits: **${N}**`}`,{verifiedFresh:H,afterUsedPercent:mX(L?.quota??{}),remainingCredits:N})}if($==="ambiguous_local")return w0(Q,$,`## Reset credit result
|
|
127
|
+
|
|
128
|
+
Account: **${Y.target.label}** (\`${Q}\`)
|
|
129
|
+
|
|
130
|
+
Code: \`${$}\`
|
|
131
|
+
|
|
132
|
+
${Y.retrySafety}`,{retryGuidance:Y.retrySafety});if($==="ambiguous"||$==="http_error"){let W=J?`/openai-reset retry ${encodeURIComponent(Q)} ${encodeURIComponent(J)}`:"/openai-reset";return w0(Q,$,`## Reset credit result
|
|
133
|
+
|
|
134
|
+
Account: **${Y.target.label}** (\`${Q}\`)
|
|
135
|
+
|
|
136
|
+
The redemption outcome is unknown (\`${$}\`).
|
|
137
|
+
|
|
138
|
+
Retry with \`${W}\`. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing.`,{retryGuidance:Y.retrySafety,chatgptAccountId:J})}let G={nothing_to_reset:"The server found no exhausted quota window to reset. No reset was confirmed. A new attempt starts fresh and must pass the current preconditions.",no_credit:"The server found no usable reset credit. No reset was confirmed. A new attempt starts fresh and must pass the current preconditions."};return w0(Q,$,`## Reset credit result
|
|
89
139
|
|
|
90
|
-
|
|
140
|
+
Account: **${Y.target.label}** (\`${Q}\`)
|
|
91
141
|
|
|
92
|
-
|
|
142
|
+
Code: \`${$}\`
|
|
93
143
|
|
|
94
|
-
${
|
|
144
|
+
${G[$]??"The server returned a no-op result. No reset was confirmed."}`)}async function n5(Y,X){let J=[X.resolveResetTarget?void 0:"resolveResetTarget",X.fetchImpl?void 0:"fetchImpl",X.now?void 0:"now",X.randomUUID?void 0:"randomUUID",X.refreshResetTargetQuota?void 0:"refreshResetTargetQuota"].filter((W)=>W!==void 0);if(J.length>0)return i.warn("reset command dependencies unwired",{missingDeps:J}),{command:j1,text:`## Reset credit
|
|
95
145
|
|
|
96
|
-
|
|
97
|
-
`).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=FX(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??j8()}class D8{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??Y5,this.tickIntervalMs=Y.tickIntervalMs??NX,this.leadMs=Y.leadMs??this.tickIntervalMs+15000;let X=Y.maxIdleWarmMs??Y.maxDurationMs;this.maxIdleWarmMs=typeof X==="number"&&Number.isFinite(X)&&X>0?X:X5;let J=Y.maxSubagentIdleMs??LX;this.maxSubagentIdleMs=typeof J==="number"&&Number.isFinite(J)&&J>0?J:LX,this.tickIntervalMs=Y.tickIntervalMs??NX,this.maxTargets=Y.maxTargets??J5,this.maxBytes=Y.maxBytes??Q5,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&&!UX(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 N=this.targets.get(Y);if(N)this.totalBytes-=N.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 N,O=Number.POSITIVE_INFINITY;for(let[L,Z]of this.targets){let j=Math.max(Z.lastRealRequestAt,Z.lastWarmedAt??0);if(j<O)N=L,O=j}if(N===void 0)break;let B=this.targets.get(N);if(B)this.totalBytes-=B.bodyText.length;this.targets.delete(N)}let H=G5(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:OX(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-HX;for(let[$,G]of this.targets){let W,K;if(this.isGpt56Subagent(G))W=Q,K=HX;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&&!UX(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;try{if(X.accountId&&X.accountId!=="main")J=await this.refreshFallback(X.accountId);else J=await this.getMainToken()}catch($){if(!this.disposed&&this.targets.get(Y)===X)X.backoffUntil=this.now()+q8;this.log.debug("cachekeep skip (no token)",this.logPayload({sessionKey:Y,accountId:X.accountId??"main",error:$ instanceof Error?$.message:String($)}));return}if(this.disposed||this.targets.get(Y)!==X)return;let Q={...X.replayHeaders,authorization:`Bearer ${J}`,"content-type":"application/json"};if(X.chatgptAccountId)Q["ChatGPT-Account-Id"]=X.chatgptAccountId;else delete Q["ChatGPT-Account-Id"];try{let $=$5(X.bodyText),G;try{let j=JSON.parse($);G={warmBodyKeys:Object.keys(j),stream:j.stream,max_output_tokens:j.max_output_tokens,store:j.store,has_stream_options:"stream_options"in j,has_max_tokens:"max_tokens"in j,model:j.model}}catch{}this.log.debug("cachekeep warm request",this.logPayload({...G,headerKeys:Object.keys(Q),hasChatGptAccountId:"ChatGPT-Account-Id"in Q}));let W=wY({method:"POST",headers:Q,body:$,signal:AbortSignal.any([AbortSignal.timeout(30000),this.abortController.signal])}),K=await this.fetchImpl(this.codexResponsesUrl,W),H="";try{H=await K.text()}catch{}if(this.disposed||this.targets.get(Y)!==X)return;if(!K.ok){X.backoffUntil=this.now()+q8,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",status:K.status,error:`HTTP ${K.status}`,responseBody:H.slice(0,600)}));return}let U=K.headers.get("content-type")??"",N=U.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(H.slice(0,200));this.log.debug("cachekeep warm response",this.logPayload({status:K.status,contentType:U,bodyLen:H.length,isSse:N}));let O=N?z5(H):W5(H),B=E1(K.headers),L=B.primary?.usedPercent??null,Z=B.secondary?.usedPercent??null;if(this.log.debug("cachekeep fired",this.logPayload({session:Y,accountId:X.accountId??"main",input_tokens:O.input_tokens,cached_tokens:O.cached_tokens,hit_rate:O.hit_rate,output_tokens:O.output_tokens,quota_primary_pct:L,quota_secondary_pct:Z})),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($){if(this.disposed||this.targets.get(Y)!==X)return;X.backoffUntil=this.now()+q8,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",error:$ instanceof Error?$.message:String($)}))}}}var DX=900000,K5=0.016666666666666666,qX=0.000001;function w8(Y,X){for(let J of[Y?.primary?.checkedAt,Y?.checkedAt,X])if(typeof J==="number"&&Number.isFinite(J))return J;return}function E8(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let X=w8(Y.quota,Y.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||Y.now-X>DX)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let J=P8(Y.quota).sort((Q,$)=>{let G=Q.windowMs,W=$.windowMs,K=typeof G==="number"&&Number.isFinite(G),H=typeof W==="number"&&Number.isFinite(W);if(K!==H)return K?-1:1;if(K&&H)return W-G;return 0});for(let{key:Q,window:$}of J)if(Number.isFinite($.remainingPercent)&&$.remainingPercent<=0)return{action:"migrate",reason:"exhausted",windowKey:Q,...typeof $.resetsAt==="string"?{resetsAt:$.resetsAt}:{}};if(Y.status===void 0||Y.status===0||!Number.isFinite(Y.status)||Y.status>=500&&Y.status<=599||Y.status===429)return{action:"retain",reason:"transient"};return{action:"retain",reason:"healthy"}}function U5(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,K5);return Q/G}function jX(Y,X){if(Y<X)return-1;if(Y>X)return 1;return 0}function H5(Y,X){if(!Y.quota)return;let J=w8(Y.quota,Y.quotaCheckedAt);if(J===void 0||X-J>DX)return;let Q=P8(Y.quota).map(({key:G,window:W})=>{return U5(W,Y.reservePercent[G]??0,X)}),$=Q.length>0?Math.min(...Q):0;return $>0?{candidate:Y,quotaCheckedAt:J,weight:$}:void 0}function PX(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(($)=>H5($,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,qX),H=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,qX);return K-H||G.candidate.configuredOrder-W.candidate.configuredOrder||jX(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||jX($.accountId,G.accountId)})[0];if(!Q)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Q.accountId,quotaCheckedAt:w8(Q.quota,Q.quotaCheckedAt),source:"mode-fallback"}}import{createHash as L5}from"node:crypto";import{chmod as N5,mkdir as V5,writeFile as M8}from"node:fs/promises";import{join as B5}from"node:path";var T8=L0("dump"),r0="x-cortexkit-openai-auth-dump-session",wX=0,M1=new Map,Z5=100;function A8(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function O5(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 MX(Y){return L5("sha256").update(Y).digest("hex")}function R8(Y){return MX(JSON.stringify(Y))}function AX(Y){try{let X=JSON.parse(Y);return X!=null&&typeof X==="object"&&!Array.isArray(X)?X:void 0}catch{return}}function F5(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 q5(Y,X){if(!M1.has(Y))while(M1.size>=Z5){let J=M1.keys().next().value;if(J===void 0)break;M1.delete(J)}M1.set(Y,X)}function j5(Y){if(Y===void 0)return;return Object.fromEntries(new Headers(Y).entries())}function C8(Y){if(Array.isArray(Y))return Y.map(C8);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]=C8(Q)}return X}function D5(Y){let X=AX(Y);if(X===void 0)return Y;let J=EX(X),Q=JSON.stringify(J);if(Q===void 0)return Y;return JSON.stringify(X)===Q?Y:Q}function P5(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function w5(Y){let X=AX(Y);if(!X)return{parseable:!1};let J=Array.isArray(X.input)?X.input:[],Q=Array.isArray(X.tools)?X.tools:[],$=Q.map(P5),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:R8(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:R8(J[0]),toolsCount:Q.length,toolTypes:$,toolsHash:R8(Q),hasWebSearch:$.includes("web_search"),clientMetadataKeys:G?Object.keys(G).sort():[]}}async function A1(Y){let X=w0();if(!X.dump)return;wX++;let J=Y.sessionID?.trim()||"session-unknown",Q=`${new Date().toISOString().replace(/[:.]/g,"-")}-${String(wX).padStart(5,"0")}-${O5(J)}-${Y.transport}-${Y.phase}`,$=B5(X.dumpDir,Q),G={body:`${$}.body.json`,metadata:`${$}.meta.json`,request:`${$}.request.json`},W=`${Y.transport}:${J}`,K=M1.get(W);try{await V5(X.dumpDir,{recursive:!0,mode:448}),await N5(X.dumpDir,448).catch(()=>{});let H=D5(Y.bodyText),U={id:Q,createdAt:new Date().toISOString(),session:A8(J),transport:Y.transport,phase:Y.phase,accountId:Y.accountId,status:Y.status,error:Y.error,bodyBytes:Y.bodyText.length,bodyHash:MX(Y.bodyText),diff:F5(K,Y.bodyText),body:w5(Y.bodyText),files:G};await Promise.all([M8(G.body,H,{encoding:"utf8",mode:384}),M8(G.metadata,`${JSON.stringify(U,null,2)}
|
|
98
|
-
`,{encoding:"utf8",mode:384}),
|
|
99
|
-
`,{encoding:"utf8",mode:384})]),
|
|
146
|
+
Unavailable: reset command runtime dependencies are not wired.`,knobs:{}};let Q=X,$=Y.trim().split(/\s+/).filter(Boolean),G=$[0];if(!G||G==="refresh"){let U=["main",...((await X.loadAccounts(X.accountStoragePath))?.accounts??[]).filter((H)=>H.enabled!==!1&&H.type==="oauth").map((H)=>H.id)];i.debug("reset accounts stage requested",{accountKeys:U});let L=await Promise.all(U.map((H)=>vX(H,Q)));return i.debug("reset accounts stage built",{rows:L.map((H)=>({accountKey:H.accountKey,eligible:H.eligible,reason:H.reason,usedPercent:H.usedPercent,availableCount:H.availableCount,applicableAvailableCount:H.applicableAvailableCount}))}),{command:j1,text:l5(L),knobs:{stage:"accounts",accounts:L}}}if(G==="select"){let W=M8($[1]);if(!W||!y0(W)||$.length!==2)return w0("","invalid_command","Usage: `/openai-reset select <encodedAccountKey>`");let U=await vX(W,Q);if(!U.eligible)return w0(W,"not_eligible",hX(U));return{command:j1,text:hX(U),knobs:{stage:"confirm",preview:U}}}if(G==="confirm"||G==="retry"){let W=M8($[1]),U=M8($[2]);if(!W||!y0(W)||!U||$.length!==3)return w0(W??"","invalid_command",`Usage: \`/openai-reset ${G} <encodedAccountKey> <encodedChatgptAccountId>\``);i.info("reset redemption decision",{accountKey:W,action:G}),i.debug("reset redemption identity binding",{accountKey:W,expectedChatgptAccountId:U});try{let L=await bX({configPath:X.accountStoragePath,mutateAccountsFn:J0,loadAccountsFn:X.loadAccounts,now:Q.now,randomUUID:Q.randomUUID,fetchImpl:Q.fetchImpl,resolveTarget:Q.resolveResetTarget,fetchUsage:(H)=>Q1({accessToken:H.accessToken,fetchImpl:Q.fetchImpl,now:Q.now,accountId:H.chatgptAccountId}),hasActiveRateLimitMark:(H)=>X.quotaManager.isRateLimited(H)},{accountKey:W,expectedChatgptAccountId:U,retry:G==="retry"});return i.info("reset redemption outcome",{accountKey:W,code:L.outcome.kind}),i5(L,Q,U)}catch(L){let H=d5(W,L,U);return i.info("reset redemption outcome",{accountKey:W,code:H.knobs.code}),H}}return w0("","invalid_command","Usage: `/openai-reset` | `/openai-reset select <encodedAccountKey>` | `/openai-reset confirm <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset retry <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset refresh`")}async function I8(Y,X,J){switch(Y){case"openai-quota":return x5(J);case"openai-account":return v5(X,J);case"openai-routing":return h5(X,J);case"openai-killswitch":return g5(X,J);case"openai-dump":return y5(X,J);case"openai-logging":return f5(X,J);case"openai-cachekeep":return c5(X,J);case"openai-reset":return n5(X,J);default:throw Error(`unhandled command: ${Y}`)}}var o5=L0("quota");async function k1(Y,X={}){let J=Y.whamFn;if(!J)throw Error("whamFn is required for refreshAllQuota");let Q=[],$=Y.logger??o5,G=(V)=>{Q.push(V);let K={pid:process.pid,accountId:V.account,status:V.ok?"ok":"error",...V.error?{error:V.error}:{}};if(V.ok)$.debug("quota refresh succeeded",K);else $.warn("quota refresh failed",K)},W=Y.skipFresherThanMs,U=!1,L;if(W!==void 0)try{L=await(Y.readSidebarState??D1)()}catch{}let H=new Map(L?.fallbacks.map((V)=>[V.id,V])??[]),N=(...V)=>W!==void 0&&V.some((K)=>typeof K==="number"&&Number.isFinite(K)&&K<=Y.now()&&Y.now()-K<W),O=await Y.loadAccounts(Y.configPath).catch(()=>{return}),Z=O?.mainAccountId??Y.storageMainAccountId;if(!X.accountKey||X.accountKey==="main")try{let V=await Y.getAuth();if(V.type==="oauth"){let K=L&&Z!==void 0&&L.main.mainAccountId===Z?L.main.quota:void 0;if(N(Y.quotaManager.peekMainForPolicy(Z)?.checkedAt,K?.primary?.checkedAt,K?.secondary?.checkedAt,K?.checkedAt))G({account:"main",ok:!0});else{if(!V.access||(V.expires??0)<Y.now()){let M=await Y.refreshMainWithLease();V={...V,access:M.access,expires:M.expires}}if(V.access)if(Y.respectBackoff&&Y.quotaManager.isBackedOff())G({account:"main",ok:!0});else{let M=await J({accessToken:V.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:Z,accountKey:"main"});Y.quotaManager.setMain(V.access,{quota:M,refreshAfter:Y.now()+300000,checkedAt:Y.now()},Z,!0),U=!0,G({account:"main",ok:!0})}else G({account:"main",ok:!1,error:"no access token"})}}else G({account:"main",ok:!1,error:"auth type is not oauth"})}catch(V){G({account:"main",ok:!1,error:$1(V)})}if(O)for(let V of O.accounts){if(X.accountKey&&(X.accountKey==="main"||V.id!==X.accountKey))continue;if(V.enabled===!1||!Y.isOAuthAccountFn(V)){if(X.accountKey)G({account:V.id,ok:!1,error:"account is not an enabled OAuth fallback"});continue}try{let K=H.get(V.id),j=V.accountId,M=K&&j!==void 0&&K.accountId===j?K.quota:void 0;if(N(Y.quotaManager.peekFallbackForPolicy(V.id,j)?.checkedAt,M?.primary?.checkedAt,M?.secondary?.checkedAt,M?.checkedAt)){G({account:V.id,ok:!0});continue}if(Y.respectBackoff&&Y.quotaManager.isFallbackBackedOff(V.id,V.access)){G({account:V.id,ok:!0});continue}let I;try{I=await Y.fallbackManager.refreshAccount(V,O)}catch{I=V}if(!I.access){G({account:V.id,ok:!1,error:"no access token"});continue}let E=await J({accessToken:I.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:I.accountId,accountKey:V.id});Y.quotaManager.setFallback(V.id,{quota:E,refreshAfter:Y.now()+300000,checkedAt:Y.now()},I.access,!0,I.accountId),U=!0,G({account:V.id,ok:!0})}catch(K){G({account:V.id,ok:!1,error:$1(K)})}}if(X.accountKey&&X.accountKey!=="main"&&!Q.some((V)=>V.account===X.accountKey))Q.push({account:X.accountKey,ok:!1,error:"account not found"});if(W===void 0||U){let V=await Y.loadAccounts(Y.configPath);await Y.writeSidebarState(Y.quotaManager,V)}return Q}var r5=300000,s5=30000,a5=240000,t5="bg-quota-refresh",e5=120000;function Y2(Y,X){return kY({name:t5,ttlMs:e5,path:Y,renew:!0,...X})}function cX(Y,X=k1,J=()=>Y2(Y.configPath)){return X2(Y,X,J)}async function X2(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:a5})}finally{await Q?.release().catch(()=>{})}}class S8{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)*s5);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=$},r5+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 _(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}function k8(Y){if(typeof Y!=="string")return!1;try{let X=JSON.parse(Y);return _(X)&&_(X.client_metadata)&&X.client_metadata.ws_request_header_x_openai_internal_codex_responses_lite==="true"}catch{return!1}}function b8(Y){if(typeof Y!=="string")return Y;try{let X=JSON.parse(Y);if(!_(X)||!_(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 bY(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"),k8(Y.body))X.set("x-openai-internal-codex-responses-lite","true");return{...Y,headers:X,body:b8(Y.body)}}function iX(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 nX(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 uX(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 J2=300000,oX=1800000,pX=2*oX+900000,Q2=3600000,lX=1800000,dX=60000,$2=32,G2=8388608,x8=600000;function rX(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 W2(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 z2(Y,X){return rX(Y)?oX:X}function v8(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function sX(Y){if(!Y||typeof Y!=="object")return v8();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 U2(Y){try{let X=JSON.parse(Y);return sX(X.usage)}catch{return v8()}}function H2(Y){let X,J=[],Q,$=()=>{if(!J.length)return;let G=J.join(`
|
|
147
|
+
`).trim();J=[];let W=X;if(X=void 0,!G||G==="[DONE]")return;try{let U=JSON.parse(G),L=U.type??W;if(L!=="response.completed"&&L!=="response.done")return;let H=U.response;Q=sX(H?.usage??U.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??v8()}class h8{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??J2,this.tickIntervalMs=Y.tickIntervalMs??dX,this.leadMs=Y.leadMs??this.tickIntervalMs+15000;let X=Y.maxIdleWarmMs??Y.maxDurationMs;this.maxIdleWarmMs=typeof X==="number"&&Number.isFinite(X)&&X>0?X:Q2;let J=Y.maxSubagentIdleMs??lX;this.maxSubagentIdleMs=typeof J==="number"&&Number.isFinite(J)&&J>0?J:lX,this.tickIntervalMs=Y.tickIntervalMs??dX,this.maxTargets=Y.maxTargets??$2,this.maxBytes=Y.maxBytes??G2,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 U=this.getWindow?.();if(U&&!uX(U,new Date(this.now()))){this.log.debug("cachekeep track skipped (outside window)",this.logPayload({sessionKey:Y,startHour:U.startHour,endHour:U.endHour}));return}if(this.targets.has(Y)){let N=this.targets.get(Y);if(N)this.totalBytes-=N.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 N,O=Number.POSITIVE_INFINITY;for(let[V,K]of this.targets){let j=Math.max(K.lastRealRequestAt,K.lastWarmedAt??0);if(j<O)N=V,O=j}if(N===void 0)break;let Z=this.targets.get(N);if(Z)this.totalBytes-=Z.bodyText.length;this.targets.delete(N)}let L=z2(X,this.ttlMs),H={bodyText:X,accountId:J||void 0,chatgptAccountId:Q,route:"main",ttlMs:L,cacheExpiresAt:this.now()+L,warmCount:0,lastRealRequestAt:this.now(),replayHeaders:$,isSubagent:G,is56:rX(X)};this.targets.set(Y,H),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-pX;for(let[$,G]of this.targets){let W,U;if(this.isGpt56Subagent(G))W=Q,U=pX;else W=G.isSubagent?J:X,U=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:U})),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&&!uX(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;try{if(X.accountId&&X.accountId!=="main")J=await this.refreshFallback(X.accountId);else J=await this.getMainToken()}catch($){if(!this.disposed&&this.targets.get(Y)===X)X.backoffUntil=this.now()+x8;this.log.debug("cachekeep skip (no token)",this.logPayload({sessionKey:Y,accountId:X.accountId??"main",error:$ instanceof Error?$.message:String($)}));return}if(this.disposed||this.targets.get(Y)!==X)return;let Q={...X.replayHeaders,authorization:`Bearer ${J}`,"content-type":"application/json"};if(X.chatgptAccountId)Q["ChatGPT-Account-Id"]=X.chatgptAccountId;else delete Q["ChatGPT-Account-Id"];try{let $=W2(X.bodyText),G;try{let j=JSON.parse($);G={warmBodyKeys:Object.keys(j),stream:j.stream,max_output_tokens:j.max_output_tokens,store:j.store,has_stream_options:"stream_options"in j,has_max_tokens:"max_tokens"in j,model:j.model}}catch{}this.log.debug("cachekeep warm request",this.logPayload({...G,headerKeys:Object.keys(Q),hasChatGptAccountId:"ChatGPT-Account-Id"in Q}));let W=bY({method:"POST",headers:Q,body:$,signal:AbortSignal.any([AbortSignal.timeout(30000),this.abortController.signal])}),U=await this.fetchImpl(this.codexResponsesUrl,W),L="";try{L=await U.text()}catch{}if(this.disposed||this.targets.get(Y)!==X)return;if(!U.ok){X.backoffUntil=this.now()+x8,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",status:U.status,error:`HTTP ${U.status}`,responseBody:L.slice(0,600)}));return}let H=U.headers.get("content-type")??"",N=H.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(L.slice(0,200));this.log.debug("cachekeep warm response",this.logPayload({status:U.status,contentType:H,bodyLen:L.length,isSse:N}));let O=N?H2(L):U2(L),Z=b1(U.headers),V=Z.primary?.usedPercent??null,K=Z.secondary?.usedPercent??null;if(this.log.debug("cachekeep fired",this.logPayload({session:Y,accountId:X.accountId??"main",input_tokens:O.input_tokens,cached_tokens:O.cached_tokens,hit_rate:O.hit_rate,output_tokens:O.output_tokens,quota_primary_pct:V,quota_secondary_pct:K})),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($){if(this.disposed||this.targets.get(Y)!==X)return;X.backoffUntil=this.now()+x8,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",error:$ instanceof Error?$.message:String($)}))}}}var eX=900000,L2=0.016666666666666666,aX=0.000001;function y8(Y,X){for(let J of[Y?.primary?.checkedAt,Y?.checkedAt,X])if(typeof J==="number"&&Number.isFinite(J))return J;return}function f8(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let X=y8(Y.quota,Y.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||Y.now-X>eX)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let J=g8(Y.quota).sort((Q,$)=>{let G=Q.windowMs,W=$.windowMs,U=typeof G==="number"&&Number.isFinite(G),L=typeof W==="number"&&Number.isFinite(W);if(U!==L)return U?-1:1;if(U&&L)return W-G;return 0});for(let{key:Q,window:$}of J)if(Number.isFinite($.remainingPercent)&&$.remainingPercent<=0)return{action:"migrate",reason:"exhausted",windowKey:Q,...typeof $.resetsAt==="string"?{resetsAt:$.resetsAt}:{}};if(Y.status===void 0||Y.status===0||!Number.isFinite(Y.status)||Y.status>=500&&Y.status<=599||Y.status===429)return{action:"retain",reason:"transient"};return{action:"retain",reason:"healthy"}}function V2(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,L2);return Q/G}function tX(Y,X){if(Y<X)return-1;if(Y>X)return 1;return 0}function N2(Y,X){if(!Y.quota)return;let J=y8(Y.quota,Y.quotaCheckedAt);if(J===void 0||X-J>eX)return;let Q=g8(Y.quota).map(({key:G,window:W})=>{return V2(W,Y.reservePercent[G]??0,X)}),$=Q.length>0?Math.min(...Q):0;return $>0?{candidate:Y,quotaCheckedAt:J,weight:$}:void 0}function YJ(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(($)=>N2($,Y.now)).filter(($)=>$!==void 0);if(J.length>0){J.sort((G,W)=>{let U=((Y.pendingBytes.get(G.candidate.accountId)??0)+Y.requestBytes)/Math.max(G.weight,aX),L=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,aX);return U-L||G.candidate.configuredOrder-W.candidate.configuredOrder||tX(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||tX($.accountId,G.accountId)})[0];if(!Q)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Q.accountId,quotaCheckedAt:y8(Q.quota,Q.quotaCheckedAt),source:"mode-fallback"}}import{createHash as B2}from"node:crypto";import{chmod as Z2,mkdir as K2,writeFile as m8}from"node:fs/promises";import{join as O2}from"node:path";var p8=L0("dump"),G1="x-cortexkit-openai-auth-dump-session",XJ=0,x1=new Map,q2=100;function c8(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function F2(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 QJ(Y){return B2("sha256").update(Y).digest("hex")}function u8(Y){return QJ(JSON.stringify(Y))}function $J(Y){try{let X=JSON.parse(Y);return X!=null&&typeof X==="object"&&!Array.isArray(X)?X:void 0}catch{return}}function j2(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 D2(Y,X){if(!x1.has(Y))while(x1.size>=q2){let J=x1.keys().next().value;if(J===void 0)break;x1.delete(J)}x1.set(Y,X)}function P2(Y){if(Y===void 0)return;return Object.fromEntries(new Headers(Y).entries())}function l8(Y){if(Array.isArray(Y))return Y.map(l8);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]=l8(Q)}return X}function M2(Y){let X=$J(Y);if(X===void 0)return Y;let J=JJ(X),Q=JSON.stringify(J);if(Q===void 0)return Y;return JSON.stringify(X)===Q?Y:Q}function w2(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function E2(Y){let X=$J(Y);if(!X)return{parseable:!1};let J=Array.isArray(X.input)?X.input:[],Q=Array.isArray(X.tools)?X.tools:[],$=Q.map(w2),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:u8(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:u8(J[0]),toolsCount:Q.length,toolTypes:$,toolsHash:u8(Q),hasWebSearch:$.includes("web_search"),clientMetadataKeys:G?Object.keys(G).sort():[]}}async function v1(Y){let X=M0();if(!X.dump)return;XJ++;let J=Y.sessionID?.trim()||"session-unknown",Q=`${new Date().toISOString().replace(/[:.]/g,"-")}-${String(XJ).padStart(5,"0")}-${F2(J)}-${Y.transport}-${Y.phase}`,$=O2(X.dumpDir,Q),G={body:`${$}.body.json`,metadata:`${$}.meta.json`,request:`${$}.request.json`},W=`${Y.transport}:${J}`,U=x1.get(W);try{await K2(X.dumpDir,{recursive:!0,mode:448}),await Z2(X.dumpDir,448).catch(()=>{});let L=M2(Y.bodyText),H={id:Q,createdAt:new Date().toISOString(),session:c8(J),transport:Y.transport,phase:Y.phase,accountId:Y.accountId,status:Y.status,error:Y.error,bodyBytes:Y.bodyText.length,bodyHash:QJ(Y.bodyText),diff:j2(U,Y.bodyText),body:E2(Y.bodyText),files:G};await Promise.all([m8(G.body,L,{encoding:"utf8",mode:384}),m8(G.metadata,`${JSON.stringify(H,null,2)}
|
|
148
|
+
`,{encoding:"utf8",mode:384}),m8(G.request,`${JSON.stringify(l8({url:Y.url,method:Y.method,accountId:Y.accountId,headers:P2(Y.headers)}),null,2)}
|
|
149
|
+
`,{encoding:"utf8",mode:384})]),p8.debug("dumped request",{id:Q,session:c8(J),body:G.body,meta:G.metadata}),D2(W,Y.bodyText)}catch(L){p8.warn("request dump failed",{session:c8(J),error:L instanceof Error?L.message:String(L)})}}async function r0(Y){if(!M0().dump)return;p8.debug("diagnostic",Y)}import{tool as s1}from"@opencode-ai/plugin";var xY="ws_",zJ=new Map,UJ=s1({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:s1.schema.string().optional(),query:s1.schema.string().optional(),queries:s1.schema.array(s1.schema.string()).optional()},async execute(Y){return{title:"OpenAI Web Search",output:JSON.stringify({action:Y}),metadata:{action:Y}}}});function i8(Y){if(A2(Y))return;if(!R2(Y))return Y;let X=Y.item;return zJ.set(X.id,X),{...Y,item:{type:"function_call",id:X.id,call_id:X.id,name:"web_search",arguments:JSON.stringify(_(X.action)?X.action:{})}}}function HJ(Y){if(!Y.body)return Y;if(!(Y.headers.get("content-type")??"").includes("text/event-stream"))return Y;return new Response(T2(Y.body),{status:Y.status,statusText:Y.statusText,headers:Y.headers})}function LJ(Y){if(!Array.isArray(Y.input))return!1;let X=!1,J=new Map,Q=[],$=new Map,G=new Map;for(let W of Y.input)if(_(W)&&typeof W.call_id==="string"&&W.call_id.startsWith(xY)){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(C2(W)){J.set(W.call_id,W),X=!0;continue}if(_2(W,J)){Q.push(d8(W.call_id,W.output,J.get(W.call_id))),X=!0;continue}if(I2(W)){let U=zJ.get(W.id);if(U)Q.push(d8(W.id,U));else{let L=$.get(W.id),H=G.get(W.id);if(L||H)Q.push(d8(W.id,H,L));else Q.push(W)}X=!0;continue}Q.push(W)}if(X)Y.input=Q;return X}function A2(Y){if(typeof Y.type==="string"&&Y.type.startsWith("response.web_search_call."))return!0;return Y.type==="response.output_item.added"&&_(Y.item)&&Y.item.type==="web_search_call"}function T2(Y){let X=new TextDecoder,J=new TextEncoder,Q="";return Y.pipeThrough(new TransformStream({transform($,G){Q+=X.decode($,{stream:!0});let W=GJ(Q);while(W){let U=Q.slice(0,W.index);Q=Q.slice(W.index+W.length);let L=WJ(U);if(L)G.enqueue(J.encode(L));W=GJ(Q)}},flush($){if(Q+=X.decode(),!Q)return;let G=WJ(Q);if(G)$.enqueue(J.encode(G))}}))}function GJ(Y){let X=Y.indexOf(`
|
|
100
150
|
|
|
101
151
|
`),J=Y.indexOf(`\r
|
|
102
152
|
\r
|
|
103
|
-
`);if(X===-1)return J===-1?void 0:{index:J,length:4};if(J===-1||X<J)return{index:X,length:2};return{index:J,length:4}}function
|
|
153
|
+
`);if(X===-1)return J===-1?void 0:{index:J,length:4};if(J===-1||X<J)return{index:X,length:2};return{index:J,length:4}}function WJ(Y){let X=Y.split(/\r?\n/).filter((J)=>J.startsWith("data:")).map((J)=>J.slice(5).trimStart()).join(`
|
|
104
154
|
`);if(!X)return`${Y}
|
|
105
155
|
|
|
106
156
|
`;if(X==="[DONE]")return`data: [DONE]
|
|
107
157
|
|
|
108
158
|
`;try{let J=JSON.parse(X);if(!_(J))return`${Y}
|
|
109
159
|
|
|
110
|
-
`;let Q=
|
|
160
|
+
`;let Q=i8(J);if(!Q)return"";return`data: ${JSON.stringify(Q)}
|
|
111
161
|
|
|
112
162
|
`}catch{return`${Y}
|
|
113
163
|
|
|
114
|
-
`}}function A5(Y){return Y.type==="response.output_item.done"&&_(Y.item)&&Y.item.type==="web_search_call"&&typeof Y.item.id==="string"}function R5(Y){return _(Y)&&Y.type==="function_call"&&Y.name==="web_search"&&typeof Y.call_id==="string"&&Y.call_id.startsWith(EY)}function T5(Y,X){return _(Y)&&Y.type==="function_call_output"&&typeof Y.call_id==="string"&&typeof Y.output==="string"&&Y.call_id.startsWith(EY)&&X.has(Y.call_id)}function C5(Y){return _(Y)&&Y.type==="item_reference"&&typeof Y.id==="string"&&Y.id.startsWith(EY)}function _8(Y,X,J){let Q=_5(X),$=_(Q?.action)?Q.action:I5(J?.arguments);return{type:"web_search_call",status:"completed",...$?{action:$}:{}}}function _5(Y){if(_(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return _(X)?X:void 0}catch{return}}function I5(Y){if(_(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return _(X)?X:void 0}catch{return}}import{readFile as S5}from"node:fs/promises";import{homedir as k5}from"node:os";import{join as kX}from"node:path";var b5="https://models.dev/api.json",x5="OPENCODE_OPENAI_AUTH_MODELS_CACHE",v5="OPENCODE_MODELS_PATH",h5="OPENCODE_DISABLE_MODELS_FETCH",g5=1e4,y5=300000;function s0(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function bX(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function S8(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=bX(Y.cache_read),$=bX(Y.cache_write);if(Q===null||$===null)return null;return{input:X,output:J,cache:{read:Q,write:$}}}function f5(Y){let X=s0(Y);if(!X)return null;let J=S8(X);if(!J)return null;let Q=J;if(Array.isArray(X.tiers)){let W=[];for(let K of X.tiers){let H=s0(K);if(!H)continue;let U=s0(H.tier),N=U?.size;if(U?.type!=="context")continue;if(typeof N!=="number"||!Number.isFinite(N)||N<=0)continue;let O=S8(H);if(!O)continue;W.push({...O,tier:{type:"context",size:N}})}if(W.length>0)Q.tiers=W}let $=s0(X.context_over_200k),G=$?S8($):null;if(G)Q.experimentalOver200K=G;return Q}function xX(Y){let X=s0(Y),J=s0(X?.openai),Q=s0(J?.models);if(!Q)return null;let $={};for(let[G,W]of Object.entries(Q)){let K=s0(W),H=f5(K?.cost);if(H)$[G]=H}return Object.keys($).length>0?$:null}function m5(){let Y=process.env[x5]?.trim();if(Y)return Y;let X=process.env[v5]?.trim();if(X)return X;let J=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||kX(k5(),".cache");return kX(J,"opencode","models.json")}function c5(){let Y=process.env[h5]?.toLowerCase();return Y==="true"||Y==="1"}async function u5(){try{let Y=xX(JSON.parse(await S5(m5(),"utf8")));if(Y)return Y}catch{}if(c5())return null;try{let Y=await fetch(b5,{signal:AbortSignal.timeout(g5)});if(!Y.ok)return null;return xX(await Y.json())}catch{return null}}var R1;function vX(){let Y=Date.now();if(R1&&R1.expiresAt>Y)return R1.promise;let X={expiresAt:Y+y5,promise:u5()};return R1=X,X.promise.then((J)=>{if(J===null&&R1===X)R1=void 0}),X.promise}function T1(Y){return typeof Y==="object"&&Y!==null}function p5(Y){if(Array.isArray(Y))return Y;if(T1(Y)&&Array.isArray(Y.data))return Y.data;return[]}function l5(Y){if(!T1(Y)||!T1(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function hX(Y){if(!T1(Y)||!T1(Y.info))return null;let X=Y.info,J=T1(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 gX(Y,X){return{agent:Y.agent??X.agent,model:Y.model??X.model,variant:Y.variant??X.variant}}function yX(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function fX(Y,X){if(!Y||!X)return null;let J=Y;if(typeof J.session?.messages!=="function")return null;let Q=[];try{Q=p5(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(l5(Q[G])!=="assistant")continue;let W=hX(Q[G]);if(!W)continue;if($=gX($,W),yX($))return $}for(let G=Q.length-1;G>=0;G--){let W=hX(Q[G]);if(!W)continue;if($=gX($,W),yX($))return $}if(!$.agent&&!$.model&&!$.variant)return null;return $}var a0=[],d5=1,k8=0,mX=new Map;function b8(Y,X){if(a0.push({id:d5++,type:"open-dialog",payload:Y,sessionId:X}),a0.length>100)a0=a0.slice(a0.length-100)}function cX(Y=0,X){let J=Date.now();if(k8=J,X!==void 0)mX.set(X,J);let Q=($)=>X===void 0||$.sessionId===void 0||$.sessionId===X;if(Y>0)a0=a0.filter(($)=>{if($.id>Y)return!0;if(X===void 0)return!1;return $.sessionId!==X});return a0.filter(($)=>$.id>Y&&Q($))}function uX(Y){let X=Date.now();if(Y!==void 0){let J=mX.get(Y)??0;return J>0&&X-J<3000}return k8>0&&X-k8<3000}import{randomBytes as i5,timingSafeEqual as n5}from"node:crypto";import{unlink as o5}from"node:fs/promises";import{createServer as r5}from"node:http";import{join as s5}from"node:path";var pX=L0("rpc");function a5(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 t5(Y,X){if(!Y?.startsWith("Bearer "))return!1;let J=Buffer.from(Y.slice(7)),Q=Buffer.from(X);return J.length===Q.length&&n5(J,Q)}async function iX(Y){let X=i5(32).toString("hex"),J=Y.timeoutMs??2000,Q=r5((W,K)=>{W.setTimeout(J,()=>{W.socket.destroy()}),$(W,K)});Q.requestTimeout=J,Q.headersTimeout=J;async function $(W,K){let H=(U,N)=>{if(K.headersSent||K.writableEnded||K.destroyed)return;K.writeHead(U,{"content-type":"application/json"}),K.end(JSON.stringify(N))};try{let U=W.url??"";if(W.method==="GET"&&U==="/health")return H(200,{ok:!0});if(W.method!=="POST"||!U.startsWith("/rpc/"))return H(404,{error:"not found"});if(!t5(W.headers.authorization,X))return H(401,{error:"unauthorized"});let N=U.slice(5),O=await a5(W),B=JSON.parse(O||"{}");if(N==="pending-notifications"){let L=Y.drain(Number(B.lastReceivedId??0),typeof B.sessionId==="string"?B.sessionId:void 0);return H(200,{messages:L})}if(N==="apply"){let L=await Y.apply(B);return H(200,L)}return H(404,{error:"unknown method"})}catch(U){H(500,{error:U instanceof Error?U.message:String(U)})}}let G=await new Promise((W,K)=>{Q.on("error",K),Q.listen(0,"127.0.0.1",()=>{let H=Q.address();if(H&&typeof H==="object")W(H.port);else K(Error("no port"))})});if(Q.unref(),Y.sweepRoot)try{await dX(Y.sweepRoot,Y.dir)}catch(W){pX.warn("rpc state sweep failed",{pid:process.pid,error:W instanceof Error?W.message:String(W)})}try{await lX(Y.dir,{port:G,token:X,pid:process.pid},{secureDir:Y.secureDir}),pX.debug("rpc server pid",{pid:process.pid,rpcPort:G})}catch(W){throw await new Promise((K)=>Q.close(()=>K())),W}return{port:G,token:X,async stop(){await new Promise((W)=>Q.close(()=>W())),await o5(s5(Y.dir,`port-${process.pid}.json`)).catch(()=>{})}}}function u0(Y){return JSON.stringify(x8(Y))??"undefined"}function x8(Y){if(Array.isArray(Y))return Y.map(x8);if(!_(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((X)=>[X,x8(Y[X])]))}function N1(){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 $1={};g8($1,{withoutInternalHeaders:()=>xG,sanitizeHttpFallbackBody:()=>F8,orderCodexBody:()=>GY,hasWebSocketResponsesLiteMetadata:()=>O8,createWebSocketFetch:()=>GN,applyTurnId:()=>SG,TITLE_HEADER:()=>k9,QUOTA_ACCOUNT_HEADER:()=>aY,OpenAIWebSocketPool:()=>$1,CODEX_BODY_KEY_ORDER:()=>_G});import{createHash as YN}from"node:crypto";var EJ="vercel.ai.error",e5=Symbol.for(EJ),nX,oX,f=class Y extends(oX=Error,nX=e5,oX){constructor({name:X,message:J,cause:Q}){super(J);this[nX]=!0,this.name=X,this.cause=Q}static isInstance(X){return Y.hasMarker(X,EJ)}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}},MJ="AI_APICallError",AJ=`vercel.ai.error.${MJ}`,Y2=Symbol.for(AJ),rX,sX,m1=class extends(sX=f,rX=Y2,sX){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:MJ,message:Y,cause:W});this[rX]=!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 f.hasMarker(Y,AJ)}},RJ="AI_EmptyResponseBodyError",TJ=`vercel.ai.error.${RJ}`,X2=Symbol.for(TJ),aX,tX,J2=class extends(tX=f,aX=X2,tX){constructor({message:Y="Empty response body"}={}){super({name:RJ,message:Y});this[aX]=!0}static isInstance(Y){return f.hasMarker(Y,TJ)}};function v8(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 CJ="AI_InvalidArgumentError",_J=`vercel.ai.error.${CJ}`,Q2=Symbol.for(_J),eX,YJ,IJ=class extends(YJ=f,eX=Q2,YJ){constructor({message:Y,cause:X,argument:J}){super({name:CJ,message:Y,cause:X});this[eX]=!0,this.argument=J}static isInstance(Y){return f.hasMarker(Y,_J)}},SJ="AI_InvalidPromptError",kJ=`vercel.ai.error.${SJ}`,$2=Symbol.for(kJ),XJ,JJ,G2=class extends(JJ=f,XJ=$2,JJ){constructor({prompt:Y,message:X,cause:J}){super({name:SJ,message:`Invalid prompt: ${X}`,cause:J});this[XJ]=!0,this.prompt=Y}static isInstance(Y){return f.hasMarker(Y,kJ)}},bJ="AI_InvalidResponseDataError",xJ=`vercel.ai.error.${bJ}`,W2=Symbol.for(xJ),QJ,$J,z2=class extends($J=f,QJ=W2,$J){constructor({data:Y,message:X=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:bJ,message:X});this[QJ]=!0,this.data=Y}static isInstance(Y){return f.hasMarker(Y,xJ)}},vJ="AI_JSONParseError",hJ=`vercel.ai.error.${vJ}`,K2=Symbol.for(hJ),GJ,WJ,MY=class extends(WJ=f,GJ=K2,WJ){constructor({text:Y,cause:X}){super({name:vJ,message:`JSON parsing failed: Text: ${Y}.
|
|
115
|
-
Error message: ${
|
|
116
|
-
Error message: ${v8(J)}`,cause:J});this[jJ]=!0,this.value=X,this.context=Q}static isInstance(X){return f.hasMarker(X,sJ)}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})}},aJ="AI_UnsupportedFunctionalityError",tJ=`vercel.ai.error.${aJ}`,w2=Symbol.for(tJ),PJ,wJ,E2=class extends(wJ=f,PJ=w2,wJ){constructor({functionality:Y,message:X=`'${Y}' functionality not supported.`}){super({name:aJ,message:X});this[PJ]=!0,this.functionality=Y}static isInstance(Y){return f.hasMarker(Y,tJ)}};var OB=Object.freeze({status:"aborted"});function q(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 N in W.prototype)if(!(N in K))Object.defineProperty(K,N,{value:W.prototype[N].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 N of U._zod.deferred)N();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 FB=Symbol("zod_brand");class p0 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class c1 extends Error{constructor(Y){super(`Encountered unidirectional transform during encode: ${Y}`);this.name="ZodEncodeError"}}var AY={};function h0(Y){if(Y)Object.assign(AY,Y);return AY}var c={};g8(c,{unwrapMessage:()=>u1,uint8ArrayToHex:()=>r2,uint8ArrayToBase64url:()=>n2,uint8ArrayToBase64:()=>W6,stringifyPrimitive:()=>J6,shallowClone:()=>Y6,safeExtend:()=>c2,required:()=>l2,randomString:()=>x2,propertyKeyTypes:()=>m8,promiseAllObject:()=>b2,primitiveTypes:()=>X6,prefixIssues:()=>d0,pick:()=>y2,partial:()=>p2,optionalKeys:()=>c8,omit:()=>f2,objectClone:()=>I2,numKeys:()=>v2,nullish:()=>l1,normalizeParams:()=>v,mergeDefs:()=>e0,merge:()=>u2,jsonStringifyReplacer:()=>C1,joinValues:()=>_2,issue:()=>I1,isPlainObject:()=>Y1,isObject:()=>V1,hexToUint8Array:()=>o2,getSizableOrigin:()=>$6,getParsedType:()=>h2,getLengthableOrigin:()=>i1,getEnumValues:()=>p1,getElementAtPath:()=>k2,floatSafeRemainder:()=>y8,finalizeIssue:()=>_0,extend:()=>m2,escapeRegex:()=>l0,esc:()=>RY,defineLazy:()=>p,createTransparentProxy:()=>g2,cloneDef:()=>S2,clone:()=>C0,cleanRegex:()=>d1,cleanEnum:()=>d2,captureStackTrace:()=>TY,cached:()=>_1,base64urlToUint8Array:()=>i2,base64ToUint8Array:()=>G6,assignProp:()=>t0,assertNotEqual:()=>A2,assertNever:()=>T2,assertIs:()=>R2,assertEqual:()=>M2,assert:()=>C2,allowsEval:()=>f8,aborted:()=>X1,NUMBER_FORMAT_RANGES:()=>u8,Class:()=>z6,BIGINT_FORMAT_RANGES:()=>Q6});function M2(Y){return Y}function A2(Y){return Y}function R2(Y){}function T2(Y){throw Error()}function C2(Y){}function p1(Y){let X=Object.values(Y).filter((Q)=>typeof Q==="number");return Object.entries(Y).filter(([Q,$])=>X.indexOf(+Q)===-1).map(([Q,$])=>$)}function _2(Y,X="|"){return Y.map((J)=>J6(J)).join(X)}function C1(Y,X){if(typeof X==="bigint")return X.toString();return X}function _1(Y){return{get value(){{let J=Y();return Object.defineProperty(this,"value",{value:J}),J}throw Error("cached value already set")}}}function l1(Y){return Y===null||Y===void 0}function d1(Y){let X=Y.startsWith("^")?1:0,J=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(X,J)}function y8(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 eJ=Symbol("evaluating");function p(Y,X,J){let Q=void 0;Object.defineProperty(Y,X,{get(){if(Q===eJ)return;if(Q===void 0)Q=eJ,Q=J();return Q},set($){Object.defineProperty(Y,X,{value:$})},configurable:!0})}function I2(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function t0(Y,X,J){Object.defineProperty(Y,X,{value:J,writable:!0,enumerable:!0,configurable:!0})}function e0(...Y){let X={};for(let J of Y){let Q=Object.getOwnPropertyDescriptors(J);Object.assign(X,Q)}return Object.defineProperties({},X)}function S2(Y){return e0(Y._zod.def)}function k2(Y,X){if(!X)return Y;return X.reduce((J,Q)=>J?.[Q],Y)}function b2(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 x2(Y=10){let J="";for(let Q=0;Q<Y;Q++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function RY(Y){return JSON.stringify(Y)}var TY="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function V1(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var f8=_1(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function Y1(Y){if(V1(Y)===!1)return!1;let X=Y.constructor;if(X===void 0)return!0;let J=X.prototype;if(V1(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function Y6(Y){if(Y1(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function v2(Y){let X=0;for(let J in Y)if(Object.prototype.hasOwnProperty.call(Y,J))X++;return X}var h2=(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}`)}},m8=new Set(["string","number","symbol"]),X6=new Set(["string","number","bigint","boolean","symbol","undefined"]);function l0(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function C0(Y,X,J){let Q=new Y._zod.constr(X??Y._zod.def);if(!X||J?.parent)Q._zod.parent=Y;return Q}function v(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 g2(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 J6(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function c8(Y){return Object.keys(Y).filter((X)=>{return Y[X]._zod.optin==="optional"&&Y[X]._zod.optout==="optional"})}var u8={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]},Q6={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function y2(Y,X){let J=Y._zod.def,Q=e0(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 t0(this,"shape",$),$},checks:[]});return C0(Y,Q)}function f2(Y,X){let J=Y._zod.def,Q=e0(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 t0(this,"shape",$),$},checks:[]});return C0(Y,Q)}function m2(Y,X){if(!Y1(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 $=e0(Y._zod.def,{get shape(){let G={...Y._zod.def.shape,...X};return t0(this,"shape",G),G},checks:[]});return C0(Y,$)}function c2(Y,X){if(!Y1(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 t0(this,"shape",Q),Q},checks:Y._zod.def.checks};return C0(Y,J)}function u2(Y,X){let J=e0(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape,...X._zod.def.shape};return t0(this,"shape",Q),Q},get catchall(){return X._zod.def.catchall},checks:[]});return C0(Y,J)}function p2(Y,X,J){let Q=e0(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 t0(this,"shape",G),G},checks:[]});return C0(X,Q)}function l2(Y,X,J){let Q=e0(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 t0(this,"shape",G),G},checks:[]});return C0(X,Q)}function X1(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 d0(Y,X){return X.map((J)=>{var Q;return(Q=J).path??(Q.path=[]),J.path.unshift(Y),J})}function u1(Y){return typeof Y==="string"?Y:Y?.message}function _0(Y,X,J){let Q={...Y,path:Y.path??[]};if(!Y.message){let $=u1(Y.inst?._zod.def?.error?.(Y))??u1(X?.error?.(Y))??u1(J.customError?.(Y))??u1(J.localeError?.(Y))??"Invalid input";Q.message=$}if(delete Q.inst,delete Q.continue,!X?.reportInput)delete Q.input;return Q}function $6(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function i1(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function I1(...Y){let[X,J,Q]=Y;if(typeof X==="string")return{message:X,code:"custom",input:J,inst:Q};return{...X}}function d2(Y){return Object.entries(Y).filter(([X,J])=>{return Number.isNaN(Number.parseInt(X,10))}).map((X)=>X[1])}function G6(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 W6(Y){let X="";for(let J=0;J<Y.length;J++)X+=String.fromCharCode(Y[J]);return btoa(X)}function i2(Y){let X=Y.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-X.length%4)%4);return G6(X+J)}function n2(Y){return W6(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function o2(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 r2(Y){return Array.from(Y).map((X)=>X.toString(16).padStart(2,"0")).join("")}class z6{constructor(...Y){}}var K6=(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,C1,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},CY=q("$ZodError",K6),p8=q("$ZodError",K6,{Parent:Error});function U6(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 H6(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 _Y=(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 p0;if(W.issues.length){let K=new($?.Err??Y)(W.issues.map((H)=>_0(H,G,h0())));throw TY(K,$?.callee),K}return W.value};var IY=(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)=>_0(H,G,h0())));throw TY(K,$?.callee),K}return W.value};var n1=(Y)=>(X,J,Q)=>{let $=Q?{...Q,async:!1}:{async:!1},G=X._zod.run({value:J,issues:[]},$);if(G instanceof Promise)throw new p0;return G.issues.length?{success:!1,error:new(Y??CY)(G.issues.map((W)=>_0(W,$,h0())))}:{success:!0,data:G.value}},L6=n1(p8),o1=(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)=>_0(W,$,h0())))}:{success:!0,data:G.value}},N6=o1(p8),V6=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return _Y(Y)(X,J,$)};var B6=(Y)=>(X,J,Q)=>{return _Y(Y)(X,J,Q)};var Z6=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return IY(Y)(X,J,$)};var O6=(Y)=>async(X,J,Q)=>{return IY(Y)(X,J,Q)};var F6=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return n1(Y)(X,J,$)};var q6=(Y)=>(X,J,Q)=>{return n1(Y)(X,J,Q)};var j6=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return o1(Y)(X,J,$)};var D6=(Y)=>async(X,J,Q)=>{return o1(Y)(X,J,Q)};var P6=/^[cC][^\s-]{8,}$/,w6=/^[0-9a-z]+$/,E6=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,M6=/^[0-9a-vA-V]{20}$/,A6=/^[A-Za-z0-9]{27}$/,R6=/^[a-zA-Z0-9_-]{21}$/,T6=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var C6=/^([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})$/,l8=(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 _6=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function I6(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var S6=/^(?:(?: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])$/,k6=/^(([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}|:))$/,b6=/^((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])$/,x6=/^(([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])$/,v6=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,d8=/^[A-Za-z0-9_-]*$/,h6=/^(?=.{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 g6=/^\+(?:[0-9]){6,14}[0-9]$/,y6="(?:(?:\\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])))",f6=new RegExp(`^${y6}$`);function m6(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 c6(Y){return new RegExp(`^${m6(Y)}$`)}function u6(Y){let X=m6({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(`^${y6}T(?:${Q})$`)}var p6=(Y)=>{let X=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${X}$`)};var l6=/^-?\d+$/,d6=/^-?\d+(?:\.\d+)?/,i6=/^(?:true|false)$/i,n6=/^null$/i;var o6=/^[^A-Z]*$/,r6=/^[^a-z]*$/;var N0=q("$ZodCheck",(Y,X)=>{var J;Y._zod??(Y._zod={}),Y._zod.def=X,(J=Y._zod).onattach??(J.onattach=[])}),s6={number:"number",bigint:"bigint",object:"date"},i8=q("$ZodCheckLessThan",(Y,X)=>{N0.init(Y,X);let J=s6[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})}}),n8=q("$ZodCheckGreaterThan",(Y,X)=>{N0.init(Y,X);let J=s6[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})}}),a6=q("$ZodCheckMultipleOf",(Y,X)=>{N0.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):y8(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})}}),t6=q("$ZodCheckNumberFormat",(Y,X)=>{N0.init(Y,X),X.format=X.format||"float64";let J=X.format?.includes("int"),Q=J?"int":"number",[$,G]=u8[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=l6}),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 e6=q("$ZodCheckMaxLength",(Y,X)=>{var J;N0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!l1($)&&$.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=i1($);Q.issues.push({origin:W,code:"too_big",maximum:X.maximum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),YQ=q("$ZodCheckMinLength",(Y,X)=>{var J;N0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!l1($)&&$.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=i1($);Q.issues.push({origin:W,code:"too_small",minimum:X.minimum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),XQ=q("$ZodCheckLengthEquals",(Y,X)=>{var J;N0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!l1($)&&$.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=i1($),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})}}),r1=q("$ZodCheckStringFormat",(Y,X)=>{var J,Q;if(N0.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=()=>{})}),JQ=q("$ZodCheckRegex",(Y,X)=>{r1.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})}}),QQ=q("$ZodCheckLowerCase",(Y,X)=>{X.pattern??(X.pattern=o6),r1.init(Y,X)}),$Q=q("$ZodCheckUpperCase",(Y,X)=>{X.pattern??(X.pattern=r6),r1.init(Y,X)}),GQ=q("$ZodCheckIncludes",(Y,X)=>{N0.init(Y,X);let J=l0(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})}}),WQ=q("$ZodCheckStartsWith",(Y,X)=>{N0.init(Y,X);let J=new RegExp(`^${l0(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})}}),zQ=q("$ZodCheckEndsWith",(Y,X)=>{N0.init(Y,X);let J=new RegExp(`.*${l0(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 KQ=q("$ZodCheckOverwrite",(Y,X)=>{N0.init(Y,X),Y._zod.check=(J)=>{J.value=X.tx(J.value)}});class o8{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(`
|
|
164
|
+
`}}function R2(Y){return Y.type==="response.output_item.done"&&_(Y.item)&&Y.item.type==="web_search_call"&&typeof Y.item.id==="string"}function C2(Y){return _(Y)&&Y.type==="function_call"&&Y.name==="web_search"&&typeof Y.call_id==="string"&&Y.call_id.startsWith(xY)}function _2(Y,X){return _(Y)&&Y.type==="function_call_output"&&typeof Y.call_id==="string"&&typeof Y.output==="string"&&Y.call_id.startsWith(xY)&&X.has(Y.call_id)}function I2(Y){return _(Y)&&Y.type==="item_reference"&&typeof Y.id==="string"&&Y.id.startsWith(xY)}function d8(Y,X,J){let Q=S2(X),$=_(Q?.action)?Q.action:k2(J?.arguments);return{type:"web_search_call",status:"completed",...$?{action:$}:{}}}function S2(Y){if(_(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return _(X)?X:void 0}catch{return}}function k2(Y){if(_(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return _(X)?X:void 0}catch{return}}import{readFile as b2}from"node:fs/promises";import{homedir as x2}from"node:os";import{join as VJ}from"node:path";var v2="https://models.dev/api.json",h2="OPENCODE_OPENAI_AUTH_MODELS_CACHE",g2="OPENCODE_MODELS_PATH",y2="OPENCODE_DISABLE_MODELS_FETCH",f2=1e4,m2=300000;function W1(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function NJ(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function n8(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=NJ(Y.cache_read),$=NJ(Y.cache_write);if(Q===null||$===null)return null;return{input:X,output:J,cache:{read:Q,write:$}}}function c2(Y){let X=W1(Y);if(!X)return null;let J=n8(X);if(!J)return null;let Q=J;if(Array.isArray(X.tiers)){let W=[];for(let U of X.tiers){let L=W1(U);if(!L)continue;let H=W1(L.tier),N=H?.size;if(H?.type!=="context")continue;if(typeof N!=="number"||!Number.isFinite(N)||N<=0)continue;let O=n8(L);if(!O)continue;W.push({...O,tier:{type:"context",size:N}})}if(W.length>0)Q.tiers=W}let $=W1(X.context_over_200k),G=$?n8($):null;if(G)Q.experimentalOver200K=G;return Q}function BJ(Y){let X=W1(Y),J=W1(X?.openai),Q=W1(J?.models);if(!Q)return null;let $={};for(let[G,W]of Object.entries(Q)){let U=W1(W),L=c2(U?.cost);if(L)$[G]=L}return Object.keys($).length>0?$:null}function u2(){let Y=process.env[h2]?.trim();if(Y)return Y;let X=process.env[g2]?.trim();if(X)return X;let J=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||VJ(x2(),".cache");return VJ(J,"opencode","models.json")}function p2(){let Y=process.env[y2]?.toLowerCase();return Y==="true"||Y==="1"}async function l2(){try{let Y=BJ(JSON.parse(await b2(u2(),"utf8")));if(Y)return Y}catch{}if(p2())return null;try{let Y=await fetch(v2,{signal:AbortSignal.timeout(f2)});if(!Y.ok)return null;return BJ(await Y.json())}catch{return null}}var h1;function ZJ(){let Y=Date.now();if(h1&&h1.expiresAt>Y)return h1.promise;let X={expiresAt:Y+m2,promise:l2()};return h1=X,X.promise.then((J)=>{if(J===null&&h1===X)h1=void 0}),X.promise}function g1(Y){return typeof Y==="object"&&Y!==null}function d2(Y){if(Array.isArray(Y))return Y;if(g1(Y)&&Array.isArray(Y.data))return Y.data;return[]}function i2(Y){if(!g1(Y)||!g1(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function KJ(Y){if(!g1(Y)||!g1(Y.info))return null;let X=Y.info,J=g1(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 U={};if(Q)U.agent=Q;if($&&G)U.model={providerID:$,modelID:G};if(W)U.variant=W;return U}function OJ(Y,X){return{agent:Y.agent??X.agent,model:Y.model??X.model,variant:Y.variant??X.variant}}function qJ(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function FJ(Y,X){if(!Y||!X)return null;let J=Y;if(typeof J.session?.messages!=="function")return null;let Q=[];try{Q=d2(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(i2(Q[G])!=="assistant")continue;let W=KJ(Q[G]);if(!W)continue;if($=OJ($,W),qJ($))return $}for(let G=Q.length-1;G>=0;G--){let W=KJ(Q[G]);if(!W)continue;if($=OJ($,W),qJ($))return $}if(!$.agent&&!$.model&&!$.variant)return null;return $}var z1=[],n2=1,o8=0,jJ=new Map;function r8(Y,X){if(z1.push({id:n2++,type:"open-dialog",payload:Y,sessionId:X}),z1.length>100)z1=z1.slice(z1.length-100)}function DJ(Y=0,X){let J=Date.now();if(o8=J,X!==void 0)jJ.set(X,J);let Q=($)=>X===void 0||$.sessionId===void 0||$.sessionId===X;if(Y>0)z1=z1.filter(($)=>{if($.id>Y)return!0;if(X===void 0)return!1;return $.sessionId!==X});return z1.filter(($)=>$.id>Y&&Q($))}function PJ(Y){let X=Date.now();if(Y!==void 0){let J=jJ.get(Y)??0;return J>0&&X-J<3000}return o8>0&&X-o8<3000}import{randomBytes as o2,timingSafeEqual as r2}from"node:crypto";import{unlink as s2}from"node:fs/promises";import{createServer as a2}from"node:http";import{join as t2}from"node:path";var MJ=L0("rpc");function e2(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 Yz(Y,X){if(!Y?.startsWith("Bearer "))return!1;let J=Buffer.from(Y.slice(7)),Q=Buffer.from(X);return J.length===Q.length&&r2(J,Q)}async function AJ(Y){let X=o2(32).toString("hex"),J=Y.timeoutMs??90000,Q=Y.receiptTimeoutMs??2000,$=a2((U,L)=>{U.setTimeout(J,()=>{U.socket.destroy()}),G(U,L)});$.requestTimeout=Q,$.headersTimeout=Q;async function G(U,L){let H=(N,O)=>{if(L.headersSent||L.writableEnded||L.destroyed)return;L.writeHead(N,{"content-type":"application/json"}),L.end(JSON.stringify(O))};try{let N=U.url??"";if(U.method==="GET"&&N==="/health")return H(200,{ok:!0});if(U.method!=="POST"||!N.startsWith("/rpc/"))return H(404,{error:"not found"});if(!Yz(U.headers.authorization,X))return H(401,{error:"unauthorized"});let O=N.slice(5),Z=await e2(U),V=JSON.parse(Z||"{}");if(O==="pending-notifications"){let K=Y.drain(Number(V.lastReceivedId??0),typeof V.sessionId==="string"?V.sessionId:void 0);return H(200,{messages:K})}if(O==="apply"){let K=await Y.apply(V);return H(200,K)}return H(404,{error:"unknown method"})}catch(N){H(500,{error:N instanceof Error?N.message:String(N)})}}let W=await new Promise((U,L)=>{$.on("error",L),$.listen(0,"127.0.0.1",()=>{let H=$.address();if(H&&typeof H==="object")U(H.port);else L(Error("no port"))})});if($.unref(),Y.sweepRoot)try{await EJ(Y.sweepRoot,Y.dir)}catch(U){MJ.warn("rpc state sweep failed",{pid:process.pid,error:U instanceof Error?U.message:String(U)})}try{await wJ(Y.dir,{port:W,token:X,pid:process.pid},{secureDir:Y.secureDir}),MJ.debug("rpc server pid",{pid:process.pid,rpcPort:W})}catch(U){throw await new Promise((L)=>$.close(()=>L())),U}return{port:W,token:X,async stop(){await new Promise((U)=>$.close(()=>U())),await s2(t2(Y.dir,`port-${process.pid}.json`)).catch(()=>{})}}}function s0(Y){return JSON.stringify(s8(Y))??"undefined"}function s8(Y){if(Array.isArray(Y))return Y.map(s8);if(!_(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((X)=>[X,s8(Y[X])]))}function P1(){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 Z1={};e8(Z1,{withoutInternalHeaders:()=>OW,sanitizeHttpFallbackBody:()=>b8,orderCodexBody:()=>OY,hasWebSocketResponsesLiteMetadata:()=>k8,createWebSocketFetch:()=>zB,applyTurnId:()=>NW,advanceTurn:()=>r9,TITLE_HEADER:()=>o9,QUOTA_ACCOUNT_HEADER:()=>U8,OpenAIWebSocketPool:()=>Z1,CODEX_BODY_KEY_ORDER:()=>LW});import{createHash as JB}from"node:crypto";var J6="vercel.ai.error",Xz=Symbol.for(J6),TJ,RJ,f=class Y extends(RJ=Error,TJ=Xz,RJ){constructor({name:X,message:J,cause:Q}){super(J);this[TJ]=!0,this.name=X,this.cause=Q}static isInstance(X){return Y.hasMarker(X,J6)}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}},Q6="AI_APICallError",$6=`vercel.ai.error.${Q6}`,Jz=Symbol.for($6),CJ,_J,a1=class extends(_J=f,CJ=Jz,_J){constructor({message:Y,url:X,requestBodyValues:J,statusCode:Q,responseHeaders:$,responseBody:G,cause:W,isRetryable:U=Q!=null&&(Q===408||Q===409||Q===429||Q>=500),data:L}){super({name:Q6,message:Y,cause:W});this[CJ]=!0,this.url=X,this.requestBodyValues=J,this.statusCode=Q,this.responseHeaders=$,this.responseBody=G,this.isRetryable=U,this.data=L}static isInstance(Y){return f.hasMarker(Y,$6)}},G6="AI_EmptyResponseBodyError",W6=`vercel.ai.error.${G6}`,Qz=Symbol.for(W6),IJ,SJ,$z=class extends(SJ=f,IJ=Qz,SJ){constructor({message:Y="Empty response body"}={}){super({name:G6,message:Y});this[IJ]=!0}static isInstance(Y){return f.hasMarker(Y,W6)}};function a8(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 z6="AI_InvalidArgumentError",U6=`vercel.ai.error.${z6}`,Gz=Symbol.for(U6),kJ,bJ,H6=class extends(bJ=f,kJ=Gz,bJ){constructor({message:Y,cause:X,argument:J}){super({name:z6,message:Y,cause:X});this[kJ]=!0,this.argument=J}static isInstance(Y){return f.hasMarker(Y,U6)}},L6="AI_InvalidPromptError",V6=`vercel.ai.error.${L6}`,Wz=Symbol.for(V6),xJ,vJ,zz=class extends(vJ=f,xJ=Wz,vJ){constructor({prompt:Y,message:X,cause:J}){super({name:L6,message:`Invalid prompt: ${X}`,cause:J});this[xJ]=!0,this.prompt=Y}static isInstance(Y){return f.hasMarker(Y,V6)}},N6="AI_InvalidResponseDataError",B6=`vercel.ai.error.${N6}`,Uz=Symbol.for(B6),hJ,gJ,Hz=class extends(gJ=f,hJ=Uz,gJ){constructor({data:Y,message:X=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:N6,message:X});this[hJ]=!0,this.data=Y}static isInstance(Y){return f.hasMarker(Y,B6)}},Z6="AI_JSONParseError",K6=`vercel.ai.error.${Z6}`,Lz=Symbol.for(K6),yJ,fJ,vY=class extends(fJ=f,yJ=Lz,fJ){constructor({text:Y,cause:X}){super({name:Z6,message:`JSON parsing failed: Text: ${Y}.
|
|
165
|
+
Error message: ${a8(X)}`,cause:X});this[yJ]=!0,this.text=Y}static isInstance(Y){return f.hasMarker(Y,K6)}},O6="AI_LoadAPIKeyError",q6=`vercel.ai.error.${O6}`,Vz=Symbol.for(q6),mJ,cJ,Nz=class extends(cJ=f,mJ=Vz,cJ){constructor({message:Y}){super({name:O6,message:Y});this[mJ]=!0}static isInstance(Y){return f.hasMarker(Y,q6)}},F6="AI_LoadSettingError",j6=`vercel.ai.error.${F6}`,Bz=Symbol.for(j6),uJ,pJ,Zz=class extends(pJ=f,uJ=Bz,pJ){constructor({message:Y}){super({name:F6,message:Y});this[uJ]=!0}static isInstance(Y){return f.hasMarker(Y,j6)}},D6="AI_NoContentGeneratedError",P6=`vercel.ai.error.${D6}`,Kz=Symbol.for(P6),lJ,dJ,Oz=class extends(dJ=f,lJ=Kz,dJ){constructor({message:Y="No content generated."}={}){super({name:D6,message:Y});this[lJ]=!0}static isInstance(Y){return f.hasMarker(Y,P6)}},M6="AI_NoSuchModelError",w6=`vercel.ai.error.${M6}`,qz=Symbol.for(w6),iJ,nJ,Fz=class extends(nJ=f,iJ=qz,nJ){constructor({errorName:Y=M6,modelId:X,modelType:J,message:Q=`No such ${J}: ${X}`}){super({name:Y,message:Q});this[iJ]=!0,this.modelId=X,this.modelType=J}static isInstance(Y){return f.hasMarker(Y,w6)}},E6="AI_NoSuchProviderReferenceError",A6=`vercel.ai.error.${E6}`,jz=Symbol.for(A6),oJ,rJ,Dz=class extends(rJ=f,oJ=jz,rJ){constructor({provider:Y,reference:X,message:J=`No provider reference found for provider '${Y}'. Available providers: ${Object.keys(X).join(", ")}`}){super({name:E6,message:J});this[oJ]=!0,this.provider=Y,this.reference=X}static isInstance(Y){return f.hasMarker(Y,A6)}},T6="AI_TooManyEmbeddingValuesForCallError",R6=`vercel.ai.error.${T6}`,Pz=Symbol.for(R6),sJ,aJ,Mz=class extends(aJ=f,sJ=Pz,aJ){constructor(Y){super({name:T6,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[sJ]=!0,this.provider=Y.provider,this.modelId=Y.modelId,this.maxEmbeddingsPerCall=Y.maxEmbeddingsPerCall,this.values=Y.values}static isInstance(Y){return f.hasMarker(Y,R6)}},C6="AI_TypeValidationError",_6=`vercel.ai.error.${C6}`,wz=Symbol.for(_6),tJ,eJ,f0=class Y extends(eJ=f,tJ=wz,eJ){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:C6,message:`${$}: Value: ${JSON.stringify(X)}.
|
|
166
|
+
Error message: ${a8(J)}`,cause:J});this[tJ]=!0,this.value=X,this.context=Q}static isInstance(X){return f.hasMarker(X,_6)}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})}},I6="AI_UnsupportedFunctionalityError",S6=`vercel.ai.error.${I6}`,Ez=Symbol.for(S6),Y6,X6,Az=class extends(X6=f,Y6=Ez,X6){constructor({functionality:Y,message:X=`'${Y}' functionality not supported.`}){super({name:I6,message:X});this[Y6]=!0,this.functionality=Y}static isInstance(Y){return f.hasMarker(Y,S6)}};var MK=Object.freeze({status:"aborted"});function F(Y,X,J){function Q(U,L){var H;Object.defineProperty(U,"_zod",{value:U._zod??{},enumerable:!1}),(H=U._zod).traits??(H.traits=new Set),U._zod.traits.add(Y),X(U,L);for(let N in W.prototype)if(!(N in U))Object.defineProperty(U,N,{value:W.prototype[N].bind(U)});U._zod.constr=W,U._zod.def=L}let $=J?.Parent??Object;class G extends ${}Object.defineProperty(G,"name",{value:Y});function W(U){var L;let H=J?.Parent?new G:this;Q(H,U),(L=H._zod).deferred??(L.deferred=[]);for(let N of H._zod.deferred)N();return H}return Object.defineProperty(W,"init",{value:Q}),Object.defineProperty(W,Symbol.hasInstance,{value:(U)=>{if(J?.Parent&&U instanceof J.Parent)return!0;return U?._zod?.traits?.has(Y)}}),Object.defineProperty(W,"name",{value:Y}),W}var wK=Symbol("zod_brand");class a0 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class t1 extends Error{constructor(Y){super(`Encountered unidirectional transform during encode: ${Y}`);this.name="ZodEncodeError"}}var hY={};function m0(Y){if(Y)Object.assign(hY,Y);return hY}var u={};e8(u,{unwrapMessage:()=>e1,uint8ArrayToHex:()=>az,uint8ArrayToBase64url:()=>rz,uint8ArrayToBase64:()=>f6,stringifyPrimitive:()=>v6,shallowClone:()=>b6,safeExtend:()=>pz,required:()=>iz,randomString:()=>hz,propertyKeyTypes:()=>J9,promiseAllObject:()=>vz,primitiveTypes:()=>x6,prefixIssues:()=>e0,pick:()=>mz,partial:()=>dz,optionalKeys:()=>Q9,omit:()=>cz,objectClone:()=>kz,numKeys:()=>gz,nullish:()=>XY,normalizeParams:()=>v,mergeDefs:()=>H1,merge:()=>lz,jsonStringifyReplacer:()=>y1,joinValues:()=>Sz,issue:()=>m1,isPlainObject:()=>L1,isObject:()=>M1,hexToUint8Array:()=>sz,getSizableOrigin:()=>g6,getParsedType:()=>yz,getLengthableOrigin:()=>QY,getEnumValues:()=>YY,getElementAtPath:()=>xz,floatSafeRemainder:()=>Y9,finalizeIssue:()=>S0,extend:()=>uz,escapeRegex:()=>t0,esc:()=>gY,defineLazy:()=>l,createTransparentProxy:()=>fz,cloneDef:()=>bz,clone:()=>I0,cleanRegex:()=>JY,cleanEnum:()=>nz,captureStackTrace:()=>yY,cached:()=>f1,base64urlToUint8Array:()=>oz,base64ToUint8Array:()=>y6,assignProp:()=>U1,assertNotEqual:()=>Rz,assertNever:()=>_z,assertIs:()=>Cz,assertEqual:()=>Tz,assert:()=>Iz,allowsEval:()=>X9,aborted:()=>V1,NUMBER_FORMAT_RANGES:()=>$9,Class:()=>m6,BIGINT_FORMAT_RANGES:()=>h6});function Tz(Y){return Y}function Rz(Y){return Y}function Cz(Y){}function _z(Y){throw Error()}function Iz(Y){}function YY(Y){let X=Object.values(Y).filter((Q)=>typeof Q==="number");return Object.entries(Y).filter(([Q,$])=>X.indexOf(+Q)===-1).map(([Q,$])=>$)}function Sz(Y,X="|"){return Y.map((J)=>v6(J)).join(X)}function y1(Y,X){if(typeof X==="bigint")return X.toString();return X}function f1(Y){return{get value(){{let J=Y();return Object.defineProperty(this,"value",{value:J}),J}throw Error("cached value already set")}}}function XY(Y){return Y===null||Y===void 0}function JY(Y){let X=Y.startsWith("^")?1:0,J=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(X,J)}function Y9(Y,X){let J=(Y.toString().split(".")[1]||"").length,Q=X.toString(),$=(Q.split(".")[1]||"").length;if($===0&&/\d?e-\d?/.test(Q)){let L=Q.match(/\d?e-(\d?)/);if(L?.[1])$=Number.parseInt(L[1])}let G=J>$?J:$,W=Number.parseInt(Y.toFixed(G).replace(".","")),U=Number.parseInt(X.toFixed(G).replace(".",""));return W%U/10**G}var k6=Symbol("evaluating");function l(Y,X,J){let Q=void 0;Object.defineProperty(Y,X,{get(){if(Q===k6)return;if(Q===void 0)Q=k6,Q=J();return Q},set($){Object.defineProperty(Y,X,{value:$})},configurable:!0})}function kz(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function U1(Y,X,J){Object.defineProperty(Y,X,{value:J,writable:!0,enumerable:!0,configurable:!0})}function H1(...Y){let X={};for(let J of Y){let Q=Object.getOwnPropertyDescriptors(J);Object.assign(X,Q)}return Object.defineProperties({},X)}function bz(Y){return H1(Y._zod.def)}function xz(Y,X){if(!X)return Y;return X.reduce((J,Q)=>J?.[Q],Y)}function vz(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 hz(Y=10){let J="";for(let Q=0;Q<Y;Q++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function gY(Y){return JSON.stringify(Y)}var yY="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function M1(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var X9=f1(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function L1(Y){if(M1(Y)===!1)return!1;let X=Y.constructor;if(X===void 0)return!0;let J=X.prototype;if(M1(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function b6(Y){if(L1(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function gz(Y){let X=0;for(let J in Y)if(Object.prototype.hasOwnProperty.call(Y,J))X++;return X}var yz=(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}`)}},J9=new Set(["string","number","symbol"]),x6=new Set(["string","number","bigint","boolean","symbol","undefined"]);function t0(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function I0(Y,X,J){let Q=new Y._zod.constr(X??Y._zod.def);if(!X||J?.parent)Q._zod.parent=Y;return Q}function v(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 fz(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 v6(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function Q9(Y){return Object.keys(Y).filter((X)=>{return Y[X]._zod.optin==="optional"&&Y[X]._zod.optout==="optional"})}var $9={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]},h6={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function mz(Y,X){let J=Y._zod.def,Q=H1(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 U1(this,"shape",$),$},checks:[]});return I0(Y,Q)}function cz(Y,X){let J=Y._zod.def,Q=H1(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 U1(this,"shape",$),$},checks:[]});return I0(Y,Q)}function uz(Y,X){if(!L1(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 $=H1(Y._zod.def,{get shape(){let G={...Y._zod.def.shape,...X};return U1(this,"shape",G),G},checks:[]});return I0(Y,$)}function pz(Y,X){if(!L1(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 U1(this,"shape",Q),Q},checks:Y._zod.def.checks};return I0(Y,J)}function lz(Y,X){let J=H1(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape,...X._zod.def.shape};return U1(this,"shape",Q),Q},get catchall(){return X._zod.def.catchall},checks:[]});return I0(Y,J)}function dz(Y,X,J){let Q=H1(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 U1(this,"shape",G),G},checks:[]});return I0(X,Q)}function iz(Y,X,J){let Q=H1(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 U1(this,"shape",G),G},checks:[]});return I0(X,Q)}function V1(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 e0(Y,X){return X.map((J)=>{var Q;return(Q=J).path??(Q.path=[]),J.path.unshift(Y),J})}function e1(Y){return typeof Y==="string"?Y:Y?.message}function S0(Y,X,J){let Q={...Y,path:Y.path??[]};if(!Y.message){let $=e1(Y.inst?._zod.def?.error?.(Y))??e1(X?.error?.(Y))??e1(J.customError?.(Y))??e1(J.localeError?.(Y))??"Invalid input";Q.message=$}if(delete Q.inst,delete Q.continue,!X?.reportInput)delete Q.input;return Q}function g6(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function QY(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function m1(...Y){let[X,J,Q]=Y;if(typeof X==="string")return{message:X,code:"custom",input:J,inst:Q};return{...X}}function nz(Y){return Object.entries(Y).filter(([X,J])=>{return Number.isNaN(Number.parseInt(X,10))}).map((X)=>X[1])}function y6(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 f6(Y){let X="";for(let J=0;J<Y.length;J++)X+=String.fromCharCode(Y[J]);return btoa(X)}function oz(Y){let X=Y.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-X.length%4)%4);return y6(X+J)}function rz(Y){return f6(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function sz(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 az(Y){return Array.from(Y).map((X)=>X.toString(16).padStart(2,"0")).join("")}class m6{constructor(...Y){}}var c6=(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,y1,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},fY=F("$ZodError",c6),G9=F("$ZodError",c6,{Parent:Error});function u6(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 p6(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((U)=>$({issues:U}));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 U=Q,L=0;while(L<W.path.length){let H=W.path[L];if(L!==W.path.length-1)U[H]=U[H]||{_errors:[]};else U[H]=U[H]||{_errors:[]},U[H]._errors.push(J(W));U=U[H],L++}}};return $(Y),Q}var mY=(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 a0;if(W.issues.length){let U=new($?.Err??Y)(W.issues.map((L)=>S0(L,G,m0())));throw yY(U,$?.callee),U}return W.value};var cY=(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 U=new($?.Err??Y)(W.issues.map((L)=>S0(L,G,m0())));throw yY(U,$?.callee),U}return W.value};var $Y=(Y)=>(X,J,Q)=>{let $=Q?{...Q,async:!1}:{async:!1},G=X._zod.run({value:J,issues:[]},$);if(G instanceof Promise)throw new a0;return G.issues.length?{success:!1,error:new(Y??fY)(G.issues.map((W)=>S0(W,$,m0())))}:{success:!0,data:G.value}},l6=$Y(G9),GY=(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)=>S0(W,$,m0())))}:{success:!0,data:G.value}},d6=GY(G9),i6=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return mY(Y)(X,J,$)};var n6=(Y)=>(X,J,Q)=>{return mY(Y)(X,J,Q)};var o6=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return cY(Y)(X,J,$)};var r6=(Y)=>async(X,J,Q)=>{return cY(Y)(X,J,Q)};var s6=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return $Y(Y)(X,J,$)};var a6=(Y)=>(X,J,Q)=>{return $Y(Y)(X,J,Q)};var t6=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return GY(Y)(X,J,$)};var e6=(Y)=>async(X,J,Q)=>{return GY(Y)(X,J,Q)};var YQ=/^[cC][^\s-]{8,}$/,XQ=/^[0-9a-z]+$/,JQ=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,QQ=/^[0-9a-vA-V]{20}$/,$Q=/^[A-Za-z0-9]{27}$/,GQ=/^[a-zA-Z0-9_-]{21}$/,WQ=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var zQ=/^([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})$/,W9=(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 UQ=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function HQ(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var LQ=/^(?:(?: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])$/,VQ=/^(([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}|:))$/,NQ=/^((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])$/,BQ=/^(([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])$/,ZQ=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,z9=/^[A-Za-z0-9_-]*$/,KQ=/^(?=.{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 OQ=/^\+(?:[0-9]){6,14}[0-9]$/,qQ="(?:(?:\\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])))",FQ=new RegExp(`^${qQ}$`);function jQ(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 DQ(Y){return new RegExp(`^${jQ(Y)}$`)}function PQ(Y){let X=jQ({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(`^${qQ}T(?:${Q})$`)}var MQ=(Y)=>{let X=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${X}$`)};var wQ=/^-?\d+$/,EQ=/^-?\d+(?:\.\d+)?/,AQ=/^(?:true|false)$/i,TQ=/^null$/i;var RQ=/^[^A-Z]*$/,CQ=/^[^a-z]*$/;var V0=F("$ZodCheck",(Y,X)=>{var J;Y._zod??(Y._zod={}),Y._zod.def=X,(J=Y._zod).onattach??(J.onattach=[])}),_Q={number:"number",bigint:"bigint",object:"date"},U9=F("$ZodCheckLessThan",(Y,X)=>{V0.init(Y,X);let J=_Q[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})}}),H9=F("$ZodCheckGreaterThan",(Y,X)=>{V0.init(Y,X);let J=_Q[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})}}),IQ=F("$ZodCheckMultipleOf",(Y,X)=>{V0.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):Y9(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})}}),SQ=F("$ZodCheckNumberFormat",(Y,X)=>{V0.init(Y,X),X.format=X.format||"float64";let J=X.format?.includes("int"),Q=J?"int":"number",[$,G]=$9[X.format];Y._zod.onattach.push((W)=>{let U=W._zod.bag;if(U.format=X.format,U.minimum=$,U.maximum=G,J)U.pattern=wQ}),Y._zod.check=(W)=>{let U=W.value;if(J){if(!Number.isInteger(U)){W.issues.push({expected:Q,format:X.format,code:"invalid_type",continue:!1,input:U,inst:Y});return}if(!Number.isSafeInteger(U)){if(U>0)W.issues.push({input:U,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:U,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(U<$)W.issues.push({origin:"number",input:U,code:"too_small",minimum:$,inclusive:!0,inst:Y,continue:!X.abort});if(U>G)W.issues.push({origin:"number",input:U,code:"too_big",maximum:G,inst:Y})}});var kQ=F("$ZodCheckMaxLength",(Y,X)=>{var J;V0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!XY($)&&$.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=QY($);Q.issues.push({origin:W,code:"too_big",maximum:X.maximum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),bQ=F("$ZodCheckMinLength",(Y,X)=>{var J;V0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!XY($)&&$.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=QY($);Q.issues.push({origin:W,code:"too_small",minimum:X.minimum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),xQ=F("$ZodCheckLengthEquals",(Y,X)=>{var J;V0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!XY($)&&$.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=QY($),U=G>X.length;Q.issues.push({origin:W,...U?{code:"too_big",maximum:X.length}:{code:"too_small",minimum:X.length},inclusive:!0,exact:!0,input:Q.value,inst:Y,continue:!X.abort})}}),WY=F("$ZodCheckStringFormat",(Y,X)=>{var J,Q;if(V0.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=()=>{})}),vQ=F("$ZodCheckRegex",(Y,X)=>{WY.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})}}),hQ=F("$ZodCheckLowerCase",(Y,X)=>{X.pattern??(X.pattern=RQ),WY.init(Y,X)}),gQ=F("$ZodCheckUpperCase",(Y,X)=>{X.pattern??(X.pattern=CQ),WY.init(Y,X)}),yQ=F("$ZodCheckIncludes",(Y,X)=>{V0.init(Y,X);let J=t0(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})}}),fQ=F("$ZodCheckStartsWith",(Y,X)=>{V0.init(Y,X);let J=new RegExp(`^${t0(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})}}),mQ=F("$ZodCheckEndsWith",(Y,X)=>{V0.init(Y,X);let J=new RegExp(`.*${t0(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 cQ=F("$ZodCheckOverwrite",(Y,X)=>{V0.init(Y,X),Y._zod.check=(J)=>{J.value=X.tx(J.value)}});class L9{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(`
|
|
117
167
|
`).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(`
|
|
118
|
-
`))}}var
|
|
119
|
-
if (${
|
|
120
|
-
payload.issues = payload.issues.concat(${
|
|
168
|
+
`))}}var pQ={major:4,minor:1,patch:8};var o=F("$ZodType",(Y,X)=>{var J;Y??(Y={}),Y._zod.def=X,Y._zod.bag=Y._zod.bag||{},Y._zod.version=pQ;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,U,L)=>{let H=V1(W),N;for(let O of U){if(O._zod.def.when){if(!O._zod.def.when(W))continue}else if(H)continue;let Z=W.issues.length,V=O._zod.check(W);if(V instanceof Promise&&L?.async===!1)throw new a0;if(N||V instanceof Promise)N=(N??Promise.resolve()).then(async()=>{if(await V,W.issues.length===Z)return;if(!H)H=V1(W,Z)});else{if(W.issues.length===Z)continue;if(!H)H=V1(W,Z)}}if(N)return N.then(()=>{return W});return W},G=(W,U,L)=>{if(V1(W))return W.aborted=!0,W;let H=$(U,Q,L);if(H instanceof Promise){if(L.async===!1)throw new a0;return H.then((N)=>Y._zod.parse(N,L))}return Y._zod.parse(H,L)};Y._zod.run=(W,U)=>{if(U.skipChecks)return Y._zod.parse(W,U);if(U.direction==="backward"){let H=Y._zod.parse({value:W.value,issues:[]},{...U,skipChecks:!0});if(H instanceof Promise)return H.then((N)=>{return G(N,W,U)});return G(H,W,U)}let L=Y._zod.parse(W,U);if(L instanceof Promise){if(U.async===!1)throw new a0;return L.then((H)=>$(H,Q,U))}return $(L,Q,U)}}Y["~standard"]={validate:($)=>{try{let G=l6(Y,$);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return d6(Y,$).then((W)=>W.success?{value:W.data}:{issues:W.error?.issues})}},vendor:"zod",version:1}}),dY=F("$ZodString",(Y,X)=>{o.init(Y,X),Y._zod.pattern=[...Y?._zod.bag?.patterns??[]].pop()??MQ(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}}),s=F("$ZodStringFormat",(Y,X)=>{WY.init(Y,X),dY.init(Y,X)}),tQ=F("$ZodGUID",(Y,X)=>{X.pattern??(X.pattern=zQ),s.init(Y,X)}),eQ=F("$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=W9(Q))}else X.pattern??(X.pattern=W9());s.init(Y,X)}),Y7=F("$ZodEmail",(Y,X)=>{X.pattern??(X.pattern=UQ),s.init(Y,X)}),X7=F("$ZodURL",(Y,X)=>{s.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:KQ.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})}}}),J7=F("$ZodEmoji",(Y,X)=>{X.pattern??(X.pattern=HQ()),s.init(Y,X)}),Q7=F("$ZodNanoID",(Y,X)=>{X.pattern??(X.pattern=GQ),s.init(Y,X)}),$7=F("$ZodCUID",(Y,X)=>{X.pattern??(X.pattern=YQ),s.init(Y,X)}),G7=F("$ZodCUID2",(Y,X)=>{X.pattern??(X.pattern=XQ),s.init(Y,X)}),W7=F("$ZodULID",(Y,X)=>{X.pattern??(X.pattern=JQ),s.init(Y,X)}),z7=F("$ZodXID",(Y,X)=>{X.pattern??(X.pattern=QQ),s.init(Y,X)}),U7=F("$ZodKSUID",(Y,X)=>{X.pattern??(X.pattern=$Q),s.init(Y,X)}),H7=F("$ZodISODateTime",(Y,X)=>{X.pattern??(X.pattern=PQ(X)),s.init(Y,X)}),L7=F("$ZodISODate",(Y,X)=>{X.pattern??(X.pattern=FQ),s.init(Y,X)}),V7=F("$ZodISOTime",(Y,X)=>{X.pattern??(X.pattern=DQ(X)),s.init(Y,X)}),N7=F("$ZodISODuration",(Y,X)=>{X.pattern??(X.pattern=WQ),s.init(Y,X)}),B7=F("$ZodIPv4",(Y,X)=>{X.pattern??(X.pattern=LQ),s.init(Y,X),Y._zod.onattach.push((J)=>{let Q=J._zod.bag;Q.format="ipv4"})}),Z7=F("$ZodIPv6",(Y,X)=>{X.pattern??(X.pattern=VQ),s.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})}}}),K7=F("$ZodCIDRv4",(Y,X)=>{X.pattern??(X.pattern=NQ),s.init(Y,X)}),O7=F("$ZodCIDRv6",(Y,X)=>{X.pattern??(X.pattern=BQ),s.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 q7(Y){if(Y==="")return!0;if(Y.length%4!==0)return!1;try{return atob(Y),!0}catch{return!1}}var F7=F("$ZodBase64",(Y,X)=>{X.pattern??(X.pattern=ZQ),s.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64"}),Y._zod.check=(J)=>{if(q7(J.value))return;J.issues.push({code:"invalid_format",format:"base64",input:J.value,inst:Y,continue:!X.abort})}});function ez(Y){if(!z9.test(Y))return!1;let X=Y.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),J=X.padEnd(Math.ceil(X.length/4)*4,"=");return q7(J)}var j7=F("$ZodBase64URL",(Y,X)=>{X.pattern??(X.pattern=z9),s.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64url"}),Y._zod.check=(J)=>{if(ez(J.value))return;J.issues.push({code:"invalid_format",format:"base64url",input:J.value,inst:Y,continue:!X.abort})}}),D7=F("$ZodE164",(Y,X)=>{X.pattern??(X.pattern=OQ),s.init(Y,X)});function YU(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 P7=F("$ZodJWT",(Y,X)=>{s.init(Y,X),Y._zod.check=(J)=>{if(YU(J.value,X.alg))return;J.issues.push({code:"invalid_format",format:"jwt",input:J.value,inst:Y,continue:!X.abort})}});var N9=F("$ZodNumber",(Y,X)=>{o.init(Y,X),Y._zod.pattern=Y._zod.bag.pattern??EQ,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}}),M7=F("$ZodNumber",(Y,X)=>{SQ.init(Y,X),N9.init(Y,X)}),w7=F("$ZodBoolean",(Y,X)=>{o.init(Y,X),Y._zod.pattern=AQ,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 E7=F("$ZodNull",(Y,X)=>{o.init(Y,X),Y._zod.pattern=TQ,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 A7=F("$ZodUnknown",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J)=>J}),T7=F("$ZodNever",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{return J.issues.push({expected:"never",code:"invalid_type",input:J.value,inst:Y}),J}});function lQ(Y,X,J){if(Y.issues.length)X.issues.push(...e0(J,Y.issues));X.value[J]=Y.value}var R7=F("$ZodArray",(Y,X)=>{o.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 U=$[W],L=X.element._zod.run({value:U,issues:[]},Q);if(L instanceof Promise)G.push(L.then((H)=>lQ(H,J,W)));else lQ(L,J,W)}if(G.length)return Promise.all(G).then(()=>J);return J}});function lY(Y,X,J,Q){if(Y.issues.length)X.issues.push(...e0(J,Y.issues));if(Y.value===void 0){if(J in Q)X.value[J]=void 0}else X.value[J]=Y.value}function C7(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=Q9(Y.shape);return{...Y,keys:X,keySet:new Set(X),numKeys:X.length,optionalKeys:new Set(J)}}function _7(Y,X,J,Q,$,G){let W=[],U=$.keySet,L=$.catchall._zod,H=L.def.type;for(let N of Object.keys(X)){if(U.has(N))continue;if(H==="never"){W.push(N);continue}let O=L.run({value:X[N],issues:[]},Q);if(O instanceof Promise)Y.push(O.then((Z)=>lY(Z,J,N,X)));else lY(O,J,N,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 XU=F("$ZodObject",(Y,X)=>{o.init(Y,X);let J=f1(()=>C7(X));l(Y._zod,"propValues",()=>{let W=X.shape,U={};for(let L in W){let H=W[L]._zod;if(H.values){U[L]??(U[L]=new Set);for(let N of H.values)U[L].add(N)}}return U});let Q=M1,$=X.catchall,G;Y._zod.parse=(W,U)=>{G??(G=J.value);let L=W.value;if(!Q(L))return W.issues.push({expected:"object",code:"invalid_type",input:L,inst:Y}),W;W.value={};let H=[],N=G.shape;for(let O of G.keys){let V=N[O]._zod.run({value:L[O],issues:[]},U);if(V instanceof Promise)H.push(V.then((K)=>lY(K,W,O,L)));else lY(V,W,O,L)}if(!$)return H.length?Promise.all(H).then(()=>W):W;return _7(H,L,W,U,J.value,Y)}}),I7=F("$ZodObjectJIT",(Y,X)=>{XU.init(Y,X);let J=Y._zod.parse,Q=f1(()=>C7(X)),$=(Z)=>{let V=new L9(["shape","payload","ctx"]),K=Q.value,j=(x)=>{let R=gY(x);return`shape[${R}]._zod.run({ value: input[${R}], issues: [] }, ctx)`};V.write("const input = payload.value;");let M=Object.create(null),I=0;for(let x of K.keys)M[x]=`key_${I++}`;V.write("const newResult = {};");for(let x of K.keys){let R=M[x],p=gY(x);V.write(`const ${R} = ${j(x)};`),V.write(`
|
|
169
|
+
if (${R}.issues.length) {
|
|
170
|
+
payload.issues = payload.issues.concat(${R}.issues.map(iss => ({
|
|
121
171
|
...iss,
|
|
122
|
-
path: iss.path ? [${
|
|
172
|
+
path: iss.path ? [${p}, ...iss.path] : [${p}]
|
|
123
173
|
})));
|
|
124
174
|
}
|
|
125
175
|
|
|
126
176
|
|
|
127
|
-
if (${
|
|
128
|
-
if (${
|
|
129
|
-
newResult[${
|
|
177
|
+
if (${R}.value === undefined) {
|
|
178
|
+
if (${p} in input) {
|
|
179
|
+
newResult[${p}] = undefined;
|
|
130
180
|
}
|
|
131
181
|
} else {
|
|
132
|
-
newResult[${
|
|
182
|
+
newResult[${p}] = ${R}.value;
|
|
133
183
|
}
|
|
134
184
|
|
|
135
|
-
`)}L.write("payload.value = newResult;"),L.write("return payload;");let k=L.compile();return(x,S)=>k(B,x,S)},G,W=V1,K=!AY.jitless,U=K&&f8.value,N=X.catchall,O;Y._zod.parse=(B,L)=>{O??(O=Q.value);let Z=B.value;if(!W(Z))return B.issues.push({expected:"object",code:"invalid_type",input:Z,inst:Y}),B;if(K&&U&&L?.async===!1&&L.jitless!==!0){if(!G)G=$(X.shape);if(B=G(B,L),!N)return B;return sQ([],Z,B,L,O,Y)}return J(B,L)}});function NQ(Y,X,J,Q){for(let G of Y)if(G.issues.length===0)return X.value=G.value,X;let $=Y.filter((G)=>!X1(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)=>_0(W,Q,h0())))}),X}var a8=q("$ZodUnion",(Y,X)=>{i.init(Y,X),p(Y._zod,"optin",()=>X.options.some(($)=>$._zod.optin==="optional")?"optional":void 0),p(Y._zod,"optout",()=>X.options.some(($)=>$._zod.optout==="optional")?"optional":void 0),p(Y._zod,"values",()=>{if(X.options.every(($)=>$._zod.values))return new Set(X.options.flatMap(($)=>Array.from($._zod.values)));return}),p(Y._zod,"pattern",()=>{if(X.options.every(($)=>$._zod.pattern)){let $=X.options.map((G)=>G._zod.pattern);return new RegExp(`^(${$.map((G)=>d1(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 NQ(K,$,Y,G);return Promise.all(K).then((H)=>{return NQ(H,$,Y,G)})}}),tQ=q("$ZodDiscriminatedUnion",(Y,X)=>{a8.init(Y,X);let J=Y._zod.parse;p(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=_1(()=>{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(!V1(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}),$}}),eQ=q("$ZodIntersection",(Y,X)=>{i.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 VQ(J,H,U)});return VQ(J,G,W)}});function r8(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(Y1(Y)&&Y1(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=r8(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=r8($,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 VQ(Y,X,J){if(X.issues.length)Y.issues.push(...X.issues);if(J.issues.length)Y.issues.push(...J.issues);if(X1(Y))return Y;let Q=r8(X.value,J.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return Y.value=Q.data,Y}var Y7=q("$ZodRecord",(Y,X)=>{i.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value;if(!Y1($))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((N)=>{if(N.issues.length)J.issues.push(...d0(H,N.issues));J.value[H]=N.value}));else{if(U.issues.length)J.issues.push(...d0(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)=>_0(U,Q,h0())),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(...d0(W,U.issues));J.value[K.value]=U.value}));else{if(H.issues.length)J.issues.push(...d0(W,H.issues));J.value[K.value]=H.value}}}if(G.length)return Promise.all(G).then(()=>J);return J}});var X7=q("$ZodEnum",(Y,X)=>{i.init(Y,X);let J=p1(X.entries),Q=new Set(J);Y._zod.values=Q,Y._zod.pattern=new RegExp(`^(${J.filter(($)=>m8.has(typeof $)).map(($)=>typeof $==="string"?l0($):$.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}),$}}),J7=q("$ZodLiteral",(Y,X)=>{if(i.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"?l0(J):J?l0(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 Q7=q("$ZodTransform",(Y,X)=>{i.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new c1(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 p0;return J.value=$,J}});function BQ(Y,X){if(Y.issues.length&&X===void 0)return{issues:[],value:void 0};return Y}var $7=q("$ZodOptional",(Y,X)=>{i.init(Y,X),Y._zod.optin="optional",Y._zod.optout="optional",p(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,void 0]):void 0}),p(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${d1(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)=>BQ(G,J.value));return BQ($,J.value)}if(J.value===void 0)return J;return X.innerType._zod.run(J,Q)}}),G7=q("$ZodNullable",(Y,X)=>{i.init(Y,X),p(Y._zod,"optin",()=>X.innerType._zod.optin),p(Y._zod,"optout",()=>X.innerType._zod.optout),p(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${d1(J.source)}|null)$`):void 0}),p(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)}}),W7=q("$ZodDefault",(Y,X)=>{i.init(Y,X),Y._zod.optin="optional",p(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)=>ZQ(G,X));return ZQ($,X)}});function ZQ(Y,X){if(Y.value===void 0)Y.value=X.defaultValue;return Y}var z7=q("$ZodPrefault",(Y,X)=>{i.init(Y,X),Y._zod.optin="optional",p(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)}}),K7=q("$ZodNonOptional",(Y,X)=>{i.init(Y,X),p(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)=>OQ(G,Y));return OQ($,Y)}});function OQ(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 U7=q("$ZodCatch",(Y,X)=>{i.init(Y,X),p(Y._zod,"optin",()=>X.innerType._zod.optin),p(Y._zod,"optout",()=>X.innerType._zod.optout),p(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)=>_0(W,Q,h0()))},input:J.value}),J.issues=[];return J});if(J.value=$.value,$.issues.length)J.value=X.catchValue({...J,error:{issues:$.issues.map((G)=>_0(G,Q,h0()))},input:J.value}),J.issues=[];return J}});var H7=q("$ZodPipe",(Y,X)=>{i.init(Y,X),p(Y._zod,"values",()=>X.in._zod.values),p(Y._zod,"optin",()=>X.in._zod.optin),p(Y._zod,"optout",()=>X.out._zod.optout),p(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)=>kY(W,X.in,Q));return kY(G,X.in,Q)}let $=X.in._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>kY(G,X.out,Q));return kY($,X.out,Q)}});function kY(Y,X,J){if(Y.issues.length)return Y.aborted=!0,Y;return X._zod.run({value:Y.value,issues:Y.issues},J)}var L7=q("$ZodReadonly",(Y,X)=>{i.init(Y,X),p(Y._zod,"propValues",()=>X.innerType._zod.propValues),p(Y._zod,"values",()=>X.innerType._zod.values),p(Y._zod,"optin",()=>X.innerType._zod.optin),p(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(FQ);return FQ($)}});function FQ(Y){return Y.value=Object.freeze(Y.value),Y}var N7=q("$ZodLazy",(Y,X)=>{i.init(Y,X),p(Y._zod,"innerType",()=>X.getter()),p(Y._zod,"pattern",()=>Y._zod.innerType._zod.pattern),p(Y._zod,"propValues",()=>Y._zod.innerType._zod.propValues),p(Y._zod,"optin",()=>Y._zod.innerType._zod.optin??void 0),p(Y._zod,"optout",()=>Y._zod.innerType._zod.optout??void 0),Y._zod.parse=(J,Q)=>{return Y._zod.innerType._zod.run(J,Q)}}),V7=q("$ZodCustom",(Y,X)=>{N0.init(Y,X),i.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)=>qQ(G,J,Q,Y));qQ($,J,Q,Y);return}});function qQ(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(I1($))}}var kB=Symbol("ZodOutput"),bB=Symbol("ZodInput");class vY{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 Yz(){return new vY}var B1=Yz();function B7(Y,X){return new Y({type:"string",...v(X)})}function Z7(Y,X){return new Y({type:"string",format:"email",check:"string_format",abort:!1,...v(X)})}function t8(Y,X){return new Y({type:"string",format:"guid",check:"string_format",abort:!1,...v(X)})}function O7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...v(X)})}function F7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...v(X)})}function q7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...v(X)})}function j7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...v(X)})}function D7(Y,X){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...v(X)})}function P7(Y,X){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...v(X)})}function w7(Y,X){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...v(X)})}function E7(Y,X){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...v(X)})}function M7(Y,X){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...v(X)})}function A7(Y,X){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...v(X)})}function R7(Y,X){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...v(X)})}function T7(Y,X){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...v(X)})}function C7(Y,X){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...v(X)})}function _7(Y,X){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...v(X)})}function I7(Y,X){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...v(X)})}function S7(Y,X){return new Y({type:"string",format:"cidrv6",check:"string_format",abort:!1,...v(X)})}function k7(Y,X){return new Y({type:"string",format:"base64",check:"string_format",abort:!1,...v(X)})}function b7(Y,X){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...v(X)})}function x7(Y,X){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...v(X)})}function v7(Y,X){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...v(X)})}function h7(Y,X){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...v(X)})}function g7(Y,X){return new Y({type:"string",format:"date",check:"string_format",...v(X)})}function y7(Y,X){return new Y({type:"string",format:"time",check:"string_format",precision:null,...v(X)})}function f7(Y,X){return new Y({type:"string",format:"duration",check:"string_format",...v(X)})}function m7(Y,X){return new Y({type:"number",checks:[],...v(X)})}function c7(Y,X){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...v(X)})}function u7(Y,X){return new Y({type:"boolean",...v(X)})}function p7(Y,X){return new Y({type:"null",...v(X)})}function l7(Y){return new Y({type:"unknown"})}function d7(Y,X){return new Y({type:"never",...v(X)})}function hY(Y,X){return new i8({check:"less_than",...v(X),value:Y,inclusive:!1})}function s1(Y,X){return new i8({check:"less_than",...v(X),value:Y,inclusive:!0})}function gY(Y,X){return new n8({check:"greater_than",...v(X),value:Y,inclusive:!1})}function a1(Y,X){return new n8({check:"greater_than",...v(X),value:Y,inclusive:!0})}function yY(Y,X){return new a6({check:"multiple_of",...v(X),value:Y})}function fY(Y,X){return new e6({check:"max_length",...v(X),maximum:Y})}function S1(Y,X){return new YQ({check:"min_length",...v(X),minimum:Y})}function mY(Y,X){return new XQ({check:"length_equals",...v(X),length:Y})}function e8(Y,X){return new JQ({check:"string_format",format:"regex",...v(X),pattern:Y})}function Y9(Y){return new QQ({check:"string_format",format:"lowercase",...v(Y)})}function X9(Y){return new $Q({check:"string_format",format:"uppercase",...v(Y)})}function J9(Y,X){return new GQ({check:"string_format",format:"includes",...v(X),includes:Y})}function Q9(Y,X){return new WQ({check:"string_format",format:"starts_with",...v(X),prefix:Y})}function $9(Y,X){return new zQ({check:"string_format",format:"ends_with",...v(X),suffix:Y})}function Z1(Y){return new KQ({check:"overwrite",tx:Y})}function G9(Y){return Z1((X)=>X.normalize(Y))}function W9(){return Z1((Y)=>Y.trim())}function z9(){return Z1((Y)=>Y.toLowerCase())}function K9(){return Z1((Y)=>Y.toUpperCase())}function i7(Y,X,J){return new Y({type:"array",element:X,...v(J)})}function n7(Y,X,J){let Q=v(J);return Q.abort??(Q.abort=!0),new Y({type:"custom",check:"custom",fn:X,...Q})}function o7(Y,X,J){return new Y({type:"custom",check:"custom",fn:X,...v(J)})}function r7(Y){let X=Xz((J)=>{return J.addIssue=(Q)=>{if(typeof Q==="string")J.issues.push(I1(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(I1($))}},Y(J.value,J)});return X}function Xz(Y,X){let J=new N0({check:"custom",...v(X)});return J._zod.check=Y,J}class U9{constructor(Y){this.counter=0,this.metadataRegistry=Y?.metadata??B1,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 N={...X,schemaPath:[...X.schemaPath,Y],path:X.path},O=Y._zod.parent;if(O)W.ref=O,this.process(O,N),this.seen.get(O).isParent=!0;else{let B=W.schema;switch(Q.type){case"string":{let L=B;L.type="string";let{minimum:Z,maximum:j,format:w,patterns:P,contentEncoding:k}=Y._zod.bag;if(typeof Z==="number")L.minLength=Z;if(typeof j==="number")L.maxLength=j;if(w){if(L.format=$[w]??w,L.format==="")delete L.format}if(k)L.contentEncoding=k;if(P&&P.size>0){let x=[...P];if(x.length===1)L.pattern=x[0].source;else if(x.length>1)W.schema.allOf=[...x.map((S)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:S.source}))]}break}case"number":{let L=B,{minimum:Z,maximum:j,format:w,multipleOf:P,exclusiveMaximum:k,exclusiveMinimum:x}=Y._zod.bag;if(typeof w==="string"&&w.includes("int"))L.type="integer";else L.type="number";if(typeof x==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")L.minimum=x,L.exclusiveMinimum=!0;else L.exclusiveMinimum=x;if(typeof Z==="number"){if(L.minimum=Z,typeof x==="number"&&this.target!=="draft-4")if(x>=Z)delete L.minimum;else delete L.exclusiveMinimum}if(typeof k==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")L.maximum=k,L.exclusiveMaximum=!0;else L.exclusiveMaximum=k;if(typeof j==="number"){if(L.maximum=j,typeof k==="number"&&this.target!=="draft-4")if(k<=j)delete L.maximum;else delete L.exclusiveMaximum}if(typeof P==="number")L.multipleOf=P;break}case"boolean":{let L=B;L.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")B.type="string",B.nullable=!0,B.enum=[null];else B.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":{B.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let L=B,{minimum:Z,maximum:j}=Y._zod.bag;if(typeof Z==="number")L.minItems=Z;if(typeof j==="number")L.maxItems=j;L.type="array",L.items=this.process(Q.element,{...N,path:[...N.path,"items"]});break}case"object":{let L=B;L.type="object",L.properties={};let Z=Q.shape;for(let P in Z)L.properties[P]=this.process(Z[P],{...N,path:[...N.path,"properties",P]});let j=new Set(Object.keys(Z)),w=new Set([...j].filter((P)=>{let k=Q.shape[P]._zod;if(this.io==="input")return k.optin===void 0;else return k.optout===void 0}));if(w.size>0)L.required=Array.from(w);if(Q.catchall?._zod.def.type==="never")L.additionalProperties=!1;else if(!Q.catchall){if(this.io==="output")L.additionalProperties=!1}else if(Q.catchall)L.additionalProperties=this.process(Q.catchall,{...N,path:[...N.path,"additionalProperties"]});break}case"union":{let L=B,Z=Q.options.map((j,w)=>this.process(j,{...N,path:[...N.path,"anyOf",w]}));L.anyOf=Z;break}case"intersection":{let L=B,Z=this.process(Q.left,{...N,path:[...N.path,"allOf",0]}),j=this.process(Q.right,{...N,path:[...N.path,"allOf",1]}),w=(k)=>("allOf"in k)&&Object.keys(k).length===1,P=[...w(Z)?Z.allOf:[Z],...w(j)?j.allOf:[j]];L.allOf=P;break}case"tuple":{let L=B;L.type="array";let Z=this.target==="draft-2020-12"?"prefixItems":"items",j=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",w=Q.items.map((S,d)=>this.process(S,{...N,path:[...N.path,Z,d]})),P=Q.rest?this.process(Q.rest,{...N,path:[...N.path,j,...this.target==="openapi-3.0"?[Q.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(L.prefixItems=w,P)L.items=P}else if(this.target==="openapi-3.0"){if(L.items={anyOf:w},P)L.items.anyOf.push(P);if(L.minItems=w.length,!P)L.maxItems=w.length}else if(L.items=w,P)L.additionalItems=P;let{minimum:k,maximum:x}=Y._zod.bag;if(typeof k==="number")L.minItems=k;if(typeof x==="number")L.maxItems=x;break}case"record":{let L=B;if(L.type="object",this.target==="draft-7"||this.target==="draft-2020-12")L.propertyNames=this.process(Q.keyType,{...N,path:[...N.path,"propertyNames"]});L.additionalProperties=this.process(Q.valueType,{...N,path:[...N.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 L=B,Z=p1(Q.entries);if(Z.every((j)=>typeof j==="number"))L.type="number";if(Z.every((j)=>typeof j==="string"))L.type="string";L.enum=Z;break}case"literal":{let L=B,Z=[];for(let j of Q.values)if(j===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof j==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else Z.push(Number(j));else Z.push(j);if(Z.length===0);else if(Z.length===1){let j=Z[0];if(L.type=j===null?"null":typeof j,this.target==="draft-4"||this.target==="openapi-3.0")L.enum=[j];else L.const=j}else{if(Z.every((j)=>typeof j==="number"))L.type="number";if(Z.every((j)=>typeof j==="string"))L.type="string";if(Z.every((j)=>typeof j==="boolean"))L.type="string";if(Z.every((j)=>j===null))L.type="null";L.enum=Z}break}case"file":{let L=B,Z={type:"string",format:"binary",contentEncoding:"binary"},{minimum:j,maximum:w,mime:P}=Y._zod.bag;if(j!==void 0)Z.minLength=j;if(w!==void 0)Z.maxLength=w;if(P)if(P.length===1)Z.contentMediaType=P[0],Object.assign(L,Z);else L.anyOf=P.map((k)=>{return{...Z,contentMediaType:k}});else Object.assign(L,Z);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let L=this.process(Q.innerType,N);if(this.target==="openapi-3.0")W.ref=Q.innerType,B.nullable=!0;else B.anyOf=[L,{type:"null"}];break}case"nonoptional":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"success":{let L=B;L.type="boolean";break}case"default":{this.process(Q.innerType,N),W.ref=Q.innerType,B.default=JSON.parse(JSON.stringify(Q.defaultValue));break}case"prefault":{if(this.process(Q.innerType,N),W.ref=Q.innerType,this.io==="input")B._prefault=JSON.parse(JSON.stringify(Q.defaultValue));break}case"catch":{this.process(Q.innerType,N),W.ref=Q.innerType;let L;try{L=Q.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}B.default=L;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let L=B,Z=Y._zod.pattern;if(!Z)throw Error("Pattern not found in template literal");L.type="string",L.pattern=Z.source;break}case"pipe":{let L=this.io==="input"?Q.in._zod.def.type==="transform"?Q.out:Q.in:Q.out;this.process(L,N),W.ref=L;break}case"readonly":{this.process(Q.innerType,N),W.ref=Q.innerType,B.readOnly=!0;break}case"promise":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"optional":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"lazy":{let L=Y._zod.innerType;this.process(L,N),W.ref=L;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"&&W0(Y))delete W.schema.examples,delete W.schema.default;if(this.io==="input"&&W.schema._prefault)(J=W.schema).default??(J.default=W.schema._prefault);return delete W.schema._prefault,this.seen.get(Y).schema}emit(Y,X){let J={cycles:X?.cycles??"ref",reused:X?.reused??"inline",external:X?.external??void 0},Q=this.seen.get(Y);if(!Q)throw Error("Unprocessed schema. This is a bug in Zod.");let $=(U)=>{let N=this.target==="draft-2020-12"?"$defs":"definitions";if(J.external){let Z=J.external.registry.get(U[0])?.id,j=J.external.uri??((P)=>P);if(Z)return{ref:j(Z)};let w=U[1].defId??U[1].schema.id??`schema${this.counter++}`;return U[1].defId=w,{defId:w,ref:`${j("__shared")}#/${N}/${w}`}}if(U[1]===Q)return{ref:"#"};let B=`${"#"}/${N}/`,L=U[1].schema.id??`__schema${this.counter++}`;return{defId:L,ref:B+L}},G=(U)=>{if(U[1].schema.$ref)return;let N=U[1],{ref:O,defId:B}=$(U);if(N.def={...N.schema},B)N.defId=B;let L=N.schema;for(let Z in L)delete L[Z];L.$ref=O};if(J.cycles==="throw")for(let U of this.seen.entries()){let N=U[1];if(N.cycle)throw Error(`Cycle detected: #/${N.cycle?.join("/")}/<root>
|
|
185
|
+
`)}V.write("payload.value = newResult;"),V.write("return payload;");let E=V.compile();return(x,R)=>E(Z,x,R)},G,W=M1,U=!hY.jitless,H=U&&X9.value,N=X.catchall,O;Y._zod.parse=(Z,V)=>{O??(O=Q.value);let K=Z.value;if(!W(K))return Z.issues.push({expected:"object",code:"invalid_type",input:K,inst:Y}),Z;if(U&&H&&V?.async===!1&&V.jitless!==!0){if(!G)G=$(X.shape);if(Z=G(Z,V),!N)return Z;return _7([],K,Z,V,O,Y)}return J(Z,V)}});function dQ(Y,X,J,Q){for(let G of Y)if(G.issues.length===0)return X.value=G.value,X;let $=Y.filter((G)=>!V1(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)=>S0(W,Q,m0())))}),X}var B9=F("$ZodUnion",(Y,X)=>{o.init(Y,X),l(Y._zod,"optin",()=>X.options.some(($)=>$._zod.optin==="optional")?"optional":void 0),l(Y._zod,"optout",()=>X.options.some(($)=>$._zod.optout==="optional")?"optional":void 0),l(Y._zod,"values",()=>{if(X.options.every(($)=>$._zod.values))return new Set(X.options.flatMap(($)=>Array.from($._zod.values)));return}),l(Y._zod,"pattern",()=>{if(X.options.every(($)=>$._zod.pattern)){let $=X.options.map((G)=>G._zod.pattern);return new RegExp(`^(${$.map((G)=>JY(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,U=[];for(let L of X.options){let H=L._zod.run({value:$.value,issues:[]},G);if(H instanceof Promise)U.push(H),W=!0;else{if(H.issues.length===0)return H;U.push(H)}}if(!W)return dQ(U,$,Y,G);return Promise.all(U).then((L)=>{return dQ(L,$,Y,G)})}}),S7=F("$ZodDiscriminatedUnion",(Y,X)=>{B9.init(Y,X);let J=Y._zod.parse;l(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[U,L]of Object.entries(W)){if(!$[U])$[U]=new Set;for(let H of L)$[U].add(H)}}return $});let Q=f1(()=>{let $=X.options,G=new Map;for(let W of $){let U=W._zod.propValues?.[X.discriminator];if(!U||U.size===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf(W)}"`);for(let L of U){if(G.has(L))throw Error(`Duplicate discriminator value "${String(L)}"`);G.set(L,W)}}return G});Y._zod.parse=($,G)=>{let W=$.value;if(!M1(W))return $.issues.push({code:"invalid_type",expected:"object",input:W,inst:Y}),$;let U=Q.value.get(W?.[X.discriminator]);if(U)return U._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}),$}}),k7=F("$ZodIntersection",(Y,X)=>{o.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(([L,H])=>{return iQ(J,L,H)});return iQ(J,G,W)}});function V9(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(L1(Y)&&L1(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=V9(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=V9($,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 iQ(Y,X,J){if(X.issues.length)Y.issues.push(...X.issues);if(J.issues.length)Y.issues.push(...J.issues);if(V1(Y))return Y;let Q=V9(X.value,J.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return Y.value=Q.data,Y}var b7=F("$ZodRecord",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value;if(!L1($))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 L of W)if(typeof L==="string"||typeof L==="number"||typeof L==="symbol"){let H=X.valueType._zod.run({value:$[L],issues:[]},Q);if(H instanceof Promise)G.push(H.then((N)=>{if(N.issues.length)J.issues.push(...e0(L,N.issues));J.value[L]=N.value}));else{if(H.issues.length)J.issues.push(...e0(L,H.issues));J.value[L]=H.value}}let U;for(let L in $)if(!W.has(L))U=U??[],U.push(L);if(U&&U.length>0)J.issues.push({code:"unrecognized_keys",input:$,inst:Y,keys:U})}else{J.value={};for(let W of Reflect.ownKeys($)){if(W==="__proto__")continue;let U=X.keyType._zod.run({value:W,issues:[]},Q);if(U instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(U.issues.length){J.issues.push({code:"invalid_key",origin:"record",issues:U.issues.map((H)=>S0(H,Q,m0())),input:W,path:[W],inst:Y}),J.value[U.value]=U.value;continue}let L=X.valueType._zod.run({value:$[W],issues:[]},Q);if(L instanceof Promise)G.push(L.then((H)=>{if(H.issues.length)J.issues.push(...e0(W,H.issues));J.value[U.value]=H.value}));else{if(L.issues.length)J.issues.push(...e0(W,L.issues));J.value[U.value]=L.value}}}if(G.length)return Promise.all(G).then(()=>J);return J}});var x7=F("$ZodEnum",(Y,X)=>{o.init(Y,X);let J=YY(X.entries),Q=new Set(J);Y._zod.values=Q,Y._zod.pattern=new RegExp(`^(${J.filter(($)=>J9.has(typeof $)).map(($)=>typeof $==="string"?t0($):$.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}),$}}),v7=F("$ZodLiteral",(Y,X)=>{if(o.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"?t0(J):J?t0(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 h7=F("$ZodTransform",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new t1(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 a0;return J.value=$,J}});function nQ(Y,X){if(Y.issues.length&&X===void 0)return{issues:[],value:void 0};return Y}var g7=F("$ZodOptional",(Y,X)=>{o.init(Y,X),Y._zod.optin="optional",Y._zod.optout="optional",l(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,void 0]):void 0}),l(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${JY(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)=>nQ(G,J.value));return nQ($,J.value)}if(J.value===void 0)return J;return X.innerType._zod.run(J,Q)}}),y7=F("$ZodNullable",(Y,X)=>{o.init(Y,X),l(Y._zod,"optin",()=>X.innerType._zod.optin),l(Y._zod,"optout",()=>X.innerType._zod.optout),l(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${JY(J.source)}|null)$`):void 0}),l(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)}}),f7=F("$ZodDefault",(Y,X)=>{o.init(Y,X),Y._zod.optin="optional",l(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)=>oQ(G,X));return oQ($,X)}});function oQ(Y,X){if(Y.value===void 0)Y.value=X.defaultValue;return Y}var m7=F("$ZodPrefault",(Y,X)=>{o.init(Y,X),Y._zod.optin="optional",l(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)}}),c7=F("$ZodNonOptional",(Y,X)=>{o.init(Y,X),l(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)=>rQ(G,Y));return rQ($,Y)}});function rQ(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 u7=F("$ZodCatch",(Y,X)=>{o.init(Y,X),l(Y._zod,"optin",()=>X.innerType._zod.optin),l(Y._zod,"optout",()=>X.innerType._zod.optout),l(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)=>S0(W,Q,m0()))},input:J.value}),J.issues=[];return J});if(J.value=$.value,$.issues.length)J.value=X.catchValue({...J,error:{issues:$.issues.map((G)=>S0(G,Q,m0()))},input:J.value}),J.issues=[];return J}});var p7=F("$ZodPipe",(Y,X)=>{o.init(Y,X),l(Y._zod,"values",()=>X.in._zod.values),l(Y._zod,"optin",()=>X.in._zod.optin),l(Y._zod,"optout",()=>X.out._zod.optout),l(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)=>pY(W,X.in,Q));return pY(G,X.in,Q)}let $=X.in._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>pY(G,X.out,Q));return pY($,X.out,Q)}});function pY(Y,X,J){if(Y.issues.length)return Y.aborted=!0,Y;return X._zod.run({value:Y.value,issues:Y.issues},J)}var l7=F("$ZodReadonly",(Y,X)=>{o.init(Y,X),l(Y._zod,"propValues",()=>X.innerType._zod.propValues),l(Y._zod,"values",()=>X.innerType._zod.values),l(Y._zod,"optin",()=>X.innerType._zod.optin),l(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(sQ);return sQ($)}});function sQ(Y){return Y.value=Object.freeze(Y.value),Y}var d7=F("$ZodLazy",(Y,X)=>{o.init(Y,X),l(Y._zod,"innerType",()=>X.getter()),l(Y._zod,"pattern",()=>Y._zod.innerType._zod.pattern),l(Y._zod,"propValues",()=>Y._zod.innerType._zod.propValues),l(Y._zod,"optin",()=>Y._zod.innerType._zod.optin??void 0),l(Y._zod,"optout",()=>Y._zod.innerType._zod.optout??void 0),Y._zod.parse=(J,Q)=>{return Y._zod.innerType._zod.run(J,Q)}}),i7=F("$ZodCustom",(Y,X)=>{V0.init(Y,X),o.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)=>aQ(G,J,Q,Y));aQ($,J,Q,Y);return}});function aQ(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(m1($))}}var yK=Symbol("ZodOutput"),fK=Symbol("ZodInput");class iY{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 JU(){return new iY}var w1=JU();function n7(Y,X){return new Y({type:"string",...v(X)})}function o7(Y,X){return new Y({type:"string",format:"email",check:"string_format",abort:!1,...v(X)})}function Z9(Y,X){return new Y({type:"string",format:"guid",check:"string_format",abort:!1,...v(X)})}function r7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...v(X)})}function s7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...v(X)})}function a7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...v(X)})}function t7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...v(X)})}function e7(Y,X){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...v(X)})}function Y$(Y,X){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...v(X)})}function X$(Y,X){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...v(X)})}function J$(Y,X){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...v(X)})}function Q$(Y,X){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...v(X)})}function $$(Y,X){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...v(X)})}function G$(Y,X){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...v(X)})}function W$(Y,X){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...v(X)})}function z$(Y,X){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...v(X)})}function U$(Y,X){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...v(X)})}function H$(Y,X){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...v(X)})}function L$(Y,X){return new Y({type:"string",format:"cidrv6",check:"string_format",abort:!1,...v(X)})}function V$(Y,X){return new Y({type:"string",format:"base64",check:"string_format",abort:!1,...v(X)})}function N$(Y,X){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...v(X)})}function B$(Y,X){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...v(X)})}function Z$(Y,X){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...v(X)})}function K$(Y,X){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...v(X)})}function O$(Y,X){return new Y({type:"string",format:"date",check:"string_format",...v(X)})}function q$(Y,X){return new Y({type:"string",format:"time",check:"string_format",precision:null,...v(X)})}function F$(Y,X){return new Y({type:"string",format:"duration",check:"string_format",...v(X)})}function j$(Y,X){return new Y({type:"number",checks:[],...v(X)})}function D$(Y,X){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...v(X)})}function P$(Y,X){return new Y({type:"boolean",...v(X)})}function M$(Y,X){return new Y({type:"null",...v(X)})}function w$(Y){return new Y({type:"unknown"})}function E$(Y,X){return new Y({type:"never",...v(X)})}function nY(Y,X){return new U9({check:"less_than",...v(X),value:Y,inclusive:!1})}function zY(Y,X){return new U9({check:"less_than",...v(X),value:Y,inclusive:!0})}function oY(Y,X){return new H9({check:"greater_than",...v(X),value:Y,inclusive:!1})}function UY(Y,X){return new H9({check:"greater_than",...v(X),value:Y,inclusive:!0})}function rY(Y,X){return new IQ({check:"multiple_of",...v(X),value:Y})}function sY(Y,X){return new kQ({check:"max_length",...v(X),maximum:Y})}function c1(Y,X){return new bQ({check:"min_length",...v(X),minimum:Y})}function aY(Y,X){return new xQ({check:"length_equals",...v(X),length:Y})}function K9(Y,X){return new vQ({check:"string_format",format:"regex",...v(X),pattern:Y})}function O9(Y){return new hQ({check:"string_format",format:"lowercase",...v(Y)})}function q9(Y){return new gQ({check:"string_format",format:"uppercase",...v(Y)})}function F9(Y,X){return new yQ({check:"string_format",format:"includes",...v(X),includes:Y})}function j9(Y,X){return new fQ({check:"string_format",format:"starts_with",...v(X),prefix:Y})}function D9(Y,X){return new mQ({check:"string_format",format:"ends_with",...v(X),suffix:Y})}function E1(Y){return new cQ({check:"overwrite",tx:Y})}function P9(Y){return E1((X)=>X.normalize(Y))}function M9(){return E1((Y)=>Y.trim())}function w9(){return E1((Y)=>Y.toLowerCase())}function E9(){return E1((Y)=>Y.toUpperCase())}function A$(Y,X,J){return new Y({type:"array",element:X,...v(J)})}function T$(Y,X,J){let Q=v(J);return Q.abort??(Q.abort=!0),new Y({type:"custom",check:"custom",fn:X,...Q})}function R$(Y,X,J){return new Y({type:"custom",check:"custom",fn:X,...v(J)})}function C$(Y){let X=QU((J)=>{return J.addIssue=(Q)=>{if(typeof Q==="string")J.issues.push(m1(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(m1($))}},Y(J.value,J)});return X}function QU(Y,X){let J=new V0({check:"custom",...v(X)});return J._zod.check=Y,J}class A9{constructor(Y){this.counter=0,this.metadataRegistry=Y?.metadata??w1,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 U=Y._zod.toJSONSchema?.();if(U)W.schema=U;else{let N={...X,schemaPath:[...X.schemaPath,Y],path:X.path},O=Y._zod.parent;if(O)W.ref=O,this.process(O,N),this.seen.get(O).isParent=!0;else{let Z=W.schema;switch(Q.type){case"string":{let V=Z;V.type="string";let{minimum:K,maximum:j,format:M,patterns:I,contentEncoding:E}=Y._zod.bag;if(typeof K==="number")V.minLength=K;if(typeof j==="number")V.maxLength=j;if(M){if(V.format=$[M]??M,V.format==="")delete V.format}if(E)V.contentEncoding=E;if(I&&I.size>0){let x=[...I];if(x.length===1)V.pattern=x[0].source;else if(x.length>1)W.schema.allOf=[...x.map((R)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:R.source}))]}break}case"number":{let V=Z,{minimum:K,maximum:j,format:M,multipleOf:I,exclusiveMaximum:E,exclusiveMinimum:x}=Y._zod.bag;if(typeof M==="string"&&M.includes("int"))V.type="integer";else V.type="number";if(typeof x==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")V.minimum=x,V.exclusiveMinimum=!0;else V.exclusiveMinimum=x;if(typeof K==="number"){if(V.minimum=K,typeof x==="number"&&this.target!=="draft-4")if(x>=K)delete V.minimum;else delete V.exclusiveMinimum}if(typeof E==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")V.maximum=E,V.exclusiveMaximum=!0;else V.exclusiveMaximum=E;if(typeof j==="number"){if(V.maximum=j,typeof E==="number"&&this.target!=="draft-4")if(E<=j)delete V.maximum;else delete V.exclusiveMaximum}if(typeof I==="number")V.multipleOf=I;break}case"boolean":{let V=Z;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")Z.type="string",Z.nullable=!0,Z.enum=[null];else Z.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":{Z.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let V=Z,{minimum:K,maximum:j}=Y._zod.bag;if(typeof K==="number")V.minItems=K;if(typeof j==="number")V.maxItems=j;V.type="array",V.items=this.process(Q.element,{...N,path:[...N.path,"items"]});break}case"object":{let V=Z;V.type="object",V.properties={};let K=Q.shape;for(let I in K)V.properties[I]=this.process(K[I],{...N,path:[...N.path,"properties",I]});let j=new Set(Object.keys(K)),M=new Set([...j].filter((I)=>{let E=Q.shape[I]._zod;if(this.io==="input")return E.optin===void 0;else return E.optout===void 0}));if(M.size>0)V.required=Array.from(M);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,{...N,path:[...N.path,"additionalProperties"]});break}case"union":{let V=Z,K=Q.options.map((j,M)=>this.process(j,{...N,path:[...N.path,"anyOf",M]}));V.anyOf=K;break}case"intersection":{let V=Z,K=this.process(Q.left,{...N,path:[...N.path,"allOf",0]}),j=this.process(Q.right,{...N,path:[...N.path,"allOf",1]}),M=(E)=>("allOf"in E)&&Object.keys(E).length===1,I=[...M(K)?K.allOf:[K],...M(j)?j.allOf:[j]];V.allOf=I;break}case"tuple":{let V=Z;V.type="array";let K=this.target==="draft-2020-12"?"prefixItems":"items",j=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",M=Q.items.map((R,p)=>this.process(R,{...N,path:[...N.path,K,p]})),I=Q.rest?this.process(Q.rest,{...N,path:[...N.path,j,...this.target==="openapi-3.0"?[Q.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(V.prefixItems=M,I)V.items=I}else if(this.target==="openapi-3.0"){if(V.items={anyOf:M},I)V.items.anyOf.push(I);if(V.minItems=M.length,!I)V.maxItems=M.length}else if(V.items=M,I)V.additionalItems=I;let{minimum:E,maximum:x}=Y._zod.bag;if(typeof E==="number")V.minItems=E;if(typeof x==="number")V.maxItems=x;break}case"record":{let V=Z;if(V.type="object",this.target==="draft-7"||this.target==="draft-2020-12")V.propertyNames=this.process(Q.keyType,{...N,path:[...N.path,"propertyNames"]});V.additionalProperties=this.process(Q.valueType,{...N,path:[...N.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=Z,K=YY(Q.entries);if(K.every((j)=>typeof j==="number"))V.type="number";if(K.every((j)=>typeof j==="string"))V.type="string";V.enum=K;break}case"literal":{let V=Z,K=[];for(let j of Q.values)if(j===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof j==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else K.push(Number(j));else K.push(j);if(K.length===0);else if(K.length===1){let j=K[0];if(V.type=j===null?"null":typeof j,this.target==="draft-4"||this.target==="openapi-3.0")V.enum=[j];else V.const=j}else{if(K.every((j)=>typeof j==="number"))V.type="number";if(K.every((j)=>typeof j==="string"))V.type="string";if(K.every((j)=>typeof j==="boolean"))V.type="string";if(K.every((j)=>j===null))V.type="null";V.enum=K}break}case"file":{let V=Z,K={type:"string",format:"binary",contentEncoding:"binary"},{minimum:j,maximum:M,mime:I}=Y._zod.bag;if(j!==void 0)K.minLength=j;if(M!==void 0)K.maxLength=M;if(I)if(I.length===1)K.contentMediaType=I[0],Object.assign(V,K);else V.anyOf=I.map((E)=>{return{...K,contentMediaType:E}});else Object.assign(V,K);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,N);if(this.target==="openapi-3.0")W.ref=Q.innerType,Z.nullable=!0;else Z.anyOf=[V,{type:"null"}];break}case"nonoptional":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"success":{let V=Z;V.type="boolean";break}case"default":{this.process(Q.innerType,N),W.ref=Q.innerType,Z.default=JSON.parse(JSON.stringify(Q.defaultValue));break}case"prefault":{if(this.process(Q.innerType,N),W.ref=Q.innerType,this.io==="input")Z._prefault=JSON.parse(JSON.stringify(Q.defaultValue));break}case"catch":{this.process(Q.innerType,N),W.ref=Q.innerType;let V;try{V=Q.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}Z.default=V;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let V=Z,K=Y._zod.pattern;if(!K)throw Error("Pattern not found in template literal");V.type="string",V.pattern=K.source;break}case"pipe":{let V=this.io==="input"?Q.in._zod.def.type==="transform"?Q.out:Q.in:Q.out;this.process(V,N),W.ref=V;break}case"readonly":{this.process(Q.innerType,N),W.ref=Q.innerType,Z.readOnly=!0;break}case"promise":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"optional":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"lazy":{let V=Y._zod.innerType;this.process(V,N),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 L=this.metadataRegistry.get(Y);if(L)Object.assign(W.schema,L);if(this.io==="input"&&z0(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 $=(H)=>{let N=this.target==="draft-2020-12"?"$defs":"definitions";if(J.external){let K=J.external.registry.get(H[0])?.id,j=J.external.uri??((I)=>I);if(K)return{ref:j(K)};let M=H[1].defId??H[1].schema.id??`schema${this.counter++}`;return H[1].defId=M,{defId:M,ref:`${j("__shared")}#/${N}/${M}`}}if(H[1]===Q)return{ref:"#"};let Z=`${"#"}/${N}/`,V=H[1].schema.id??`__schema${this.counter++}`;return{defId:V,ref:Z+V}},G=(H)=>{if(H[1].schema.$ref)return;let N=H[1],{ref:O,defId:Z}=$(H);if(N.def={...N.schema},Z)N.defId=Z;let V=N.schema;for(let K in V)delete V[K];V.$ref=O};if(J.cycles==="throw")for(let H of this.seen.entries()){let N=H[1];if(N.cycle)throw Error(`Cycle detected: #/${N.cycle?.join("/")}/<root>
|
|
136
186
|
|
|
137
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let U of this.seen.entries()){let N=U[1];if(Y===U[0]){G(U);continue}if(J.external){let B=J.external.registry.get(U[0])?.id;if(Y!==U[0]&&B){G(U);continue}}if(this.metadataRegistry.get(U[0])?.id){G(U);continue}if(N.cycle){G(U);continue}if(N.count>1){if(J.reused==="ref"){G(U);continue}}}let W=(U,N)=>{let O=this.seen.get(U),B=O.def??O.schema,L={...B};if(O.ref===null)return;let Z=O.ref;if(O.ref=null,Z){W(Z,N);let j=this.seen.get(Z).schema;if(j.$ref&&(N.target==="draft-7"||N.target==="draft-4"||N.target==="openapi-3.0"))B.allOf=B.allOf??[],B.allOf.push(j);else Object.assign(B,j),Object.assign(B,L)}if(!O.isParent)this.override({zodSchema:U,jsonSchema:B,path:O.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 N=U[1];if(N.def&&N.defId)H[N.defId]=N.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 s7(Y,X){if(Y instanceof vY){let Q=new U9(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 U9(X);return J.process(Y),J.emit(Y,X)}function W0(Y,X){let J=X??{seen:new Set};if(J.seen.has(Y))return!1;J.seen.add(Y);let $=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 W0($.element,J);case"object":{for(let G in $.shape)if(W0($.shape[G],J))return!0;return!1}case"union":{for(let G of $.options)if(W0(G,J))return!0;return!1}case"intersection":return W0($.left,J)||W0($.right,J);case"tuple":{for(let G of $.items)if(W0(G,J))return!0;if($.rest&&W0($.rest,J))return!0;return!1}case"record":return W0($.keyType,J)||W0($.valueType,J);case"map":return W0($.keyType,J)||W0($.valueType,J);case"set":return W0($.valueType,J);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return W0($.innerType,J);case"lazy":return W0($.getter(),J);case"default":return W0($.innerType,J);case"prefault":return W0($.innerType,J);case"custom":return!1;case"transform":return!0;case"pipe":return W0($.in,J)||W0($.out,J);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${$.type}`)}var zz=q("ZodISODateTime",(Y,X)=>{IQ.init(Y,X),o.init(Y,X)});function a7(Y){return h7(zz,Y)}var Kz=q("ZodISODate",(Y,X)=>{SQ.init(Y,X),o.init(Y,X)});function t7(Y){return g7(Kz,Y)}var Uz=q("ZodISOTime",(Y,X)=>{kQ.init(Y,X),o.init(Y,X)});function e7(Y){return y7(Uz,Y)}var Hz=q("ZodISODuration",(Y,X)=>{bQ.init(Y,X),o.init(Y,X)});function Y$(Y){return f7(Hz,Y)}var X$=(Y,X)=>{CY.init(Y,X),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(J)=>H6(Y,J)},flatten:{value:(J)=>U6(Y,J)},addIssue:{value:(J)=>{Y.issues.push(J),Y.message=JSON.stringify(Y.issues,C1,2)}},addIssues:{value:(J)=>{Y.issues.push(...J),Y.message=JSON.stringify(Y.issues,C1,2)}},isEmpty:{get(){return Y.issues.length===0}}})},UZ=q("ZodError",X$),E0=q("ZodError",X$,{Parent:Error});var J$=_Y(E0),Q$=IY(E0),$$=n1(E0),uY=o1(E0),G$=V6(E0),W$=B6(E0),z$=Z6(E0),K$=O6(E0),U$=F6(E0),H$=q6(E0),L$=j6(E0),N$=D6(E0);var r=q("ZodType",(Y,X)=>{return i.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)=>C0(Y,J,Q),Y.brand=()=>Y,Y.register=(J,Q)=>{return J.add(Y,Q),Y},Y.parse=(J,Q)=>J$(Y,J,Q,{callee:Y.parse}),Y.safeParse=(J,Q)=>$$(Y,J,Q),Y.parseAsync=async(J,Q)=>Q$(Y,J,Q,{callee:Y.parseAsync}),Y.safeParseAsync=async(J,Q)=>uY(Y,J,Q),Y.spa=Y.safeParseAsync,Y.encode=(J,Q)=>G$(Y,J,Q),Y.decode=(J,Q)=>W$(Y,J,Q),Y.encodeAsync=async(J,Q)=>z$(Y,J,Q),Y.decodeAsync=async(J,Q)=>K$(Y,J,Q),Y.safeEncode=(J,Q)=>U$(Y,J,Q),Y.safeDecode=(J,Q)=>H$(Y,J,Q),Y.safeEncodeAsync=async(J,Q)=>L$(Y,J,Q),Y.safeDecodeAsync=async(J,Q)=>N$(Y,J,Q),Y.refine=(J,Q)=>Y.check(QK(J,Q)),Y.superRefine=(J)=>Y.check($K(J)),Y.overwrite=(J)=>Y.check(Z1(J)),Y.optional=()=>Z$(Y),Y.nullable=()=>O$(Y),Y.nullish=()=>Z$(O$(Y)),Y.nonoptional=(J)=>sz(Y,J),Y.array=()=>N9(Y),Y.or=(J)=>V9([Y,J]),Y.and=(J)=>mz(Y,J),Y.transform=(J)=>F$(Y,lz(J)),Y.default=(J)=>nz(Y,J),Y.prefault=(J)=>rz(Y,J),Y.catch=(J)=>tz(Y,J),Y.pipe=(J)=>F$(Y,J),Y.readonly=()=>XK(Y),Y.describe=(J)=>{let Q=Y.clone();return B1.add(Q,{description:J}),Q},Object.defineProperty(Y,"description",{get(){return B1.get(Y)?.description},configurable:!0}),Y.meta=(...J)=>{if(J.length===0)return B1.get(Y);let Q=Y.clone();return B1.add(Q,J[0]),Q},Y.isOptional=()=>Y.safeParse(void 0).success,Y.isNullable=()=>Y.safeParse(null).success,Y}),q$=q("_ZodString",(Y,X)=>{xY.init(Y,X),r.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(e8(...Q)),Y.includes=(...Q)=>Y.check(J9(...Q)),Y.startsWith=(...Q)=>Y.check(Q9(...Q)),Y.endsWith=(...Q)=>Y.check($9(...Q)),Y.min=(...Q)=>Y.check(S1(...Q)),Y.max=(...Q)=>Y.check(fY(...Q)),Y.length=(...Q)=>Y.check(mY(...Q)),Y.nonempty=(...Q)=>Y.check(S1(1,...Q)),Y.lowercase=(Q)=>Y.check(Y9(Q)),Y.uppercase=(Q)=>Y.check(X9(Q)),Y.trim=()=>Y.check(W9()),Y.normalize=(...Q)=>Y.check(G9(...Q)),Y.toLowerCase=()=>Y.check(z9()),Y.toUpperCase=()=>Y.check(K9())}),Bz=q("ZodString",(Y,X)=>{xY.init(Y,X),q$.init(Y,X),Y.email=(J)=>Y.check(Z7(Zz,J)),Y.url=(J)=>Y.check(D7(Oz,J)),Y.jwt=(J)=>Y.check(v7(Sz,J)),Y.emoji=(J)=>Y.check(P7(Fz,J)),Y.guid=(J)=>Y.check(t8(V$,J)),Y.uuid=(J)=>Y.check(O7(pY,J)),Y.uuidv4=(J)=>Y.check(F7(pY,J)),Y.uuidv6=(J)=>Y.check(q7(pY,J)),Y.uuidv7=(J)=>Y.check(j7(pY,J)),Y.nanoid=(J)=>Y.check(w7(qz,J)),Y.guid=(J)=>Y.check(t8(V$,J)),Y.cuid=(J)=>Y.check(E7(jz,J)),Y.cuid2=(J)=>Y.check(M7(Dz,J)),Y.ulid=(J)=>Y.check(A7(Pz,J)),Y.base64=(J)=>Y.check(k7(Cz,J)),Y.base64url=(J)=>Y.check(b7(_z,J)),Y.xid=(J)=>Y.check(R7(wz,J)),Y.ksuid=(J)=>Y.check(T7(Ez,J)),Y.ipv4=(J)=>Y.check(C7(Mz,J)),Y.ipv6=(J)=>Y.check(_7(Az,J)),Y.cidrv4=(J)=>Y.check(I7(Rz,J)),Y.cidrv6=(J)=>Y.check(S7(Tz,J)),Y.e164=(J)=>Y.check(x7(Iz,J)),Y.datetime=(J)=>Y.check(a7(J)),Y.date=(J)=>Y.check(t7(J)),Y.time=(J)=>Y.check(e7(J)),Y.duration=(J)=>Y.check(Y$(J))});function j$(Y){return B7(Bz,Y)}var o=q("ZodStringFormat",(Y,X)=>{n.init(Y,X),q$.init(Y,X)}),Zz=q("ZodEmail",(Y,X)=>{PQ.init(Y,X),o.init(Y,X)});var V$=q("ZodGUID",(Y,X)=>{jQ.init(Y,X),o.init(Y,X)});var pY=q("ZodUUID",(Y,X)=>{DQ.init(Y,X),o.init(Y,X)});var Oz=q("ZodURL",(Y,X)=>{wQ.init(Y,X),o.init(Y,X)});var Fz=q("ZodEmoji",(Y,X)=>{EQ.init(Y,X),o.init(Y,X)});var qz=q("ZodNanoID",(Y,X)=>{MQ.init(Y,X),o.init(Y,X)});var jz=q("ZodCUID",(Y,X)=>{AQ.init(Y,X),o.init(Y,X)});var Dz=q("ZodCUID2",(Y,X)=>{RQ.init(Y,X),o.init(Y,X)});var Pz=q("ZodULID",(Y,X)=>{TQ.init(Y,X),o.init(Y,X)});var wz=q("ZodXID",(Y,X)=>{CQ.init(Y,X),o.init(Y,X)});var Ez=q("ZodKSUID",(Y,X)=>{_Q.init(Y,X),o.init(Y,X)});var Mz=q("ZodIPv4",(Y,X)=>{xQ.init(Y,X),o.init(Y,X)});var Az=q("ZodIPv6",(Y,X)=>{vQ.init(Y,X),o.init(Y,X)});var Rz=q("ZodCIDRv4",(Y,X)=>{hQ.init(Y,X),o.init(Y,X)});var Tz=q("ZodCIDRv6",(Y,X)=>{gQ.init(Y,X),o.init(Y,X)});var Cz=q("ZodBase64",(Y,X)=>{fQ.init(Y,X),o.init(Y,X)});var _z=q("ZodBase64URL",(Y,X)=>{mQ.init(Y,X),o.init(Y,X)});var Iz=q("ZodE164",(Y,X)=>{cQ.init(Y,X),o.init(Y,X)});var Sz=q("ZodJWT",(Y,X)=>{uQ.init(Y,X),o.init(Y,X)});var D$=q("ZodNumber",(Y,X)=>{s8.init(Y,X),r.init(Y,X),Y.gt=(Q,$)=>Y.check(gY(Q,$)),Y.gte=(Q,$)=>Y.check(a1(Q,$)),Y.min=(Q,$)=>Y.check(a1(Q,$)),Y.lt=(Q,$)=>Y.check(hY(Q,$)),Y.lte=(Q,$)=>Y.check(s1(Q,$)),Y.max=(Q,$)=>Y.check(s1(Q,$)),Y.int=(Q)=>Y.check(B$(Q)),Y.safe=(Q)=>Y.check(B$(Q)),Y.positive=(Q)=>Y.check(gY(0,Q)),Y.nonnegative=(Q)=>Y.check(a1(0,Q)),Y.negative=(Q)=>Y.check(hY(0,Q)),Y.nonpositive=(Q)=>Y.check(s1(0,Q)),Y.multipleOf=(Q,$)=>Y.check(yY(Q,$)),Y.step=(Q,$)=>Y.check(yY(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 P$(Y){return m7(D$,Y)}var kz=q("ZodNumberFormat",(Y,X)=>{pQ.init(Y,X),D$.init(Y,X)});function B$(Y){return c7(kz,Y)}var bz=q("ZodBoolean",(Y,X)=>{lQ.init(Y,X),r.init(Y,X)});function w$(Y){return u7(bz,Y)}var xz=q("ZodNull",(Y,X)=>{dQ.init(Y,X),r.init(Y,X)});function E$(Y){return p7(xz,Y)}var vz=q("ZodUnknown",(Y,X)=>{iQ.init(Y,X),r.init(Y,X)});function t1(){return l7(vz)}var hz=q("ZodNever",(Y,X)=>{nQ.init(Y,X),r.init(Y,X)});function L9(Y){return d7(hz,Y)}var gz=q("ZodArray",(Y,X)=>{oQ.init(Y,X),r.init(Y,X),Y.element=X.element,Y.min=(J,Q)=>Y.check(S1(J,Q)),Y.nonempty=(J)=>Y.check(S1(1,J)),Y.max=(J,Q)=>Y.check(fY(J,Q)),Y.length=(J,Q)=>Y.check(mY(J,Q)),Y.unwrap=()=>Y.element});function N9(Y,X){return i7(gz,Y,X)}var M$=q("ZodObject",(Y,X)=>{aQ.init(Y,X),r.init(Y,X),c.defineLazy(Y,"shape",()=>X.shape),Y.keyof=()=>B9(Object.keys(Y._zod.def.shape)),Y.catchall=(J)=>Y.clone({...Y._zod.def,catchall:J}),Y.passthrough=()=>Y.clone({...Y._zod.def,catchall:t1()}),Y.loose=()=>Y.clone({...Y._zod.def,catchall:t1()}),Y.strict=()=>Y.clone({...Y._zod.def,catchall:L9()}),Y.strip=()=>Y.clone({...Y._zod.def,catchall:void 0}),Y.extend=(J)=>{return c.extend(Y,J)},Y.safeExtend=(J)=>{return c.safeExtend(Y,J)},Y.merge=(J)=>c.merge(Y,J),Y.pick=(J)=>c.pick(Y,J),Y.omit=(J)=>c.omit(Y,J),Y.partial=(...J)=>c.partial(S$,Y,J[0]),Y.required=(...J)=>c.required(k$,Y,J[0])});function A$(Y,X){let J={type:"object",get shape(){return c.assignProp(this,"shape",Y?c.objectClone(Y):{}),this.shape},...c.normalizeParams(X)};return new M$(J)}function R$(Y,X){return new M$({type:"object",get shape(){return c.assignProp(this,"shape",c.objectClone(Y)),this.shape},catchall:t1(),...c.normalizeParams(X)})}var T$=q("ZodUnion",(Y,X)=>{a8.init(Y,X),r.init(Y,X),Y.options=X.options});function V9(Y,X){return new T$({type:"union",options:Y,...c.normalizeParams(X)})}var yz=q("ZodDiscriminatedUnion",(Y,X)=>{T$.init(Y,X),tQ.init(Y,X)});function C$(Y,X,J){return new yz({type:"union",options:X,discriminator:Y,...c.normalizeParams(J)})}var fz=q("ZodIntersection",(Y,X)=>{eQ.init(Y,X),r.init(Y,X)});function mz(Y,X){return new fz({type:"intersection",left:Y,right:X})}var cz=q("ZodRecord",(Y,X)=>{Y7.init(Y,X),r.init(Y,X),Y.keyType=X.keyType,Y.valueType=X.valueType});function _$(Y,X,J){return new cz({type:"record",keyType:Y,valueType:X,...c.normalizeParams(J)})}var H9=q("ZodEnum",(Y,X)=>{X7.init(Y,X),r.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 H9({...X,checks:[],...c.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 H9({...X,checks:[],...c.normalizeParams($),entries:G})}});function B9(Y,X){let J=Array.isArray(Y)?Object.fromEntries(Y.map((Q)=>[Q,Q])):Y;return new H9({type:"enum",entries:J,...c.normalizeParams(X)})}var uz=q("ZodLiteral",(Y,X)=>{J7.init(Y,X),r.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 I$(Y,X){return new uz({type:"literal",values:Array.isArray(Y)?Y:[Y],...c.normalizeParams(X)})}var pz=q("ZodTransform",(Y,X)=>{Q7.init(Y,X),r.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new c1(Y.constructor.name);J.addIssue=(G)=>{if(typeof G==="string")J.issues.push(c.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(c.issue(W))}};let $=X.transform(J.value,J);if($ instanceof Promise)return $.then((G)=>{return J.value=G,J});return J.value=$,J}});function lz(Y){return new pz({type:"transform",transform:Y})}var S$=q("ZodOptional",(Y,X)=>{$7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function Z$(Y){return new S$({type:"optional",innerType:Y})}var dz=q("ZodNullable",(Y,X)=>{G7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function O$(Y){return new dz({type:"nullable",innerType:Y})}var iz=q("ZodDefault",(Y,X)=>{W7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function nz(Y,X){return new iz({type:"default",innerType:Y,get defaultValue(){return typeof X==="function"?X():c.shallowClone(X)}})}var oz=q("ZodPrefault",(Y,X)=>{z7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function rz(Y,X){return new oz({type:"prefault",innerType:Y,get defaultValue(){return typeof X==="function"?X():c.shallowClone(X)}})}var k$=q("ZodNonOptional",(Y,X)=>{K7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function sz(Y,X){return new k$({type:"nonoptional",innerType:Y,...c.normalizeParams(X)})}var az=q("ZodCatch",(Y,X)=>{U7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function tz(Y,X){return new az({type:"catch",innerType:Y,catchValue:typeof X==="function"?X:()=>X})}var ez=q("ZodPipe",(Y,X)=>{H7.init(Y,X),r.init(Y,X),Y.in=X.in,Y.out=X.out});function F$(Y,X){return new ez({type:"pipe",in:Y,out:X})}var YK=q("ZodReadonly",(Y,X)=>{L7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function XK(Y){return new YK({type:"readonly",innerType:Y})}var JK=q("ZodLazy",(Y,X)=>{N7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.getter()});function b$(Y){return new JK({type:"lazy",getter:Y})}var Z9=q("ZodCustom",(Y,X)=>{V7.init(Y,X),r.init(Y,X)});function x$(Y,X){return n7(Z9,Y??(()=>!0),X)}function QK(Y,X={}){return o7(Z9,Y,X)}function $K(Y){return r7(Y)}function v$(Y,X={error:`Input not instance of ${Y.name}`}){let J=new Z9({type:"custom",check:"custom",fn:(Q)=>Q instanceof Y,abort:!0,...c.normalizeParams(X)});return J._zod.bag.Class=Y,J}var GK=[{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]}],sZ=[...GK,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];var WK=12,zK=131072,aZ=zK+WK;async function lY(Y){var X;try{await((X=Y.body)==null?void 0:X.cancel())}catch(J){}}var d$="AI_DownloadError",i$=`vercel.ai.error.${d$}`,KK=Symbol.for(i$),h$,g$,F0=class extends(g$=f,h$=KK,g$){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:d$,message:$,cause:Q});this[h$]=!0,this.url=Y,this.statusCode=X,this.statusText=J}static isInstance(Y){return f.hasMarker(Y,i$)}};function UK(Y=globalThis){return Y.window!=null}function y$(Y,X){try{return new URL(Y).origin===new URL(X).origin}catch(J){return!1}}function HK(Y){let X;try{X=new URL(Y)}catch(Q){throw new F0({url:Y,message:`Invalid URL: ${Y}`})}if(X.protocol==="data:")return;if(X.protocol!=="http:"&&X.protocol!=="https:")throw new F0({url:Y,message:`URL scheme must be http, https, or data, got ${X.protocol}`});let J=X.hostname.toLowerCase().replace(/\.+$/,"");if(!J)throw new F0({url:Y,message:"URL must have a hostname"});if(J==="localhost"||J.endsWith(".local")||J.endsWith(".localhost"))throw new F0({url:Y,message:`URL with hostname ${J} is not allowed`});if(J.startsWith("[")&&J.endsWith("]")){let Q=J.slice(1,-1);if(n$(Q))throw new F0({url:Y,message:`URL with IPv6 address ${J} is not allowed`});return}if(P9(J)){if(w9(J))throw new F0({url:Y,message:`URL with IP address ${J} is not allowed`});return}}function LK({address:Y,family:X,hostname:J}){if(X===4?!P9(Y)||w9(Y):X===6?n$(Y):!0)throw new F0({url:J,message:`Hostname ${J} resolved to disallowed IP address ${Y}`})}function P9(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 w9(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 NK(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 N=H[U];if(N.includes(".")){if(U!==H.length-1||!P9(N))return null;let[O,B,L,Z]=N.split(".").map(Number);K.push(O<<8|B,L<<8|Z);continue}if(!/^[0-9a-f]{1,4}$/.test(N))return null;K.push(parseInt(N,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 n$(Y){let X=NK(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 w9(`${$}.${G}.${W}.${K}`)}return!1}function VK(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)LK({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 O9,o$=globalThis.fetch,BK=FK(o$);function ZK(){var Y,X;let J=globalThis.process;return((Y=J==null?void 0:J.release)==null?void 0:Y.name)==="node"&&((X=J.versions)==null?void 0:X.bun)==null}async function OK(){if(!ZK()||!BK||globalThis.fetch!==o$)return globalThis.fetch;return O9!=null?O9:O9=Promise.resolve().then(qK)}function FK(Y){if(typeof Y!=="function")return!1;let X=Function.prototype.toString.call(Y);return X.includes("internal/deps/undici")||X.includes("lazy loading of undici")}function qK(){let{createRequire:Y}=f$("node:module"),{lookup:X}=f$("node:dns"),{Agent:J,fetch:Q}=Y(r$())("undici"),$=new J({connect:{lookup:VK(X)}});return(G,W)=>Q(G,{...W,dispatcher:$})}function f$(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 r$(){let Y=Error.prepareStackTrace;try{Error.prepareStackTrace=($,G)=>G;let X=Error("Capture current module path");Error.captureStackTrace(X,r$);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 jK=["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 DK(Y){let X=new Headers(Y);for(let J of jK)X.delete(J);return X}var PK=10,wK=new Set([301,302,303,307,308]);async function s$({url:Y,headers:X,abortSignal:J,maxRedirects:Q=PK,fetch:$,trustedOrigin:G}){let W=X===void 0?void 0:DK(X),K=(U)=>{let N={signal:J,redirect:U};if(W!==void 0)N.headers=new Headers(W);return N},H=Y;for(let U=0;U<=Q;U++){let N=G!==void 0&&y$(H,G);if(!N)HK(H);let O=$!=null?$:N?globalThis.fetch:await OK(),B=await O(H,K("manual"));if(B.type==="opaqueredirect"){if(!UK())throw new F0({url:Y,message:`Redirect from ${H} could not be validated and was blocked`});return await O(H,K("follow"))}let L=B.headers.get("location");if(wK.has(B.status)&&L){await lY(B);let Z=new URL(L,H).toString();if(W!==void 0&&!y$(Z,H)){let j=W.get("user-agent");W=new Headers(j==null?void 0:{"user-agent":j})}H=Z;continue}return B}throw new F0({url:Y,message:`Too many redirects (max ${Q})`})}var E9=2147483648;async function a$({response:Y,url:X,maxBytes:J=E9}){let Q=Y.headers.get("content-length");if(Q!=null){let N=parseInt(Q,10);if(!isNaN(N)&&N>J)throw await lY(Y),new F0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes (Content-Length: ${N}).`})}let $=Y.body;if($==null)return new Uint8Array(0);let G=$.getReader(),W=[],K=0;try{while(!0){let{done:N,value:O}=await G.read();if(N)break;if(K+=O.length,K>J)throw new F0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes.`});W.push(O)}}finally{try{await G.cancel()}finally{G.releaseLock()}}let H=new Uint8Array(K),U=0;for(let N of W)H.set(N,U),U+=N.length;return H}var J0=({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 IJ({argument:"separator",message:`The separator "${Q}" must not be part of the alphabet "${J}".`});return()=>`${Y}${Q}${$()}`},YO=J0();function t$(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 EK(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 k1(Y,...X){let J=new Headers(EK(Y)),Q=J.get("user-agent")||"";return J.set("user-agent",[Q,...X].filter(Boolean).join(" ")),Object.fromEntries(J.entries())}function e$(Y){var X,J;return(J=(X=globalThis.Buffer)==null?void 0:X.isBuffer(Y))!=null?J:!1}var MK=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,AK=/"(?: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 m$(Y){let X=JSON.parse(Y);if(X===null||typeof X!=="object")return X;if(MK.test(Y)===!1&&AK.test(Y)===!1)return X;return RK(X)}function RK(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 TK(Y){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(J){return m$(Y)}try{return m$(Y)}finally{Error.stackTraceLimit=X}}function M9(Y){if(Y.type==="object"||Array.isArray(Y.type)&&Y.type.includes("object")){Y.additionalProperties=!1;let{properties:J}=Y;if(J!=null)for(let Q of Object.keys(J))J[Q]=O1(J[Q])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(O1):O1(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(O1);if(Y.allOf!=null)Y.allOf=Y.allOf.map(O1);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(O1);let{definitions:X}=Y;if(X!=null)for(let J of Object.keys(X))X[J]=O1(X[J]);return Y}function O1(Y){if(typeof Y==="boolean")return Y;return M9(Y)}var CK=Symbol("Let zodToJsonSchema decide on which parser to use"),c$={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"},_K=(Y)=>typeof Y==="string"?{...c$,name:Y}:{...c$,...Y};function M0(){return{}}function IK(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=l(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 SK(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 kK(){return{type:"boolean"}}function YG(Y,X){return l(Y.type._def,X)}var bK=(Y,X)=>{return l(Y.innerType._def,X)};function XG(Y,X,J){let Q=J!=null?J:X.dateStrategy;if(Array.isArray(Q))return{anyOf:Q.map(($)=>XG(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 xK(Y)}}var xK=(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 vK(Y,X){return{...l(Y.innerType._def,X),default:Y.defaultValue()}}function hK(Y,X){return X.effectStrategy==="input"?l(Y.schema._def,X):M0()}function gK(Y){return{type:"string",enum:Array.from(Y.values)}}var yK=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function fK(Y,X){let J=[l(Y.left._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),l(Y.right._def,{...X,currentPath:[...X.currentPath,"allOf","1"]})].filter(($)=>!!$),Q=[];return J.forEach(($)=>{if(yK($))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 mK(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 F9=void 0,I0={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(F9===void 0)F9=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return F9},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 JG(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":S0(J,"email",Q.message,X);break;case"format:idn-email":S0(J,"idn-email",Q.message,X);break;case"pattern:zod":O0(J,I0.email,Q.message,X);break}break;case"url":S0(J,"uri",Q.message,X);break;case"uuid":S0(J,"uuid",Q.message,X);break;case"regex":O0(J,Q.regex,Q.message,X);break;case"cuid":O0(J,I0.cuid,Q.message,X);break;case"cuid2":O0(J,I0.cuid2,Q.message,X);break;case"startsWith":O0(J,RegExp(`^${q9(Q.value,X)}`),Q.message,X);break;case"endsWith":O0(J,RegExp(`${q9(Q.value,X)}$`),Q.message,X);break;case"datetime":S0(J,"date-time",Q.message,X);break;case"date":S0(J,"date",Q.message,X);break;case"time":S0(J,"time",Q.message,X);break;case"duration":S0(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":{O0(J,RegExp(q9(Q.value,X)),Q.message,X);break}case"ip":{if(Q.version!=="v6")S0(J,"ipv4",Q.message,X);if(Q.version!=="v4")S0(J,"ipv6",Q.message,X);break}case"base64url":O0(J,I0.base64url,Q.message,X);break;case"jwt":O0(J,I0.jwt,Q.message,X);break;case"cidr":{if(Q.version!=="v6")O0(J,I0.ipv4Cidr,Q.message,X);if(Q.version!=="v4")O0(J,I0.ipv6Cidr,Q.message,X);break}case"emoji":O0(J,I0.emoji(),Q.message,X);break;case"ulid":{O0(J,I0.ulid,Q.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{S0(J,"binary",Q.message,X);break}case"contentEncoding:base64":{J.contentEncoding="base64";break}case"pattern:zod":{O0(J,I0.base64,Q.message,X);break}}break}case"nanoid":O0(J,I0.nanoid,Q.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return J}function q9(Y,X){return X.patternStrategy==="escape"?uK(Y):Y}var cK=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function uK(Y){let X="";for(let J=0;J<Y.length;J++){if(!cK.has(Y[J]))X+="\\";X+=Y[J]}return X}function S0(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 O0(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:u$(X,Q),...J&&Q.errorMessages&&{errorMessage:{pattern:J}}})}else Y.pattern=u$(X,Q)}function u$(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
|
|
138
|
-
]))`;continue}else if($[
|
|
139
|
-
]))`;continue}}if(Q.s&&$[
|
|
140
|
-
`:`[${$[
|
|
141
|
-
]`;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 QG(Y,X){var J,Q,$,G,W,K;let H={type:"object",additionalProperties:(J=l(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,...N}=JG(Y.keyType._def,X);return{...H,propertyNames:N}}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,...N}=YG(Y.keyType._def,X);return{...H,propertyNames:N}}return H}function pK(Y,X){if(X.mapStrategy==="record")return QG(Y,X);let J=l(Y.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||M0(),Q=l(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||M0();return{type:"array",maxItems:125,items:{type:"array",items:[J,Q],minItems:2,maxItems:2}}}function lK(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 dK(){return{not:M0()}}function iK(){return{type:"null"}}var j9={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function nK(Y,X){let J=Y.options instanceof Map?Array.from(Y.options.values()):Y.options;if(J.every((Q)=>(Q._def.typeName in j9)&&(!Q._def.checks||!Q._def.checks.length))){let Q=J.reduce(($,G)=>{let W=j9[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 oK(Y,X)}var oK=(Y,X)=>{let J=(Y.options instanceof Map?Array.from(Y.options.values()):Y.options).map((Q,$)=>l(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 rK(Y,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Y.innerType._def.typeName)&&(!Y.innerType._def.checks||!Y.innerType._def.checks.length))return{type:[j9[Y.innerType._def.typeName],"null"]};let J=l(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return J&&{anyOf:[J,{type:"null"}]}}function sK(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 aK(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=eK(K),U=l(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=tK(Y,X);if(G!==void 0)J.additionalProperties=G;return J}function tK(Y,X){if(Y.catchall._def.typeName!=="ZodNever")return l(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 eK(Y){try{return Y.isOptional()}catch(X){return!0}}var YU=(Y,X)=>{var J;if(X.currentPath.toString()===((J=X.propertyPath)==null?void 0:J.toString()))return l(Y.innerType._def,X);let Q=l(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return Q?{anyOf:[{not:M0()},Q]}:M0()},XU=(Y,X)=>{if(X.pipeStrategy==="input")return l(Y.in._def,X);else if(X.pipeStrategy==="output")return l(Y.out._def,X);let J=l(Y.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),Q=l(Y.out._def,{...X,currentPath:[...X.currentPath,"allOf",J?"1":"0"]});return{allOf:[J,Q].filter(($)=>$!==void 0)}};function JU(Y,X){return l(Y.type._def,X)}function QU(Y,X){let Q={type:"array",uniqueItems:!0,items:l(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 $U(Y,X){if(Y.rest)return{type:"array",minItems:Y.items.length,items:Y.items.map((J,Q)=>l(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[]),additionalItems:l(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)=>l(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[])}}function GU(){return{not:M0()}}function WU(){return M0()}var zU=(Y,X)=>{return l(Y.innerType._def,X)},KU=(Y,X,J)=>{switch(X){case"ZodString":return JG(Y,J);case"ZodNumber":return sK(Y);case"ZodObject":return aK(Y,J);case"ZodBigInt":return SK(Y);case"ZodBoolean":return kK();case"ZodDate":return XG(Y,J);case"ZodUndefined":return GU();case"ZodNull":return iK();case"ZodArray":return IK(Y,J);case"ZodUnion":case"ZodDiscriminatedUnion":return nK(Y,J);case"ZodIntersection":return fK(Y,J);case"ZodTuple":return $U(Y,J);case"ZodRecord":return QG(Y,J);case"ZodLiteral":return mK(Y);case"ZodEnum":return gK(Y);case"ZodNativeEnum":return lK(Y);case"ZodNullable":return rK(Y,J);case"ZodOptional":return YU(Y,J);case"ZodMap":return pK(Y,J);case"ZodSet":return QU(Y,J);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return JU(Y,J);case"ZodNaN":case"ZodNever":return dK();case"ZodEffects":return hK(Y,J);case"ZodAny":return M0();case"ZodUnknown":return WU();case"ZodDefault":return vK(Y,J);case"ZodBranded":return YG(Y,J);case"ZodReadonly":return zU(Y,J);case"ZodCatch":return bK(Y,J);case"ZodPipeline":return XU(Y,J);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Q)=>{return})(X)}},UU=(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 l(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!==CK)return H}if($&&!J){let H=HU($,X);if(H!==void 0)return H}let G={def:Y,path:X.currentPath,jsonSchema:void 0};X.seen.set(Y,G);let W=KU(Y,Y.typeName,X),K=typeof W==="function"?l(W(),X):W;if(K)LU(Y,X,K);if(X.postProcess){let H=X.postProcess(K,Y,X);return G.jsonSchema=K,H}return G.jsonSchema=K,K}var HU=(Y,X)=>{switch(X.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:UU(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`),M0();return X.$refStrategy==="seen"?M0():void 0}}},LU=(Y,X,J)=>{if(Y.description)J.description=Y.description;return J},NU=(Y)=>{let X=_K(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}]))}},VU=(Y,X)=>{var J;let Q=NU(X),$=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((U,[N,O])=>{var B;return{...U,[N]:(B=l(O._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,N]},!0))!=null?B:M0()}},{}):void 0,G=typeof X==="string"?X:(X==null?void 0:X.nameStrategy)==="title"?void 0:X==null?void 0:X.name,W=(J=l(Y._def,G===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,G]},!1))!=null?J:M0(),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},D9=Symbol.for("vercel.ai.schema");function dY(Y){let X;return()=>{if(X==null)X=Y();return X}}function iY(Y,{validate:X}={}){return{[D9]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:X}}function BU(Y){return typeof Y==="object"&&Y!==null&&D9 in Y&&Y[D9]===!0&&"jsonSchema"in Y&&"validate"in Y}function nY(Y){return Y==null?iY({type:"object",properties:{},additionalProperties:!1}):BU(Y)?Y:("~standard"in Y)?Y["~standard"].vendor==="zod"?e1(Y):ZU(Y):Y()}function ZU(Y){return iY(()=>{if(!OU(Y))throw Error(`Standard schema vendor '${Y["~standard"].vendor}' does not support JSON Schema conversion.`);return M9(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 v0({value:X,cause:J.issues})}}})}function OU(Y){return Y["~standard"].jsonSchema!=null}function FU(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return iY(()=>VU(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 qU(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return iY(()=>M9(s7(Y,{target:"draft-7",io:"input",reused:Q?"ref":"inline"})),{validate:async($)=>{let G=await uY(Y,$);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function jU(Y){return"_zod"in Y}function e1(Y,X){if(jU(Y))return qU(Y,X);else return FU(Y,X)}async function YY({value:Y,schema:X,context:J}){let Q=nY(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:v0.wrap({value:Y,cause:$.error,context:J}),rawValue:Y}}catch($){return{success:!1,error:v0.wrap({value:Y,cause:$,context:J}),rawValue:Y}}}async function J1({text:Y,schema:X}){try{let J=TK(Y);if(X==null)return{success:!0,value:J,rawValue:J};return await YY({value:J,schema:X})}catch(J){return{success:!1,error:MY.isInstance(J)?J:new MY({text:Y,cause:J}),rawValue:void 0}}}async function A9(Y){if(typeof Y==="function")Y=Y();return Promise.resolve(Y)}var $G="AI_SerializationError",GG=`vercel.ai.error.${$G}`,DU=Symbol.for(GG),p$,l$,zO=class extends(l$=f,p$=DU,l$){constructor({message:Y="Failed to serialize value.",cause:X}={}){super({name:$G,message:Y,cause:X});this[p$]=!0}static isInstance(Y){return f.hasMarker(Y,GG)}};var EU=Object.defineProperty,MU=(Y,X)=>{for(var J in X)EU(Y,J,{get:X[J],enumerable:!0})},AU="AI_InvalidArgumentError",RU=`vercel.ai.error.${AU}`,TU=Symbol.for(RU),CU;CU=TU;var _U="AI_InvalidStreamPartError",IU=`vercel.ai.error.${_U}`,SU=Symbol.for(IU),kU;kU=SU;var bU="AI_InvalidToolApprovalError",xU=`vercel.ai.error.${bU}`,vU=Symbol.for(xU),hU;hU=vU;var gU="AI_InvalidToolApprovalSignatureError",yU=`vercel.ai.error.${gU}`,fU=Symbol.for(yU),mU;mU=fU;var cU="AI_InvalidToolInputError",uU=`vercel.ai.error.${cU}`,pU=Symbol.for(uU),lU;lU=pU;var dU="AI_ToolCallNotFoundForApprovalError",iU=`vercel.ai.error.${dU}`,nU=Symbol.for(iU),oU;oU=nU;var rU="AI_MissingToolResultsError",sU=`vercel.ai.error.${rU}`,aU=Symbol.for(sU),tU;tU=aU;var eU="AI_NoImageGeneratedError",YH=`vercel.ai.error.${eU}`,XH=Symbol.for(YH),JH;JH=XH;var WG="AI_NoObjectGeneratedError",zG=`vercel.ai.error.${WG}`,QH=Symbol.for(zG),KG,Q1=class extends f{constructor({message:Y="No object generated.",cause:X,text:J,response:Q,usage:$,finishReason:G}){super({name:WG,message:Y,cause:X});this[KG]=!0,this.text=J,this.response=Q,this.usage=$,this.finishReason=G}static isInstance(Y){return f.hasMarker(Y,zG)}};KG=QH;var $H="AI_NoOutputGeneratedError",GH=`vercel.ai.error.${$H}`,WH=Symbol.for(GH),zH;zH=WH;var KH="AI_NoSpeechGeneratedError",UH=`vercel.ai.error.${KH}`,HH=Symbol.for(UH),LH;LH=HH;var NH="AI_NoTranscriptGeneratedError",VH=`vercel.ai.error.${NH}`,BH=Symbol.for(VH),ZH;ZH=BH;var OH="AI_NoTranslationGeneratedError",FH=`vercel.ai.error.${OH}`,qH=Symbol.for(FH),jH;jH=qH;var DH="AI_NoVideoGeneratedError",PH=`vercel.ai.error.${DH}`,wH=Symbol.for(PH),EH;EH=wH;var MH="AI_NoSuchToolError",AH=`vercel.ai.error.${MH}`,RH=Symbol.for(AH),TH;TH=RH;var CH="AI_ToolCallRepairError",_H=`vercel.ai.error.${CH}`,IH=Symbol.for(_H),SH;SH=IH;var kH="AI_UIMessageStreamError",bH=`vercel.ai.error.${kH}`,xH=Symbol.for(bH),vH;vH=xH;var hH="AI_InvalidDataContentError",gH=`vercel.ai.error.${hH}`,yH=Symbol.for(gH),fH;fH=yH;var mH="AI_InvalidMessageRoleError",cH=`vercel.ai.error.${mH}`,uH=Symbol.for(cH),pH;pH=uH;var lH="AI_MessageConversionError",dH=`vercel.ai.error.${lH}`,iH=Symbol.for(dH),nH;nH=iH;var oH="AI_RetryError",rH=`vercel.ai.error.${oH}`,sH=Symbol.for(rH),aH;aH=sH;var tH="7.0.59",eH=async({url:Y,maxBytes:X,abortSignal:J})=>{var Q;let $=Y.toString();try{let G=k1({},`ai-sdk/${tH}`,t$()),W=await s$({url:$,headers:G,abortSignal:J});if(!W.ok)throw await lY(W),new F0({url:$,statusCode:W.status,statusText:W.statusText});return{data:await a$({response:W,url:$,maxBytes:X!=null?X:E9}),mediaType:(Q=W.headers.get("content-type"))!=null?Q:void 0}}catch(G){if(F0.isInstance(G))throw G;throw new F0({url:$,cause:G})}};var z={array:N9,boolean:w$,custom:x$,discriminatedUnion:C$,enum:B9,instanceof:v$,lazy:b$,literal:I$,looseObject:R$,never:L9,null:E$,number:P$,object:A$,record:_$,string:j$,union:V9,unknown:t1},F1=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),F1.optional()),z.array(F1)])),A=z.record(z.string(),z.record(z.string(),F1.optional())),JY=z.union([z.string(),z.instanceof(Uint8Array),z.instanceof(ArrayBuffer),z.custom(e$,{message:"Must be a Buffer"})]),R9=z.record(z.string(),z.string()),UG=z.object({type:z.literal("text"),text:z.string(),providerOptions:A.optional()}),YL=z.object({type:z.literal("image"),image:z.union([JY,z.instanceof(URL),R9]),mediaType:z.string().optional(),providerOptions:A.optional()}),HG=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:JY}),z.object({type:z.literal("url"),url:z.instanceof(URL)}),z.object({type:z.literal("reference"),reference:R9}),z.object({type:z.literal("text"),text:z.string()})]),XL=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:JY}),z.object({type:z.literal("url"),url:z.instanceof(URL)})]),LG=z.object({type:z.literal("file"),data:z.union([HG,JY,z.instanceof(URL),R9]),filename:z.string().optional(),mediaType:z.string(),providerOptions:A.optional()}),JL=z.object({type:z.literal("reasoning"),text:z.string(),providerOptions:A.optional()}),QL=z.object({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerOptions:A.optional()}),$L=z.object({type:z.literal("reasoning-file"),data:z.union([XL,JY,z.instanceof(URL)]),mediaType:z.string(),providerOptions:A.optional()}),GL=z.object({type:z.literal("tool-call"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerOptions:A.optional(),providerExecuted:z.boolean().optional()}),WL=z.discriminatedUnion("type",[z.object({type:z.literal("text"),value:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("json"),value:F1,providerOptions:A.optional()}),z.object({type:z.literal("execution-denied"),reason:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("error-text"),value:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("error-json"),value:F1,providerOptions:A.optional()}),z.object({type:z.literal("content"),value:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("file"),data:HG,mediaType:z.string(),filename:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("file-data"),data:z.string(),mediaType:z.string(),filename:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("file-url"),url:z.string(),mediaType:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:A.optional()}),z.object({type:z.literal("file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:A.optional()}),z.object({type:z.literal("image-data"),data:z.string(),mediaType:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("image-url"),url:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("image-file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:A.optional()}),z.object({type:z.literal("image-file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:A.optional()}),z.object({type:z.literal("custom"),providerOptions:A.optional()})]))})]),NG=z.object({type:z.literal("tool-result"),toolCallId:z.string(),toolName:z.string(),output:WL,providerOptions:A.optional()}),zL=z.object({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string()}),KL=z.object({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional()}),UL=z.object({role:z.literal("system"),content:z.string(),providerOptions:A.optional()}),HL=z.object({role:z.literal("user"),content:z.union([z.string(),z.array(z.union([UG,YL,LG]))]),providerOptions:A.optional()}),LL=z.object({role:z.literal("assistant"),content:z.union([z.string(),z.array(z.union([UG,QL,LG,JL,$L,GL,NG,zL]))]),providerOptions:A.optional()}),NL=z.object({role:z.literal("tool"),content:z.array(z.union([NG,KL])),providerOptions:A.optional()}),PO=z.union([UL,HL,LL,NL]);var VL={};MU(VL,{array:()=>FL,choice:()=>qL,json:()=>jL,object:()=>OL,text:()=>ZL});function BL(Y){let X=["ROOT"],J=-1,Q=null,$=0;function G(N){return N>="0"&&N<="9"||N>="A"&&N<="F"||N>="a"&&N<="f"}function W(N,O,B){switch(N){case'"':{J=O,X.pop(),X.push(B),X.push("INSIDE_STRING");break}case"f":case"t":case"n":{J=O,Q=O,X.pop(),X.push(B),X.push("INSIDE_LITERAL");break}case"-":{X.pop(),X.push(B),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=O,X.pop(),X.push(B),X.push("INSIDE_NUMBER");break}case"{":{J=O,X.pop(),X.push(B),X.push("INSIDE_OBJECT_START");break}case"[":{J=O,X.pop(),X.push(B),X.push("INSIDE_ARRAY_START");break}}}function K(N,O){switch(N){case",":{X.pop(),X.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{J=O,X.pop();break}}}function H(N,O){switch(N){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=O,X.pop();break}}}for(let N=0;N<Y.length;N++){let O=Y[N];switch(X[X.length-1]){case"ROOT":W(O,N,"FINISH");break;case"INSIDE_OBJECT_START":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}case"}":{J=N,X.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(O){case":":{X.pop(),X.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{W(O,N,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{K(O,N);break}case"INSIDE_STRING":{switch(O){case'"':{X.pop(),J=N;break}case"\\":{X.push("INSIDE_STRING_ESCAPE");break}default:J=N}break}case"INSIDE_ARRAY_START":{switch(O){case"]":{J=N,X.pop();break}default:{J=N,W(O,N,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(O){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=N,X.pop();break}default:{J=N;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{W(O,N,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{if(X.pop(),O==="u")$=0,X.push("INSIDE_STRING_UNICODE_ESCAPE");else J=N;break}case"INSIDE_STRING_UNICODE_ESCAPE":{if(G(O)){if($++,$===4)X.pop(),J=N}break}case"INSIDE_NUMBER":{switch(O){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=N;break}case"e":case"E":case"-":case".":break;case",":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")H(O,N);if(X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(O,N);break}case"}":{if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(O,N);break}case"]":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")H(O,N);break}default:{X.pop();break}}break}case"INSIDE_LITERAL":{let L=Y.substring(Q,N+1);if(!"false".startsWith(L)&&!"true".startsWith(L)&&!"null".startsWith(L)){if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(O,N);else if(X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")H(O,N)}else J=N;break}}}let U=Y.slice(0,J+1);for(let N=X.length-1;N>=0;N--)switch(X[N]){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 B=Y.substring(Q,Y.length);if("true".startsWith(B))U+="true".slice(B.length);else if("false".startsWith(B))U+="false".slice(B.length);else if("null".startsWith(B))U+="null".slice(B.length)}}return U}async function oY(Y){if(Y===void 0)return{value:void 0,state:"undefined-input"};let X=await J1({text:Y});if(X.success)return{value:X.value,state:"successful-parse"};if(X=await J1({text:BL(Y)}),X.success)return{value:X.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var ZL=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:Y}){return Y},async parsePartialOutput({text:Y}){return{partial:Y}},createElementStreamTransform(){return}}),OL=({schema:Y,name:X,description:J})=>{let Q=nY(Y);return{name:"object",responseFormat:A9(Q.jsonSchema).then(($)=>({type:"json",schema:$,...X!=null&&{name:X},...J!=null&&{description:J}})),async parseCompleteOutput({text:$},G){let W=await J1({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 YY({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 oY($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:G.value}}},createElementStreamTransform(){return}}},FL=({element:Y,name:X,description:J})=>{let Q=nY(Y);return{name:"array",responseFormat:A9(Q.jsonSchema).then(($)=>{let{$schema:G,...W}=$;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:W}},required:["elements"],additionalProperties:!1},...X!=null&&{name:X},...J!=null&&{description:J}}}),async parseCompleteOutput({text:$},G){let W=await J1({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=W.value;if(K==null||typeof K!=="object"||!("elements"in K)||!Array.isArray(K.elements))throw new Q1({message:"No object generated: response did not match schema.",cause:new v0({value:K,cause:"response must be an object with an elements array"}),text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let H=[];for(let U of K.elements){let N=await YY({value:U,schema:Q});if(!N.success)throw new Q1({message:"No object generated: response did not match schema.",cause:N.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});H.push(N.value)}return H},async parsePartialOutput({text:$}){let G=await oY($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let W=G.value;if(W==null||typeof W!=="object"||!("elements"in W)||!Array.isArray(W.elements))return;let K=G.state==="repaired-parse"&&W.elements.length>0?W.elements.slice(0,-1):W.elements,H=[];for(let U of K){let N=await YY({value:U,schema:Q});if(N.success)H.push(N.value)}return{partial:H}}}},createElementStreamTransform(){let $=0;return new TransformStream({transform({partialOutput:G},W){if(G!=null)for(;$<G.length;$++)W.enqueue(G[$])}})}}},qL=({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 J1({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 v0({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 oY(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}}},jL=({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 J1({text:J});if(!$.success)throw new Q1({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 oY(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 AO=J0({prefix:"aitxt",size:24}),RO=J0({prefix:"call",size:24});var CO=class extends TransformStream{constructor(){super({transform(Y,X){X.enqueue(`data: ${JSON.stringify(Y)}
|
|
187
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let H of this.seen.entries()){let N=H[1];if(Y===H[0]){G(H);continue}if(J.external){let Z=J.external.registry.get(H[0])?.id;if(Y!==H[0]&&Z){G(H);continue}}if(this.metadataRegistry.get(H[0])?.id){G(H);continue}if(N.cycle){G(H);continue}if(N.count>1){if(J.reused==="ref"){G(H);continue}}}let W=(H,N)=>{let O=this.seen.get(H),Z=O.def??O.schema,V={...Z};if(O.ref===null)return;let K=O.ref;if(O.ref=null,K){W(K,N);let j=this.seen.get(K).schema;if(j.$ref&&(N.target==="draft-7"||N.target==="draft-4"||N.target==="openapi-3.0"))Z.allOf=Z.allOf??[],Z.allOf.push(j);else Object.assign(Z,j),Object.assign(Z,V)}if(!O.isParent)this.override({zodSchema:H,jsonSchema:Z,path:O.path??[]})};for(let H of[...this.seen.entries()].reverse())W(H[0],{target:this.target});let U={};if(this.target==="draft-2020-12")U.$schema="https://json-schema.org/draft/2020-12/schema";else if(this.target==="draft-7")U.$schema="http://json-schema.org/draft-07/schema#";else if(this.target==="draft-4")U.$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 H=J.external.registry.get(Y)?.id;if(!H)throw Error("Schema is missing an `id` property");U.$id=J.external.uri(H)}Object.assign(U,Q.def);let L=J.external?.defs??{};for(let H of this.seen.entries()){let N=H[1];if(N.def&&N.defId)L[N.defId]=N.def}if(J.external);else if(Object.keys(L).length>0)if(this.target==="draft-2020-12")U.$defs=L;else U.definitions=L;try{return JSON.parse(JSON.stringify(U))}catch(H){throw Error("Error converting schema to JSON.")}}}function _$(Y,X){if(Y instanceof iY){let Q=new A9(X),$={};for(let U of Y._idmap.entries()){let[L,H]=U;Q.process(H)}let G={},W={registry:Y,uri:X?.uri,defs:$};for(let U of Y._idmap.entries()){let[L,H]=U;G[L]=Q.emit(H,{...X,external:W})}if(Object.keys($).length>0){let U=Q.target==="draft-2020-12"?"$defs":"definitions";G.__shared={[U]:$}}return{schemas:G}}let J=new A9(X);return J.process(Y),J.emit(Y,X)}function z0(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 z0($.element,J);case"object":{for(let G in $.shape)if(z0($.shape[G],J))return!0;return!1}case"union":{for(let G of $.options)if(z0(G,J))return!0;return!1}case"intersection":return z0($.left,J)||z0($.right,J);case"tuple":{for(let G of $.items)if(z0(G,J))return!0;if($.rest&&z0($.rest,J))return!0;return!1}case"record":return z0($.keyType,J)||z0($.valueType,J);case"map":return z0($.keyType,J)||z0($.valueType,J);case"set":return z0($.valueType,J);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return z0($.innerType,J);case"lazy":return z0($.getter(),J);case"default":return z0($.innerType,J);case"prefault":return z0($.innerType,J);case"custom":return!1;case"transform":return!0;case"pipe":return z0($.in,J)||z0($.out,J);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${$.type}`)}var HU=F("ZodISODateTime",(Y,X)=>{H7.init(Y,X),a.init(Y,X)});function I$(Y){return K$(HU,Y)}var LU=F("ZodISODate",(Y,X)=>{L7.init(Y,X),a.init(Y,X)});function S$(Y){return O$(LU,Y)}var VU=F("ZodISOTime",(Y,X)=>{V7.init(Y,X),a.init(Y,X)});function k$(Y){return q$(VU,Y)}var NU=F("ZodISODuration",(Y,X)=>{N7.init(Y,X),a.init(Y,X)});function b$(Y){return F$(NU,Y)}var x$=(Y,X)=>{fY.init(Y,X),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(J)=>p6(Y,J)},flatten:{value:(J)=>u6(Y,J)},addIssue:{value:(J)=>{Y.issues.push(J),Y.message=JSON.stringify(Y.issues,y1,2)}},addIssues:{value:(J)=>{Y.issues.push(...J),Y.message=JSON.stringify(Y.issues,y1,2)}},isEmpty:{get(){return Y.issues.length===0}}})},KO=F("ZodError",x$),E0=F("ZodError",x$,{Parent:Error});var v$=mY(E0),h$=cY(E0),g$=$Y(E0),eY=GY(E0),y$=i6(E0),f$=n6(E0),m$=o6(E0),c$=r6(E0),u$=s6(E0),p$=a6(E0),l$=t6(E0),d$=e6(E0);var t=F("ZodType",(Y,X)=>{return o.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)=>I0(Y,J,Q),Y.brand=()=>Y,Y.register=(J,Q)=>{return J.add(Y,Q),Y},Y.parse=(J,Q)=>v$(Y,J,Q,{callee:Y.parse}),Y.safeParse=(J,Q)=>g$(Y,J,Q),Y.parseAsync=async(J,Q)=>h$(Y,J,Q,{callee:Y.parseAsync}),Y.safeParseAsync=async(J,Q)=>eY(Y,J,Q),Y.spa=Y.safeParseAsync,Y.encode=(J,Q)=>y$(Y,J,Q),Y.decode=(J,Q)=>f$(Y,J,Q),Y.encodeAsync=async(J,Q)=>m$(Y,J,Q),Y.decodeAsync=async(J,Q)=>c$(Y,J,Q),Y.safeEncode=(J,Q)=>u$(Y,J,Q),Y.safeDecode=(J,Q)=>p$(Y,J,Q),Y.safeEncodeAsync=async(J,Q)=>l$(Y,J,Q),Y.safeDecodeAsync=async(J,Q)=>d$(Y,J,Q),Y.refine=(J,Q)=>Y.check(GH(J,Q)),Y.superRefine=(J)=>Y.check(WH(J)),Y.overwrite=(J)=>Y.check(E1(J)),Y.optional=()=>o$(Y),Y.nullable=()=>r$(Y),Y.nullish=()=>o$(r$(Y)),Y.nonoptional=(J)=>tU(Y,J),Y.array=()=>C9(Y),Y.or=(J)=>_9([Y,J]),Y.and=(J)=>uU(Y,J),Y.transform=(J)=>s$(Y,iU(J)),Y.default=(J)=>rU(Y,J),Y.prefault=(J)=>aU(Y,J),Y.catch=(J)=>YH(Y,J),Y.pipe=(J)=>s$(Y,J),Y.readonly=()=>QH(Y),Y.describe=(J)=>{let Q=Y.clone();return w1.add(Q,{description:J}),Q},Object.defineProperty(Y,"description",{get(){return w1.get(Y)?.description},configurable:!0}),Y.meta=(...J)=>{if(J.length===0)return w1.get(Y);let Q=Y.clone();return w1.add(Q,J[0]),Q},Y.isOptional=()=>Y.safeParse(void 0).success,Y.isNullable=()=>Y.safeParse(null).success,Y}),a$=F("_ZodString",(Y,X)=>{dY.init(Y,X),t.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(K9(...Q)),Y.includes=(...Q)=>Y.check(F9(...Q)),Y.startsWith=(...Q)=>Y.check(j9(...Q)),Y.endsWith=(...Q)=>Y.check(D9(...Q)),Y.min=(...Q)=>Y.check(c1(...Q)),Y.max=(...Q)=>Y.check(sY(...Q)),Y.length=(...Q)=>Y.check(aY(...Q)),Y.nonempty=(...Q)=>Y.check(c1(1,...Q)),Y.lowercase=(Q)=>Y.check(O9(Q)),Y.uppercase=(Q)=>Y.check(q9(Q)),Y.trim=()=>Y.check(M9()),Y.normalize=(...Q)=>Y.check(P9(...Q)),Y.toLowerCase=()=>Y.check(w9()),Y.toUpperCase=()=>Y.check(E9())}),OU=F("ZodString",(Y,X)=>{dY.init(Y,X),a$.init(Y,X),Y.email=(J)=>Y.check(o7(qU,J)),Y.url=(J)=>Y.check(e7(FU,J)),Y.jwt=(J)=>Y.check(Z$(bU,J)),Y.emoji=(J)=>Y.check(Y$(jU,J)),Y.guid=(J)=>Y.check(Z9(i$,J)),Y.uuid=(J)=>Y.check(r7(Y8,J)),Y.uuidv4=(J)=>Y.check(s7(Y8,J)),Y.uuidv6=(J)=>Y.check(a7(Y8,J)),Y.uuidv7=(J)=>Y.check(t7(Y8,J)),Y.nanoid=(J)=>Y.check(X$(DU,J)),Y.guid=(J)=>Y.check(Z9(i$,J)),Y.cuid=(J)=>Y.check(J$(PU,J)),Y.cuid2=(J)=>Y.check(Q$(MU,J)),Y.ulid=(J)=>Y.check($$(wU,J)),Y.base64=(J)=>Y.check(V$(IU,J)),Y.base64url=(J)=>Y.check(N$(SU,J)),Y.xid=(J)=>Y.check(G$(EU,J)),Y.ksuid=(J)=>Y.check(W$(AU,J)),Y.ipv4=(J)=>Y.check(z$(TU,J)),Y.ipv6=(J)=>Y.check(U$(RU,J)),Y.cidrv4=(J)=>Y.check(H$(CU,J)),Y.cidrv6=(J)=>Y.check(L$(_U,J)),Y.e164=(J)=>Y.check(B$(kU,J)),Y.datetime=(J)=>Y.check(I$(J)),Y.date=(J)=>Y.check(S$(J)),Y.time=(J)=>Y.check(k$(J)),Y.duration=(J)=>Y.check(b$(J))});function t$(Y){return n7(OU,Y)}var a=F("ZodStringFormat",(Y,X)=>{s.init(Y,X),a$.init(Y,X)}),qU=F("ZodEmail",(Y,X)=>{Y7.init(Y,X),a.init(Y,X)});var i$=F("ZodGUID",(Y,X)=>{tQ.init(Y,X),a.init(Y,X)});var Y8=F("ZodUUID",(Y,X)=>{eQ.init(Y,X),a.init(Y,X)});var FU=F("ZodURL",(Y,X)=>{X7.init(Y,X),a.init(Y,X)});var jU=F("ZodEmoji",(Y,X)=>{J7.init(Y,X),a.init(Y,X)});var DU=F("ZodNanoID",(Y,X)=>{Q7.init(Y,X),a.init(Y,X)});var PU=F("ZodCUID",(Y,X)=>{$7.init(Y,X),a.init(Y,X)});var MU=F("ZodCUID2",(Y,X)=>{G7.init(Y,X),a.init(Y,X)});var wU=F("ZodULID",(Y,X)=>{W7.init(Y,X),a.init(Y,X)});var EU=F("ZodXID",(Y,X)=>{z7.init(Y,X),a.init(Y,X)});var AU=F("ZodKSUID",(Y,X)=>{U7.init(Y,X),a.init(Y,X)});var TU=F("ZodIPv4",(Y,X)=>{B7.init(Y,X),a.init(Y,X)});var RU=F("ZodIPv6",(Y,X)=>{Z7.init(Y,X),a.init(Y,X)});var CU=F("ZodCIDRv4",(Y,X)=>{K7.init(Y,X),a.init(Y,X)});var _U=F("ZodCIDRv6",(Y,X)=>{O7.init(Y,X),a.init(Y,X)});var IU=F("ZodBase64",(Y,X)=>{F7.init(Y,X),a.init(Y,X)});var SU=F("ZodBase64URL",(Y,X)=>{j7.init(Y,X),a.init(Y,X)});var kU=F("ZodE164",(Y,X)=>{D7.init(Y,X),a.init(Y,X)});var bU=F("ZodJWT",(Y,X)=>{P7.init(Y,X),a.init(Y,X)});var e$=F("ZodNumber",(Y,X)=>{N9.init(Y,X),t.init(Y,X),Y.gt=(Q,$)=>Y.check(oY(Q,$)),Y.gte=(Q,$)=>Y.check(UY(Q,$)),Y.min=(Q,$)=>Y.check(UY(Q,$)),Y.lt=(Q,$)=>Y.check(nY(Q,$)),Y.lte=(Q,$)=>Y.check(zY(Q,$)),Y.max=(Q,$)=>Y.check(zY(Q,$)),Y.int=(Q)=>Y.check(n$(Q)),Y.safe=(Q)=>Y.check(n$(Q)),Y.positive=(Q)=>Y.check(oY(0,Q)),Y.nonnegative=(Q)=>Y.check(UY(0,Q)),Y.negative=(Q)=>Y.check(nY(0,Q)),Y.nonpositive=(Q)=>Y.check(zY(0,Q)),Y.multipleOf=(Q,$)=>Y.check(rY(Q,$)),Y.step=(Q,$)=>Y.check(rY(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 YG(Y){return j$(e$,Y)}var xU=F("ZodNumberFormat",(Y,X)=>{M7.init(Y,X),e$.init(Y,X)});function n$(Y){return D$(xU,Y)}var vU=F("ZodBoolean",(Y,X)=>{w7.init(Y,X),t.init(Y,X)});function XG(Y){return P$(vU,Y)}var hU=F("ZodNull",(Y,X)=>{E7.init(Y,X),t.init(Y,X)});function JG(Y){return M$(hU,Y)}var gU=F("ZodUnknown",(Y,X)=>{A7.init(Y,X),t.init(Y,X)});function HY(){return w$(gU)}var yU=F("ZodNever",(Y,X)=>{T7.init(Y,X),t.init(Y,X)});function R9(Y){return E$(yU,Y)}var fU=F("ZodArray",(Y,X)=>{R7.init(Y,X),t.init(Y,X),Y.element=X.element,Y.min=(J,Q)=>Y.check(c1(J,Q)),Y.nonempty=(J)=>Y.check(c1(1,J)),Y.max=(J,Q)=>Y.check(sY(J,Q)),Y.length=(J,Q)=>Y.check(aY(J,Q)),Y.unwrap=()=>Y.element});function C9(Y,X){return A$(fU,Y,X)}var QG=F("ZodObject",(Y,X)=>{I7.init(Y,X),t.init(Y,X),u.defineLazy(Y,"shape",()=>X.shape),Y.keyof=()=>I9(Object.keys(Y._zod.def.shape)),Y.catchall=(J)=>Y.clone({...Y._zod.def,catchall:J}),Y.passthrough=()=>Y.clone({...Y._zod.def,catchall:HY()}),Y.loose=()=>Y.clone({...Y._zod.def,catchall:HY()}),Y.strict=()=>Y.clone({...Y._zod.def,catchall:R9()}),Y.strip=()=>Y.clone({...Y._zod.def,catchall:void 0}),Y.extend=(J)=>{return u.extend(Y,J)},Y.safeExtend=(J)=>{return u.safeExtend(Y,J)},Y.merge=(J)=>u.merge(Y,J),Y.pick=(J)=>u.pick(Y,J),Y.omit=(J)=>u.omit(Y,J),Y.partial=(...J)=>u.partial(LG,Y,J[0]),Y.required=(...J)=>u.required(VG,Y,J[0])});function $G(Y,X){let J={type:"object",get shape(){return u.assignProp(this,"shape",Y?u.objectClone(Y):{}),this.shape},...u.normalizeParams(X)};return new QG(J)}function GG(Y,X){return new QG({type:"object",get shape(){return u.assignProp(this,"shape",u.objectClone(Y)),this.shape},catchall:HY(),...u.normalizeParams(X)})}var WG=F("ZodUnion",(Y,X)=>{B9.init(Y,X),t.init(Y,X),Y.options=X.options});function _9(Y,X){return new WG({type:"union",options:Y,...u.normalizeParams(X)})}var mU=F("ZodDiscriminatedUnion",(Y,X)=>{WG.init(Y,X),S7.init(Y,X)});function zG(Y,X,J){return new mU({type:"union",options:X,discriminator:Y,...u.normalizeParams(J)})}var cU=F("ZodIntersection",(Y,X)=>{k7.init(Y,X),t.init(Y,X)});function uU(Y,X){return new cU({type:"intersection",left:Y,right:X})}var pU=F("ZodRecord",(Y,X)=>{b7.init(Y,X),t.init(Y,X),Y.keyType=X.keyType,Y.valueType=X.valueType});function UG(Y,X,J){return new pU({type:"record",keyType:Y,valueType:X,...u.normalizeParams(J)})}var T9=F("ZodEnum",(Y,X)=>{x7.init(Y,X),t.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 T9({...X,checks:[],...u.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 T9({...X,checks:[],...u.normalizeParams($),entries:G})}});function I9(Y,X){let J=Array.isArray(Y)?Object.fromEntries(Y.map((Q)=>[Q,Q])):Y;return new T9({type:"enum",entries:J,...u.normalizeParams(X)})}var lU=F("ZodLiteral",(Y,X)=>{v7.init(Y,X),t.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 HG(Y,X){return new lU({type:"literal",values:Array.isArray(Y)?Y:[Y],...u.normalizeParams(X)})}var dU=F("ZodTransform",(Y,X)=>{h7.init(Y,X),t.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new t1(Y.constructor.name);J.addIssue=(G)=>{if(typeof G==="string")J.issues.push(u.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(u.issue(W))}};let $=X.transform(J.value,J);if($ instanceof Promise)return $.then((G)=>{return J.value=G,J});return J.value=$,J}});function iU(Y){return new dU({type:"transform",transform:Y})}var LG=F("ZodOptional",(Y,X)=>{g7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function o$(Y){return new LG({type:"optional",innerType:Y})}var nU=F("ZodNullable",(Y,X)=>{y7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function r$(Y){return new nU({type:"nullable",innerType:Y})}var oU=F("ZodDefault",(Y,X)=>{f7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function rU(Y,X){return new oU({type:"default",innerType:Y,get defaultValue(){return typeof X==="function"?X():u.shallowClone(X)}})}var sU=F("ZodPrefault",(Y,X)=>{m7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function aU(Y,X){return new sU({type:"prefault",innerType:Y,get defaultValue(){return typeof X==="function"?X():u.shallowClone(X)}})}var VG=F("ZodNonOptional",(Y,X)=>{c7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function tU(Y,X){return new VG({type:"nonoptional",innerType:Y,...u.normalizeParams(X)})}var eU=F("ZodCatch",(Y,X)=>{u7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function YH(Y,X){return new eU({type:"catch",innerType:Y,catchValue:typeof X==="function"?X:()=>X})}var XH=F("ZodPipe",(Y,X)=>{p7.init(Y,X),t.init(Y,X),Y.in=X.in,Y.out=X.out});function s$(Y,X){return new XH({type:"pipe",in:Y,out:X})}var JH=F("ZodReadonly",(Y,X)=>{l7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function QH(Y){return new JH({type:"readonly",innerType:Y})}var $H=F("ZodLazy",(Y,X)=>{d7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.getter()});function NG(Y){return new $H({type:"lazy",getter:Y})}var S9=F("ZodCustom",(Y,X)=>{i7.init(Y,X),t.init(Y,X)});function BG(Y,X){return T$(S9,Y??(()=>!0),X)}function GH(Y,X={}){return R$(S9,Y,X)}function WH(Y){return C$(Y)}function ZG(Y,X={error:`Input not instance of ${Y.name}`}){let J=new S9({type:"custom",check:"custom",fn:(Q)=>Q instanceof Y,abort:!0,...u.normalizeParams(X)});return J._zod.bag.Class=Y,J}var zH=[{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]}],J4=[...zH,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];var UH=12,HH=131072,Q4=HH+UH;async function X8(Y){var X;try{await((X=Y.body)==null?void 0:X.cancel())}catch(J){}}var EG="AI_DownloadError",AG=`vercel.ai.error.${EG}`,LH=Symbol.for(AG),KG,OG,O0=class extends(OG=f,KG=LH,OG){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:EG,message:$,cause:Q});this[KG]=!0,this.url=Y,this.statusCode=X,this.statusText=J}static isInstance(Y){return f.hasMarker(Y,AG)}};function VH(Y=globalThis){return Y.window!=null}function qG(Y,X){try{return new URL(Y).origin===new URL(X).origin}catch(J){return!1}}function NH(Y){let X;try{X=new URL(Y)}catch(Q){throw new O0({url:Y,message:`Invalid URL: ${Y}`})}if(X.protocol==="data:")return;if(X.protocol!=="http:"&&X.protocol!=="https:")throw new O0({url:Y,message:`URL scheme must be http, https, or data, got ${X.protocol}`});let J=X.hostname.toLowerCase().replace(/\.+$/,"");if(!J)throw new O0({url:Y,message:"URL must have a hostname"});if(J==="localhost"||J.endsWith(".local")||J.endsWith(".localhost"))throw new O0({url:Y,message:`URL with hostname ${J} is not allowed`});if(J.startsWith("[")&&J.endsWith("]")){let Q=J.slice(1,-1);if(TG(Q))throw new O0({url:Y,message:`URL with IPv6 address ${J} is not allowed`});return}if(g9(J)){if(y9(J))throw new O0({url:Y,message:`URL with IP address ${J} is not allowed`});return}}function BH({address:Y,family:X,hostname:J}){if(X===4?!g9(Y)||y9(Y):X===6?TG(Y):!0)throw new O0({url:J,message:`Hostname ${J} resolved to disallowed IP address ${Y}`})}function g9(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 y9(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 ZH(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 U=[],L=W.split(":");for(let H=0;H<L.length;H++){let N=L[H];if(N.includes(".")){if(H!==L.length-1||!g9(N))return null;let[O,Z,V,K]=N.split(".").map(Number);U.push(O<<8|Z,V<<8|K);continue}if(!/^[0-9a-f]{1,4}$/.test(N))return null;U.push(parseInt(N,16))}return U},G=$(Q[0]);if(G===null)return null;if(Q.length===2){let W=$(Q[1]);if(W===null)return null;let U=8-G.length-W.length;if(U<0)return null;return[...G,...Array(U).fill(0),...W]}return G.length===8?G:null}function TG(Y){let X=ZH(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,U=X[7]&255;return y9(`${$}.${G}.${W}.${U}`)}return!1}function KH(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:U,family:L}of G)BH({address:U,family:L,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 k9,RG=globalThis.fetch,OH=jH(RG);function qH(){var Y,X;let J=globalThis.process;return((Y=J==null?void 0:J.release)==null?void 0:Y.name)==="node"&&((X=J.versions)==null?void 0:X.bun)==null}async function FH(){if(!qH()||!OH||globalThis.fetch!==RG)return globalThis.fetch;return k9!=null?k9:k9=Promise.resolve().then(DH)}function jH(Y){if(typeof Y!=="function")return!1;let X=Function.prototype.toString.call(Y);return X.includes("internal/deps/undici")||X.includes("lazy loading of undici")}function DH(){let{createRequire:Y}=FG("node:module"),{lookup:X}=FG("node:dns"),{Agent:J,fetch:Q}=Y(CG())("undici"),$=new J({connect:{lookup:KH(X)}});return(G,W)=>Q(G,{...W,dispatcher:$})}function FG(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 CG(){let Y=Error.prepareStackTrace;try{Error.prepareStackTrace=($,G)=>G;let X=Error("Capture current module path");Error.captureStackTrace(X,CG);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 PH=["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 MH(Y){let X=new Headers(Y);for(let J of PH)X.delete(J);return X}var wH=10,EH=new Set([301,302,303,307,308]);async function _G({url:Y,headers:X,abortSignal:J,maxRedirects:Q=wH,fetch:$,trustedOrigin:G}){let W=X===void 0?void 0:MH(X),U=(H)=>{let N={signal:J,redirect:H};if(W!==void 0)N.headers=new Headers(W);return N},L=Y;for(let H=0;H<=Q;H++){let N=G!==void 0&&qG(L,G);if(!N)NH(L);let O=$!=null?$:N?globalThis.fetch:await FH(),Z=await O(L,U("manual"));if(Z.type==="opaqueredirect"){if(!VH())throw new O0({url:Y,message:`Redirect from ${L} could not be validated and was blocked`});return await O(L,U("follow"))}let V=Z.headers.get("location");if(EH.has(Z.status)&&V){await X8(Z);let K=new URL(V,L).toString();if(W!==void 0&&!qG(K,L)){let j=W.get("user-agent");W=new Headers(j==null?void 0:{"user-agent":j})}L=K;continue}return Z}throw new O0({url:Y,message:`Too many redirects (max ${Q})`})}var f9=2147483648;async function IG({response:Y,url:X,maxBytes:J=f9}){let Q=Y.headers.get("content-length");if(Q!=null){let N=parseInt(Q,10);if(!isNaN(N)&&N>J)throw await X8(Y),new O0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes (Content-Length: ${N}).`})}let $=Y.body;if($==null)return new Uint8Array(0);let G=$.getReader(),W=[],U=0;try{while(!0){let{done:N,value:O}=await G.read();if(N)break;if(U+=O.length,U>J)throw new O0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes.`});W.push(O)}}finally{try{await G.cancel()}finally{G.releaseLock()}}let L=new Uint8Array(U),H=0;for(let N of W)L.set(N,H),H+=N.length;return L}var G0=({prefix:Y,size:X=16,alphabet:J="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:Q="-"}={})=>{let $=()=>{let G=J.length,W=Array(X);for(let U=0;U<X;U++)W[U]=J[Math.random()*G|0];return W.join("")};if(Y==null)return $;if(J.includes(Q))throw new H6({argument:"separator",message:`The separator "${Q}" must not be part of the alphabet "${J}".`});return()=>`${Y}${Q}${$()}`},W4=G0();function SG(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 AH(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 u1(Y,...X){let J=new Headers(AH(Y)),Q=J.get("user-agent")||"";return J.set("user-agent",[Q,...X].filter(Boolean).join(" ")),Object.fromEntries(J.entries())}function kG(Y){var X,J;return(J=(X=globalThis.Buffer)==null?void 0:X.isBuffer(Y))!=null?J:!1}var TH=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,RH=/"(?: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 jG(Y){let X=JSON.parse(Y);if(X===null||typeof X!=="object")return X;if(TH.test(Y)===!1&&RH.test(Y)===!1)return X;return CH(X)}function CH(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 _H(Y){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(J){return jG(Y)}try{return jG(Y)}finally{Error.stackTraceLimit=X}}function m9(Y){if(Y.type==="object"||Array.isArray(Y.type)&&Y.type.includes("object")){Y.additionalProperties=!1;let{properties:J}=Y;if(J!=null)for(let Q of Object.keys(J))J[Q]=A1(J[Q])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(A1):A1(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(A1);if(Y.allOf!=null)Y.allOf=Y.allOf.map(A1);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(A1);let{definitions:X}=Y;if(X!=null)for(let J of Object.keys(X))X[J]=A1(X[J]);return Y}function A1(Y){if(typeof Y==="boolean")return Y;return m9(Y)}var IH=Symbol("Let zodToJsonSchema decide on which parser to use"),DG={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"},SH=(Y)=>typeof Y==="string"?{...DG,name:Y}:{...DG,...Y};function A0(){return{}}function kH(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=n(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 bH(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 xH(){return{type:"boolean"}}function bG(Y,X){return n(Y.type._def,X)}var vH=(Y,X)=>{return n(Y.innerType._def,X)};function xG(Y,X,J){let Q=J!=null?J:X.dateStrategy;if(Array.isArray(Q))return{anyOf:Q.map(($)=>xG(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 hH(Y)}}var hH=(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 gH(Y,X){return{...n(Y.innerType._def,X),default:Y.defaultValue()}}function yH(Y,X){return X.effectStrategy==="input"?n(Y.schema._def,X):A0()}function fH(Y){return{type:"string",enum:Array.from(Y.values)}}var mH=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function cH(Y,X){let J=[n(Y.left._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),n(Y.right._def,{...X,currentPath:[...X.currentPath,"allOf","1"]})].filter(($)=>!!$),Q=[];return J.forEach(($)=>{if(mH($))Q.push(...$.allOf);else{let G=$;if("additionalProperties"in $&&$.additionalProperties===!1){let{additionalProperties:W,...U}=$;G=U}Q.push(G)}}),Q.length?{allOf:Q}:void 0}function uH(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 b9=void 0,k0={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(b9===void 0)b9=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return b9},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 vG(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":b0(J,"email",Q.message,X);break;case"format:idn-email":b0(J,"idn-email",Q.message,X);break;case"pattern:zod":K0(J,k0.email,Q.message,X);break}break;case"url":b0(J,"uri",Q.message,X);break;case"uuid":b0(J,"uuid",Q.message,X);break;case"regex":K0(J,Q.regex,Q.message,X);break;case"cuid":K0(J,k0.cuid,Q.message,X);break;case"cuid2":K0(J,k0.cuid2,Q.message,X);break;case"startsWith":K0(J,RegExp(`^${x9(Q.value,X)}`),Q.message,X);break;case"endsWith":K0(J,RegExp(`${x9(Q.value,X)}$`),Q.message,X);break;case"datetime":b0(J,"date-time",Q.message,X);break;case"date":b0(J,"date",Q.message,X);break;case"time":b0(J,"time",Q.message,X);break;case"duration":b0(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":{K0(J,RegExp(x9(Q.value,X)),Q.message,X);break}case"ip":{if(Q.version!=="v6")b0(J,"ipv4",Q.message,X);if(Q.version!=="v4")b0(J,"ipv6",Q.message,X);break}case"base64url":K0(J,k0.base64url,Q.message,X);break;case"jwt":K0(J,k0.jwt,Q.message,X);break;case"cidr":{if(Q.version!=="v6")K0(J,k0.ipv4Cidr,Q.message,X);if(Q.version!=="v4")K0(J,k0.ipv6Cidr,Q.message,X);break}case"emoji":K0(J,k0.emoji(),Q.message,X);break;case"ulid":{K0(J,k0.ulid,Q.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{b0(J,"binary",Q.message,X);break}case"contentEncoding:base64":{J.contentEncoding="base64";break}case"pattern:zod":{K0(J,k0.base64,Q.message,X);break}}break}case"nanoid":K0(J,k0.nanoid,Q.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return J}function x9(Y,X){return X.patternStrategy==="escape"?lH(Y):Y}var pH=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function lH(Y){let X="";for(let J=0;J<Y.length;J++){if(!pH.has(Y[J]))X+="\\";X+=Y[J]}return X}function b0(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 K0(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:PG(X,Q),...J&&Q.errorMessages&&{errorMessage:{pattern:J}}})}else Y.pattern=PG(X,Q)}function PG(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,U=!1,L=!1;for(let H=0;H<$.length;H++){if(W){G+=$[H],W=!1;continue}if(Q.i){if(U){if($[H].match(/[a-z]/)){if(L)G+=$[H],G+=`${$[H-2]}-${$[H]}`.toUpperCase(),L=!1;else if($[H+1]==="-"&&((J=$[H+2])==null?void 0:J.match(/[a-z]/)))G+=$[H],L=!0;else G+=`${$[H]}${$[H].toUpperCase()}`;continue}}else if($[H].match(/[a-z]/)){G+=`[${$[H]}${$[H].toUpperCase()}]`;continue}}if(Q.m){if($[H]==="^"){G+=`(^|(?<=[\r
|
|
188
|
+
]))`;continue}else if($[H]==="$"){G+=`($|(?=[\r
|
|
189
|
+
]))`;continue}}if(Q.s&&$[H]==="."){G+=U?`${$[H]}\r
|
|
190
|
+
`:`[${$[H]}\r
|
|
191
|
+
]`;continue}if(G+=$[H],$[H]==="\\")W=!0;else if(U&&$[H]==="]")U=!1;else if(!U&&$[H]==="[")U=!0}try{new RegExp(G)}catch(H){return console.warn(`Could not convert regex pattern at ${X.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Y.source}return G}function hG(Y,X){var J,Q,$,G,W,U;let L={type:"object",additionalProperties:(J=n(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:H,...N}=vG(Y.keyType._def,X);return{...L,propertyNames:N}}else if(((G=Y.keyType)==null?void 0:G._def.typeName)==="ZodEnum")return{...L,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"&&((U=Y.keyType._def.type._def.checks)==null?void 0:U.length)){let{type:H,...N}=bG(Y.keyType._def,X);return{...L,propertyNames:N}}return L}function dH(Y,X){if(X.mapStrategy==="record")return hG(Y,X);let J=n(Y.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||A0(),Q=n(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||A0();return{type:"array",maxItems:125,items:{type:"array",items:[J,Q],minItems:2,maxItems:2}}}function iH(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 nH(){return{not:A0()}}function oH(){return{type:"null"}}var v9={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function rH(Y,X){let J=Y.options instanceof Map?Array.from(Y.options.values()):Y.options;if(J.every((Q)=>(Q._def.typeName in v9)&&(!Q._def.checks||!Q._def.checks.length))){let Q=J.reduce(($,G)=>{let W=v9[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,U)=>U.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 sH(Y,X)}var sH=(Y,X)=>{let J=(Y.options instanceof Map?Array.from(Y.options.values()):Y.options).map((Q,$)=>n(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 aH(Y,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Y.innerType._def.typeName)&&(!Y.innerType._def.checks||!Y.innerType._def.checks.length))return{type:[v9[Y.innerType._def.typeName],"null"]};let J=n(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return J&&{anyOf:[J,{type:"null"}]}}function tH(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 eH(Y,X){let J={type:"object",properties:{}},Q=[],$=Y.shape();for(let W in $){let U=$[W];if(U===void 0||U._def===void 0)continue;let L=XL(U),H=n(U._def,{...X,currentPath:[...X.currentPath,"properties",W],propertyPath:[...X.currentPath,"properties",W]});if(H===void 0)continue;if(J.properties[W]=H,!L)Q.push(W)}if(Q.length)J.required=Q;let G=YL(Y,X);if(G!==void 0)J.additionalProperties=G;return J}function YL(Y,X){if(Y.catchall._def.typeName!=="ZodNever")return n(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 XL(Y){try{return Y.isOptional()}catch(X){return!0}}var JL=(Y,X)=>{var J;if(X.currentPath.toString()===((J=X.propertyPath)==null?void 0:J.toString()))return n(Y.innerType._def,X);let Q=n(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return Q?{anyOf:[{not:A0()},Q]}:A0()},QL=(Y,X)=>{if(X.pipeStrategy==="input")return n(Y.in._def,X);else if(X.pipeStrategy==="output")return n(Y.out._def,X);let J=n(Y.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),Q=n(Y.out._def,{...X,currentPath:[...X.currentPath,"allOf",J?"1":"0"]});return{allOf:[J,Q].filter(($)=>$!==void 0)}};function $L(Y,X){return n(Y.type._def,X)}function GL(Y,X){let Q={type:"array",uniqueItems:!0,items:n(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 WL(Y,X){if(Y.rest)return{type:"array",minItems:Y.items.length,items:Y.items.map((J,Q)=>n(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[]),additionalItems:n(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)=>n(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[])}}function zL(){return{not:A0()}}function UL(){return A0()}var HL=(Y,X)=>{return n(Y.innerType._def,X)},LL=(Y,X,J)=>{switch(X){case"ZodString":return vG(Y,J);case"ZodNumber":return tH(Y);case"ZodObject":return eH(Y,J);case"ZodBigInt":return bH(Y);case"ZodBoolean":return xH();case"ZodDate":return xG(Y,J);case"ZodUndefined":return zL();case"ZodNull":return oH();case"ZodArray":return kH(Y,J);case"ZodUnion":case"ZodDiscriminatedUnion":return rH(Y,J);case"ZodIntersection":return cH(Y,J);case"ZodTuple":return WL(Y,J);case"ZodRecord":return hG(Y,J);case"ZodLiteral":return uH(Y);case"ZodEnum":return fH(Y);case"ZodNativeEnum":return iH(Y);case"ZodNullable":return aH(Y,J);case"ZodOptional":return JL(Y,J);case"ZodMap":return dH(Y,J);case"ZodSet":return GL(Y,J);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return $L(Y,J);case"ZodNaN":case"ZodNever":return nH();case"ZodEffects":return yH(Y,J);case"ZodAny":return A0();case"ZodUnknown":return UL();case"ZodDefault":return gH(Y,J);case"ZodBranded":return bG(Y,J);case"ZodReadonly":return HL(Y,J);case"ZodCatch":return vH(Y,J);case"ZodPipeline":return QL(Y,J);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Q)=>{return})(X)}},VL=(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 n(Y,X,J=!1){var Q;let $=X.seen.get(Y);if(X.override){let L=(Q=X.override)==null?void 0:Q.call(X,Y,X,$,J);if(L!==IH)return L}if($&&!J){let L=NL($,X);if(L!==void 0)return L}let G={def:Y,path:X.currentPath,jsonSchema:void 0};X.seen.set(Y,G);let W=LL(Y,Y.typeName,X),U=typeof W==="function"?n(W(),X):W;if(U)BL(Y,X,U);if(X.postProcess){let L=X.postProcess(U,Y,X);return G.jsonSchema=U,L}return G.jsonSchema=U,U}var NL=(Y,X)=>{switch(X.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:VL(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`),A0();return X.$refStrategy==="seen"?A0():void 0}}},BL=(Y,X,J)=>{if(Y.description)J.description=Y.description;return J},ZL=(Y)=>{let X=SH(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}]))}},KL=(Y,X)=>{var J;let Q=ZL(X),$=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((H,[N,O])=>{var Z;return{...H,[N]:(Z=n(O._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,N]},!0))!=null?Z:A0()}},{}):void 0,G=typeof X==="string"?X:(X==null?void 0:X.nameStrategy)==="title"?void 0:X==null?void 0:X.name,W=(J=n(Y._def,G===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,G]},!1))!=null?J:A0(),U=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if(U!==void 0)W.title=U;let L=G===void 0?$?{...W,[Q.definitionPath]:$}:W:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,G].join("/"),[Q.definitionPath]:{...$,[G]:W}};return L.$schema="http://json-schema.org/draft-07/schema#",L},h9=Symbol.for("vercel.ai.schema");function J8(Y){let X;return()=>{if(X==null)X=Y();return X}}function Q8(Y,{validate:X}={}){return{[h9]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:X}}function OL(Y){return typeof Y==="object"&&Y!==null&&h9 in Y&&Y[h9]===!0&&"jsonSchema"in Y&&"validate"in Y}function $8(Y){return Y==null?Q8({type:"object",properties:{},additionalProperties:!1}):OL(Y)?Y:("~standard"in Y)?Y["~standard"].vendor==="zod"?LY(Y):qL(Y):Y()}function qL(Y){return Q8(()=>{if(!FL(Y))throw Error(`Standard schema vendor '${Y["~standard"].vendor}' does not support JSON Schema conversion.`);return m9(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 f0({value:X,cause:J.issues})}}})}function FL(Y){return Y["~standard"].jsonSchema!=null}function jL(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return Q8(()=>KL(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 DL(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return Q8(()=>m9(_$(Y,{target:"draft-7",io:"input",reused:Q?"ref":"inline"})),{validate:async($)=>{let G=await eY(Y,$);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function PL(Y){return"_zod"in Y}function LY(Y,X){if(PL(Y))return DL(Y,X);else return jL(Y,X)}async function VY({value:Y,schema:X,context:J}){let Q=$8(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:f0.wrap({value:Y,cause:$.error,context:J}),rawValue:Y}}catch($){return{success:!1,error:f0.wrap({value:Y,cause:$,context:J}),rawValue:Y}}}async function N1({text:Y,schema:X}){try{let J=_H(Y);if(X==null)return{success:!0,value:J,rawValue:J};return await VY({value:J,schema:X})}catch(J){return{success:!1,error:vY.isInstance(J)?J:new vY({text:Y,cause:J}),rawValue:void 0}}}async function c9(Y){if(typeof Y==="function")Y=Y();return Promise.resolve(Y)}var gG="AI_SerializationError",yG=`vercel.ai.error.${gG}`,ML=Symbol.for(yG),MG,wG,B4=class extends(wG=f,MG=ML,wG){constructor({message:Y="Failed to serialize value.",cause:X}={}){super({name:gG,message:Y,cause:X});this[MG]=!0}static isInstance(Y){return f.hasMarker(Y,yG)}};var AL=Object.defineProperty,TL=(Y,X)=>{for(var J in X)AL(Y,J,{get:X[J],enumerable:!0})},RL="AI_InvalidArgumentError",CL=`vercel.ai.error.${RL}`,_L=Symbol.for(CL),IL;IL=_L;var SL="AI_InvalidStreamPartError",kL=`vercel.ai.error.${SL}`,bL=Symbol.for(kL),xL;xL=bL;var vL="AI_InvalidToolApprovalError",hL=`vercel.ai.error.${vL}`,gL=Symbol.for(hL),yL;yL=gL;var fL="AI_InvalidToolApprovalSignatureError",mL=`vercel.ai.error.${fL}`,cL=Symbol.for(mL),uL;uL=cL;var pL="AI_InvalidToolInputError",lL=`vercel.ai.error.${pL}`,dL=Symbol.for(lL),iL;iL=dL;var nL="AI_ToolCallNotFoundForApprovalError",oL=`vercel.ai.error.${nL}`,rL=Symbol.for(oL),sL;sL=rL;var aL="AI_MissingToolResultsError",tL=`vercel.ai.error.${aL}`,eL=Symbol.for(tL),YV;YV=eL;var XV="AI_NoImageGeneratedError",JV=`vercel.ai.error.${XV}`,QV=Symbol.for(JV),$V;$V=QV;var fG="AI_NoObjectGeneratedError",mG=`vercel.ai.error.${fG}`,GV=Symbol.for(mG),cG,B1=class extends f{constructor({message:Y="No object generated.",cause:X,text:J,response:Q,usage:$,finishReason:G}){super({name:fG,message:Y,cause:X});this[cG]=!0,this.text=J,this.response=Q,this.usage=$,this.finishReason=G}static isInstance(Y){return f.hasMarker(Y,mG)}};cG=GV;var WV="AI_NoOutputGeneratedError",zV=`vercel.ai.error.${WV}`,UV=Symbol.for(zV),HV;HV=UV;var LV="AI_NoSpeechGeneratedError",VV=`vercel.ai.error.${LV}`,NV=Symbol.for(VV),BV;BV=NV;var ZV="AI_NoTranscriptGeneratedError",KV=`vercel.ai.error.${ZV}`,OV=Symbol.for(KV),qV;qV=OV;var FV="AI_NoTranslationGeneratedError",jV=`vercel.ai.error.${FV}`,DV=Symbol.for(jV),PV;PV=DV;var MV="AI_NoVideoGeneratedError",wV=`vercel.ai.error.${MV}`,EV=Symbol.for(wV),AV;AV=EV;var TV="AI_NoSuchToolError",RV=`vercel.ai.error.${TV}`,CV=Symbol.for(RV),_V;_V=CV;var IV="AI_ToolCallRepairError",SV=`vercel.ai.error.${IV}`,kV=Symbol.for(SV),bV;bV=kV;var xV="AI_UIMessageStreamError",vV=`vercel.ai.error.${xV}`,hV=Symbol.for(vV),gV;gV=hV;var yV="AI_InvalidDataContentError",fV=`vercel.ai.error.${yV}`,mV=Symbol.for(fV),cV;cV=mV;var uV="AI_InvalidMessageRoleError",pV=`vercel.ai.error.${uV}`,lV=Symbol.for(pV),dV;dV=lV;var iV="AI_MessageConversionError",nV=`vercel.ai.error.${iV}`,oV=Symbol.for(nV),rV;rV=oV;var sV="AI_RetryError",aV=`vercel.ai.error.${sV}`,tV=Symbol.for(aV),eV;eV=tV;var YN="7.0.59",XN=async({url:Y,maxBytes:X,abortSignal:J})=>{var Q;let $=Y.toString();try{let G=u1({},`ai-sdk/${YN}`,SG()),W=await _G({url:$,headers:G,abortSignal:J});if(!W.ok)throw await X8(W),new O0({url:$,statusCode:W.status,statusText:W.statusText});return{data:await IG({response:W,url:$,maxBytes:X!=null?X:f9}),mediaType:(Q=W.headers.get("content-type"))!=null?Q:void 0}}catch(G){if(O0.isInstance(G))throw G;throw new O0({url:$,cause:G})}};var z={array:C9,boolean:XG,custom:BG,discriminatedUnion:zG,enum:I9,instanceof:ZG,lazy:NG,literal:HG,looseObject:GG,never:R9,null:JG,number:YG,object:$G,record:UG,string:t$,union:_9,unknown:HY},T1=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),T1.optional()),z.array(T1)])),A=z.record(z.string(),z.record(z.string(),T1.optional())),BY=z.union([z.string(),z.instanceof(Uint8Array),z.instanceof(ArrayBuffer),z.custom(kG,{message:"Must be a Buffer"})]),u9=z.record(z.string(),z.string()),uG=z.object({type:z.literal("text"),text:z.string(),providerOptions:A.optional()}),JN=z.object({type:z.literal("image"),image:z.union([BY,z.instanceof(URL),u9]),mediaType:z.string().optional(),providerOptions:A.optional()}),pG=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:BY}),z.object({type:z.literal("url"),url:z.instanceof(URL)}),z.object({type:z.literal("reference"),reference:u9}),z.object({type:z.literal("text"),text:z.string()})]),QN=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:BY}),z.object({type:z.literal("url"),url:z.instanceof(URL)})]),lG=z.object({type:z.literal("file"),data:z.union([pG,BY,z.instanceof(URL),u9]),filename:z.string().optional(),mediaType:z.string(),providerOptions:A.optional()}),$N=z.object({type:z.literal("reasoning"),text:z.string(),providerOptions:A.optional()}),GN=z.object({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerOptions:A.optional()}),WN=z.object({type:z.literal("reasoning-file"),data:z.union([QN,BY,z.instanceof(URL)]),mediaType:z.string(),providerOptions:A.optional()}),zN=z.object({type:z.literal("tool-call"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerOptions:A.optional(),providerExecuted:z.boolean().optional()}),UN=z.discriminatedUnion("type",[z.object({type:z.literal("text"),value:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("json"),value:T1,providerOptions:A.optional()}),z.object({type:z.literal("execution-denied"),reason:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("error-text"),value:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("error-json"),value:T1,providerOptions:A.optional()}),z.object({type:z.literal("content"),value:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("file"),data:pG,mediaType:z.string(),filename:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("file-data"),data:z.string(),mediaType:z.string(),filename:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("file-url"),url:z.string(),mediaType:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:A.optional()}),z.object({type:z.literal("file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:A.optional()}),z.object({type:z.literal("image-data"),data:z.string(),mediaType:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("image-url"),url:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("image-file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:A.optional()}),z.object({type:z.literal("image-file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:A.optional()}),z.object({type:z.literal("custom"),providerOptions:A.optional()})]))})]),dG=z.object({type:z.literal("tool-result"),toolCallId:z.string(),toolName:z.string(),output:UN,providerOptions:A.optional()}),HN=z.object({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string()}),LN=z.object({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional()}),VN=z.object({role:z.literal("system"),content:z.string(),providerOptions:A.optional()}),NN=z.object({role:z.literal("user"),content:z.union([z.string(),z.array(z.union([uG,JN,lG]))]),providerOptions:A.optional()}),BN=z.object({role:z.literal("assistant"),content:z.union([z.string(),z.array(z.union([uG,GN,lG,$N,WN,zN,dG,HN]))]),providerOptions:A.optional()}),ZN=z.object({role:z.literal("tool"),content:z.array(z.union([dG,LN])),providerOptions:A.optional()}),R4=z.union([VN,NN,BN,ZN]);var KN={};TL(KN,{array:()=>jN,choice:()=>DN,json:()=>PN,object:()=>FN,text:()=>qN});function ON(Y){let X=["ROOT"],J=-1,Q=null,$=0;function G(N){return N>="0"&&N<="9"||N>="A"&&N<="F"||N>="a"&&N<="f"}function W(N,O,Z){switch(N){case'"':{J=O,X.pop(),X.push(Z),X.push("INSIDE_STRING");break}case"f":case"t":case"n":{J=O,Q=O,X.pop(),X.push(Z),X.push("INSIDE_LITERAL");break}case"-":{X.pop(),X.push(Z),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=O,X.pop(),X.push(Z),X.push("INSIDE_NUMBER");break}case"{":{J=O,X.pop(),X.push(Z),X.push("INSIDE_OBJECT_START");break}case"[":{J=O,X.pop(),X.push(Z),X.push("INSIDE_ARRAY_START");break}}}function U(N,O){switch(N){case",":{X.pop(),X.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{J=O,X.pop();break}}}function L(N,O){switch(N){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=O,X.pop();break}}}for(let N=0;N<Y.length;N++){let O=Y[N];switch(X[X.length-1]){case"ROOT":W(O,N,"FINISH");break;case"INSIDE_OBJECT_START":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}case"}":{J=N,X.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(O){case":":{X.pop(),X.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{W(O,N,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{U(O,N);break}case"INSIDE_STRING":{switch(O){case'"':{X.pop(),J=N;break}case"\\":{X.push("INSIDE_STRING_ESCAPE");break}default:J=N}break}case"INSIDE_ARRAY_START":{switch(O){case"]":{J=N,X.pop();break}default:{J=N,W(O,N,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(O){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=N,X.pop();break}default:{J=N;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{W(O,N,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{if(X.pop(),O==="u")$=0,X.push("INSIDE_STRING_UNICODE_ESCAPE");else J=N;break}case"INSIDE_STRING_UNICODE_ESCAPE":{if(G(O)){if($++,$===4)X.pop(),J=N}break}case"INSIDE_NUMBER":{switch(O){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=N;break}case"e":case"E":case"-":case".":break;case",":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")L(O,N);if(X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")U(O,N);break}case"}":{if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")U(O,N);break}case"]":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")L(O,N);break}default:{X.pop();break}}break}case"INSIDE_LITERAL":{let V=Y.substring(Q,N+1);if(!"false".startsWith(V)&&!"true".startsWith(V)&&!"null".startsWith(V)){if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")U(O,N);else if(X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")L(O,N)}else J=N;break}}}let H=Y.slice(0,J+1);for(let N=X.length-1;N>=0;N--)switch(X[N]){case"INSIDE_STRING":{H+='"';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":{H+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{H+="]";break}case"INSIDE_LITERAL":{let Z=Y.substring(Q,Y.length);if("true".startsWith(Z))H+="true".slice(Z.length);else if("false".startsWith(Z))H+="false".slice(Z.length);else if("null".startsWith(Z))H+="null".slice(Z.length)}}return H}async function G8(Y){if(Y===void 0)return{value:void 0,state:"undefined-input"};let X=await N1({text:Y});if(X.success)return{value:X.value,state:"successful-parse"};if(X=await N1({text:ON(Y)}),X.success)return{value:X.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var qN=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:Y}){return Y},async parsePartialOutput({text:Y}){return{partial:Y}},createElementStreamTransform(){return}}),FN=({schema:Y,name:X,description:J})=>{let Q=$8(Y);return{name:"object",responseFormat:c9(Q.jsonSchema).then(($)=>({type:"json",schema:$,...X!=null&&{name:X},...J!=null&&{description:J}})),async parseCompleteOutput({text:$},G){let W=await N1({text:$});if(!W.success)throw new B1({message:"No object generated: could not parse the response.",cause:W.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let U=await VY({value:W.value,schema:Q});if(!U.success)throw new B1({message:"No object generated: response did not match schema.",cause:U.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});return U.value},async parsePartialOutput({text:$}){let G=await G8($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:G.value}}},createElementStreamTransform(){return}}},jN=({element:Y,name:X,description:J})=>{let Q=$8(Y);return{name:"array",responseFormat:c9(Q.jsonSchema).then(($)=>{let{$schema:G,...W}=$;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:W}},required:["elements"],additionalProperties:!1},...X!=null&&{name:X},...J!=null&&{description:J}}}),async parseCompleteOutput({text:$},G){let W=await N1({text:$});if(!W.success)throw new B1({message:"No object generated: could not parse the response.",cause:W.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let U=W.value;if(U==null||typeof U!=="object"||!("elements"in U)||!Array.isArray(U.elements))throw new B1({message:"No object generated: response did not match schema.",cause:new f0({value:U,cause:"response must be an object with an elements array"}),text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let L=[];for(let H of U.elements){let N=await VY({value:H,schema:Q});if(!N.success)throw new B1({message:"No object generated: response did not match schema.",cause:N.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});L.push(N.value)}return L},async parsePartialOutput({text:$}){let G=await G8($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let W=G.value;if(W==null||typeof W!=="object"||!("elements"in W)||!Array.isArray(W.elements))return;let U=G.state==="repaired-parse"&&W.elements.length>0?W.elements.slice(0,-1):W.elements,L=[];for(let H of U){let N=await VY({value:H,schema:Q});if(N.success)L.push(N.value)}return{partial:L}}}},createElementStreamTransform(){let $=0;return new TransformStream({transform({partialOutput:G},W){if(G!=null)for(;$<G.length;$++)W.enqueue(G[$])}})}}},DN=({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 N1({text:Q});if(!G.success)throw new B1({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 B1({message:"No object generated: response did not match schema.",cause:new f0({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 G8(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((U)=>U.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}}},PN=({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 N1({text:J});if(!$.success)throw new B1({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 G8(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 S4=G0({prefix:"aitxt",size:24}),k4=G0({prefix:"call",size:24});var x4=class extends TransformStream{constructor(){super({transform(Y,X){X.enqueue(`data: ${JSON.stringify(Y)}
|
|
142
192
|
|
|
143
193
|
`)},flush(Y){Y.enqueue(`data: [DONE]
|
|
144
194
|
|
|
145
|
-
`)}})}};var XY=z.record(z.string(),F1.optional()),IO=dY(()=>e1(z.union([z.looseObject({type:z.literal("text-start"),id:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("text-delta"),id:z.string(),delta:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("text-end"),id:z.string(),providerMetadata:A.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:A.optional(),toolMetadata:XY.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:A.optional(),toolMetadata:XY.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:A.optional(),toolMetadata:XY.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(),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:A.optional()}),z.looseObject({type:z.literal("tool-output-available"),toolCallId:z.string(),output:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional(),toolMetadata:XY.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:A.optional(),toolMetadata:XY.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:A.optional()}),z.looseObject({type:z.literal("reasoning-delta"),id:z.string(),delta:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("reasoning-end"),id:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerMetadata:A.optional()}),z.looseObject({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("file"),url:z.string(),mediaType:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("reasoning-file"),url:z.string(),mediaType:z.string(),providerMetadata:A.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("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 kO=J0({prefix:"aitxt",size:24}),bO=J0({prefix:"call",size:24});var xO=J0({prefix:"aitxt",size:24}),vO=J0({prefix:"call",size:24});var j0=z.record(z.string(),F1.optional()),DL=z.record(z.string(),z.string()),gO=dY(()=>e1(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:A.optional()}),z.object({type:z.literal("reasoning"),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:A.optional()}),z.object({type:z.literal("custom"),kind:z.string(),providerMetadata:A.optional()}),z.object({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:A.optional()}),z.object({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:A.optional()}),z.object({type:z.literal("file"),mediaType:z.string(),filename:z.string().optional(),url:z.string(),providerReference:DL.optional(),providerMetadata:A.optional()}),z.object({type:z.literal("reasoning-file"),mediaType:z.string(),url:z.string(),providerMetadata:A.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(),toolMetadata:j0.optional(),state:z.literal("input-streaming"),input:z.unknown().optional(),providerExecuted:z.boolean().optional(),callProviderMetadata:A.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(),toolMetadata:j0.optional(),state:z.literal("input-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.never().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(),toolMetadata:j0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.boolean(),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(),toolMetadata:j0.optional(),state:z.literal("output-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),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(),toolMetadata:j0.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:A.optional(),resultProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),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(),toolMetadata:j0.optional(),state:z.literal("output-denied"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("input-streaming"),providerExecuted:z.boolean().optional(),callProviderMetadata:A.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(),toolMetadata:j0.optional(),state:z.literal("input-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),reason:z.never().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.boolean(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("output-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.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:A.optional(),resultProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("output-denied"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),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 fO=J0({prefix:"call",size:24});var cO=J0({prefix:"call",size:24});var pO=J0({prefix:"aiobj",size:24});function VG(Y){return({url:X,abortSignal:J})=>eH({url:X,maxBytes:Y==null?void 0:Y.maxBytes,abortSignal:J})}var dO=J0({prefix:"aiobj",size:24});var iO=VG();var PL="AI_NoSuchProviderError",wL=`vercel.ai.error.${PL}`,EL=Symbol.for(wL),ML;ML=EL;var oO=J0({prefix:"call",size:24});var rO=VG();class R0 extends m1{name="ProviderResponseStreamError";constructor(Y,X){super({message:Y,url:"",requestBodyValues:void 0,cause:X?.cause,isRetryable:!0})}}var D0={};g8(D0,{toWebSocketUrl:()=>uL,streamResponsesWebSocket:()=>iL,parseRateLimitSignal:()=>$Y,normalizeHeaders:()=>pL,isUpgradeFailure:()=>lL,isAbortError:()=>I9,connectResponsesWebSocket:()=>dL,PROTOCOL_HEADER:()=>PG,OpenAIWebSocket:()=>D0});function QY(Y){let X=Number(Y.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(X)?X:void 0}function rY(Y,X,J=!1){let $=Buffer.from(Y.slice(0,X)).toString("latin1").split(`\r
|
|
146
|
-
`),G=$[0]??"",W=
|
|
195
|
+
`)}})}};var NY=z.record(z.string(),T1.optional()),h4=J8(()=>LY(z.union([z.looseObject({type:z.literal("text-start"),id:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("text-delta"),id:z.string(),delta:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("text-end"),id:z.string(),providerMetadata:A.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:A.optional(),toolMetadata:NY.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:A.optional(),toolMetadata:NY.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:A.optional(),toolMetadata:NY.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(),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:A.optional()}),z.looseObject({type:z.literal("tool-output-available"),toolCallId:z.string(),output:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional(),toolMetadata:NY.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:A.optional(),toolMetadata:NY.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:A.optional()}),z.looseObject({type:z.literal("reasoning-delta"),id:z.string(),delta:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("reasoning-end"),id:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerMetadata:A.optional()}),z.looseObject({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("file"),url:z.string(),mediaType:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("reasoning-file"),url:z.string(),mediaType:z.string(),providerMetadata:A.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("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 y4=G0({prefix:"aitxt",size:24}),f4=G0({prefix:"call",size:24});var m4=G0({prefix:"aitxt",size:24}),c4=G0({prefix:"call",size:24});var j0=z.record(z.string(),T1.optional()),MN=z.record(z.string(),z.string()),p4=J8(()=>LY(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:A.optional()}),z.object({type:z.literal("reasoning"),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:A.optional()}),z.object({type:z.literal("custom"),kind:z.string(),providerMetadata:A.optional()}),z.object({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:A.optional()}),z.object({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:A.optional()}),z.object({type:z.literal("file"),mediaType:z.string(),filename:z.string().optional(),url:z.string(),providerReference:MN.optional(),providerMetadata:A.optional()}),z.object({type:z.literal("reasoning-file"),mediaType:z.string(),url:z.string(),providerMetadata:A.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(),toolMetadata:j0.optional(),state:z.literal("input-streaming"),input:z.unknown().optional(),providerExecuted:z.boolean().optional(),callProviderMetadata:A.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(),toolMetadata:j0.optional(),state:z.literal("input-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.never().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(),toolMetadata:j0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.boolean(),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(),toolMetadata:j0.optional(),state:z.literal("output-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),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(),toolMetadata:j0.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:A.optional(),resultProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),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(),toolMetadata:j0.optional(),state:z.literal("output-denied"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("input-streaming"),providerExecuted:z.boolean().optional(),callProviderMetadata:A.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(),toolMetadata:j0.optional(),state:z.literal("input-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),reason:z.never().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.boolean(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("output-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.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:A.optional(),resultProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("output-denied"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),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 d4=G0({prefix:"call",size:24});var n4=G0({prefix:"call",size:24});var r4=G0({prefix:"aiobj",size:24});function iG(Y){return({url:X,abortSignal:J})=>XN({url:X,maxBytes:Y==null?void 0:Y.maxBytes,abortSignal:J})}var a4=G0({prefix:"aiobj",size:24});var t4=iG();var wN="AI_NoSuchProviderError",EN=`vercel.ai.error.${wN}`,AN=Symbol.for(EN),TN;TN=AN;var Yq=G0({prefix:"call",size:24});var Xq=iG();class R0 extends a1{name="ProviderResponseStreamError";constructor(Y,X){super({message:Y,url:"",requestBodyValues:void 0,cause:X?.cause,isRetryable:!0})}}var D0={};e8(D0,{toWebSocketUrl:()=>lN,streamResponsesWebSocket:()=>oN,parseRateLimitSignal:()=>KY,normalizeHeaders:()=>dN,isUpgradeFailure:()=>iN,isAbortError:()=>i9,connectResponsesWebSocket:()=>nN,PROTOCOL_HEADER:()=>YW,OpenAIWebSocket:()=>D0});function ZY(Y){let X=Number(Y.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(X)?X:void 0}function W8(Y,X,J=!1){let $=Buffer.from(Y.slice(0,X)).toString("latin1").split(`\r
|
|
196
|
+
`),G=$[0]??"",W=ZY(G);if(W===void 0||W===101)return;let U=Object.fromEntries($.slice(1).flatMap((V)=>{let K=V.indexOf(":");return K===-1?[]:[[V.slice(0,K).trim().toLowerCase(),V.slice(K+1).trim()]]})),L=Y.slice(X+4),H=U["content-length"],N=Number(H);if(!J&&(H===void 0||Number.isFinite(N)&&L.length<N))return;let O=Buffer.from(L).toString("utf8"),Z=(()=>{try{let V=JSON.parse(O);return _(V)?V:void 0}catch{return}})();return{message:`WS upgrade failed: ${G}`,status:W,status_code:W,headers:U,body:O,..._(Z?.error)?{error:Z.error}:{}}}var RN="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",nG=["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 p9{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)}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)),U=Buffer.from(W).toString("base64"),L=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(U+RN));this.expectedAccept=Buffer.from(new Uint8Array(L)).toString("base64");let H={};for(let[Z,V]of Object.entries(X))H[Z.toLowerCase()]=V;let N=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${U}`];for(let Z of nG)if(H[Z]!==void 0)N.push(`${CN(Z)}: ${H[Z]}`);for(let[Z,V]of Object.entries(X))if(!nG.includes(Z.toLowerCase())&&Z.toLowerCase()!=="content-length")N.push(`${Z}: ${V}`);let O=`${N.join(`\r
|
|
147
197
|
`)}\r
|
|
148
198
|
\r
|
|
149
|
-
`;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let
|
|
199
|
+
`;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let Z=globalThis.Bun?.connect;if(!Z)throw Error("Bun.connect is not available");this.socket=await Z({hostname:Q,port:$,tls:J.protocol==="https:"?{serverName:Q}:void 0,socket:{open:(V)=>{this.socket=V,this.enqueueWrite(new TextEncoder().encode(O))},data:(V,K)=>this.onData(K),drain:()=>this.flushWrites(),error:(V,K)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let j=K instanceof Error?K.message:String(K);this.log("socket_error",{message:j}),this.emit("error",{message:j})},close:()=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close"),this.emit("close",{code:1006,reason:"socket closed"})}}})}catch(Z){this.readyState=3;let V=Z instanceof Error?Z.message:String(Z);this.log("connect_exception",{message:V}),this.emit("error",{message:V})}}onData(Y){if(this.rxBuffer=_N(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
|
|
150
200
|
\r
|
|
151
201
|
`);if(J===-1)return;let Q=X.slice(0,J),$=Q.split(`\r
|
|
152
|
-
`)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=
|
|
202
|
+
`)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=ZY($);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
|
|
153
203
|
\r
|
|
154
|
-
`);if(X===-1)return!1;let J=
|
|
204
|
+
`);if(X===-1)return!1;let J=W8(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,U=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],U=4}else if(W===127){if(Y.length<10)return;W=0;for(let H=0;H<8;H++)W=W*256+Y[2+H];U=10}if(G)U+=4;if(Y.length<U+W)return;let L=Y.slice(U,U+W);this.rxBuffer=Y.slice(U+W),this.handleFrame(Q,$,L)}}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;try{this.socket?.end()}catch{}this.log("close_frame",{code:$,reason:G}),this.emit("close",{code:$,reason: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=IN(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 U=7;U>=0;U--)$.push(J/2**(8*U)&255)}let G=new Uint8Array(J);for(let U=0;U<J;U++)G[U]=X[U]^Q[U%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 r0({component:"raw-ws-bun",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function CN(Y){return Y}function _N(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function IN(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 SN}from"node:net";import{connect as kN}from"node:tls";var bN="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",oG=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class l9{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)}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)),U=Buffer.from(W).toString("base64"),L=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(U+bN));this.expectedAccept=Buffer.from(new Uint8Array(L)).toString("base64");let H={};for(let[Z,V]of Object.entries(X))H[Z.toLowerCase()]=V;let N=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${U}`];for(let Z of oG)if(H[Z]!==void 0)N.push(`${xN(Z)}: ${H[Z]}`);for(let[Z,V]of Object.entries(X))if(!oG.includes(Z.toLowerCase())&&Z.toLowerCase()!=="content-length")N.push(`${Z}: ${V}`);let O=`${N.join(`\r
|
|
155
205
|
`)}\r
|
|
156
206
|
\r
|
|
157
|
-
`;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let
|
|
207
|
+
`;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let Z=()=>{this.socket?.write(O)},V=J.protocol==="https:"?kN({host:Q,port:$,servername:Q},Z):SN({host:Q,port:$},Z);this.socket=V,V.on("data",(K)=>{this.onData(typeof K==="string"?Buffer.from(K,"binary"):K)}),V.on("error",(K)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let j=K instanceof Error?K.message:String(K);this.log("socket_error",{message:j}),this.emit("error",{message:j})}),V.on("close",(K)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close",{hadError:K}),this.emit("close",{code:1006,reason:"socket closed"})})}catch(Z){this.readyState=3,this.log("connect_exception",{message:Z instanceof Error?Z.message:String(Z)}),this.emit("error",{message:Z instanceof Error?Z.message:String(Z)})}}onData(Y){if(this.rxBuffer=vN(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
|
|
158
208
|
\r
|
|
159
209
|
`);if(J===-1)return;let Q=X.slice(0,J),$=Q.split(`\r
|
|
160
|
-
`)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=
|
|
210
|
+
`)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=ZY($);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
|
|
161
211
|
\r
|
|
162
|
-
`);if(X===-1)return!1;let J=
|
|
212
|
+
`);if(X===-1)return!1;let J=W8(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,U=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],U=4}else if(W===127){if(Y.length<10)return;W=0;for(let H=0;H<8;H++)W=W*256+Y[2+H];U=10}if(G)U+=4;if(Y.length<U+W)return;let L=Y.slice(U,U+W);this.rxBuffer=Y.slice(U+W),this.handleFrame(Q,$,L)}}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;try{this.socket?.end()}catch{}this.emit("close",{code:$,reason: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=hN(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 U=7;U>=0;U--)$.push(J/2**(8*U)&255)}let G=new Uint8Array(J);for(let U=0;U<J;U++)G[U]=X[U]^Q[U%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 r0({component:"raw-ws-node",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function xN(Y){return Y}function vN(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function hN(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 gN(){return typeof globalThis.Bun?.connect==="function"}var rG=gN()?p9:l9;function z8(Y){return process.env[Y]??process.env[Y.toLowerCase()]}function yN(Y){let X=z8("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 fN(Y){let X=new URL(Y);if(yN(X))return;if(X.protocol==="http:")return z8("HTTP_PROXY");if(X.protocol==="https:")return z8("HTTPS_PROXY")??z8("HTTP_PROXY");return}var sG={getProxyForUrl:fN};var mN=L0("quota"),YW="responses_websockets=2026-02-06",aG=["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"],cN=new Set([G1,"x-opencode-title"]);function uN(Y){let X=new Map;for(let Q of Object.keys(Y))X.set(Q.toLowerCase(),Q);let J={};for(let Q of aG){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(!aG.includes(Q.toLowerCase()))J[Q]=$;return J}function pN(Y){let X={};for(let[J,Q]of Object.entries(Y)){if(cN.has(J.toLowerCase()))continue;X[J]=Q}return X}function lN(Y){return Y.replace(/^http/,"ws")}function dN(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 i9(Y){return Y instanceof DOMException&&Y.name==="AbortError"}var XW=new WeakSet;function iN(Y){return typeof Y==="object"&&Y!==null&&XW.has(Y)}function tG(Y,X){let J=Error(Y,X===void 0?void 0:{cause:X});return XW.add(J),J}function nN(Y){return new Promise((X,J)=>{if(Y.signal?.aborted){J(d9(Y.signal));return}let Q={...Y.headers,"openai-beta":Y.headers["openai-beta"]??YW},$=Q[G1]??Q["session-id"];delete Q["content-length"],Q=uN(pN(Q));let G=typeof Bun>"u"?void 0:sG.getProxyForUrl(Y.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),W=!0,U=Y.rawWebSocket?new rG(Y.url,Q,{sessionID:$}):new globalThis.WebSocket(Y.url,{headers:Q,...G?{proxy:G}:{},perMessageDeflate:W}),L=Y.timeout?setTimeout(()=>{H(),U.close(),J(Error("WebSocket connect timed out"))},Y.timeout):void 0;function H(){if(L)clearTimeout(L);U.removeEventListener("open",N),U.removeEventListener("error",O),U.removeEventListener("close",Z),Y.signal?.removeEventListener("abort",V)}function N(){H(),X(U)}function O(K){H(),J(tG($1(K),K))}function Z(K){H(),J(tG(QW("WebSocket closed before open",K.code,K.reason)))}function V(){H(),U.close(),J(d9(Y.signal))}U.addEventListener("open",N,{once:!0}),U.addEventListener("error",O,{once:!0}),U.addEventListener("close",Z,{once:!0}),Y.signal?.addEventListener("abort",V,{once:!0})})}function oN(Y){let X=new TextEncoder,J=Y.socket,Q,$=()=>{},G=!1,W=!1,U,L=new Set;function H(){if(U)clearTimeout(U);$(),Y.signal?.removeEventListener("abort",I)}function N(R=J){R.close()}function O(){H(),Q?.enqueue(X.encode(`data: [DONE]
|
|
163
213
|
|
|
164
|
-
`)),Q?.close()}function
|
|
214
|
+
`)),Q?.close()}function Z(R){if(G)return;G=!0,H(),Y.onConnectionInvalid?.(R),Q?.error(R)}function V(R){if(G)return;if(!Y.idleTimeout)return;if(U)clearTimeout(U);U=setTimeout(()=>Z(new R0(R)),Y.idleTimeout)}async function K(R){if(G)return;if(typeof R.data!=="string"){Z(new R0("Unexpected binary WebSocket frame"));return}let p=R.data,m=(()=>{try{let c=JSON.parse(p);return typeof c==="object"&&c!==null?c:void 0}catch{return}})();if(m?.type==="codex.rate_limits"){mN.debug("codex.rate_limits frame received",{pid:process.pid}),V("idle timeout waiting for websocket");let c=eG(m);Y.onQuota?.(c);return}let d=!W?KY(m):void 0;if(d&&m){G=!0,H(),Y.onRateLimitReached?.(d.window,d.resetAt),Y.onTerminal?.(m),Y.onFirstEvent?.(),Q?.error(new R0(`OpenAI account rate limit reached at admission (${d.window})`));return}if(m?.type==="error"&&Y.onRetryableTerminal){if($(),U)clearTimeout(U);U=void 0;try{let c=await Y.onRetryableTerminal(m);if(G){if(c)N(c);return}if(c){x(c);return}}catch(c){Z(new R0(c instanceof Error?c.message:String(c),{cause:c}));return}}let y=eN(m,p);if(y&&m){if(!W)Y.onFirstEvent?.(y);G=!0,H(),Y.onTerminal?.(m),Q?.error(new a1({message:y.message,url:J.url,requestBodyValues:Y.body,statusCode:y.status,responseHeaders:y.headers,responseBody:y.body}));return}if(_(m)&&m.type==="response.failed"){let c=_(m.response)?m.response.failed:void 0,X1=_(c)?c.rate_limit_reached_type:void 0;if(typeof X1==="string"){if(G=!0,H(),Y.onRateLimitReached?.(X1),Y.onTerminal?.(m),!W)Y.onFirstEvent?.(),Q?.error(new R0(`OpenAI account rate limit reached mid-stream (${X1})`));else O();return}}if(m)rN(m,Y.sessionID),aN(m,L);let Y0=m?i8(m):m;if(!Y0){if(!W)Y.onFirstEvent?.();V("idle timeout waiting for websocket");return}let p0=Y0===m?p:JSON.stringify(Y0);if(!W)Y.onFirstEvent?.();if(Q?.enqueue(X.encode(`${p0.split(/\r?\n/).map((c)=>`data: ${c}`).join(`
|
|
165
215
|
`)}
|
|
166
216
|
|
|
167
|
-
`)),W=!0,L("idle timeout waiting for websocket"),!s)return;if(s.type==="response.completed"||s.type==="response.done"){G=!0,sL(s,H),Y.onComplete?.(s,H),Y.onTerminal?.(s),O();return}if(s.type==="response.failed"||s.type==="response.incomplete"||s.type==="error")G=!0,Y.onTerminal?.(s),O()}function j(S){B(new R0(o0(S),{cause:S}))}function w(S){if(G)return;B(new R0(MG("WebSocket closed before response.completed",S.code,S.reason)))}function P(){let S=_9(Y.signal);if(G)return;G=!0,U(),N(),Y.onAbort?.(S),Q?.error(S)}function k(S){if(G)return;G=!0,U(),N(),Y.onAbort?.(tL(S))}function x(S){$(),J=S,J.addEventListener("message",Z),J.addEventListener("error",j,{once:!0}),J.addEventListener("close",w,{once:!0}),$=()=>{J.removeEventListener("message",Z),J.removeEventListener("error",j),J.removeEventListener("close",w)};let{background:d,...m}=Y.body;L("idle timeout sending websocket request");try{J.send(JSON.stringify({type:"response.create",...m})),L("idle timeout waiting for websocket")}catch(e){if(G)return;B(new R0(e instanceof Error?e.message:String(e),{cause:e}))}}return new Response(new ReadableStream({start(S){if(Q=S,Y.signal?.addEventListener("abort",P,{once:!0}),Y.signal?.aborted){P();return}x(J)},cancel(S){k(S)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function nL(Y,X){if(!oL(Y))return;await c0({component:"ws",event:"provider_native_web_search_event",sessionID:X,serverEventType:Y.type,itemType:_(Y.item)?Y.item.type:void 0,serverEvent:Y})}function oL(Y){if(typeof Y.type==="string"&&(Y.type.startsWith("response.web_search_call.")||Y.type.startsWith("response.web_search_preview_call.")))return!0;if(_(Y.item)&&typeof Y.item.type==="string")return Y.item.type==="web_search_call"||Y.item.type==="web_search_preview_call";return!1}function rL(Y,X){if(Y.type!=="response.output_item.done")return;if(!_(Y.item))return;EG(Y.item,X)}function sL(Y,X){let J=Y.response;if(!_(J)||!Array.isArray(J.output))return;for(let Q of J.output)if(_(Q))EG(Q,X)}function EG(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 aL(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:_(Y.headers)?Object.fromEntries(Object.entries(Y.headers).flatMap(([Q,$])=>typeof $==="string"||typeof $==="number"||typeof $==="boolean"?[[Q,String($)]]:[])):void 0,body:X,message:_(Y.error)&&typeof Y.error.message==="string"?Y.error.message:`${J}`}}function $Y(Y){if(typeof Y==="string")try{return $Y(JSON.parse(Y))}catch{return}if(!_(Y))return;let X=$Y(Y.cause);if(X)return X;let J=$Y(Y.body);if(J)return J;let Q=_(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 tL(Y){if(I9(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function _9(Y){let X=Y?.reason;if(I9(X))return X;if(eL(X))return X;return new DOMException(X instanceof Error?X.message:"Aborted","AbortError")}function eL(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function MG(Y,X,J){let Q=[`code ${X}`];if(X===1009)Q.push("message too big");if(J.length>0)Q.push(J.toString());return`${Y} (${Q.join(": ")})`}var k9="x-opencode-title",aY="x-openai-auth-quota-account",S9=new Set([k9,r0,aY,"x-opencode-session"]),XN=15000,JN=300000,QN=3300000,AG="websocket_connection_limit_reached";function $N(Y){let X=typeof Y.authorization==="string"&&Y.authorization.startsWith("Bearer ")?Y.authorization.slice(7):"",J=typeof Y["chatgpt-account-id"]==="string"?Y["chatgpt-account-id"]:"";return YN("sha256").update(`${X}:${J}`).digest("hex").slice(0,12)}function GN(Y){let X=Y?.httpFetch??globalThis.fetch,J=new Map,Q=Y?.connectTimeout??XN,$=Y?.idleTimeout??JN,G=Y?.maxConnectionAge??QN,W=Y?.streamRetries??5,K=Y?.firstEventGraceMs??250,H=Y?.rawWebSocket??!1,U=Y?.onQuota,N=Y?.onRateLimitReached,O=setInterval(()=>Z(),Math.min($,60000));if(typeof O==="object"&&"unref"in O&&typeof O.unref==="function")O.unref();async function B(P,k){let x=P instanceof URL?P.toString():typeof P==="string"?P:P.url,S=D0.normalizeHeaders(k?.headers),d=xG(k),m=wY(d);if(k?.method!=="POST"||!new URL(x).pathname.endsWith("/responses"))return X(P,m);let e=(()=>{try{if(typeof k?.body!=="string")return;let a=JSON.parse(k.body);return typeof a==="object"&&a!==null?a:void 0}catch{return}})();if(!e?.stream)return X(P,m);if(S[k9]==="true")return X(P,m);let y=S[r0]??S["x-session-affinity"]??S["session-id"],s=y;if(!y)return X(P,m);let j1=D0.normalizeHeaders(d?.headers),u=$N(j1),g0=`${y}:${u}:conversation`,x1=typeof S[aY]==="string"?S[aY]:void 0,D1=N?(a,z0)=>N(a,x1,z0):void 0,g=J.get(g0)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};if(J.set(g0,g),g.fallback)return X(P,m);if(g.busy)return X(P,m);g.busy=!0,g.lastUsedAt=Date.now();try{let a=ZN(e),z0=D0.normalizeHeaders(d?.headers),J8=typeof z0.authorization==="string"&&z0.authorization.startsWith("Bearer ")?z0.authorization.slice(7):"",Q8=typeof z0["chatgpt-account-id"]==="string"?z0["chatgpt-account-id"]:void 0,P1=U?(Q0)=>U(Q0,J8,x1,Q8):void 0,VY=!g.socket&&!g.continuation?BN(z0):z0;if(g.socket=await UN(g,Y?.url??x,VY,Q,G,H,k?.signal),jN(g,a))await HN(g,a,$,{signal:k?.signal??void 0,sessionID:s,url:Y?.url??x,headers:d?.headers,onRateLimitReached:D1});let y0=()=>{},G1=()=>{},n0=new Promise((Q0,k0)=>{y0=Q0,G1=k0}),W1=qN(g,a),v1=GY(SG(g,W1,a)),z1=typeof v1.previous_response_id==="string";await A1({sessionID:s,transport:"websocket",phase:"main",bodyText:JSON.stringify(v1),url:Y?.url??x,method:d?.method,headers:d?.headers});let B0=D0.streamResponsesWebSocket({socket:g.socket,body:v1,sessionID:s??void 0,idleTimeout:$,signal:k?.signal??void 0,onQuota:P1,onRateLimitReached:D1,onFirstEvent:(Q0)=>y0(Q0??!0),onComplete:(Q0,k0)=>{let K1=TG(Q0);c0({component:"ws-pool",event:"main_completed",sessionID:s,responseID:RG(Q0),usage:K1}),IG(g,a,Q0,k0,z1)},onTerminal:(Q0)=>{if(g.busy=!1,g.lastUsedAt=Date.now(),g.streamFailures=0,Q0.type!=="response.completed"&&Q0.type!=="response.done")g.continuation=void 0,i0(g)},onConnectionInvalid:()=>{if(g.busy=!1,g.lastUsedAt=Date.now(),!g.fallback)L(g);g.continuation=void 0,i0(g),y0(!1)},onAbort:(Q0)=>{g.busy=!1,g.lastUsedAt=Date.now(),g.streamFailures=0,g.continuation=void 0,i0(g),G1(Q0)},onRetryableTerminal:async(Q0)=>{let k0=WN(Q0);if(!k0)return;throw g.fallback=!0,k0}}),q0=await zN(n0,K);if(q0!==!1){if(q0===!0||q0.status<200||q0.status>599)return B0;return new Response(q0.body,{status:q0.status,headers:{"content-type":"application/json",...q0.headers}})}if(!g.fallback)return B0;return X(P,m)}catch(a){if(g.busy=!1,g.lastUsedAt=Date.now(),D0.isAbortError(a))throw g.streamFailures=0,g.continuation=void 0,i0(g),a;let z0=D0.parseRateLimitSignal(a);if(z0)D1?.(z0.window,z0.resetAt);if(D0.isUpgradeFailure(a)&&!H)g.fallback=!0;if(L(g),g.continuation=void 0,i0(g),g.fallback)return X(P,m);return KN(new R0(a instanceof Error?a.message:String(a),{cause:a}))}}function L(P){if(P.streamFailures++,P.streamFailures>W)P.fallback=!0}function Z(){let P=Date.now();for(let[k,x]of J){if(x.busy)continue;if(P-x.lastUsedAt<$)continue;i0(x),J.delete(k)}}function j(){clearInterval(O);for(let P of J.values())i0(P);J.clear()}function w(P){let k=`${P}:`;for(let[x,S]of J){if(!x.startsWith(k))continue;i0(S),J.delete(x)}}return Object.assign(B,{close:j,remove:w})}function WN(Y){if(Y.type!=="error"||!_(Y.error)||Y.error.code!==AG)return;return Error(typeof Y.error.message==="string"?Y.error.message:AG)}async function zN(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 KN(Y){return new Response(new ReadableStream({start(X){X.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function UN(Y,X,J,Q,$,G,W){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<$)return Y.socket;i0(Y);let K=await D0.connectResponsesWebSocket({url:D0.toWebSocketUrl(X),headers:J,timeout:Q,rawWebSocket:G,signal:W??void 0});return Y.connectedAt=Date.now(),K}function i0(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function HN(Y,X,J,Q){if(!Y.socket||!Array.isArray(X.input)||X.input.length===0)return;let $=NN(X);await A1({sessionID:Q.sessionID,transport:"websocket",phase:"prewarm",bodyText:JSON.stringify($),url:Q.url,method:"POST",headers:Q.headers});let G=D0.streamResponsesWebSocket({socket:Y.socket,body:$,sessionID:Q.sessionID,idleTimeout:J,signal:Q.signal,onRateLimitReached:Q.onRateLimitReached,onComplete:(W,K)=>{c0({component:"ws-pool",event:"prewarm_completed",sessionID:Q.sessionID,responseID:RG(W),usage:TG(W)}),IG(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}});await LN(G)}function RG(Y){let X=Y.response;if(!_(X))return;return typeof X.id==="string"?X.id:void 0}function TG(Y){let X=Y.response;if(!_(X))return;return _(X.usage)?X.usage:void 0}async function LN(Y){let X=Y.body?.getReader();if(!X)return;while(!0)if((await X.read()).done)return}function NN(Y){return GY({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:VN(Y.client_metadata)})}function CG(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 VN(Y){if(!_(Y))return Y;if(typeof Y["x-codex-turn-metadata"]!=="string")return Y;try{let X=JSON.parse(Y["x-codex-turn-metadata"]);if(!_(X))return Y;return{...Y,"x-codex-turn-metadata":CG(X),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function BN(Y){let X=Y["x-codex-turn-metadata"];if(!X)return Y;try{let J=JSON.parse(X);if(!_(J))return Y;return{...Y,"x-codex-turn-metadata":CG(J)}}catch{return Y}}var _G=["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 ZN(Y){let X={...Y};if(Array.isArray(Y.input))X.input=Y.input.map(ON);return X}function GY(Y){let X={};for(let J of _G)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 ON(Y){if(!_(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 IG(Y,X,J,Q,$){let G=J.response,W=_(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:b9(X),finalizedCallIds:K}}function SG(Y,X,J=X){let Q=Array.isArray(X.input)?X.input:[],$=Array.isArray(J.input)?J.input:Q,G=b9(J),W=Y.turnInput&&Y.turnSignature===G?FN(Y.turnInput,$):void 0,K=W===void 0?Q:$.slice(W);if(K.length>0&&K.some(kG)||!Y.turnID)Y.turnID=N1(),Y.turnStartedAt=Date.now();Y.turnInput=$.slice(),Y.turnSignature=G;let U=X.client_metadata;if(!_(U)||typeof U["x-codex-turn-metadata"]!=="string")return X;let N;try{N=JSON.parse(U["x-codex-turn-metadata"])}catch{return X}if(!_(N))return X;let O=JSON.stringify({session_id:N.session_id,thread_id:N.thread_id,thread_source:N.thread_source,turn_id:Y.turnID,sandbox:N.sandbox,turn_started_at_unix_ms:Y.turnStartedAt,request_kind:"turn",window_id:N.window_id});return{...X,client_metadata:{...U,"x-codex-turn-metadata":O}}}function FN(Y,X){if(Y.length>X.length)return;for(let J=0;J<Y.length;J++)if(u0(Y[J])!==u0(X[J]))return;return Y.length}function qN(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!J||!Y.continuation)return X;if(Y.continuation.signature!==b9(X))return Y.continuation=void 0,X;if(!bG(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),$=DN(Q,Y.continuation.finalizedCallIds);if($.length===0)return X;return{...X,previous_response_id:Y.continuation.responseID,input:$}}function jN(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!Y.continuation)return!0;if(!J)return!1;if(!bG(Y.continuation.input,J))return!0;return J.slice(Y.continuation.input.length).some(kG)}function kG(Y){if(!_(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function DN(Y,X){return Y.filter((J)=>{if(!_(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 b9(Y){return u0(PN(Object.fromEntries(Object.entries(Y).filter(([X])=>X!=="input"&&X!=="stream"&&X!=="background"&&X!=="previous_response_id"&&X!=="generate"))))}function PN(Y){if(!_(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 bG(Y,X){if(Y.length>=X.length)return!1;for(let J=0;J<Y.length;J++)if(u0(Y[J])!==u0(X[J]))return!1;return!0}function xG(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let X=new Headers(Y.headers);for(let J of S9)X.delete(J);return{...Y,headers:X}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((X)=>!S9.has(X[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([X])=>!S9.has(X.toLowerCase())))}}var CN=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),_N=new Set(["gpt-5.6"]),IN=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),SN="opencode-oauth-dummy-key",kN="terminal_resize_reflow",g9="0.144.0",bN=`codex_exec/${g9} (Debian 12.0.0; aarch64) unknown (codex_exec; ${g9})`,xN="seccomp",vN="main-refresh",hN=120000,gN=90000,yN=4000,vG=50,hG=3,fN=25,mN=60000,cN="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",gG=!1,yG=L0("models"),fG=!1,mG=!1;class f9 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"}}function v9(Y){return Y instanceof f9}function cG(){throw Error(cN)}function uN(Y){return Math.floor(Math.random()*Y)}function pN(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 lN(Y,X,J){let Q=Y.get(X);if(Q)return Q;let $=N1(),G={threadID:$,turnID:N1(),windowID:`${$}:0`};return Y.set(X,G),J?.(),G}function PW(){return TN(jY(),"openai-auth-sessions.json")}function dN(){let Y=new Map;try{let X=JSON.parse(EN(PW(),"utf8"));if(!_(X.sessions))return Y;for(let[J,Q]of Object.entries(X.sessions)){if(!_(Q)||typeof Q.threadID!=="string")continue;Y.set(J,{threadID:Q.threadID,turnID:N1(),windowID:`${Q.threadID}:0`})}}catch{}return Y}function iN(Y){let X=PW(),J=`${X}.tmp-${process.pid}`;try{wN(jY(),{recursive:!0});let Q={version:1,sessions:Object.fromEntries([...Y.entries()].map(([$,G])=>[$,{threadID:G.threadID}]))};RN(J,`${JSON.stringify(Q,null,2)}
|
|
168
|
-
`,"utf8"),MN(J,X)}catch{}}function uG(Y,X){return _(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===X}function nN(Y,X){if(Y.length>X.length)return!1;for(let J=0;J<Y.length;J++)if(u0(Y[J])!==u0(X[J]))return!1;return!0}function oN(Y,X){if(!Y.input)return X.length>0;if(!nN(Y.input,X))return!0;return X.slice(Y.input.length).some((Q)=>uG(Q,"user")||uG(Q,"developer"))}function rN(Y,X){let J=Array.isArray(X?.input)?X.input:void 0;if(J&&(oN(Y,J)||!Y.turnID))Y.turnID=N1(),Y.turnStartedAt=Date.now();else if(!Y.turnStartedAt)Y.turnStartedAt=Date.now();if(J)Y.input=J}function sN(Y){if(!Y.metadata)return{init:Y.init};let X=pN(Y.init?.body);if(!Y.websocket)rN(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:xN,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",kN),Y.headers.set("x-codex-turn-metadata",J),Y.headers.set("user-agent",bN),Y.headers.set("version",g9),Y.dumpSessionID)Y.headers.set(r0,Y.dumpSessionID);let Q=X;if(!Q)return{init:Y.init};let $=Y.responsesLite&&typeof Q.model==="string"&&IN.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(QV);if(XV(Q),JV(Q),SX(Q),eN(Q),$)YV(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(GY(Q))}}}function aN(Y,X){return Y.find((J)=>J.enabled!==!1&&q1(J)&&(J.id===X||J.accountId===X))}function pG(Y,X){if(Y.resetCreditsAvailable!==void 0||X?.resetCreditsAvailable===void 0)return Y;return{...Y,resetCreditsAvailable:X.resetCreditsAvailable}}function tY(Y,X){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:X}}function wW(Y,X,J=Date.now(),Q=X.mainAccountId){let $=Y.getMain(),G=$?.quota;return{main:{quota:G?{...G,checkedAt:$.checkedAt,primary:tY(G.primary,$.checkedAt),secondary:tY(G.secondary,$.checkedAt)}:null,...typeof Q==="string"?{mainAccountId:Q}:{},killed:!1,...G?.resetCreditsAvailable!==void 0?{resetCredits:G.resetCreditsAvailable}:{}},fallbacks:X.accounts.filter((W)=>W.enabled).map((W)=>{let K=Y.getFallback(W.id),H=K?.quota;return{id:W.id,label:W.label,accountId:K?.accountId??W.accountId,quota:H?{...H,checkedAt:K.checkedAt,primary:tY(H.primary,K.checkedAt),secondary:tY(H.secondary,K.checkedAt)}:null,killed:!1,enabled:!0,...H?.resetCreditsAvailable!==void 0?{resetCredits:H.resetCreditsAvailable}:{}}}),route:X.routing?.mode??"main-first",lastUpdated:J}}function H4(Y,X,J,Q=Date.now()){return{...wW(Y,X,Q),activeId:J}}function lG(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 tN(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 dG(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}function eN(Y){if(!w0().webSearch)return;if(!Array.isArray(Y.tools)||Y.tools.length===0)return;if(Y.tools.some((X)=>_(X)&&X.type==="web_search"))return;Y.tools=[...Y.tools,{type:"web_search",external_web_access:!1,search_content_types:["text","image"]}]}function y9(Y){if(Array.isArray(Y)){for(let X of Y)y9(X);return}if(!_(Y))return;if(Y.type==="input_image")delete Y.detail;for(let X of Object.values(Y))y9(X)}function YV(Y){let X=_(Y.reasoning)?{...Y.reasoning}:{};X.context="all_turns",Y.reasoning=X,Y.parallel_tool_calls=!1;let J=Array.isArray(Y.input)?Y.input:[];y9(J);let $=[{type:"additional_tools",role:"developer",tools:Array.isArray(Y.tools)?Y.tools.filter((G)=>!(_(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 XV(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(_(X)&&X.type==="function"&&X.name==="web_search"))}function JV(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(_(X)&&X.type==="function"&&X.name==="websearch_web_search_exa"))}function QV(Y){if(!_(Y))return Y;if(Y.type!=="function")return Y;let X=_(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 $V(Y,X={}){let J=X.codexApiEndpoint??w0().codexApiEndpoint,Q=crypto.randomUUID(),$=dN(),G=()=>iN($),W=!1,K=[],H=null,U=null,N,O=new Z8;async function B(L,Z){let j=Y.client.session;if(typeof j?.promptAsync==="function"){let w=await fX(Y.client,L),P={noReply:!0,parts:[{type:"text",text:Z,ignored:!0}]};if(w?.agent)P.agent=w.agent;if(w?.model)P.model=w.model;if(w?.variant)P.variant=w.variant;await j.promptAsync({path:{id:L},body:P});return}}return{async dispose(){O.stop();for(let L of K)L.close();if(K.length=0,U){await U.stop().catch(()=>{});let L=globalThis;if(L.__openaiAuthRpcServer===U)L.__openaiAuthRpcServer=void 0;U=null}},async event(L){if(L.event.type!=="session.deleted")return;let Z=L.event.properties.info,j=$.get(Z.id);if(j)H?.cacheKeepManager?.remove(j.threadID);if($.delete(Z.id))G();if(N){let w=(await A0(U0()))?.accounts;await FW(Z.id,w,N)}for(let w of K)w.remove(Z.id)},provider:{id:"openai",async models(L,Z){if(Z.auth?.type!=="oauth")return L.models;let j=await A0(U0()),w=!j||zW(j),P=w?null:await vX();if(!w&&P&&!fG)fG=!0,yG.debug("restoring OAuth model costs from models.dev catalog");if(!w&&!P&&!mG)mG=!0,yG.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(L.models).filter(([,k])=>{if(k.options.reasoningMode==="pro")return!1;if(CN.has(k.api.id))return!0;if(_N.has(k.api.id))return!1;let S=k.api.id.match(/^gpt-(\d+\.\d+)/)?.[1];return S?parseFloat(S)>5.4:!1}).map(([k,x])=>[k,{...x,cost:w?{input:0,output:0,cache:{read:0,write:0}}:P?.[x.api.id]??P?.[k]??x.cost,limit:x.id.includes("gpt-5.5")?{context:400000,input:272000,output:128000}:x.id.includes("gpt-5.6")?{context:372000,input:244000,output:128000}:x.limit}]))}},tool:{web_search:_X},auth:{provider:"openai",async loader(L){let Z=await L();if(Z.type!=="oauth")return{};await UW({type:"oauth",access:Z.access??"",refresh:Z.refresh??"",expires:Z.expires??0},U0());let j=await A0(U0()).catch((V)=>{let F=U0();throw Error(`OpenAI auth store at ${F} is corrupt or unreadable: ${V instanceof Error?V.message:String(V)}. Fix or remove it to continue.`,{cause:V})}),w;async function P(){let V=U0();try{let F=AN(V);if(w?.path===V&&w.mtimeMs===F.mtimeMs&&w.size===F.size)return w.storage;let D=await A0(V);return w={path:V,mtimeMs:F.mtimeMs,size:F.size,storage:D},D}catch{return w=void 0,A0(V)}}function k(){w=void 0}if(j&&Z.access){let V=eY({id_token:"",access_token:Z.access,refresh_token:Z.refresh??""});if(V&&V!==j.mainAccountId)await X0((F)=>{return F.mainAccountId=V,F},U0()),j.mainAccountId=V,k()}let x=j?.logging?.level;if(x&&typeof x==="string")DY(x);let S=L0("transport"),d=L0("quota"),m=L0("refresh"),e=L0("accounts");S.info("codex auth loader ready",{codexApiEndpoint:J,transport:w0().rawWebSocket?"raw-websocket":w0().webSockets?"websocket":"http",webSearch:w0().webSearch});let y=new WW({storage:j,fetchQuotaFn:void 0}),s,j1=0,u=new HW({refreshFn:(V)=>b1({refreshToken:V.refreshToken,fetchImpl:V.fetchImpl,now:V.now}),quotaManager:y,onFallbackStorageChanged:k});if(j&&j.accounts.length>0)u.startBackgroundRefresh();let g0=L0("cachekeep"),x1=j?.cachekeep?.enabled===!0,D1=j?.cachekeep?.subagents===!0,g=j?.cachekeep?.sustain===!0,a=BX(j),z0;async function J8(V){await new Promise((F)=>setTimeout(F,V))}async function Q8(V){let F;for(let D=1;D<=hG;D++)try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:V.refresh,access:V.access,expires:V.expires}});return}catch(R){if(F=R,D<hG)await J8(fN*D)}throw new f9(F)}async function P1(V){await X0((F)=>{return F.refresh=F.refresh??{},V(F),F},U0()),k()}async function VY(V){let F=Date.now()+yN;while(Date.now()<F){await new Promise((I)=>setTimeout(I,vG+uN(vG)));let D=await L();if(D.type!=="oauth"||!D.access)continue;if((D.access!==V.access||D.refresh!==V.refresh||(D.expires??0)>(V.expires??0)+60000)&&(!D.expires||D.expires>Date.now()))return m.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:D.expires?D.expires-Date.now():void 0}),{access:D.access,refresh:D.refresh??V.refresh??"",expires:D.expires??0}}return null}async function y0(){if(!z0)z0=(async()=>{let V=await L();if(V.type!=="oauth")throw Error("not oauth");if(!V.refresh)throw Error("Token refresh failed: missing refresh token");let F=iG(V.refresh),D=await A0(U0()),R=D?.refresh?.mainLastRefreshError;if(R&&oG(R,V.refresh,Date.now()))throw Error(rG(R,Date.now()));if(D?.refresh?.mainRefreshLeaseUntil&&D.refresh.mainRefreshLeaseUntil>Date.now()&&D.refresh.mainRefreshLeaseTokenHash===F){let M=await VY(V);if(M)return M;throw Error("Codex OAuth refresh is already in progress")}let I=await PY({name:vN,ttlMs:hN,path:U0(),renew:!0});if(!I){let M=await VY(V);if(M)return M;throw Error("Codex OAuth refresh is already in progress")}let T=crypto.randomUUID(),C=F;try{await P1((h)=>{h.refresh=h.refresh??{},h.refresh.mainRefreshLeaseId=T,h.refresh.mainRefreshLeaseUntil=Date.now()+gN,h.refresh.mainRefreshLeaseTokenHash=F});let M=await A0(U0());if(M?.refresh?.mainRefreshLeaseId!==T||M.refresh.mainRefreshLeaseTokenHash!==F)throw Error("Codex OAuth refresh is already in progress");let E=await b1({refreshToken:V.refresh,fetchImpl:fetch,now:Date.now});return await Q8(E),await P1((h)=>{if(h.refresh=h.refresh??{},h.refresh.mainLastRefreshError=void 0,h.refresh.mainRefreshLeaseId===T)h.refresh.mainRefreshLeaseId=void 0,h.refresh.mainRefreshLeaseUntil=void 0,h.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),C=void 0,E}catch(M){if(V.refresh&&!v9(M))await P1((E)=>{E.refresh=E.refresh??{},E.refresh.mainLastRefreshError=nG({error:M,now:Date.now(),refreshToken:V.refresh??"",previous:E.refresh.mainLastRefreshError})}).catch(()=>{});throw M}finally{if(C)await P1((M)=>{if(M.refresh?.mainRefreshLeaseId===T&&M.refresh.mainRefreshLeaseTokenHash===C)M.refresh.mainRefreshLeaseId=void 0,M.refresh.mainRefreshLeaseUntil=void 0,M.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await I.release().catch(()=>{})}})().finally(()=>{z0=void 0});return z0}let G1=globalThis;G1.__openaiAuthCacheKeepManager?.stop();let n0=new D8({fetchImpl:fetch,getMainToken:async()=>{let V=await L();if(V.type!=="oauth")throw Error("not oauth");if(!V.access||(V.expires??0)<Date.now())try{return(await y0()).access}catch(F){if(v9(F))throw F;if(V.access)return V.access;throw Error("main token refresh failed")}return V.access},refreshFallback:async(V)=>{let F=await P(),D=F?aN(F.accounts,V):void 0;if(!D)throw Error(`fallback account ${V} not found`);let R=await u.refreshAccount(D,F??{version:1,accounts:[D]});if(!R.access)throw Error(`no access token for ${V}`);return R.access},codexResponsesUrl:J,logger:g0,now:Date.now,getWindow:()=>a,getSustain:()=>g});G1.__openaiAuthCacheKeepManager=n0;async function W1(V,F,D,R,I=!1){if(Object.keys(V).length===0&&!I)return;let T=Date.now(),C=V,M={quota:C,refreshAfter:T+300000,checkedAt:T},E;if(D&&D!=="main"){let b=F?LY(F):null,Y0=b?NY(b):void 0,Z0=y.peekFallbackForPolicy(D)?.quota,b0=pG(C,Z0);M={...M,quota:b0},y.setFallback(D,M,F,I,Y0)}else{if(E=R,!E&&F){let Z0=LY(F);E=Z0?NY(Z0):void 0}if(E&&s&&E!==s){d.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:E,currentMainIdentity:s});return}let b=y.peekMainForPolicy(E)?.quota,Y0=pG(C,b);M={...M,quota:Y0},y.setMain(F,M,E,I)}d.debug("quota pushed",{pid:process.pid,accountId:D??"main",snapshot:M.quota});let h=await P();await q0(y,h,D&&D!=="main"?h?.mainAccountId:E)}function v1(V,F,D){let R=V==="main"?y.peekMainForPolicy()?.quota:y.peekFallbackForPolicy(V)?.quota;return GW(R,F,Date.now(),mN,D)}let z1=X.experimentalWebSockets?$1.createWebSocketFetch({httpFetch:fetch,rawWebSocket:w0().rawWebSocket,onQuota:(V,F,D,R)=>{W1(V,F,D,!D||D==="main"?R:void 0,!0)},onRateLimitReached:(V,F,D)=>{if(!F)d.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:V});let R=F??"main",I=v1(R,V,D);y.markRateLimited(R,I),d.debug("mid-stream rate limit mark",{pid:process.pid,accountId:R,window:V})}}):void 0;if(z1)K.push(z1),W=!0;let B0=LW();N=B0;async function q0(V,F,D=F?.mainAccountId){if(!F)return;await ZW(wW(V,F,Date.now(),D),B0)}async function Q0(V,F,D,R,I){let T={activeId:D,route:R,updatedAt:Date.now()};if(V){if(await X8({sessionId:V,...T},I,B0),F&&F!==V){if(R==="sticky-balanced"){let C=(await L1(B0)).stickyAssignments?.[HY(F)]?.accountId,M=I===void 0||C==="main"||I.some((E)=>E.enabled!==!1&&E.id===C);if(!C||!M)return;await X8({sessionId:F,activeId:C,route:R,updatedAt:Date.now()},I,B0);return}await X8({sessionId:F,...T},I,B0)}return}await OW(T,B0)}H={accountStoragePath:U0(),quotaManager:y,loadAccounts:A0,client:Y.client,cacheKeepManager:n0,setCacheKeepEnabled:(V)=>{x1=V},setCacheKeepSubagents:(V)=>{D1=V},setCacheKeepSustain:(V)=>{g=V},setCacheKeepWindow:(V)=>{a=V},clearStickyRouting:(V)=>jW(V,B0),getStickyRouting:async(V)=>BW(await L1(B0),V),refreshSidebar:async()=>{let V=await A0(U0());await q0(y,V)},refreshAllQuota:async()=>y1({getAuth:L,codexRefreshFn:b1,refreshMainWithLease:y0,fallbackManager:u,quotaManager:y,loadAccounts:A0,writeSidebarState:q0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:U0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:q1,whamFn:Y8})};let k0=null;if(Y.directory){let V=await DW(Y.directory),F=globalThis;if(F.__openaiAuthRpcServer)await F.__openaiAuthRpcServer.stop().catch(()=>{}),F.__openaiAuthRpcServer=void 0;try{k0=await iX({dir:V.dir,secureDir:V.secureDir,sweepRoot:V.sweepRoot,drain:cX,apply:async(D)=>{let R={...H,sessionId:D.sessionId},I=await B8(D.command,D.arguments,R);return{text:I.text,knobs:I.knobs}}}),F.__openaiAuthRpcServer=k0,U=k0}catch{}}async function K1(V,F,D,R,I="main"){let T=lG(V,F);if(T.delete("x-api-key"),T.delete("api-key"),T.set("authorization",`Bearer ${D}`),R)T.set("ChatGPT-Account-Id",R);T.set($1.QUOTA_ACCOUNT_HEADER,I);let C=dG(T),M=C?lN($,C,G):void 0,E=V instanceof URL?V:new URL(typeof V==="string"?V:V.url),h=E.pathname.includes("/v1/responses")||E.pathname.includes("/chat/completions")?new URL(J):E,Y0=sN({init:{...F,headers:T},headers:T,metadata:M,installationID:Q,websocket:Boolean(z1&&E.pathname.endsWith("/responses")),responsesLite:X.responsesLite??!1,dumpSessionID:C}).init,Z0=x1,b0=new Headers(Y0?.headers),$0=VX({enabled:Z0,includeSubagents:D1,headers:b0,body:Y0?.body});if(Z0)g0.trace("cachekeep headers",{pid:process.pid,hasParent:b0.has("x-parent-session-id"),sessionKey:$0?.sessionKey,captured:Boolean($0),affinity:b0.get("x-session-affinity"),opencodeSession:b0.get("x-opencode-session"),sessionId:b0.get("session-id")});if(z1&&E.pathname.endsWith("/responses")){if(S.debug("WS transport",{pid:process.pid,pathname:E.pathname,accountId:I}),$0)n0.track($0.sessionKey,$0.bodyText,I,R,$0.replayHeaders,$0.isSubagent);return z1(h,Y0)}let V0=$1.withoutInternalHeaders(Y0);if(typeof V0?.body!=="string")return fetch(h,V0);if($0)n0.track($0.sessionKey,$0.bodyText,I,R,$0.replayHeaders,$0.isSubagent);S.debug("HTTP transport",{pid:process.pid,pathname:E.pathname,accountId:I});try{let T0=await fetch(h,V0);return await A1({sessionID:C,transport:"http",phase:"http",bodyText:V0.body,accountId:I,url:h.toString(),method:V0.method,headers:V0.headers,status:T0.status}),IX(T0)}catch(T0){throw await A1({sessionID:C,transport:"http",phase:"http",bodyText:V0.body,accountId:I,url:h.toString(),method:V0.method,headers:V0.headers,error:T0 instanceof Error?T0.message:String(T0)}),T0}}function BY(V,F){if((F?.method??(V instanceof Request?V.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof F?.body!=="string")return!1;try{let R=V instanceof URL?V.toString():typeof V==="string"?V:V.url;return new URL(R).pathname.endsWith("/responses")}catch{return!1}}function EW(V){return y.peekMainForPolicy(V)?.quota}function m9(V,F){for(let D of[V?.primary?.checkedAt,V?.secondary?.checkedAt,V?.checkedAt,F])if(typeof D==="number"&&Number.isFinite(D))return D;return}function h1(V,F,D,R,I){let T=m9(V,F),C=m9(D),M=R===I&&D!=null&&(V===void 0||C!==void 0&&(T===void 0||C>T));return{quota:M?D:V,quotaCheckedAt:M?C:T,source:M?"file":"memory"}}function c9(V,F,D,R,I){let T=V?.quota,C=h1(T,V?.checkedAt,F,R,I),M=C.source,E=C.quota;if(!VW(E,D))return{exhausted:!1};let h=NW(E,D);if(!h)return{exhausted:!1};return{exhausted:!0,source:M,...h}}function u9(V,F){d.debug("admission skip: exhausted account",{accountId:V,source:F.source,resetsAt:F.resetsAt})}function MW(V,F="killswitch",D){let R=Date.now(),I=y.getMain()?.quota,T=(V?.accounts??[]).filter((b)=>b.enabled!==!1&&q1(b)).map((b)=>({accountId:b.id,quota:y.getFallback(b.id)?.quota})),C=KW(I,T,R,V);if(F==="quota-exhausted"&&D!==void 0)C=Math.max(1,Math.ceil((D-R)/1000));else if(F==="mid-stream-rate-limit"&&D!==void 0){let b=Math.max(1,Math.ceil((D-R)/1000));C=Math.min(C,b)}let M=Math.floor(C/60),E=C%60,h=F==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${M}m ${E}s.`:F==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${M}m ${E}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${M}m ${E}s.`;return new Response(JSON.stringify({error:{message:h,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(C)}})}function p9(V){let F=V?.resetCreditsAvailable;return typeof F==="number"&&Number.isFinite(F)?F:void 0}async function AW(V){let F=KY(V.storage),D=Date.now(),R=y.peekMainForPolicy(V.mainAccountIdentity),I=h1(R?.quota,R?.checkedAt,V.sidebarState.main.quota,V.sidebarState.main.mainAccountId,V.mainAccountIdentity),T=F?UY(R?.quota,V.storage,void 0,D):void 0,C=[{accountId:"main",wireAccountId:V.mainAccountIdentity,access:V.primaryAccess,keepwarmAccountKey:"main",quota:I.quota,quotaCheckedAt:I.quotaCheckedAt,reservePercent:h9(V.storage),configuredOrder:0,resetCreditsApplicable:p9(I.quota),killswitchPasses:T}],M=await u.getUsableFallbackAccounts(V.storage);for(let E of M){if(!E.access)continue;let h=V.sidebarState.fallbacks.find((b0)=>b0.id===E.id),b=y.peekFallbackForPolicy(E.id,E.accountId),Y0=h1(b?.quota,b?.checkedAt,h?.quota,h?.accountId,E.accountId),Z0=F?UY(b?.quota,V.storage,E.id,D):void 0;C.push({accountId:E.id,wireAccountId:E.accountId,access:E.access,keepwarmAccountKey:E.id,fallback:E,quota:Y0.quota,quotaCheckedAt:Y0.quotaCheckedAt,reservePercent:h9(V.storage,E.id),configuredOrder:C.length,resetCreditsApplicable:p9(Y0.quota),killswitchPasses:Z0})}return C}function l9(V,F,D,R,I){let T=KY(I)?V.killswitchPasses:void 0;if(V.accountId==="main"){let h=y.peekMainForPolicy(V.wireAccountId),b=h1(h?.quota,h?.checkedAt,F.main.quota,F.main.mainAccountId,V.wireAccountId);return E8({quota:b.quota,quotaCheckedAt:b.quotaCheckedAt,status:D,now:R,killswitchPasses:T})}let C=F.fallbacks.find((h)=>h.id===V.accountId),M=y.peekFallbackForPolicy(V.accountId,V.wireAccountId),E=h1(M?.quota,M?.checkedAt,C?.quota,C?.accountId,V.wireAccountId);return E8({quota:E.quota,quotaCheckedAt:E.quotaCheckedAt,status:D,now:R,killswitchPasses:T})}function RW(V){return V.accountId==="main"?"main":V.keepwarmAccountKey}function d9(V){return y.isRateLimited(RW(V))}async function $8(V){let F=V.candidates.filter((M)=>!d9(M)),D=new Map(F.map((M)=>[M.accountId,M])),R=Object.fromEntries(F.map((M)=>[M.accountId,M.quotaCheckedAt])),I=new Set(V.excludeAccountIds),T,C=await qW({sessionId:V.sessionId,requestBytes:V.requestBytes,now:V.now,validPinnedAccountIds:[...D.keys()],excludeAccountIds:V.excludeAccountIds,quotaCheckedAtByAccount:R,choose:(M)=>{let E=F.filter((b)=>!I.has(b.accountId));if(E.length===0)return;let h=PX({candidates:E,pendingBytes:M,requestBytes:V.requestBytes,now:V.now,onEmptyWeightedSet:()=>{e.debug("sticky routing: no fresh weighted candidates; using configured order")}});if(!h)return;return T={accountId:h.accountId,source:h.source,pendingBytes:M.get(h.accountId)??0},h}},B0);if(T&&C?.accountId===T.accountId)e.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:HY(V.sessionId),accountId:T.accountId,source:T.source,requestBytes:V.requestBytes,pendingBytes:T.pendingBytes});return C?D.get(C.accountId):void 0}async function TW(V,F){let D=await u.getUsableFallbackAccounts(V),R=[];for(let b of D)if(b.access)R.push({access:b.access,accountId:b.accountId,keepwarmAccountKey:b.id,quotaAccountId:b.id,fallback:b});let I=R.filter((b)=>!y.isRateLimited(b.quotaAccountId)),T=KY(V)?I.filter((b)=>UY(y.peekFallbackForPolicy(b.quotaAccountId,b.accountId)?.quota,V,b.quotaAccountId,Date.now())):I,C=new Map(F.fallbacks.map((b)=>[b.id,{quota:b.quota,accountId:b.accountId}])),M=[],E=[],h=Date.now();for(let b of T){let Y0=C.get(b.quotaAccountId),Z0=c9(y.peekFallbackForPolicy(b.quotaAccountId,b.accountId),Y0?.quota,h,Y0?.accountId,b.accountId);if(Z0.exhausted)E.push({candidate:b,decision:Z0});else M.push(b)}return{current:T,retained:M,skipped:E}}function i9(V,F){if(V.retained.length===0&&!F)return V.current;for(let{candidate:D,decision:R}of V.skipped)u9(D.quotaAccountId,R);return V.retained}async function n9(V,F){try{let D=E1(V.headers);await W1(D,F.access,F.quotaAccountId,void 0,WY(V.headers))}catch{}}async function CW(V,F,D,R){for(let I of R){let T;try{T=await K1(V,F,I.access,I.accountId,I.keepwarmAccountKey)}catch(C){if(C instanceof DOMException&&C.name==="AbortError")throw C;if(F?.signal?.aborted)throw C;throw e.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:I.quotaAccountId}),C}if(!zY(T.status,D))return await u.markUsed(I.fallback),{response:T,accessToken:I.access,quotaAccountId:I.quotaAccountId,activeId:I.keepwarmAccountKey};await n9(T,I),T.body?.cancel().catch(()=>{})}return}async function _W(V,F,D,R,I){if(!BY(V,F))return{response:D};if(!I.length)return{response:D};let T=D,C;for(let M of I){let E;try{E=await K1(V,F,M.access,M.accountId,M.keepwarmAccountKey)}catch(h){if(h instanceof DOMException&&h.name==="AbortError")throw h;if(F?.signal?.aborted)throw h;return e.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:M.quotaAccountId}),{response:T,...C}}if(T.body?.cancel().catch(()=>{}),T=E,C={accessToken:M.access,accountId:M.quotaAccountId},!zY(E.status,R))return await u.markUsed(M.fallback),{response:E,...C};await n9(E,M)}return{response:T,...C}}if(!gG){if(gG=!0,j){let V=[];for(let F of j.accounts)if(q1(F))V.push(F);y.seedFallbacksFromAccounts(V)}q0(y,j).catch(()=>{}),y1({getAuth:L,codexRefreshFn:b1,refreshMainWithLease:y0,fallbackManager:u,quotaManager:y,loadAccounts:A0,writeSidebarState:q0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:U0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:q1,whamFn:Y8,respectBackoff:!0}).catch((V)=>d.warn("boot quota seed failed",{pid:process.pid,error:o0(V)}))}return O.start(async()=>{let F=(await KX({getAuth:L,codexRefreshFn:b1,refreshMainWithLease:y0,fallbackManager:u,quotaManager:y,loadAccounts:A0,writeSidebarState:(D,R)=>O.isStopped()?Promise.resolve():q0(D,R),client:Y.client,fetchImpl:fetch,now:Date.now,configPath:U0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:q1,whamFn:Y8,readSidebarState:()=>L1(B0)})).filter((D)=>!D.ok);if(F.length>0)d.warn("background quota refresh completed with failures",{pid:process.pid,failures:F})},(V)=>{d.warn("background quota refresh failed",{pid:process.pid,error:V instanceof Error?V.message:String(V)})}),{apiKey:SN,async fetch(V,F){let D=lG(V,F),R=dG(D),I=D.get("x-parent-session-id")?.trim()||void 0,T=await P(),C=await L(),M=++j1;if(C.type!=="oauth")return fetch(V,F);F=await tN(V,F);let E=C.access??"";if(!C.access||(C.expires??0)<Date.now()){m.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(C.access),expiresInMs:C.expires?C.expires-Date.now():void 0});try{let t=await y0();C.access=t.access,C.refresh=t.refresh,C.expires=t.expires}catch(t){if(v9(t))throw t}}E=C.access??"";let b=C.accountId??(E?NY(LY(E)??{}):void 0);if(M===j1)s=b;let Y0=T?.routing?.mode??"main-first",Z0,$0=await(()=>{return Z0??=L1(B0),Z0})();if(Y0==="sticky-balanced"&&R&&BY(V,F)&&typeof F?.body==="string"){let t=Buffer.byteLength(F.body,"utf8"),H0=await AW({storage:T,sidebarState:$0,primaryAccess:E,mainAccountIdentity:b}),K0=await $8({sessionId:R,requestBytes:t,candidates:H0,now:Date.now()});if(K0){let YX=d9(K0)?{action:"migrate",reason:"exhausted"}:l9(K0,$0,void 0,Date.now(),T);if(YX.action==="migrate"){let P0=await $8({sessionId:R,requestBytes:t,candidates:H0,excludeAccountIds:[K0.accountId],now:Date.now()});if(P0)e.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:HY(R),fromAccountId:K0.accountId,toAccountId:P0.accountId,reason:YX.reason}),K0=P0}let x0=await K1(V,F,K0.access,K0.wireAccountId,K0.keepwarmAccountKey),XX=async(P0,U1)=>{try{let IW=E1(P0.headers);await W1(IW,U1.access,U1.accountId==="main"?void 0:U1.accountId,U1.accountId==="main"?U1.wireAccountId:void 0,WY(P0.headers))}catch{}};await XX(x0,K0);let JX=l9(K0,$0,x0.status,Date.now(),T);if((x0.status===401||x0.status===403||x0.status===429)&&JX.action==="migrate"){let P0=await $8({sessionId:R,requestBytes:t,candidates:H0,excludeAccountIds:[K0.accountId],now:Date.now()});if(P0){e.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:HY(R),fromAccountId:K0.accountId,toAccountId:P0.accountId,reason:JX.reason});let U1=x0;x0=await K1(V,F,P0.access,P0.wireAccountId,P0.keepwarmAccountKey),U1.body?.cancel().catch(()=>{}),K0=P0,await XX(x0,K0)}}if(K0.fallback&&!zY(x0.status,T))await u.markUsed(K0.fallback);return await Q0(R,I,K0.accountId,Y0,T?.accounts).catch(()=>{}),x0}}let V0=c9(y.peekMainForPolicy(b),$0.main.quota,Date.now(),$0.main.mainAccountId,b),T0=KY(T)&&!UY(EW(b),T,void 0,Date.now()),ZY=y.isRateLimited("main"),o9,G8=()=>{return o9??=TW(T,$0),o9},f0,w1,r9=!1,OY;if(Y0==="fallback-first"&&BY(V,F)){r9=!0;let t=await G8();OY=i9(t,!T0&&!ZY&&!V0.exhausted);let H0=await CW(V,F,T,OY);if(H0)f0=H0.response,w1={accessToken:H0.accessToken,accountId:H0.quotaAccountId,activeId:H0.activeId}}if(!f0){let t=V0.exhausted&&BY(V,F)&&(await G8()).retained.length>0;if(T0||ZY||t){let H0=T0?"killswitch":ZY?"mid-stream-rate-limit":"quota-exhausted";if(H0==="quota-exhausted"&&V0.exhausted)u9("main",V0);e.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:H0}),f0=MW(T,H0,H0==="quota-exhausted"&&V0.exhausted?V0.resetAtMs:ZY?y.rateLimitedUntil("main"):void 0)}else f0=await K1(V,F,E,b,"main")}let s9=Boolean(w1),g1=f0,a9=w1?.accessToken??E,t9=w1?.accountId,e9=w1?.activeId??"main";if(!w1&&!r9&&zY(f0.status,T)){e.debug("reactive fallback triggered",{pid:process.pid,status:f0.status}),OY??=i9(await G8(),!1);let t=await _W(V,F,f0,T,OY),H0=t.response;if(H0!==f0){if(s9=!0,g1=H0,a9=t.accessToken??E,t9=t.accountId,t.accountId)e9=t.accountId}}try{let t=E1(g1.headers);if(s9)await W1(t,a9,t9,void 0,WY(g1.headers));else await W1(t,E,void 0,b,WY(g1.headers))}catch{}return await Q0(R,I,e9,Y0,T?.accounts).catch(()=>{}),g1},async dispose(){if(O.stop(),n0.stop(),G1.__openaiAuthCacheKeepManager===n0)G1.__openaiAuthCacheKeepManager=void 0;if(u.stopBackgroundRefresh(),U){await U.stop().catch(()=>{});let V=globalThis;if(V.__openaiAuthRpcServer===U)V.__openaiAuthRpcServer=void 0;U=null}}}},methods:[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:async()=>{let{redirectUri:L}=await XW(),Z=await tG(),j=aG(crypto.getRandomValues(new Uint8Array(32)).buffer),w=eG(L,Z,j),P=JW(Z,j);return{url:w,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let k=await P,x=eY(k);return{type:"success",refresh:k.refresh_token,access:k.access_token,expires:Date.now()+(k.expires_in??3600)*1000,accountId:x}}finally{YW(j)}}}}},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:async()=>{let{deviceData:L,url:Z,instructions:j}=await QW();return{url:Z,instructions:j,method:"auto",async callback(){try{let w=await $W(L);return{type:"success",refresh:w.refresh_token,access:w.access_token,expires:Date.now()+(w.expires_in??3600)*1000,accountId:eY(w)}}catch{return{type:"failed"}}}}}},{label:"Manually enter API Key",type:"api"}]},"chat.headers":async(L,Z)=>{if(L.model.providerID!=="openai")return;if(Z.headers.originator="opencode",Z.headers["User-Agent"]=`${sG} (${x9.platform()} ${x9.release()}; ${x9.arch()})`,Z.headers["session-id"]=L.sessionID,W&&L.agent==="title")Z.headers[$1.TITLE_HEADER]="true"},"chat.params":async(L,Z)=>{if(L.model.providerID!=="openai")return;Z.maxOutputTokens=void 0},config:async(L)=>{L.command={...L.command??{},[z8]:{template:z8,description:"Show current OpenAI Codex OAuth quota usage for all accounts."},[K8]:{template:K8,description:"Manage OpenAI accounts — add, switch, remove, or reorder."},[U8]:{template:U8,description:"Show or change OpenAI account routing between main-first, fallback-first, and sticky-balanced."},[H8]:{template:H8,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."},[L8]:{template:L8,description:"Show or toggle OpenAI Codex request dump capture for debugging."},[N8]:{template:N8,description:"Show or change the plugin log level (error, warn, info, debug, trace)."},[V8]:{template:V8,description:"Keep Codex prompt cache alive during idle by shadow-replaying the last request."}}},"command.execute.before":async(L)=>{if(!zX.includes(L.command))return;if(!H)await B(L.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),cG();let Z=L.command,j={...H,sessionId:L.sessionID,notify:(P)=>{b8(P,L.sessionID)}},w=await B8(Z,L.arguments,j);if(uX(L.sessionID))b8(w,L.sessionID);else await B(L.sessionID,w.text);cG()}}}var GV=async(Y)=>{let X=w0();return $V(Y,{codexApiEndpoint:X.codexApiEndpoint,experimentalWebSockets:X.webSockets,responsesLite:X.responsesLite})},L4={id:"cortexkit-openai-auth",server:GV};export{dG as resolveSidebarSessionId,LY as parseJwtClaims,pG as mergePushedQuotaMetadata,aN as findCachekeepFallbackAccount,NY as extractAccountIdFromClaims,L4 as default,H4 as buildSidebarState,wW as buildSidebarMachineState,GV as OpenAIAuthPlugin,hN as MAIN_REFRESH_LOCK_TTL_MS,gN as MAIN_REFRESH_LEASE_TTL_MS,$V as CodexAuthPlugin,f9 as AuthPersistError};
|
|
217
|
+
`)),W=!0,V("idle timeout waiting for websocket"),!Y0)return;if(Y0.type==="response.completed"||Y0.type==="response.done"){G=!0,tN(Y0,L),Y.onComplete?.(Y0,L),Y.onTerminal?.(Y0),O();return}if(Y0.type==="response.failed"||Y0.type==="response.incomplete"||Y0.type==="error")G=!0,Y.onTerminal?.(Y0),O()}function j(R){Z(new R0($1(R),{cause:R}))}function M(R){if(G)return;Z(new R0(QW("WebSocket closed before response.completed",R.code,R.reason)))}function I(){let R=d9(Y.signal);if(G)return;G=!0,H(),N(),Y.onAbort?.(R),Q?.error(R)}function E(R){if(G)return;G=!0,H(),N(),Y.onAbort?.(YB(R))}function x(R){$(),J=R,J.addEventListener("message",K),J.addEventListener("error",j,{once:!0}),J.addEventListener("close",M,{once:!0}),$=()=>{J.removeEventListener("message",K),J.removeEventListener("error",j),J.removeEventListener("close",M)};let{background:p,...m}=Y.body;V("idle timeout sending websocket request");try{J.send(JSON.stringify({type:"response.create",...m})),V("idle timeout waiting for websocket")}catch(d){if(G)return;Z(new R0(d instanceof Error?d.message:String(d),{cause:d}))}}return new Response(new ReadableStream({start(R){if(Q=R,Y.signal?.addEventListener("abort",I,{once:!0}),Y.signal?.aborted){I();return}x(J)},cancel(R){E(R)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function rN(Y,X){if(!sN(Y))return;await r0({component:"ws",event:"provider_native_web_search_event",sessionID:X,serverEventType:Y.type,itemType:_(Y.item)?Y.item.type:void 0,serverEvent:Y})}function sN(Y){if(typeof Y.type==="string"&&(Y.type.startsWith("response.web_search_call.")||Y.type.startsWith("response.web_search_preview_call.")))return!0;if(_(Y.item)&&typeof Y.item.type==="string")return Y.item.type==="web_search_call"||Y.item.type==="web_search_preview_call";return!1}function aN(Y,X){if(Y.type!=="response.output_item.done")return;if(!_(Y.item))return;JW(Y.item,X)}function tN(Y,X){let J=Y.response;if(!_(J)||!Array.isArray(J.output))return;for(let Q of J.output)if(_(Q))JW(Q,X)}function JW(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 eN(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:_(Y.headers)?Object.fromEntries(Object.entries(Y.headers).flatMap(([Q,$])=>typeof $==="string"||typeof $==="number"||typeof $==="boolean"?[[Q,String($)]]:[])):void 0,body:X,message:_(Y.error)&&typeof Y.error.message==="string"?Y.error.message:`${J}`}}function KY(Y){if(typeof Y==="string")try{return KY(JSON.parse(Y))}catch{return}if(!_(Y))return;let X=KY(Y.cause);if(X)return X;let J=KY(Y.body);if(J)return J;let Q=_(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:U}=Q,L=typeof W==="number"&&Number.isFinite(W)&&W>0?W*1000:typeof U==="number"&&Number.isFinite(U)&&U>0?Date.now()+U*1000:void 0;return{window:$??"primary",resetAt:L}}function YB(Y){if(i9(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function d9(Y){let X=Y?.reason;if(i9(X))return X;if(XB(X))return X;return new DOMException(X instanceof Error?X.message:"Aborted","AbortError")}function XB(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function QW(Y,X,J){let Q=[`code ${X}`];if(X===1009)Q.push("message too big");if(J.length>0)Q.push(J.toString());return`${Y} (${Q.join(": ")})`}var o9="x-opencode-title",U8="x-openai-auth-quota-account",n9=new Set([o9,G1,U8,"x-opencode-session"]),QB=15000,$B=300000,GB=3300000,$W="websocket_connection_limit_reached";function WB(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 JB("sha256").update(Q).digest("hex").slice(0,12)}function zB(Y){let X=Y?.httpFetch??globalThis.fetch,J=new Map,Q=Y?.connectTimeout??QB,$=Y?.idleTimeout??$B,G=Y?.maxConnectionAge??GB,W=Y?.streamRetries??5,U=Y?.firstEventGraceMs??250,L=Y?.rawWebSocket??!1,H=Y?.onQuota,N=Y?.onRateLimitReached,O=setInterval(()=>j(),Math.min($,60000));if(typeof O==="object"&&"unref"in O&&typeof O.unref==="function")O.unref();function Z(E,x,R){if(!x||!R)return R;r9(E,GW(x));let p=new Headers(R.headers),m=p.get("x-codex-turn-metadata");if(!m)return R;let d=BW(m,E.turnID,E.turnStartedAt);if(!d)return R;return p.set("x-codex-turn-metadata",d),{...R,headers:p}}async function V(E,x){let R=E instanceof URL?E.toString():typeof E==="string"?E:E.url,p=D0.normalizeHeaders(x?.headers),m=OW(x),d=bY(m);if(x?.method!=="POST"||!new URL(R).pathname.endsWith("/responses"))return X(E,d);let y=(()=>{try{if(typeof x?.body!=="string")return;let r=JSON.parse(x.body);return typeof r==="object"&&r!==null?r:void 0}catch{return}})();if(!y?.stream)return X(E,d);if(p[o9]==="true")return X(E,d);let Y0=p[G1]??p["x-session-affinity"]??p["session-id"],p0=Y0;if(!Y0)return X(E,d);let c=D0.normalizeHeaders(m?.headers),X1=WB(c),d1=`${Y0}:${X1}:conversation`,i1=typeof p[U8]==="string"?p[U8]:void 0,C1=N?(r,B0)=>N(r,i1,B0):void 0,h=J.get(d1)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};if(J.set(d1,h),h.fallback)return X(E,Z(h,y,d));if(h.busy)return X(E,Z(h,y,d));h.busy=!0,h.lastUsedAt=Date.now();try{let r=GW(y),B0=D0.normalizeHeaders(m?.headers),N8=typeof B0.authorization==="string"&&B0.authorization.startsWith("Bearer ")?B0.authorization.slice(7):"",_1=typeof B0["chatgpt-account-id"]==="string"?B0["chatgpt-account-id"]:void 0,MY=H?(Q0)=>H(Q0,N8,i1,_1):void 0,l0=!h.socket&&!h.continuation?KB(B0):B0;if(h.socket=await LB(h,Y?.url??R,l0,Q,G,L,x?.signal),jB(h,r))await VB(h,r,$,{signal:x?.signal??void 0,sessionID:p0,url:Y?.url??R,headers:m?.headers,onRateLimitReached:C1});let J1=()=>{},d0=()=>{},K1=new Promise((Q0,T0)=>{J1=Q0,d0=T0}),B8=FB(h,r),i0=OY(NW(h,B8,r)),F0=typeof i0.previous_response_id==="string";await v1({sessionID:p0,transport:"websocket",phase:"main",bodyText:JSON.stringify(i0),url:Y?.url??R,method:m?.method,headers:m?.headers});let x0=D0.streamResponsesWebSocket({socket:h.socket,body:i0,sessionID:p0??void 0,idleTimeout:$,signal:x?.signal??void 0,onQuota:MY,onRateLimitReached:C1,onFirstEvent:(Q0)=>J1(Q0??!0),onComplete:(Q0,T0)=>{let I1=UW(Q0);r0({component:"ws-pool",event:"main_completed",sessionID:p0,responseID:zW(Q0),usage:I1}),VW(h,r,Q0,T0,F0)},onTerminal:(Q0)=>{if(h.busy=!1,h.lastUsedAt=Date.now(),h.streamFailures=0,Q0.type!=="response.completed"&&Q0.type!=="response.done")h.continuation=void 0,Y1(h)},onConnectionInvalid:()=>{if(h.busy=!1,h.lastUsedAt=Date.now(),!h.fallback)K(h);h.continuation=void 0,Y1(h),J1(!1)},onAbort:(Q0)=>{h.busy=!1,h.lastUsedAt=Date.now(),h.streamFailures=0,h.continuation=void 0,Y1(h),d0(Q0)},onRetryableTerminal:async(Q0)=>{let T0=WW(Q0);if(!T0)return;throw h.fallback=!0,T0}}),v0=await UB(K1,U);if(v0!==!1){if(v0===!0||v0.status<200||v0.status>599)return x0;return new Response(v0.body,{status:v0.status,headers:{"content-type":"application/json",...v0.headers}})}if(!h.fallback)return x0;return X(E,Z(h,y,d))}catch(r){if(h.busy=!1,h.lastUsedAt=Date.now(),D0.isAbortError(r))throw h.streamFailures=0,h.continuation=void 0,Y1(h),r;let B0=D0.parseRateLimitSignal(r);if(B0)C1?.(B0.window,B0.resetAt);if(D0.isUpgradeFailure(r)&&!L)h.fallback=!0;if(K(h),h.continuation=void 0,Y1(h),h.fallback)return X(E,Z(h,y,d));return HB(new R0(r instanceof Error?r.message:String(r),{cause:r}))}}function K(E){if(E.streamFailures++,E.streamFailures>W)E.fallback=!0}function j(){let E=Date.now();for(let[x,R]of J){if(R.busy)continue;if(E-R.lastUsedAt<$)continue;Y1(R),J.delete(x)}}function M(){clearInterval(O);for(let E of J.values())Y1(E);J.clear()}function I(E){let x=`${E}:`;for(let[R,p]of J){if(!R.startsWith(x))continue;Y1(p),J.delete(R)}}return Object.assign(V,{close:M,remove:I})}function WW(Y){if(Y.type!=="error"||!_(Y.error)||Y.error.code!==$W)return;return Error(typeof Y.error.message==="string"?Y.error.message:$W)}async function UB(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 HB(Y){return new Response(new ReadableStream({start(X){X.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function LB(Y,X,J,Q,$,G,W){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<$)return Y.socket;Y1(Y);let U=await D0.connectResponsesWebSocket({url:D0.toWebSocketUrl(X),headers:J,timeout:Q,rawWebSocket:G,signal:W??void 0});return Y.connectedAt=Date.now(),U}function Y1(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function VB(Y,X,J,Q){if(!Y.socket||!Array.isArray(X.input)||X.input.length===0)return;let $=BB(X);await v1({sessionID:Q.sessionID,transport:"websocket",phase:"prewarm",bodyText:JSON.stringify($),url:Q.url,method:"POST",headers:Q.headers});let G=D0.streamResponsesWebSocket({socket:Y.socket,body:$,sessionID:Q.sessionID,idleTimeout:J,signal:Q.signal,onRateLimitReached:Q.onRateLimitReached,onComplete:(W,U)=>{r0({component:"ws-pool",event:"prewarm_completed",sessionID:Q.sessionID,responseID:zW(W),usage:UW(W)}),VW(Y,$,W,U,!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 U=WW(W);if(!U)return;throw Y.fallback=!0,U}});await NB(G)}function zW(Y){let X=Y.response;if(!_(X))return;return typeof X.id==="string"?X.id:void 0}function UW(Y){let X=Y.response;if(!_(X))return;return _(X.usage)?X.usage:void 0}async function NB(Y){let X=Y.body?.getReader();if(!X)return;while(!0)if((await X.read()).done)return}function BB(Y){return OY({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:ZB(Y.client_metadata)})}function HW(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 ZB(Y){if(!_(Y))return Y;if(typeof Y["x-codex-turn-metadata"]!=="string")return Y;try{let X=JSON.parse(Y["x-codex-turn-metadata"]);if(!_(X))return Y;return{...Y,"x-codex-turn-metadata":HW(X),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function KB(Y){let X=Y["x-codex-turn-metadata"];if(!X)return Y;try{let J=JSON.parse(X);if(!_(J))return Y;return{...Y,"x-codex-turn-metadata":HW(J)}}catch{return Y}}var LW=["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 GW(Y){let X={...Y};if(Array.isArray(Y.input))X.input=Y.input.map(OB);return X}function OY(Y){let X={};for(let J of LW)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 OB(Y){if(!_(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 VW(Y,X,J,Q,$){let G=J.response,W=_(G)&&typeof G.id==="string"?G.id:void 0;if(!W||!Array.isArray(X.input)){Y.continuation=void 0;return}let U=$?new Set(Y.continuation?.finalizedCallIds):new Set;for(let L of Q)U.add(L);Y.continuation={responseID:W,input:X.input,signature:s9(X),finalizedCallIds:U}}function r9(Y,X,J=X){let Q=Array.isArray(X.input)?X.input:[],$=Array.isArray(J.input)?J.input:Q,G=s9(J),W=Y.turnInput&&Y.turnSignature===G?qB(Y.turnInput,$):void 0,U=W===void 0?Q:$.slice(W);if(U.length>0&&U.some(ZW)||!Y.turnID)Y.turnID=P1(),Y.turnStartedAt=Date.now();Y.turnInput=$.slice(),Y.turnSignature=G}function NW(Y,X,J=X){r9(Y,X,J);let Q=X.client_metadata;if(!_(Q)||typeof Q["x-codex-turn-metadata"]!=="string")return X;let $=BW(Q["x-codex-turn-metadata"],Y.turnID,Y.turnStartedAt);if(!$)return X;return{...X,client_metadata:{...Q,"x-codex-turn-metadata":$}}}function BW(Y,X,J){let Q;try{Q=JSON.parse(Y)}catch{return}if(!_(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 qB(Y,X){if(Y.length>X.length)return;for(let J=0;J<Y.length;J++)if(s0(Y[J])!==s0(X[J]))return;return Y.length}function FB(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!J||!Y.continuation)return X;if(Y.continuation.signature!==s9(X))return Y.continuation=void 0,X;if(!KW(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),$=DB(Q,Y.continuation.finalizedCallIds);if($.length===0)return X;return{...X,previous_response_id:Y.continuation.responseID,input:$}}function jB(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!Y.continuation)return!0;if(!J)return!1;if(!KW(Y.continuation.input,J))return!0;return J.slice(Y.continuation.input.length).some(ZW)}function ZW(Y){if(!_(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function DB(Y,X){return Y.filter((J)=>{if(!_(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 s9(Y){return s0(PB(Object.fromEntries(Object.entries(Y).filter(([X])=>X!=="input"&&X!=="stream"&&X!=="background"&&X!=="previous_response_id"&&X!=="generate"))))}function PB(Y){if(!_(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 KW(Y,X){if(Y.length>=X.length)return!1;for(let J=0;J<Y.length;J++)if(s0(Y[J])!==s0(X[J]))return!1;return!0}function OW(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let X=new Headers(Y.headers);for(let J of n9)X.delete(J);return{...Y,headers:X}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((X)=>!n9.has(X[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([X])=>!n9.has(X.toLowerCase())))}}var CB=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),_B=new Set(["gpt-5.6"]),IB=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),SB="opencode-oauth-dummy-key",kB="terminal_resize_reflow",YX="0.144.0",bB=`codex_exec/${YX} (Debian 12.0.0; aarch64) unknown (codex_exec; ${YX})`,xB="seccomp",vB="main-refresh",hB=120000,gB=90000,yB=4000,qW=50,FW=3,fB=25,mB=60000,cB="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",jW=!1,DW=L0("models"),PW=!1,MW=!1;class JX 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 c0 extends Error{code;constructor(Y,X){super(X);this.name="ResetTargetResolutionError",this.code=Y}}function wW(Y,X,J,Q){let $=(J?.refresh?.refreshBeforeExpiryMinutes??240)*60000;return!Y||!X||X-Q<=$}function uB(Y){return async(X)=>{if(X==="main"){let U=await Y.loadAccounts(Y.accountStoragePath),L=await Y.getAuth();if(L.type!=="oauth")throw new c0("non_oauth_account","Main OpenAI account is not authenticated with OAuth.");if(wW(L.access,L.expires,U,Y.now()))L={type:"oauth",...await Y.refreshMainWithLease()};if(!L.access)throw new c0("token_unavailable","Main OpenAI account has no usable access token.");let H=p1(L.access),N=H?l1(H):void 0,O=await Y.loadAccounts(Y.accountStoragePath);return{accountKey:X,label:"Main account",accessToken:L.access,chatgptAccountId:N??O?.mainAccountId}}let J=await Y.loadAccounts(Y.accountStoragePath),Q=J?.accounts.find((U)=>U.id===X);if(!J||!Q)throw new c0("unknown_account",`Fallback account ${X} was not found.`);if(Q.enabled===!1)throw new c0("disabled_account",`Fallback account ${X} is disabled.`);if(!u0(Q))throw new c0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);let $=Q;if(wW($.access,$.expires,J,Y.now()))$=await Y.refreshFallbackAccount($,J);if(!$.access)throw new c0("token_unavailable",`Fallback account ${X} has no usable access token.`);let G=await Y.loadAccounts(Y.accountStoragePath),W=G?.accounts.find((U)=>U.id===X);if(!G||!W)throw new c0("unknown_account",`Fallback account ${X} was not found.`);if(W.enabled===!1)throw new c0("disabled_account",`Fallback account ${X} is disabled.`);if(!u0(W))throw new c0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);return{accountKey:X,label:$.label??X,accessToken:$.access,chatgptAccountId:W.accountId}}}function pB(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function t9(Y){return Y instanceof JX}function EW(){throw Error(cB)}function lB(Y){return Math.floor(Math.random()*Y)}function dB(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 iB(Y,X,J){let Q=Y.get(X);if(Q)return Q;let $=P1(),G={threadID:$,turnID:P1(),windowID:`${$}:0`};return Y.set(X,G),J?.(),G}function $5(){return RB(RY(),"openai-auth-sessions.json")}function nB(){let Y=new Map;try{let X=JSON.parse(wB($5(),"utf8"));if(!_(X.sessions))return Y;for(let[J,Q]of Object.entries(X.sessions)){if(!_(Q)||typeof Q.threadID!=="string")continue;Y.set(J,{threadID:Q.threadID,turnID:P1(),windowID:`${Q.threadID}:0`})}}catch{}return Y}function oB(Y){let X=$5(),J=`${X}.tmp-${process.pid}`;try{MB(RY(),{recursive:!0});let Q={version:1,sessions:Object.fromEntries([...Y.entries()].map(([$,G])=>[$,{threadID:G.threadID}]))};TB(J,`${JSON.stringify(Q,null,2)}
|
|
218
|
+
`,"utf8"),EB(J,X)}catch{}}function AW(Y,X){return _(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===X}function rB(Y,X){if(Y.length>X.length)return!1;for(let J=0;J<Y.length;J++)if(s0(Y[J])!==s0(X[J]))return!1;return!0}function sB(Y,X){if(!Y.input)return X.length>0;if(!rB(Y.input,X))return!0;return X.slice(Y.input.length).some((Q)=>AW(Q,"user")||AW(Q,"developer"))}function aB(Y,X){let J=Array.isArray(X?.input)?X.input:void 0;if(J&&(sB(Y,J)||!Y.turnID))Y.turnID=P1(),Y.turnStartedAt=Date.now();else if(!Y.turnStartedAt)Y.turnStartedAt=Date.now();if(J)Y.input=J}function tB(Y){if(!Y.metadata)return{init:Y.init};let X=dB(Y.init?.body);if(!Y.websocket)aB(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:xB,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",kB),Y.headers.set("x-codex-turn-metadata",J),Y.headers.set("user-agent",bB),Y.headers.set("version",YX),Y.dumpSessionID)Y.headers.set(G1,Y.dumpSessionID);let Q=X;if(!Q)return{init:Y.init};let $=Y.responsesLite&&typeof Q.model==="string"&&IB.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(GZ);if(QZ(Q),$Z(Q),LJ(Q),XZ(Q),$)JZ(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(OY(Q))}}}function eB(Y,X){return Y.find((J)=>J.enabled!==!1&&u0(J)&&(J.id===X||J.accountId===X))}function TW(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]=$}return J}function H8(Y,X){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:X}}function G5(Y,X,J=Date.now(),Q=X.mainAccountId){let $=Y.getMain(),G=$?.quota;return{main:{quota:G?{...G,checkedAt:$.checkedAt,primary:H8(G.primary,$.checkedAt),secondary:H8(G.secondary,$.checkedAt)}:null,...typeof Q==="string"?{mainAccountId:Q}:{},killed:!1,...G?.resetCreditsAvailable!==void 0?{resetCredits:G.resetCreditsAvailable}:{}},fallbacks:X.accounts.filter((W)=>W.enabled).map((W)=>{let U=Y.getFallback(W.id),L=U?.quota;return{id:W.id,label:W.label,accountId:U?.accountId??W.accountId,quota:L?{...L,checkedAt:U.checkedAt,primary:H8(L.primary,U.checkedAt),secondary:H8(L.secondary,U.checkedAt)}:null,killed:!1,enabled:!0,...L?.resetCreditsAvailable!==void 0?{resetCredits:L.resetCreditsAvailable}:{}}}),route:X.routing?.mode??"main-first",lastUpdated:J}}function OF(Y,X,J,Q=Date.now()){return{...G5(Y,X,Q),activeId:J}}function RW(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 YZ(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 CW(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}function XZ(Y){if(!M0().webSearch)return;if(!Array.isArray(Y.tools)||Y.tools.length===0)return;if(Y.tools.some((X)=>_(X)&&X.type==="web_search"))return;Y.tools=[...Y.tools,{type:"web_search",external_web_access:!1,search_content_types:["text","image"]}]}function XX(Y){if(Array.isArray(Y)){for(let X of Y)XX(X);return}if(!_(Y))return;if(Y.type==="input_image")delete Y.detail;for(let X of Object.values(Y))XX(X)}function JZ(Y){let X=_(Y.reasoning)?{...Y.reasoning}:{};X.context="all_turns",Y.reasoning=X,Y.parallel_tool_calls=!1;let J=Array.isArray(Y.input)?Y.input:[];XX(J);let $=[{type:"additional_tools",role:"developer",tools:Array.isArray(Y.tools)?Y.tools.filter((G)=>!(_(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 QZ(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(_(X)&&X.type==="function"&&X.name==="web_search"))}function $Z(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(_(X)&&X.type==="function"&&X.name==="websearch_web_search_exa"))}function GZ(Y){if(!_(Y))return Y;if(Y.type!=="function")return Y;let X=_(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:L,...H}=Y.parameters;return H})():Y.parameters,{type:J,name:Q,description:$,strict:G,parameters:W,...U}=Y;return{type:J,name:Q,description:$,strict:G??!1,parameters:X,...U}}async function WZ(Y,X={}){let J=X.codexApiEndpoint??M0().codexApiEndpoint,Q=crypto.randomUUID(),$=nB(),G=()=>oB($),W=!1,U=[],L=null,H=null,N,O=new S8;async function Z(V,K){let j=Y.client.session;if(typeof j?.promptAsync==="function"){let M=await FJ(Y.client,V),I={noReply:!0,parts:[{type:"text",text:K,ignored:!0}]};if(M?.agent)I.agent=M.agent;if(M?.model)I.model=M.model;if(M?.variant)I.variant=M.variant;await j.promptAsync({path:{id:V},body:I});return}}return{async dispose(){O.stop();for(let V of U)V.close();if(U.length=0,H){await H.stop().catch(()=>{});let V=globalThis;if(V.__openaiAuthRpcServer===H)V.__openaiAuthRpcServer=void 0;H=null}},async event(V){if(V.event.type!=="session.deleted")return;let K=V.event.properties.info,j=$.get(K.id);if(j)L?.cacheKeepManager?.remove(j.threadID);if($.delete(K.id))G();if(N){let M=(await q0($0()))?.accounts;await Y5(K.id,M,N)}for(let M of U)M.remove(K.id)},provider:{id:"openai",async models(V,K){if(K.auth?.type!=="oauth")return V.models;let j=await q0($0()),M=!j||lW(j),I=M?null:await ZJ();if(!M&&I&&!PW)PW=!0,DW.debug("restoring OAuth model costs from models.dev catalog");if(!M&&!I&&!MW)MW=!0,DW.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(V.models).filter(([,E])=>{if(E.options.reasoningMode==="pro")return!1;if(CB.has(E.api.id))return!0;if(_B.has(E.api.id))return!1;let R=E.api.id.match(/^gpt-(\d+\.\d+)/)?.[1];return R?parseFloat(R)>5.4:!1}).map(([E,x])=>[E,{...x,cost:M?{input:0,output:0,cache:{read:0,write:0}}:I?.[x.api.id]??I?.[E]??x.cost,limit:x.id.includes("gpt-5.5")?{context:400000,input:272000,output:128000}:x.id.includes("gpt-5.6")?{context:372000,input:244000,output:128000}:x.limit}]))}},tool:{web_search:UJ},auth:{provider:"openai",async loader(V){let K=await V();if(K.type!=="oauth")return{};await iW({type:"oauth",access:K.access??"",refresh:K.refresh??"",expires:K.expires??0},$0());let j=await q0($0()).catch((B)=>{let q=$0();throw Error(`OpenAI auth store at ${q} is corrupt or unreadable: ${B instanceof Error?B.message:String(B)}. Fix or remove it to continue.`,{cause:B})}),M;async function I(){let B=$0();try{let q=AB(B);if(M?.path===B&&M.mtimeMs===q.mtimeMs&&M.size===q.size)return M.storage;let D=await q0(B);return M={path:B,mtimeMs:q.mtimeMs,size:q.size,storage:D},D}catch{return M=void 0,q0(B)}}function E(){M=void 0}if(j&&K.access){let B=L8({id_token:"",access_token:K.access,refresh_token:K.refresh??""});if(B&&B!==j.mainAccountId)await J0((q)=>{return q.mainAccountId=B,q},$0()),j.mainAccountId=B,E()}let x=j?.logging?.level;if(x&&typeof x==="string")SY(x);let R=L0("transport"),p=L0("quota"),m=L0("refresh"),d=L0("accounts");R.info("codex auth loader ready",{codexApiEndpoint:J,transport:M0().rawWebSocket?"raw-websocket":M0().webSockets?"websocket":"http",webSearch:M0().webSearch});let y=new pW({storage:j,fetchQuotaFn:void 0}),Y0,p0=0,c=new nW({refreshFn:(B)=>R1({refreshToken:B.refreshToken,fetchImpl:B.fetchImpl,now:B.now}),quotaManager:y,onFallbackStorageChanged:E});if(j&&j.accounts.length>0)c.startBackgroundRefresh();let X1=L0("cachekeep"),d1=j?.cachekeep?.enabled===!0,i1=j?.cachekeep?.subagents===!0,C1=j?.cachekeep?.sustain===!0,h=nX(j),r;async function B0(B){await new Promise((q)=>setTimeout(q,B))}async function N8(B){let q;for(let D=1;D<=FW;D++)try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:B.refresh,access:B.access,expires:B.expires}});return}catch(T){if(q=T,D<FW)await B0(fB*D)}throw new JX(q)}async function _1(B){await J0((q)=>{return q.refresh=q.refresh??{},B(q),q},$0()),E()}async function MY(B){let q=Date.now()+yB;while(Date.now()<q){await new Promise((k)=>setTimeout(k,qW+lB(qW)));let D=await V();if(D.type!=="oauth"||!D.access)continue;if((D.access!==B.access||D.refresh!==B.refresh||(D.expires??0)>(B.expires??0)+60000)&&(!D.expires||D.expires>Date.now()))return m.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:D.expires?D.expires-Date.now():void 0}),{access:D.access,refresh:D.refresh??B.refresh??"",expires:D.expires??0}}return null}async function l0(){if(!r)r=(async()=>{let B=await V();if(B.type!=="oauth")throw Error("not oauth");if(!B.refresh)throw Error("Token refresh failed: missing refresh token");let q=_W(B.refresh),D=await q0($0()),T=D?.refresh?.mainLastRefreshError;if(T&&SW(T,B.refresh,Date.now()))throw Error(kW(T,Date.now()));if(D?.refresh?.mainRefreshLeaseUntil&&D.refresh.mainRefreshLeaseUntil>Date.now()&&D.refresh.mainRefreshLeaseTokenHash===q){let S=await MY(B);if(S)return S;throw Error("Codex OAuth refresh is already in progress")}let k=await kY({name:vB,ttlMs:hB,path:$0(),renew:!0});if(!k){let S=await MY(B);if(S)return S;throw Error("Codex OAuth refresh is already in progress")}let C=crypto.randomUUID(),w=q;try{await _1((g)=>{g.refresh=g.refresh??{},g.refresh.mainRefreshLeaseId=C,g.refresh.mainRefreshLeaseUntil=Date.now()+gB,g.refresh.mainRefreshLeaseTokenHash=q});let S=await q0($0());if(S?.refresh?.mainRefreshLeaseId!==C||S.refresh.mainRefreshLeaseTokenHash!==q)throw Error("Codex OAuth refresh is already in progress");let P=await R1({refreshToken:B.refresh,fetchImpl:fetch,now:Date.now});return await N8(P),await _1((g)=>{if(g.refresh=g.refresh??{},g.refresh.mainLastRefreshError=void 0,g.refresh.mainRefreshLeaseId===C)g.refresh.mainRefreshLeaseId=void 0,g.refresh.mainRefreshLeaseUntil=void 0,g.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),w=void 0,P}catch(S){if(B.refresh&&!t9(S))await _1((P)=>{P.refresh=P.refresh??{},P.refresh.mainLastRefreshError=IW({error:S,now:Date.now(),refreshToken:B.refresh??"",previous:P.refresh.mainLastRefreshError})}).catch(()=>{});throw S}finally{if(w)await _1((S)=>{if(S.refresh?.mainRefreshLeaseId===C&&S.refresh.mainRefreshLeaseTokenHash===w)S.refresh.mainRefreshLeaseId=void 0,S.refresh.mainRefreshLeaseUntil=void 0,S.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await k.release().catch(()=>{})}})().finally(()=>{r=void 0});return r}let J1=globalThis;J1.__openaiAuthCacheKeepManager?.stop();let d0=new h8({fetchImpl:fetch,getMainToken:async()=>{let B=await V();if(B.type!=="oauth")throw Error("not oauth");if(!B.access||(B.expires??0)<Date.now())try{return(await l0()).access}catch(q){if(t9(q))throw q;if(B.access)return B.access;throw Error("main token refresh failed")}return B.access},refreshFallback:async(B)=>{let q=await I(),D=q?eB(q.accounts,B):void 0;if(!D)throw Error(`fallback account ${B} not found`);let T=await c.refreshAccount(D,q??{version:1,accounts:[D]});if(!T.access)throw Error(`no access token for ${B}`);return T.access},codexResponsesUrl:J,logger:X1,now:Date.now,getWindow:()=>h,getSustain:()=>C1});J1.__openaiAuthCacheKeepManager=d0;async function K1(B,q,D,T,k=!1){if(Object.keys(B).length===0&&!k)return;let C=Date.now(),w=B,S={quota:w,refreshAfter:C+300000,checkedAt:C},P;if(D&&D!=="main"){let b=q?p1(q):null,X0=b?l1(b):void 0,Z0=y.peekFallbackForPolicy(D)?.quota,h0=TW(w,Z0);S={...S,quota:h0},y.setFallback(D,S,q,k,X0)}else{if(P=T,!P&&q){let Z0=p1(q);P=Z0?l1(Z0):void 0}if(P&&Y0&&P!==Y0){p.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:P,currentMainIdentity:Y0});return}let b=y.peekMainForPolicy(P)?.quota,X0=TW(w,b);S={...S,quota:X0},y.setMain(q,S,P,k)}p.debug("quota pushed",{pid:process.pid,accountId:D??"main",snapshot:S.quota});let g=await I();await x0(y,g,D&&D!=="main"?g?.mainAccountId:P)}function B8(B,q,D){let T=B==="main"?y.peekMainForPolicy()?.quota:y.peekFallbackForPolicy(B)?.quota;return uW(T,q,Date.now(),mB,D)}let i0=X.experimentalWebSockets?Z1.createWebSocketFetch({httpFetch:fetch,rawWebSocket:M0().rawWebSocket,onQuota:(B,q,D,T)=>{K1(B,q,D,!D||D==="main"?T:void 0,!0)},onRateLimitReached:(B,q,D)=>{if(!q)p.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:B});let T=q??"main",k=B8(T,B,D);y.markRateLimited(T,k),p.debug("mid-stream rate limit mark",{pid:process.pid,accountId:T,window:B})}}):void 0;if(i0)U.push(i0),W=!0;let F0=oW();N=F0;async function x0(B,q,D=q?.mainAccountId){if(!q)return;await tW(G5(B,q,Date.now(),D),F0)}async function v0(B,q,D,T,k){let C={activeId:D,route:T,updatedAt:Date.now()};if(B){if(await V8({sessionId:B,...C},k,F0),q&&q!==B){if(T==="sticky-balanced"){let w=(await D1(F0)).stickyAssignments?.[PY(q)]?.accountId,S=k===void 0||w==="main"||k.some((P)=>P.enabled!==!1&&P.id===w);if(!w||!S)return;await V8({sessionId:q,activeId:w,route:T,updatedAt:Date.now()},k,F0);return}await V8({sessionId:q,...C},k,F0)}return}await eW(C,F0)}L={accountStoragePath:$0(),quotaManager:y,loadAccounts:q0,client:Y.client,resolveResetTarget:uB({getAuth:V,refreshMainWithLease:l0,refreshFallbackAccount:(B,q)=>c.refreshAccount(B,q),loadAccounts:q0,accountStoragePath:$0(),now:Date.now}),...pB(),cacheKeepManager:d0,setCacheKeepEnabled:(B)=>{d1=B},setCacheKeepSubagents:(B)=>{i1=B},setCacheKeepSustain:(B)=>{C1=B},setCacheKeepWindow:(B)=>{h=B},clearStickyRouting:(B)=>J5(B,F0),getStickyRouting:async(B)=>aW(await D1(F0),B),refreshSidebar:async()=>{let B=await q0($0());await x0(y,B)},refreshAllQuota:async()=>k1({getAuth:V,codexRefreshFn:R1,refreshMainWithLease:l0,fallbackManager:c,quotaManager:y,loadAccounts:q0,writeSidebarState:x0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:$0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:u0,whamFn:Q1}),refreshResetTargetQuota:async(B)=>{return(await k1({getAuth:V,codexRefreshFn:R1,refreshMainWithLease:l0,fallbackManager:c,quotaManager:y,loadAccounts:q0,writeSidebarState:x0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:$0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:u0,whamFn:Q1,respectBackoff:!1},{accountKey:B})).find((D)=>D.account===B)??{account:B,ok:!1,error:"targeted quota refresh returned no result"}}};let Q0=null;if(Y.directory){let B=await Q5(Y.directory),q=globalThis;if(q.__openaiAuthRpcServer)await q.__openaiAuthRpcServer.stop().catch(()=>{}),q.__openaiAuthRpcServer=void 0;try{Q0=await AJ({dir:B.dir,secureDir:B.secureDir,sweepRoot:B.sweepRoot,drain:DJ,apply:async(D)=>{let T={...L,sessionId:D.sessionId},k=await I8(D.command,D.arguments,T);return{text:k.text,knobs:k.knobs}}}),q.__openaiAuthRpcServer=Q0,H=Q0}catch{}}async function T0(B,q,D,T,k="main"){let C=RW(B,q);if(C.delete("x-api-key"),C.delete("api-key"),C.set("authorization",`Bearer ${D}`),T)C.set("ChatGPT-Account-Id",T);C.set(Z1.QUOTA_ACCOUNT_HEADER,k);let w=CW(C),S=w?iB($,w,G):void 0,P=B instanceof URL?B:new URL(typeof B==="string"?B:B.url),g=P.pathname.includes("/v1/responses")||P.pathname.includes("/chat/completions")?new URL(J):P,X0=tB({init:{...q,headers:C},headers:C,metadata:S,installationID:Q,websocket:Boolean(i0&&P.pathname.endsWith("/responses")),responsesLite:X.responsesLite??!1,dumpSessionID:w}).init,Z0=d1,h0=new Headers(X0?.headers),W0=iX({enabled:Z0,includeSubagents:i1,headers:h0,body:X0?.body});if(Z0)X1.trace("cachekeep headers",{pid:process.pid,hasParent:h0.has("x-parent-session-id"),sessionKey:W0?.sessionKey,captured:Boolean(W0),affinity:h0.get("x-session-affinity"),opencodeSession:h0.get("x-opencode-session"),sessionId:h0.get("session-id")});if(i0&&P.pathname.endsWith("/responses")){if(R.debug("WS transport",{pid:process.pid,pathname:P.pathname,accountId:k}),W0)d0.track(W0.sessionKey,W0.bodyText,k,T,W0.replayHeaders,W0.isSubagent);return i0(g,X0)}let N0=Z1.withoutInternalHeaders(X0);if(typeof N0?.body!=="string")return fetch(g,N0);if(W0)d0.track(W0.sessionKey,W0.bodyText,k,T,W0.replayHeaders,W0.isSubagent);R.debug("HTTP transport",{pid:process.pid,pathname:P.pathname,accountId:k});try{let C0=await fetch(g,N0);return await v1({sessionID:w,transport:"http",phase:"http",bodyText:N0.body,accountId:k,url:g.toString(),method:N0.method,headers:N0.headers,status:C0.status}),HJ(C0)}catch(C0){throw await v1({sessionID:w,transport:"http",phase:"http",bodyText:N0.body,accountId:k,url:g.toString(),method:N0.method,headers:N0.headers,error:C0 instanceof Error?C0.message:String(C0)}),C0}}function I1(B,q){if((q?.method??(B instanceof Request?B.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof q?.body!=="string")return!1;try{let T=B instanceof URL?B.toString():typeof B==="string"?B:B.url;return new URL(T).pathname.endsWith("/responses")}catch{return!1}}function W5(B){return y.peekMainForPolicy(B)?.quota}function QX(B,q){for(let D of[B?.primary?.checkedAt,B?.secondary?.checkedAt,B?.checkedAt,q])if(typeof D==="number"&&Number.isFinite(D))return D;return}function n1(B,q,D,T,k){let C=QX(B,q),w=QX(D),S=T===k&&D!=null&&(B===void 0||w!==void 0&&(C===void 0||w>C));return{quota:S?D:B,quotaCheckedAt:S?w:C,source:S?"file":"memory"}}function $X(B,q,D,T,k){let C=B?.quota,w=n1(C,B?.checkedAt,q,T,k),S=w.source,P=w.quota;if(!sW(P,D))return{exhausted:!1};let g=rW(P,D);if(!g)return{exhausted:!1};return{exhausted:!0,source:S,...g}}function GX(B,q){p.debug("admission skip: exhausted account",{accountId:B,source:q.source,resetsAt:q.resetsAt})}function z5(B,q="killswitch",D){let T=Date.now(),k=y.getMain()?.quota,C=(B?.accounts??[]).filter((b)=>b.enabled!==!1&&u0(b)).map((b)=>({accountId:b.id,quota:y.getFallback(b.id)?.quota})),w=dW(k,C,T,B);if(q==="quota-exhausted"&&D!==void 0)w=Math.max(1,Math.ceil((D-T)/1000));else if(q==="mid-stream-rate-limit"&&D!==void 0){let b=Math.max(1,Math.ceil((D-T)/1000));w=Math.min(w,b)}let S=Math.floor(w/60),P=w%60,g=q==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${S}m ${P}s.`:q==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${S}m ${P}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${S}m ${P}s.`;return new Response(JSON.stringify({error:{message:g,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(w)}})}function WX(B){let q=B?.resetCreditsAvailable;return typeof q==="number"&&Number.isFinite(q)?q:void 0}async function U5(B){let q=jY(B.storage),D=Date.now(),T=y.peekMainForPolicy(B.mainAccountIdentity),k=n1(T?.quota,T?.checkedAt,B.sidebarState.main.quota,B.sidebarState.main.mainAccountId,B.mainAccountIdentity),C=q?DY(T?.quota,B.storage,void 0,D):void 0,w=[{accountId:"main",wireAccountId:B.mainAccountIdentity,access:B.primaryAccess,keepwarmAccountKey:"main",quota:k.quota,quotaCheckedAt:k.quotaCheckedAt,reservePercent:e9(B.storage),configuredOrder:0,resetCreditsApplicable:WX(k.quota),killswitchPasses:C}],S=await c.getUsableFallbackAccounts(B.storage);for(let P of S){if(!P.access)continue;let g=B.sidebarState.fallbacks.find((h0)=>h0.id===P.id),b=y.peekFallbackForPolicy(P.id,P.accountId),X0=n1(b?.quota,b?.checkedAt,g?.quota,g?.accountId,P.accountId),Z0=q?DY(b?.quota,B.storage,P.id,D):void 0;w.push({accountId:P.id,wireAccountId:P.accountId,access:P.access,keepwarmAccountKey:P.id,fallback:P,quota:X0.quota,quotaCheckedAt:X0.quotaCheckedAt,reservePercent:e9(B.storage,P.id),configuredOrder:w.length,resetCreditsApplicable:WX(X0.quota),killswitchPasses:Z0})}return w}function zX(B,q,D,T,k){let C=jY(k)?B.killswitchPasses:void 0;if(B.accountId==="main"){let g=y.peekMainForPolicy(B.wireAccountId),b=n1(g?.quota,g?.checkedAt,q.main.quota,q.main.mainAccountId,B.wireAccountId);return f8({quota:b.quota,quotaCheckedAt:b.quotaCheckedAt,status:D,now:T,killswitchPasses:C})}let w=q.fallbacks.find((g)=>g.id===B.accountId),S=y.peekFallbackForPolicy(B.accountId,B.wireAccountId),P=n1(S?.quota,S?.checkedAt,w?.quota,w?.accountId,B.wireAccountId);return f8({quota:P.quota,quotaCheckedAt:P.quotaCheckedAt,status:D,now:T,killswitchPasses:C})}function H5(B){return B.accountId==="main"?"main":B.keepwarmAccountKey}function UX(B){return y.isRateLimited(H5(B))}async function Z8(B){let q=B.candidates.filter((P)=>!UX(P)),D=new Map(q.map((P)=>[P.accountId,P])),T=Object.fromEntries(q.map((P)=>[P.accountId,P.quotaCheckedAt])),k=Object.fromEntries(q.map((P)=>[P.accountId,P.wireAccountId])),C=new Set(B.excludeAccountIds),w,S=await X5({sessionId:B.sessionId,requestBytes:B.requestBytes,now:B.now,validPinnedAccountIds:[...D.keys()],excludeAccountIds:B.excludeAccountIds,quotaCheckedAtByAccount:T,wireAccountIdByAccount:k,choose:(P)=>{let g=q.filter((X0)=>!C.has(X0.accountId));if(g.length===0)return;let b=YJ({candidates:g,pendingBytes:P,requestBytes:B.requestBytes,now:B.now,onEmptyWeightedSet:()=>{d.debug("sticky routing: no fresh weighted candidates; using configured order")}});if(!b)return;return w={accountId:b.accountId,source:b.source,pendingBytes:P.get(b.accountId)??0},b}},F0);if(w&&S?.accountId===w.accountId)d.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:PY(B.sessionId),accountId:w.accountId,source:w.source,requestBytes:B.requestBytes,pendingBytes:w.pendingBytes});return S?D.get(S.accountId):void 0}async function L5(B,q){let D=await c.getUsableFallbackAccounts(B),T=[];for(let b of D)if(b.access)T.push({access:b.access,accountId:b.accountId,keepwarmAccountKey:b.id,quotaAccountId:b.id,fallback:b});let k=T.filter((b)=>!y.isRateLimited(b.quotaAccountId)),C=jY(B)?k.filter((b)=>DY(y.peekFallbackForPolicy(b.quotaAccountId,b.accountId)?.quota,B,b.quotaAccountId,Date.now())):k,w=new Map(q.fallbacks.map((b)=>[b.id,{quota:b.quota,accountId:b.accountId}])),S=[],P=[],g=Date.now();for(let b of C){let X0=w.get(b.quotaAccountId),Z0=$X(y.peekFallbackForPolicy(b.quotaAccountId,b.accountId),X0?.quota,g,X0?.accountId,b.accountId);if(Z0.exhausted)P.push({candidate:b,decision:Z0});else S.push(b)}return{current:C,retained:S,skipped:P}}function HX(B,q){if(B.retained.length===0&&!q)return B.current;for(let{candidate:D,decision:T}of B.skipped)GX(D.quotaAccountId,T);return B.retained}async function LX(B,q){try{let D=b1(B.headers);await K1(D,q.access,q.quotaAccountId,void 0,qY(B.headers))}catch{}}async function V5(B,q,D,T){for(let k of T){let C;try{C=await T0(B,q,k.access,k.accountId,k.keepwarmAccountKey)}catch(w){if(w instanceof DOMException&&w.name==="AbortError")throw w;if(q?.signal?.aborted)throw w;throw d.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:k.quotaAccountId}),w}if(!FY(C.status,D))return await c.markUsed(k.fallback),{response:C,accessToken:k.access,quotaAccountId:k.quotaAccountId,activeId:k.keepwarmAccountKey};await LX(C,k),C.body?.cancel().catch(()=>{})}return}async function N5(B,q,D,T,k){if(!I1(B,q))return{response:D};if(!k.length)return{response:D};let C=D,w;for(let S of k){let P;try{P=await T0(B,q,S.access,S.accountId,S.keepwarmAccountKey)}catch(g){if(g instanceof DOMException&&g.name==="AbortError")throw g;if(q?.signal?.aborted)throw g;return d.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:S.quotaAccountId}),{response:C,...w}}if(C.body?.cancel().catch(()=>{}),C=P,w={accessToken:S.access,accountId:S.quotaAccountId},!FY(P.status,T))return await c.markUsed(S.fallback),{response:P,...w};await LX(P,S)}return{response:C,...w}}if(!jW){if(jW=!0,j){let B=[];for(let q of j.accounts)if(u0(q))B.push(q);y.seedFallbacksFromAccounts(B)}x0(y,j).catch(()=>{}),k1({getAuth:V,codexRefreshFn:R1,refreshMainWithLease:l0,fallbackManager:c,quotaManager:y,loadAccounts:q0,writeSidebarState:x0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:$0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:u0,whamFn:Q1,respectBackoff:!0}).catch((B)=>p.warn("boot quota seed failed",{pid:process.pid,error:$1(B)}))}return O.start(async()=>{let q=(await cX({getAuth:V,codexRefreshFn:R1,refreshMainWithLease:l0,fallbackManager:c,quotaManager:y,loadAccounts:q0,writeSidebarState:(D,T)=>O.isStopped()?Promise.resolve():x0(D,T),client:Y.client,fetchImpl:fetch,now:Date.now,configPath:$0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:u0,whamFn:Q1,readSidebarState:()=>D1(F0)})).filter((D)=>!D.ok);if(q.length>0)p.warn("background quota refresh completed with failures",{pid:process.pid,failures:q})},(B)=>{p.warn("background quota refresh failed",{pid:process.pid,error:B instanceof Error?B.message:String(B)})}),{apiKey:SB,async fetch(B,q){let D=RW(B,q),T=CW(D),k=D.get("x-parent-session-id")?.trim()||void 0,C=await I(),w=await V(),S=++p0;if(w.type!=="oauth")return fetch(B,q);q=await YZ(B,q);let P=w.access??"";if(!w.access||(w.expires??0)<Date.now()){m.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(w.access),expiresInMs:w.expires?w.expires-Date.now():void 0});try{let e=await l0();w.access=e.access,w.refresh=e.refresh,w.expires=e.expires}catch(e){if(t9(e))throw e}}P=w.access??"";let b=w.accountId??(P?l1(p1(P)??{}):void 0);if(S===p0)Y0=b;let X0=C?.routing?.mode??"main-first",Z0,W0=await(()=>{return Z0??=D1(F0),Z0})();if(X0==="sticky-balanced"&&T&&I1(B,q)&&typeof q?.body==="string"){let e=Buffer.byteLength(q.body,"utf8"),H0=await U5({storage:C,sidebarState:W0,primaryAccess:P,mainAccountIdentity:b}),U0=await Z8({sessionId:T,requestBytes:e,candidates:H0,now:Date.now()});if(U0){let qX=UX(U0)?{action:"migrate",reason:"exhausted"}:zX(U0,W0,void 0,Date.now(),C);if(qX.action==="migrate"){let P0=await Z8({sessionId:T,requestBytes:e,candidates:H0,excludeAccountIds:[U0.accountId],now:Date.now()});if(P0)d.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:PY(T),fromAccountId:U0.accountId,toAccountId:P0.accountId,reason:qX.reason}),U0=P0}let g0=await T0(B,q,U0.access,U0.wireAccountId,U0.keepwarmAccountKey),FX=async(P0,O1)=>{try{let B5=b1(P0.headers);await K1(B5,O1.access,O1.accountId==="main"?void 0:O1.accountId,O1.accountId==="main"?O1.wireAccountId:void 0,qY(P0.headers))}catch{}};await FX(g0,U0);let jX=zX(U0,W0,g0.status,Date.now(),C);if((g0.status===401||g0.status===403||g0.status===429)&&jX.action==="migrate"){let P0=await Z8({sessionId:T,requestBytes:e,candidates:H0,excludeAccountIds:[U0.accountId],now:Date.now()});if(P0){d.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:PY(T),fromAccountId:U0.accountId,toAccountId:P0.accountId,reason:jX.reason});let O1=g0;g0=await T0(B,q,P0.access,P0.wireAccountId,P0.keepwarmAccountKey),O1.body?.cancel().catch(()=>{}),U0=P0,await FX(g0,U0)}}if(U0.fallback&&!FY(g0.status,C))await c.markUsed(U0.fallback);return await v0(T,k,U0.accountId,X0,C?.accounts).catch(()=>{}),g0}}let N0=$X(y.peekMainForPolicy(b),W0.main.quota,Date.now(),W0.main.mainAccountId,b),C0=jY(C)&&!DY(W5(b),C,void 0,Date.now()),wY=y.isRateLimited("main"),VX,K8=()=>{return VX??=L5(C,W0),VX},n0,S1,NX=!1,EY;if(X0==="fallback-first"&&I1(B,q)){NX=!0;let e=await K8();EY=HX(e,!C0&&!wY&&!N0.exhausted);let H0=await V5(B,q,C,EY);if(H0)n0=H0.response,S1={accessToken:H0.accessToken,accountId:H0.quotaAccountId,activeId:H0.activeId}}if(!n0){let e=N0.exhausted&&I1(B,q)&&(await K8()).retained.length>0;if(C0||wY||e){let H0=C0?"killswitch":wY?"mid-stream-rate-limit":"quota-exhausted";if(H0==="quota-exhausted"&&N0.exhausted)GX("main",N0);d.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:H0}),n0=z5(C,H0,H0==="quota-exhausted"&&N0.exhausted?N0.resetAtMs:wY?y.rateLimitedUntil("main"):void 0)}else n0=await T0(B,q,P,b,"main")}let BX=Boolean(S1),o1=n0,ZX=S1?.accessToken??P,KX=S1?.accountId,OX=S1?.activeId??"main";if(!S1&&!NX&&FY(n0.status,C)){d.debug("reactive fallback triggered",{pid:process.pid,status:n0.status}),EY??=HX(await K8(),!1);let e=await N5(B,q,n0,C,EY),H0=e.response;if(H0!==n0){if(BX=!0,o1=H0,ZX=e.accessToken??P,KX=e.accountId,e.accountId)OX=e.accountId}}try{let e=b1(o1.headers);if(BX)await K1(e,ZX,KX,void 0,qY(o1.headers));else await K1(e,P,void 0,b,qY(o1.headers))}catch{}return await v0(T,k,OX,X0,C?.accounts).catch(()=>{}),o1},async dispose(){if(O.stop(),d0.stop(),J1.__openaiAuthCacheKeepManager===d0)J1.__openaiAuthCacheKeepManager=void 0;if(c.stopBackgroundRefresh(),H){await H.stop().catch(()=>{});let B=globalThis;if(B.__openaiAuthRpcServer===H)B.__openaiAuthRpcServer=void 0;H=null}}}},methods:[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:async()=>{let{redirectUri:V}=await yW(),K=await vW(),j=xW(crypto.getRandomValues(new Uint8Array(32)).buffer),M=hW(V,K,j),I=fW(K,j);return{url:M,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let E=await I,x=L8(E);return{type:"success",refresh:E.refresh_token,access:E.access_token,expires:Date.now()+(E.expires_in??3600)*1000,accountId:x}}finally{gW(j)}}}}},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:async()=>{let{deviceData:V,url:K,instructions:j}=await mW();return{url:K,instructions:j,method:"auto",async callback(){try{let M=await cW(V);return{type:"success",refresh:M.refresh_token,access:M.access_token,expires:Date.now()+(M.expires_in??3600)*1000,accountId:L8(M)}}catch{return{type:"failed"}}}}}},{label:"Manually enter API Key",type:"api"}]},"chat.headers":async(V,K)=>{if(V.model.providerID!=="openai")return;if(K.headers.originator="opencode",K.headers["User-Agent"]=`${bW} (${a9.platform()} ${a9.release()}; ${a9.arch()})`,K.headers["session-id"]=V.sessionID,W&&V.agent==="title")K.headers[Z1.TITLE_HEADER]="true"},"chat.params":async(V,K)=>{if(V.model.providerID!=="openai")return;K.maxOutputTokens=void 0},config:async(V)=>{V.command={...V.command??{},[w8]:{template:w8,description:"Show current OpenAI Codex OAuth quota usage for all accounts."},[E8]:{template:E8,description:"Manage OpenAI accounts — add, switch, remove, or reorder."},[A8]:{template:A8,description:"Show or change OpenAI account routing between main-first, fallback-first, and sticky-balanced."},[T8]:{template:T8,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."},[R8]:{template:R8,description:"Show or toggle OpenAI Codex request dump capture for debugging."},[C8]:{template:C8,description:"Show or change the plugin log level (error, warn, info, debug, trace)."},[_8]:{template:_8,description:"Keep Codex prompt cache alive during idle by shadow-replaying the last request."},[j1]:{template:j1,description:"Spend one reset credit on an exhausted Codex account."}}},"command.execute.before":async(V)=>{if(!fX.includes(V.command))return;if(!L)await Z(V.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),EW();let K=V.command,j={...L,sessionId:V.sessionID,notify:(I)=>{r8(I,V.sessionID)}},M=await I8(K,V.arguments,j);if(PJ(V.sessionID))r8(M,V.sessionID);else await Z(V.sessionID,M.text);EW()}}}var zZ=async(Y)=>{let X=M0();return WZ(Y,{codexApiEndpoint:X.codexApiEndpoint,experimentalWebSockets:X.webSockets,responsesLite:X.responsesLite})},qF={id:"cortexkit-openai-auth",server:zZ};export{CW as resolveSidebarSessionId,p1 as parseJwtClaims,TW as mergePushedQuotaMetadata,eB as findCachekeepFallbackAccount,l1 as extractAccountIdFromClaims,qF as default,uB as createResetTargetResolver,OF as buildSidebarState,G5 as buildSidebarMachineState,pB as buildResetRedemptionDeps,c0 as ResetTargetResolutionError,zZ as OpenAIAuthPlugin,hB as MAIN_REFRESH_LOCK_TTL_MS,gB as MAIN_REFRESH_LEASE_TTL_MS,WZ as CodexAuthPlugin,JX as AuthPersistError};
|