@cortexkit/opencode-openai-auth 0.6.5 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +1 -1
- package/dist/core/oauth.d.ts +1 -1
- package/dist/core/reset-credits.d.ts +5 -3
- package/dist/{index-kmy1bsj7.js → index-n2s7s3h6.js} +5 -5
- package/dist/index.js +40 -40
- package/dist/version.d.ts +1 -1
- package/package.json +1 -1
- package/src/tui/command-dialogs.tsx +3 -3
- package/src/tui-compiled/tui/command-dialogs.tsx +3 -3
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{d as g1,e as jY,f as r2}from"./index-87145jkw.js";import{A as t0,B as S1,C as W1,D as h4,E as g4,F as i0,G as y4,H as M1,I as u0,J as nX,K as D0,L as J0,M as DY,N as PY,O as WX,P as MY,Q as f4,R as m4,S as c4,h as A4,i as T4,j as xY,k as vY,l as R4,m as _4,n as C4,o as o1,p as r1,q as B8,s as I4,t as S4,u as k4,v as b4,w as x4,x as v4,y as dX,z as iX}from"./index-kmy1bsj7.js";import{$ as w1,U as p8,X as EY,Y as u4,da as p4,ea as l4,fa as d4,ka as i4,la as K8,ma as n4,na as o4,oa as r4,pa as s4}from"./index-zbpt7v1a.js";import{wa as hY}from"./index-8f1200qx.js";import{xa as vJ,ya as hJ}from"./index-00rp531h.js";import{Aa as bY,Ba as VJ,Ca as V0}from"./index-80gqxa1f.js";import{Fa as a4}from"./index-4agbg1ec.js";import{Ia as G9}from"./index-x55z0b3y.js";import{mkdirSync as KZ,readFileSync as OZ,renameSync as FZ,statSync as qZ,writeFileSync as jZ}from"node:fs";import $X from"node:os";import{join as DZ}from"node:path";import{readFileSync as Uz}from"node:fs";import{homedir as Lz,tmpdir as Hz}from"node:os";import{join as _Y}from"node:path";var Nz="https://chatgpt.com/backend-api/codex/responses",Vz="openai-auth.json",a0={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 CY(){let Y=process.env[a0.configDir]?.trim();if(Y)return Y;return _Y(process.env.XDG_CONFIG_HOME||_Y(Lz(),".config"),"opencode")}function G0(){return process.env[a0.configFile]?.trim()||_Y(CY(),Vz)}function Zz(){try{let Y=JSON.parse(Uz(G0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function RX(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 RY(Y,X,J){let Q=RX(Y);if(Q!==void 0)return Q;if(typeof X==="boolean")return X;return J}function Bz(){let Y=Zz(),X=RX(a0.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:RY(a0.webSockets,Y.webSockets,!1),rawWebSocket:RY(a0.rawWebSocket,Y.rawWebSocket,!1),responsesLite:RY(a0.responsesLite,Y.responsesLite,!1),dump:RY(a0.dump,Q,!1),dumpDir:process.env[a0.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():_Y(Hz(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[a0.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():Nz)}}var D8;function A0(){if(!D8)D8=Bz();return D8}var P8="/backend-api/wham/rate-limit-reset-credits",Kz=`https://chatgpt.com${P8}`,kX=`${P8}/consume`,Oz=`https://chatgpt.com${kX}`,Fz=300000,qz=60000,jz=15000,Dz=60000;class k0 extends Error{kind;cooldownUntil;constructor(Y,X,J){super(X);this.name="ResetRedemptionError",this.kind=Y,this.cooldownUntil=J}}class P1 extends Error{kind;status;constructor(Y,X,J){super(X);this.name="ResetCreditError",this.kind=Y,this.status=J}}function bX(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 IY(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}function xX(Y){if(!Y)return;return{...Y.inFlight?{inFlight:{...Y.inFlight}}:{},...Y.lastOutcome?{lastOutcome:{...Y.lastOutcome}}:{},...Y.cooldownUntil!==void 0?{cooldownUntil:Y.cooldownUntil}:{}}}function M8(Y){if(!IY(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 vX(Y){return Boolean(Y&&Object.hasOwn(Y,"inFlight"))}function hX(Y,X){return X-Y.startedAt<Fz}function SY(Y,X){if(!u0(X))return;return Y.reset?.[X]}function gX(Y){if(!Y.reset)Y.reset=Object.create(null);return Y.reset}function yX(Y,X,J){if(!u0(X))return;let Q=gX(Y),$=Q[X]??{},G=$.lastOutcome;delete $.inFlight,$.lastOutcome={code:"ambiguous_local",at:J,...G?{previousOutcome:{code:G.code,at:G.at}}:{}},Q[X]=$}function fX(Y,X){let J=xX(Y),Q=M8(Y?.inFlight);if(vX(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&&hX(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 Pz(Y,X){if(!u0(X))return{kind:"fresh",beforeState:void 0};let J=await Y.loadAccountsFn(Y.configPath);return fX(J?SY(J,X):void 0,Y.now())}async function Mz(Y,X){let J;if(await Y.mutateAccountsFn((Q)=>{let $=Y.now(),G=SY(Q,X);if(J=fX(G,$),J.kind==="corrupt")yX(Q,X,$);return Q},Y.configPath),!J)throw Error("corrupt reset state mutation did not run");return J}async function Ez(Y,X,J){if(!u0(X))return{kind:"fresh",beforeState:void 0};let Q;if(await Y.mutateAccountsFn(($)=>{let G=Y.now(),W=SY($,X),U=xX(W),L=M8(W?.inFlight);if(vX(W)&&!L)return yX($,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&&hX(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=kY(J);if(!H)return Q={kind:"fresh",beforeState:U},$;let V={redeemRequestId:Y.randomUUID(),creditId:H.id,startedAt:G},O=gX($);return O[X]={...W,inFlight:V},Q={kind:"claim",beforeState:U,claim:{inFlight:V,selectedCredit:H}},$},Y.configPath),!Q)throw Error("reset claim mutation did not run");return Q}async function wz(Y,X,J,Q){if(!u0(X))return;if(!A8(Q.kind))return;await Y.mutateAccountsFn(($)=>{let G=SY($,X),W=M8(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+Dz;else delete G.cooldownUntil;return $},Y.configPath)}function t1(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 E8(Y,X,J,Q){if(!(X||t1(Y.primary,Q)||t1(Y.secondary,Q)))return{ok:!1,reason:"not exhausted"};if(J<=0)return{ok:!1,reason:"no applicable credits"};return{ok:!0}}function _X(Y,X){let J=Y[X];if(J===void 0||J===null)return;return typeof J==="string"?J:null}function Az(Y){if(!IY(Y))return;let X=_X(Y,"granted_at"),J=_X(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 w8(Y,X,J){let Q;try{Q=await Y(Kz,{method:"GET",headers:bX(X,P8,J),signal:AbortSignal.timeout(jz)})}catch{throw new P1("http_error","reset credit list request failed")}if(!Q.ok)throw new P1("http_error",`reset credit list request failed: ${Q.status}`,Q.status);let $;try{$=await Q.json()}catch{throw new P1("invalid_response","reset credit list response was not valid JSON",Q.status)}if(!IY($))throw new P1("invalid_response","reset credit list response was not an object",Q.status);return{credits:(Array.isArray($.credits)?$.credits:[]).flatMap((W)=>{let U=Az(W);return U===void 0?[]:[U]}),availableCount:typeof $.available_count==="number"&&Number.isFinite($.available_count)?$.available_count:void 0}}function kY(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 A8(Y){return Y==="reset"||Y==="already_redeemed"||Y==="nothing_to_reset"||Y==="no_credit"}async function Tz(Y,X,J,Q,$){let G;try{G=await Y(Oz,{method:"POST",headers:{...bX(X,kX,J),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:$,credit_id:Q}),signal:AbortSignal.timeout(qz)})}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||!IY(U)||!A8(U.code))return{kind:"ambiguous",raw:U};return{kind:U.code,raw:U}}function CX(Y){if(Y.kind==="cooldown")throw new k0("cooldown_active","reset credit redemption is cooling down",Y.cooldownUntil);throw Error(`unexpected reset state decision: ${Y.kind}`)}function IX(){throw new k0("expired_unreconciled","the previous reset attempt outcome is unknown")}function SX(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 Rz(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 mX(Y,X){if(!u0(X.accountKey))throw new k0("invalid_account_key","the reset account key is reserved");let J=await Y.resolveTarget(X.accountKey);if(J.chatgptAccountId!==X.expectedChatgptAccountId)throw new k0("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let Q=J.accountKey==="main"?void 0:J.chatgptAccountId,$=await Pz(Y,X.accountKey);if($.kind==="corrupt"){if($=await Mz(Y,X.accountKey),$.kind==="corrupt")return SX(J,$.beforeState)}if($.kind==="cooldown")CX($);let G;if($.kind==="claim")G=$.claim;else if($.kind==="expired_unreconciled"){if(!X.retry)IX();G=$.claim}else{if(X.retry)throw new k0("retry_without_inflight","there is no active reset credit redemption to retry");let[L,H]=await Promise.all([Y.fetchUsage(J),w8(Y.fetchImpl,J.accessToken,Q)]),V=E8(L,Y.hasActiveRateLimitMark(X.accountKey),L.resetCreditsApplicable??0,Y.now());if(!V.ok)throw new k0(V.reason==="not exhausted"?"not_exhausted":"no_applicable_credits",V.reason);if(!kY(H.credits))throw new k0("no_eligible_credit","no eligible reset credit was returned");let O=await Ez(Y,X.accountKey,H.credits);if(O.kind==="corrupt")return SX(J,O.beforeState);if(O.kind==="cooldown")CX(O);if(O.kind==="expired_unreconciled")IX();if(O.kind!=="claim")throw new k0("no_eligible_credit","no eligible reset credit was available while claiming");G=O.claim}let W=await Tz(Y.fetchImpl,J.accessToken,Q,G.inFlight.creditId,G.inFlight.redeemRequestId),U=!1;try{await wz(Y,X.accountKey,G.inFlight,W)}catch{U=A8(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.":Rz(W),...U?{finalizeStateWriteFailed:!0}:{}}}function _(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var _8="openai-quota",C8="openai-account",I8="openai-routing",S8="openai-killswitch",k8="openai-dump",b8="openai-logging",x8="openai-cachekeep",E1="openai-reset",oX=["openai-quota","openai-account","openai-routing","openai-killswitch","openai-dump","openai-logging","openai-cachekeep","openai-reset"],i=V0("commands");function cX(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."}var _z=900000;function uX(Y,X){if(typeof Y!=="number"||!Number.isFinite(Y))return" (age unknown)";let J=X-Y;if(J<_z)return"";let Q=Math.floor(J/3600000);if(Q>=24)return` (${Math.floor(Q/24)}d old)`;if(Q>=1)return` (${Q}h old)`;return` (${Math.floor(J/60000)}m old)`}async function Cz(Y){let X=await Y.refreshAllQuota?.(),J=Y.quotaManager.getMain(),Q=Date.now(),$=["## OpenAI Quota",""];if(J?.quota){let U=J.quota;$.push("### Main account");for(let L of["primary","secondary"]){let H=U[L];if(H){let V=Math.round(H.usedPercent),O="█".repeat(Math.max(0,Math.min(Math.round(V/10),10)))+"░".repeat(Math.max(0,10-Math.min(Math.round(V/10),10)));$.push(`- ${L}: ${O} ${V}% used (${Math.round(H.remainingPercent)}% remaining)${uX(H.checkedAt??J.checkedAt,Q)}`)}}if(U.resetCreditsAvailable!==void 0)$.push(`- resets: ${U.resetCreditsAvailable}`)}else $.push("No main quota snapshot available. Send a request first.");let W=[...Y.quotaManager.getAllFallbacks().entries()].filter(([,U])=>U);if(W.length>0){$.push(""),$.push("### Fallback accounts");for(let[U,L]of W){if(!L?.quota)continue;$.push(`**${U}**`);for(let H of["primary","secondary"]){let V=L.quota[H];if(V){let O=Math.round(V.usedPercent);$.push(` - ${H}: ${O}% used (${Math.round(V.remainingPercent)}% remaining)${uX(V.checkedAt??L.checkedAt,Q)}`)}}if(L.quota.resetCreditsAvailable!==void 0)$.push(` - resets: ${L.quota.resetCreditsAvailable}`)}}if(X?.length){let U=X.filter((L)=>!L.ok);if(U.length>0){$.push("");for(let L of U)$.push(L.permanent?`- ${L.account}: sign-in no longer accepted — remove and add this account again`:`- ${L.account}: fetch failed — Refresh to retry`)}}return{command:"openai-quota",text:$.join(`
|
|
2
|
-
`),knobs:{}}}function v1(Y){return{id:Y.id,type:Y.type??"oauth",enabled:Y.enabled,label:Y.label}}async function
|
|
3
|
-
`),knobs:{accounts:$.map(v1)}}}if(J[0]==="remove"&&J[1]){let G=J[1],W=await
|
|
1
|
+
import{d as g1,e as jY,f as t2}from"./index-87145jkw.js";import{A as t0,B as S1,C as W1,D as f4,E as m4,F as i0,G as c4,H as M1,I as u0,J as rX,K as D0,L as J0,M as DY,N as PY,O as WX,P as MY,Q as u4,R as p4,S as l4,h as _4,i as C4,j as xY,k as vY,l as I4,m as S4,n as k4,o as o1,p as r1,q as B8,s as b4,t as x4,u as v4,v as h4,w as g4,x as y4,y as nX,z as oX}from"./index-n2s7s3h6.js";import{$ as A1,U as p8,X as EY,Y as d4,da as i4,ea as n4,fa as o4,ka as r4,la as K8,ma as s4,na as a4,oa as t4,pa as e4}from"./index-zbpt7v1a.js";import{wa as hY}from"./index-8f1200qx.js";import{xa as gJ,ya as yJ}from"./index-00rp531h.js";import{Aa as bY,Ba as BJ,Ca as H0}from"./index-80gqxa1f.js";import{Fa as Yz}from"./index-4agbg1ec.js";import{Ia as G9}from"./index-x55z0b3y.js";import{mkdirSync as qZ,readFileSync as jZ,renameSync as DZ,statSync as PZ,writeFileSync as MZ}from"node:fs";import $X from"node:os";import{join as EZ}from"node:path";import{readFileSync as Nz}from"node:fs";import{homedir as Vz,tmpdir as Zz}from"node:os";import{join as _Y}from"node:path";var Bz="https://chatgpt.com/backend-api/codex/responses",Kz="openai-auth.json",a0={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 CY(){let Y=process.env[a0.configDir]?.trim();if(Y)return Y;return _Y(process.env.XDG_CONFIG_HOME||_Y(Vz(),".config"),"opencode")}function G0(){return process.env[a0.configFile]?.trim()||_Y(CY(),Kz)}function Oz(){try{let Y=JSON.parse(Nz(G0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function RX(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 RY(Y,X,J){let Q=RX(Y);if(Q!==void 0)return Q;if(typeof X==="boolean")return X;return J}function Fz(){let Y=Oz(),X=RX(a0.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:RY(a0.webSockets,Y.webSockets,!1),rawWebSocket:RY(a0.rawWebSocket,Y.rawWebSocket,!1),responsesLite:RY(a0.responsesLite,Y.responsesLite,!1),dump:RY(a0.dump,Q,!1),dumpDir:process.env[a0.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():_Y(Zz(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[a0.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():Bz)}}var D8;function w0(){if(!D8)D8=Fz();return D8}var P8="/backend-api/wham/rate-limit-reset-credits",qz=`https://chatgpt.com${P8}`,kX=`${P8}/consume`,jz=`https://chatgpt.com${kX}`,Dz=300000,Pz=60000,Mz=15000,Ez=60000;class k0 extends Error{kind;cooldownUntil;constructor(Y,X,J){super(X);this.name="ResetRedemptionError",this.kind=Y,this.cooldownUntil=J}}class P1 extends Error{kind;status;constructor(Y,X,J){super(X);this.name="ResetCreditError",this.kind=Y,this.status=J}}function bX(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 IY(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}function xX(Y){if(!Y)return;return{...Y.inFlight?{inFlight:{...Y.inFlight}}:{},...Y.lastOutcome?{lastOutcome:{...Y.lastOutcome}}:{},...Y.cooldownUntil!==void 0?{cooldownUntil:Y.cooldownUntil}:{}}}function M8(Y){if(!IY(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 vX(Y){return Boolean(Y&&Object.hasOwn(Y,"inFlight"))}function hX(Y,X){return X-Y.startedAt<Dz}function SY(Y,X){if(!u0(X))return;return Y.reset?.[X]}function gX(Y){if(!Y.reset)Y.reset=Object.create(null);return Y.reset}function yX(Y,X,J){if(!u0(X))return;let Q=gX(Y),$=Q[X]??{},G=$.lastOutcome;delete $.inFlight,$.lastOutcome={code:"ambiguous_local",at:J,...G?{previousOutcome:{code:G.code,at:G.at}}:{}},Q[X]=$}function fX(Y,X){let J=xX(Y),Q=M8(Y?.inFlight);if(vX(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&&hX(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 Az(Y,X){if(!u0(X))return{kind:"fresh",beforeState:void 0};let J=await Y.loadAccountsFn(Y.configPath);return fX(J?SY(J,X):void 0,Y.now())}async function wz(Y,X){let J;if(await Y.mutateAccountsFn((Q)=>{let $=Y.now(),G=SY(Q,X);if(J=fX(G,$),J.kind==="corrupt")yX(Q,X,$);return Q},Y.configPath),!J)throw Error("corrupt reset state mutation did not run");return J}async function Tz(Y,X,J){if(!u0(X))return{kind:"fresh",beforeState:void 0};let Q;if(await Y.mutateAccountsFn(($)=>{let G=Y.now(),W=SY($,X),U=xX(W),L=M8(W?.inFlight);if(vX(W)&&!L)return yX($,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&&hX(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=kY(J);if(!H)return Q={kind:"fresh",beforeState:U},$;let V={redeemRequestId:Y.randomUUID(),creditId:H.id,startedAt:G},O=gX($);return O[X]={...W,inFlight:V},Q={kind:"claim",beforeState:U,claim:{inFlight:V,selectedCredit:H}},$},Y.configPath),!Q)throw Error("reset claim mutation did not run");return Q}async function Rz(Y,X,J,Q){if(!u0(X))return;if(!w8(Q.kind))return;await Y.mutateAccountsFn(($)=>{let G=SY($,X),W=M8(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+Ez;else delete G.cooldownUntil;return $},Y.configPath)}function t1(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 E8(Y,X,J){if(!(X||t1(Y.primary,J)||t1(Y.secondary,J)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function _X(Y,X){let J=Y[X];if(J===void 0||J===null)return;return typeof J==="string"?J:null}function _z(Y){if(!IY(Y))return;let X=_X(Y,"granted_at"),J=_X(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 A8(Y,X,J){let Q;try{Q=await Y(qz,{method:"GET",headers:bX(X,P8,J),signal:AbortSignal.timeout(Mz)})}catch{throw new P1("http_error","reset credit list request failed")}if(!Q.ok)throw new P1("http_error",`reset credit list request failed: ${Q.status}`,Q.status);let $;try{$=await Q.json()}catch{throw new P1("invalid_response","reset credit list response was not valid JSON",Q.status)}if(!IY($))throw new P1("invalid_response","reset credit list response was not an object",Q.status);return{credits:(Array.isArray($.credits)?$.credits:[]).flatMap((W)=>{let U=_z(W);return U===void 0?[]:[U]}),availableCount:typeof $.available_count==="number"&&Number.isFinite($.available_count)?$.available_count:void 0}}function kY(Y){return[...Y].filter(mX).sort((X,J)=>Date.parse(X.expiresAt)-Date.parse(J.expiresAt))[0]}function mX(Y){return Y.status==="available"&&Y.isSupportedByPlan&&Y.resetType==="codex_rate_limits"}function cX(Y){return Y.filter(mX).length}function w8(Y){return Y==="reset"||Y==="already_redeemed"||Y==="nothing_to_reset"||Y==="no_credit"}async function Cz(Y,X,J,Q,$){let G;try{G=await Y(jz,{method:"POST",headers:{...bX(X,kX,J),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:$,credit_id:Q}),signal:AbortSignal.timeout(Pz)})}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||!IY(U)||!w8(U.code))return{kind:"ambiguous",raw:U};return{kind:U.code,raw:U}}function CX(Y){if(Y.kind==="cooldown")throw new k0("cooldown_active","reset credit redemption is cooling down",Y.cooldownUntil);throw Error(`unexpected reset state decision: ${Y.kind}`)}function IX(){throw new k0("expired_unreconciled","the previous reset attempt outcome is unknown")}function SX(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 Iz(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 uX(Y,X){if(!u0(X.accountKey))throw new k0("invalid_account_key","the reset account key is reserved");let J=await Y.resolveTarget(X.accountKey);if(J.chatgptAccountId!==X.expectedChatgptAccountId)throw new k0("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let Q=J.accountKey==="main"?void 0:J.chatgptAccountId,$=await Az(Y,X.accountKey);if($.kind==="corrupt"){if($=await wz(Y,X.accountKey),$.kind==="corrupt")return SX(J,$.beforeState)}if($.kind==="cooldown")CX($);let G;if($.kind==="claim")G=$.claim;else if($.kind==="expired_unreconciled"){if(!X.retry)IX();G=$.claim}else{if(X.retry)throw new k0("retry_without_inflight","there is no active reset credit redemption to retry");let[L,H]=await Promise.all([Y.fetchUsage(J),A8(Y.fetchImpl,J.accessToken,Q)]),V=E8(L,Y.hasActiveRateLimitMark(X.accountKey),Y.now());if(!V.ok)throw new k0("not_exhausted",V.reason);if(!kY(H.credits))throw new k0("no_eligible_credit","no eligible reset credit was returned");let O=await Tz(Y,X.accountKey,H.credits);if(O.kind==="corrupt")return SX(J,O.beforeState);if(O.kind==="cooldown")CX(O);if(O.kind==="expired_unreconciled")IX();if(O.kind!=="claim")throw new k0("no_eligible_credit","no eligible reset credit was available while claiming");G=O.claim}let W=await Cz(Y.fetchImpl,J.accessToken,Q,G.inFlight.creditId,G.inFlight.redeemRequestId),U=!1;try{await Rz(Y,X.accountKey,G.inFlight,W)}catch{U=w8(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.":Iz(W),...U?{finalizeStateWriteFailed:!0}:{}}}function _(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var _8="openai-quota",C8="openai-account",I8="openai-routing",S8="openai-killswitch",k8="openai-dump",b8="openai-logging",x8="openai-cachekeep",E1="openai-reset",sX=["openai-quota","openai-account","openai-routing","openai-killswitch","openai-dump","openai-logging","openai-cachekeep","openai-reset"],i=H0("commands");function pX(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."}var Sz=900000;function lX(Y,X){if(typeof Y!=="number"||!Number.isFinite(Y))return" (age unknown)";let J=X-Y;if(J<Sz)return"";let Q=Math.floor(J/3600000);if(Q>=24)return` (${Math.floor(Q/24)}d old)`;if(Q>=1)return` (${Q}h old)`;return` (${Math.floor(J/60000)}m old)`}async function kz(Y){let X=await Y.refreshAllQuota?.(),J=Y.quotaManager.getMain(),Q=Date.now(),$=["## OpenAI Quota",""];if(J?.quota){let U=J.quota;$.push("### Main account");for(let L of["primary","secondary"]){let H=U[L];if(H){let V=Math.round(H.usedPercent),O="█".repeat(Math.max(0,Math.min(Math.round(V/10),10)))+"░".repeat(Math.max(0,10-Math.min(Math.round(V/10),10)));$.push(`- ${L}: ${O} ${V}% used (${Math.round(H.remainingPercent)}% remaining)${lX(H.checkedAt??J.checkedAt,Q)}`)}}if(U.resetCreditsAvailable!==void 0)$.push(`- resets: ${U.resetCreditsAvailable}`)}else $.push("No main quota snapshot available. Send a request first.");let W=[...Y.quotaManager.getAllFallbacks().entries()].filter(([,U])=>U);if(W.length>0){$.push(""),$.push("### Fallback accounts");for(let[U,L]of W){if(!L?.quota)continue;$.push(`**${U}**`);for(let H of["primary","secondary"]){let V=L.quota[H];if(V){let O=Math.round(V.usedPercent);$.push(` - ${H}: ${O}% used (${Math.round(V.remainingPercent)}% remaining)${lX(V.checkedAt??L.checkedAt,Q)}`)}}if(L.quota.resetCreditsAvailable!==void 0)$.push(` - resets: ${L.quota.resetCreditsAvailable}`)}}if(X?.length){let U=X.filter((L)=>!L.ok);if(U.length>0){$.push("");for(let L of U)$.push(L.permanent?`- ${L.account}: sign-in no longer accepted — remove and add this account again`:`- ${L.account}: fetch failed — Refresh to retry`)}}return{command:"openai-quota",text:$.join(`
|
|
2
|
+
`),knobs:{}}}function v1(Y){return{id:Y.id,type:Y.type??"oauth",enabled:Y.enabled,label:Y.label}}async function bz(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:$.map(v1)}}}if(J[0]==="remove"&&J[1]){let G=J[1],W=await rX(X.accountStoragePath),U=W?W.has(G):!1,L=!1,H=await J0((O)=>{let B=O.accounts.findIndex((N)=>N.id===G);if(B===-1)return O;return O.accounts.splice(B,1),L=!0,O},X.accountStoragePath,{allowDrop:[G]});if(!(L||U))return{command:"openai-account",text:`## Account Not Found
|
|
4
4
|
|
|
5
5
|
No account with id \`${G}\` exists.`,knobs:{accounts:H.accounts.map(v1)}};return i.info("account removed",{id:G}),X.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Account Removed
|
|
6
6
|
|
|
@@ -8,7 +8,7 @@ Removed account \`${G}\`.`,knobs:{accounts:H.accounts.map(v1)}}}if(J[0]==="order
|
|
|
8
8
|
|
|
9
9
|
Both account IDs must exist.`,knobs:{accounts:W.accounts.map(v1)}};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.map(v1)}}}if(J[0]==="add"){let G=J.includes("--headless"),W=J.filter((N)=>N!=="add"&&N!=="--headless"),U=W.length>0?W.join(" "):void 0,{url:L,instructions:H,completion:V}=await
|
|
11
|
+
Swapped positions of \`${J[1]}\` and \`${J[2]}\`.`,knobs:{accounts:W.accounts.map(v1)}}}if(J[0]==="add"){let G=J.includes("--headless"),W=J.filter((N)=>N!=="add"&&N!=="--headless"),U=W.length>0?W.join(" "):void 0,{url:L,instructions:H,completion:V}=await oX({label:U,headless:G}),O=X.notify,B=X.sessionId;if(V.then(async(N)=>{let K=!1;if(await J0((j)=>{if(N.accountId&&j.mainAccountId&&N.accountId===j.mainAccountId)return K=!0,j;return nX(j.accounts,N),j},X.accountStoragePath),K){i.warn("account add rejected (main identity)",{id:N.id,sessionId:B}),O?.({command:"openai-account",text:`## Add Failed
|
|
12
12
|
|
|
13
13
|
${"That account is already your main account — not added as a fallback."}`,knobs:{}});return}i.info("account added",{id:N.id,label:N.label}),X.refreshSidebar?.().catch(()=>{}),O?.({command:"openai-account",text:`## Account Added
|
|
14
14
|
|
|
@@ -34,7 +34,7 @@ ${L}
|
|
|
34
34
|
|
|
35
35
|
${H}
|
|
36
36
|
|
|
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:$.map(v1)}}}async function
|
|
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:$.map(v1)}}}async function xz(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
|
|
|
@@ -43,17 +43,17 @@ This runtime cannot clear the current session pin.`,knobs:{mode:$}};return await
|
|
|
43
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
45
|
Mode: \`${U}\`
|
|
46
|
-
- ${
|
|
46
|
+
- ${pX(U)}
|
|
47
47
|
|
|
48
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
|
+
- ${pX($)}${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:M1.primary,secondary:M1.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,V,O]=L,B={primary:Number.parseInt(V,10),secondary:Number.parseInt(O,10)};if(H==="main")W.main=B;else if(H==="all"){W.main=B;for(let N of $)W.accounts[N]=B}else W.accounts[H]=B}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
|
|
55
|
+
Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:$}}}async function vz(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"]??M1.primary,V=L.secondary??L["1w"]??M1.secondary;U.push(`| main | ≥ ${H}% | ≥ ${V}% |`);for(let O of $){let B=Q.accounts?.[O]??Q.main??{},N=B.primary??B["5h"]??M1.primary,K=B.secondary??B["1w"]??M1.secondary;U.push(`| ${O} | ≥ ${N}% | ≥ ${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:M1.primary,secondary:M1.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,V,O]=L,B={primary:Number.parseInt(V,10),secondary:Number.parseInt(O,10)};if(H==="main")W.main=B;else if(H==="all"){W.main=B;for(let N of $)W.accounts[N]=B}else W.accounts[H]=B}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 hz(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),Q=w0(),$=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}
|
|
@@ -62,7 +62,7 @@ Usage: \`/openai-dump on\` or \`/openai-dump off\``,knobs:{enabled:$}};if(J[0]==
|
|
|
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 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
|
|
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 gz(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
|
|
|
@@ -72,7 +72,7 @@ Usage: \`/openai-logging <level>\``,knobs:{level:W}}}let $=J[0];if($&&Q.includes
|
|
|
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 yz(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 fz(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
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)",V=["## 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(V.push(`Tracked sessions: **${U.tracked}**`),U.targets.length>0){V.push("");for(let B of U.targets){let N=B.sessionKey.length>12?`${B.sessionKey.slice(0,12)}…`:B.sessionKey,K=Math.ceil((B.cacheExpiresAt-U.generatedAt)/1000);V.push(`- \`${N}\` (${B.accountId??"main"}) — expires in ${K}s`+(B.lastWarmedAt?`, last warm ${Math.ceil((U.generatedAt-B.lastWarmedAt)/1000)}s ago`:"")+(B.backoffUntil&&B.backoffUntil>U.generatedAt?`, backoff ${Math.ceil((B.backoffUntil-U.generatedAt)/1000)}s`:""))}}V.push(""),V.push(`TTL: ${Math.round(U.ttlMs/1000)}s | Lead: ${Math.round(U.leadMs/1000)}s | Max idle warm: ${Math.round(U.maxIdleWarmMs/60000)}min`),V.push(""),V.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((B)=>B.lastWarmedAt??0));return{command:"openai-cachekeep",text:V.join(`
|
|
78
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
|
|
@@ -89,13 +89,13 @@ Main-agent sessions again stop warming at the configured idle cap.`,knobs:{enabl
|
|
|
89
89
|
|
|
90
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
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=
|
|
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=yz(W);if(!U.ok)return{command:"openai-cachekeep",text:`## Cachekeep Window Invalid
|
|
93
93
|
|
|
94
94
|
${U.reason}`,knobs:{}};let{startHour:L,endHour:H}=U;await J0((B)=>{return B.cachekeep={...B.cachekeep??{},startHour:L,endHour:H},B},X.accountStoragePath),X.setCacheKeepWindow?.({startHour:L,endHour:H}),i.info("cachekeep window set",{startHour:L,endHour:H});let V=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Set
|
|
95
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:V?.sustain??$?.cachekeep?.sustain===!0,window:{startHour:L,endHour:H},running:V?.running??!1,tracked:V?.tracked??0,generatedAt:V?.generatedAt??Date.now(),maxIdleWarmMs:V?.maxIdleWarmMs??3600000,maxSubagentIdleMs:V?.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
|
|
97
|
-
`)}function
|
|
98
|
-
`)}function T0(Y,X,J,Q={}){return{command:E1,text:J,knobs:{stage:"result",accountKey:Y,code:X,...Q}}}function
|
|
96
|
+
Warming limited to **${`${String(L).padStart(2,"0")}-${String(H).padStart(2,"0")}`}** local hours.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:V?.sustain??$?.cachekeep?.sustain===!0,window:{startHour:L,endHour:H},running:V?.running??!1,tracked:V?.tracked??0,generatedAt:V?.generatedAt??Date.now(),maxIdleWarmMs:V?.maxIdleWarmMs??3600000,maxSubagentIdleMs:V?.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 aX(Y){let X=[Y.primary?.usedPercent,Y.secondary?.usedPercent].filter((J)=>J!==void 0);return X.length>0?Math.max(...X):void 0}function mz(Y,X){let J=[Y.primary,Y.secondary].filter(($)=>$!==void 0),Q=J.filter(($)=>t1($,X));return(Q.length>0?Q:J).sort(($,G)=>G.usedPercent-$.usedPercent)[0]?.resetsAt}function cz(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)=>!t1(Q,X))}function T8(Y){if(!Y)return;try{return decodeURIComponent(Y)}catch{return}}async function dX(Y,X){try{let J=await X.resolveResetTarget(Y),Q=J.accountKey==="main"?void 0:J.chatgptAccountId,[$,G]=await Promise.all([W1({accessToken:J.accessToken,fetchImpl:X.fetchImpl,now:X.now,accountId:J.chatgptAccountId}),A8(X.fetchImpl,J.accessToken,Q)]),W=kY(G.credits),U=cX(G.credits),L=G.availableCount??$.resetCreditsAvailable??(U>0?U:void 0),H=$.resetCreditsApplicable,V=E8($,X.quotaManager.isRateLimited(Y),X.now()),O;if(!J.chatgptAccountId)O="stable ChatGPT account identity unavailable";else if(!V.ok)O=V.reason;else if(!W)O="no eligible credit";return{accountKey:J.accountKey,label:J.label,chatgptAccountId:J.chatgptAccountId,usedPercent:aX($),resetTime:mz($,X.now()),availableCount:L,applicableAvailableCount:H,eligible:O===void 0,reason:O,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 uz(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===void 0?"?":J.applicableAvailableCount}/${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 iX(Y){let X=["## Confirm reset credit","",`Account: **${Y.label}** (\`${Y.accountKey}\`)`,`Current quota: **${Y.usedPercent??"unknown"}% used**`,`Credit: **Spend 1 of ${Y.availableCount??"unknown"}**`,`Credit expires: **${Y.selectedCreditExpiresAt??"unavailable"}**`,`Quota resets: **${Y.resetTime??"unavailable"}**`,""];if((Y.availableCount??0)>0&&Y.applicableAvailableCount===0)X.push("The server does not currently count this credit as applicable; redemption may return a no-op, and a no-op does not spend the credit."),X.push("");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 T0(Y,X,J,Q={}){return{command:E1,text:J,knobs:{stage:"result",accountKey:Y,code:X,...Q}}}function pz(Y,X,J){if(X instanceof k0){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_eligible_credit:"No credit was spent: no eligible credit was returned."};return T0(Y,X.kind,`## Reset credit
|
|
99
99
|
|
|
100
100
|
${$[X.kind]}
|
|
101
101
|
|
|
@@ -109,11 +109,11 @@ No redemption was attempted: reset credit availability could not be loaded.
|
|
|
109
109
|
|
|
110
110
|
Code: \`${X.kind}\``);return i.warn("reset command failed before a known result",{accountKey:Y,error:X?.message??String(X)}),T0(Y,"error",`## Reset credit
|
|
111
111
|
|
|
112
|
-
The reset request failed before a known result: internal command failure — see plugin log.`)}async function
|
|
112
|
+
The reset request failed before a known result: internal command failure — see plugin log.`)}async function lz(Y,X,J){let{accountKey:Q}=Y.target,$=Y.outcome.kind;if(Y.finalizeStateWriteFailed)return T0(Q,$,`## Reset credit result
|
|
113
113
|
|
|
114
114
|
Account: **${Y.target.label}** (\`${Q}\`)
|
|
115
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(N){W.error=N?.message??String(N)}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&&
|
|
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(N){W.error=N?.message??String(N)}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&&cz(L?.quota,X.now()),V=L?.quota.resetCreditsApplicable,O=H?"Post-verification: **window fresh**.":`Post-verification: **window not yet refreshed** (server code \`${$}\`).`,B=U?`
|
|
117
117
|
|
|
118
118
|
quota re-check failed — see log.`:"";return T0(Q,$,`## Reset credit result
|
|
119
119
|
|
|
@@ -123,7 +123,7 @@ Code: \`${$}\`
|
|
|
123
123
|
|
|
124
124
|
${O}${B}${V===void 0?"":`
|
|
125
125
|
|
|
126
|
-
Remaining applicable credits: **${V}**`}`,{verifiedFresh:H,afterUsedPercent:
|
|
126
|
+
Remaining applicable credits: **${V}**`}`,{verifiedFresh:H,afterUsedPercent:aX(L?.quota??{}),remainingCredits:V})}if($==="ambiguous_local")return T0(Q,$,`## Reset credit result
|
|
127
127
|
|
|
128
128
|
Account: **${Y.target.label}** (\`${Q}\`)
|
|
129
129
|
|
|
@@ -141,16 +141,16 @@ Account: **${Y.target.label}** (\`${Q}\`)
|
|
|
141
141
|
|
|
142
142
|
Code: \`${$}\`
|
|
143
143
|
|
|
144
|
-
${G[$]??"The server returned a no-op result. No reset was confirmed."}`)}async function
|
|
144
|
+
${G[$]??"The server returned a no-op result. No reset was confirmed."}`)}async function dz(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:E1,text:`## Reset credit
|
|
145
145
|
|
|
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)=>pX(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:E1,text:fz(L),knobs:{stage:"accounts",accounts:L}}}if(G==="select"){let W=T8($[1]);if(!W||!u0(W)||$.length!==2)return T0("","invalid_command","Usage: `/openai-reset select <encodedAccountKey>`");let U=await pX(W,Q);if(!U.eligible)return T0(W,"not_eligible",lX(U));return{command:E1,text:lX(U),knobs:{stage:"confirm",preview:U}}}if(G==="confirm"||G==="retry"){let W=T8($[1]),U=T8($[2]);if(!W||!u0(W)||!U||$.length!==3)return T0(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 mX({configPath:X.accountStoragePath,mutateAccountsFn:J0,loadAccountsFn:X.loadAccounts,now:Q.now,randomUUID:Q.randomUUID,fetchImpl:Q.fetchImpl,resolveTarget:Q.resolveResetTarget,fetchUsage:(H)=>W1({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}),cz(L,Q,U)}catch(L){let H=mz(W,L,U);return i.info("reset redemption outcome",{accountKey:W,code:H.knobs.code}),H}}return T0("","invalid_command","Usage: `/openai-reset` | `/openai-reset select <encodedAccountKey>` | `/openai-reset confirm <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset retry <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset refresh`")}var pz=new Set(["access","refresh","apikey","authheader","password","secret"]);function lz(Y){let X=Y.toLowerCase().replace(/[-_]/g,"");if(pz.has(X))return!0;return X.endsWith("token")}function R8(Y,X,J){if(Array.isArray(Y))return Y.map(($,G)=>R8($,`${X}[${G}]`,J));if(!_(Y))return Y;let Q={};for(let[$,G]of Object.entries(Y)){if(lz($)){J.push(`${X}.${$}`);continue}Q[$]=R8(G,`${X}.${$}`,J)}return Q}async function v8(Y,X,J){let Q=await dz(Y,X,J),$=[],G=R8(Q.knobs,"knobs",$);if($.length>0)return i.warn("credential-shaped knob stripped before RPC",{command:Y,fields:$}),{...Q,knobs:G};return Q}async function dz(Y,X,J){switch(Y){case"openai-quota":return Cz(J);case"openai-account":return Iz(X,J);case"openai-routing":return Sz(X,J);case"openai-killswitch":return kz(X,J);case"openai-dump":return bz(X,J);case"openai-logging":return xz(X,J);case"openai-cachekeep":return hz(X,J);case"openai-reset":return uz(X,J);default:throw Error(`unhandled command: ${Y}`)}}var h8=V0("quota");function iz(Y){return Y?.status===401}async function h1(Y,X={}){let J=Y.whamFn;if(!J)throw Error("whamFn is required for refreshAllQuota");let Q=[],$=Y.logger??h8,G=(N)=>{Q.push(N);let K={pid:process.pid,accountId:N.account,status:N.ok?"ok":"error",...N.error?{error:N.error}:{}};if(N.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??w1)()}catch{}let H=new Map(L?.fallbacks.map((N)=>[N.id,N])??[]),V=(...N)=>W!==void 0&&N.some((K)=>typeof K==="number"&&Number.isFinite(K)&&K<=Y.now()&&Y.now()-K<W),O=await Y.loadAccounts(Y.configPath).catch(()=>{return}),B=O?.mainAccountId??Y.storageMainAccountId;if(!X.accountKey||X.accountKey==="main")try{let N=await Y.getAuth();if(N.type==="oauth"){let K=L&&B!==void 0&&L.main.mainAccountId===B?L.main.quota:void 0;if(V(Y.quotaManager.peekMainForPolicy(B)?.checkedAt,K?.primary?.checkedAt,K?.secondary?.checkedAt,K?.checkedAt))G({account:"main",ok:!0});else{if(!N.access||(N.expires??0)<Y.now()){let w=await Y.refreshMainWithLease();N={...N,access:w.access,expires:w.expires}}if(N.access)if(Y.respectBackoff&&Y.quotaManager.isBackedOff())G({account:"main",ok:!0});else{let w=await J({accessToken:N.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:B,accountKey:"main"});Y.quotaManager.setMain(N.access,{quota:w,refreshAfter:Y.now()+300000,checkedAt:Y.now()},B,!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(N){G({account:"main",ok:!1,error:t0(N)})}if(O)for(let N of O.accounts){if(X.accountKey&&(X.accountKey==="main"||N.id!==X.accountKey))continue;if(N.enabled===!1||!Y.isOAuthAccountFn(N)){if(X.accountKey)G({account:N.id,ok:!1,error:"account is not an enabled OAuth fallback"});continue}try{let K=H.get(N.id),j=N.accountId,w=K&&j!==void 0&&K.accountId===j?K.quota:void 0;if(V(Y.quotaManager.peekFallbackForPolicy(N.id,j)?.checkedAt,w?.primary?.checkedAt,w?.secondary?.checkedAt,w?.checkedAt)){G({account:N.id,ok:!0});continue}if(Y.respectBackoff&&Y.quotaManager.isFallbackBackedOff(N.id,N.access)){G({account:N.id,ok:!0});continue}let x=N.lastRefreshError;if(xY(x,N.refresh,Y.now())){G({account:N.id,ok:!1,error:vY(x,Y.now()),permanent:!0});continue}let E;try{E=await Y.fallbackManager.refreshAccount(N,O)}catch(y){h8.warn("fallback token refresh failed during quota poll",{pid:process.pid,accountId:N.id,error:t0(y)}),E=N}if(!E.access||(E.expires??0)<Y.now()){G({account:N.id,ok:!1,error:"no usable access token"});continue}let S;try{S=await J({accessToken:E.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:E.accountId,accountKey:N.id})}catch(y){if(!iz(y))throw y;if(h8.warn("quota endpoint rejected the token; forcing a refresh",{pid:process.pid,accountId:N.id}),E=await Y.fallbackManager.refreshAccount(N,O,{force:!0}),!E.access){G({account:N.id,ok:!1,error:"no usable access token after forced refresh"});continue}S=await J({accessToken:E.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:E.accountId,accountKey:N.id})}Y.quotaManager.setFallback(N.id,{quota:S,refreshAfter:Y.now()+300000,checkedAt:Y.now()},E.access,!0,E.accountId),U=!0,G({account:N.id,ok:!0})}catch(K){G({account:N.id,ok:!1,error:t0(K)})}}if(X.accountKey&&X.accountKey!=="main"&&!Q.some((N)=>N.account===X.accountKey))Q.push({account:X.accountKey,ok:!1,error:"account not found"});if(W===void 0||U){let N=await Y.loadAccounts(Y.configPath);await Y.writeSidebarState(Y.quotaManager,N)}return Q}var nz=300000,oz=30000,rz=240000,sz="bg-quota-refresh",az=120000;function tz(Y,X){return hY({name:sz,ttlMs:az,path:Y,renew:!0,...X})}function sX(Y,X=h1,J=()=>tz(Y.configPath)){return ez(Y,X,J)}async function ez(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:rz})}finally{await Q?.release().catch(()=>{})}}class g8{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)*oz);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=$},nz+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 y8(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 f8(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 gY(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"),y8(Y.body))X.set("x-openai-internal-codex-responses-lite","true");return{...Y,headers:X,body:f8(Y.body)}}function XJ(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 JJ(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 aX(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 YU=300000,QJ=1800000,tX=2*QJ+900000,XU=3600000,eX=1800000,YJ=60000,JU=32,QU=8388608,m8=600000;function $J(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 $U(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 GU(Y,X){return $J(Y)?QJ:X}function c8(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function GJ(Y){if(!Y||typeof Y!=="object")return c8();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 WU(Y){try{let X=JSON.parse(Y);return GJ(X.usage)}catch{return c8()}}function zU(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=GJ(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??c8()}class u8{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??YU,this.tickIntervalMs=Y.tickIntervalMs??YJ,this.leadMs=Y.leadMs??this.tickIntervalMs+15000;let X=Y.maxIdleWarmMs??Y.maxDurationMs;this.maxIdleWarmMs=typeof X==="number"&&Number.isFinite(X)&&X>0?X:XU;let J=Y.maxSubagentIdleMs??eX;this.maxSubagentIdleMs=typeof J==="number"&&Number.isFinite(J)&&J>0?J:eX,this.tickIntervalMs=Y.tickIntervalMs??YJ,this.maxTargets=Y.maxTargets??JU,this.maxBytes=Y.maxBytes??QU,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&&!aX(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 V=this.targets.get(Y);if(V)this.totalBytes-=V.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 V,O=Number.POSITIVE_INFINITY;for(let[N,K]of this.targets){let j=Math.max(K.lastRealRequestAt,K.lastWarmedAt??0);if(j<O)V=N,O=j}if(V===void 0)break;let B=this.targets.get(V);if(B)this.totalBytes-=B.bodyText.length;this.targets.delete(V)}let L=GU(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:$J(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-tX;for(let[$,G]of this.targets){let W,U;if(this.isGpt56Subagent(G))W=Q,U=tX;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&&!aX(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()+m8;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 $=$U(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=gY({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()+m8,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")??"",V=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:V}));let O=V?zU(L):WU(L),B=g1(U.headers),N=B.primary?.usedPercent??null,K=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:N,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()+m8,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",error:$ instanceof Error?$.message:String($)}))}}}var UJ=900000,UU=0.016666666666666666,WJ=0.000001;function l8(Y,X){for(let J of[Y?.primary?.checkedAt,Y?.checkedAt,X])if(typeof J==="number"&&Number.isFinite(J))return J;return}function d8(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let X=l8(Y.quota,Y.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||Y.now-X>UJ)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,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 LU(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,UU);return Q/G}function zJ(Y,X){if(Y<X)return-1;if(Y>X)return 1;return 0}function HU(Y,X){if(!Y.quota)return;let J=l8(Y.quota,Y.quotaCheckedAt);if(J===void 0||X-J>UJ)return;let Q=p8(Y.quota).map(({key:G,window:W})=>{return LU(W,Y.reservePercent[G]??0,X)}),$=Q.length>0?Math.min(...Q):0;return $>0?{candidate:Y,quotaCheckedAt:J,weight:$}:void 0}function LJ(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(($)=>HU($,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,WJ),L=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,WJ);return U-L||G.candidate.configuredOrder-W.candidate.configuredOrder||zJ(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||zJ($.accountId,G.accountId)})[0];if(!Q)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Q.accountId,quotaCheckedAt:l8(Q.quota,Q.quotaCheckedAt),source:"mode-fallback"}}import{createHash as NU}from"node:crypto";import{chmod as VU,mkdir as ZU,readdir as BU,readFile as KU,writeFile as i8}from"node:fs/promises";import{join as ZJ}from"node:path";var r8=V0("dump"),z1="x-cortexkit-openai-auth-dump-session",OU=["http","prewarm","main"],HJ=0,y1=new Map,FU=100;function n8(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function BJ(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 KJ(Y){return NU("sha256").update(Y).digest("hex")}function o8(Y){return KJ(JSON.stringify(Y))}function OJ(Y){try{let X=JSON.parse(Y);return X!=null&&typeof X==="object"&&!Array.isArray(X)?X:void 0}catch{return}}function qU(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 jU(Y,X){if(!y1.has(Y))while(y1.size>=FU){let J=y1.keys().next().value;if(J===void 0)break;y1.delete(J)}y1.set(Y,X)}var NJ=new Set;async function DU(Y,X,J){let Q=BJ(X),$=OU.map((G)=>`-${Q}-${J}-${G}.body.json`);try{let W=(await BU(Y)).filter((U)=>$.some((L)=>U.endsWith(L))).sort().pop();if(!W)return;return await KU(ZJ(Y,W),"utf8")}catch{return}}function PU(Y){if(Y===void 0)return;return Object.fromEntries(new Headers(Y).entries())}function s8(Y){if(Array.isArray(Y))return Y.map(s8);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]=s8(Q)}return X}function MU(Y){let X=OJ(Y);if(X===void 0)return Y;let J=VJ(X),Q=JSON.stringify(J);if(Q===void 0)return Y;return JSON.stringify(X)===Q?Y:Q}function EU(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function wU(Y){let X=OJ(Y);if(!X)return{parseable:!1};let J=Array.isArray(X.input)?X.input:[],Q=Array.isArray(X.tools)?X.tools:[],$=Q.map(EU),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:o8(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:o8(J[0]),toolsCount:Q.length,toolTypes:$,toolsHash:o8(Q),hasWebSearch:$.includes("web_search"),clientMetadataKeys:G?Object.keys(G).sort():[]}}async function f1(Y){let X=A0();if(!X.dump)return;HJ++;let J=Y.sessionID?.trim()||"session-unknown",Q=`${new Date().toISOString().replace(/[:.]/g,"-")}-${process.pid}-${String(HJ).padStart(5,"0")}-${BJ(J)}-${Y.transport}-${Y.phase}`,$=ZJ(X.dumpDir,Q),G={body:`${$}.body.json`,metadata:`${$}.meta.json`,request:`${$}.request.json`},W=`${Y.transport}:${J}`,U=y1.get(W),L=U?"memory":void 0;if(U===void 0&&!NJ.has(W)){if(NJ.add(W),U=await DU(X.dumpDir,J,Y.transport),U!==void 0)L="disk"}try{await ZU(X.dumpDir,{recursive:!0,mode:448}),await VU(X.dumpDir,448).catch(()=>{});let H=MU(Y.bodyText),V={id:Q,createdAt:new Date().toISOString(),session:n8(J),transport:Y.transport,phase:Y.phase,accountId:Y.accountId,status:Y.status,error:Y.error,bodyBytes:Y.bodyText.length,bodyHash:KJ(Y.bodyText),diff:qU(U,H),baselineSource:L,body:wU(Y.bodyText),files:G};await Promise.all([i8(G.body,H,{encoding:"utf8",mode:384}),i8(G.metadata,`${JSON.stringify(V,null,2)}
|
|
148
|
-
`,{encoding:"utf8",mode:384}),i8(G.request,`${JSON.stringify(s8({url:Y.url,method:Y.method,accountId:Y.accountId,headers:
|
|
149
|
-
`,{encoding:"utf8",mode:384})]),r8.debug("dumped request",{id:Q,session:n8(J),body:G.body,meta:G.metadata}),
|
|
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)=>dX(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:E1,text:uz(L),knobs:{stage:"accounts",accounts:L}}}if(G==="select"){let W=T8($[1]);if(!W||!u0(W)||$.length!==2)return T0("","invalid_command","Usage: `/openai-reset select <encodedAccountKey>`");let U=await dX(W,Q);if(!U.eligible)return T0(W,"not_eligible",iX(U));return{command:E1,text:iX(U),knobs:{stage:"confirm",preview:U}}}if(G==="confirm"||G==="retry"){let W=T8($[1]),U=T8($[2]);if(!W||!u0(W)||!U||$.length!==3)return T0(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 uX({configPath:X.accountStoragePath,mutateAccountsFn:J0,loadAccountsFn:X.loadAccounts,now:Q.now,randomUUID:Q.randomUUID,fetchImpl:Q.fetchImpl,resolveTarget:Q.resolveResetTarget,fetchUsage:(H)=>W1({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}),lz(L,Q,U)}catch(L){let H=pz(W,L,U);return i.info("reset redemption outcome",{accountKey:W,code:H.knobs.code}),H}}return T0("","invalid_command","Usage: `/openai-reset` | `/openai-reset select <encodedAccountKey>` | `/openai-reset confirm <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset retry <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset refresh`")}var iz=new Set(["access","refresh","apikey","authheader","password","secret"]);function nz(Y){let X=Y.toLowerCase().replace(/[-_]/g,"");if(iz.has(X))return!0;return X.endsWith("token")}function R8(Y,X,J){if(Array.isArray(Y))return Y.map(($,G)=>R8($,`${X}[${G}]`,J));if(!_(Y))return Y;let Q={};for(let[$,G]of Object.entries(Y)){if(nz($)){J.push(`${X}.${$}`);continue}Q[$]=R8(G,`${X}.${$}`,J)}return Q}async function v8(Y,X,J){let Q=await oz(Y,X,J),$=[],G=R8(Q.knobs,"knobs",$);if($.length>0)return i.warn("credential-shaped knob stripped before RPC",{command:Y,fields:$}),{...Q,knobs:G};return Q}async function oz(Y,X,J){switch(Y){case"openai-quota":return kz(J);case"openai-account":return bz(X,J);case"openai-routing":return xz(X,J);case"openai-killswitch":return vz(X,J);case"openai-dump":return hz(X,J);case"openai-logging":return gz(X,J);case"openai-cachekeep":return fz(X,J);case"openai-reset":return dz(X,J);default:throw Error(`unhandled command: ${Y}`)}}var h8=H0("quota");function rz(Y){return Y?.status===401}async function h1(Y,X={}){let J=Y.whamFn;if(!J)throw Error("whamFn is required for refreshAllQuota");let Q=[],$=Y.logger??h8,G=(N)=>{Q.push(N);let K={pid:process.pid,accountId:N.account,status:N.ok?"ok":"error",...N.error?{error:N.error}:{}};if(N.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??A1)()}catch{}let H=new Map(L?.fallbacks.map((N)=>[N.id,N])??[]),V=(...N)=>W!==void 0&&N.some((K)=>typeof K==="number"&&Number.isFinite(K)&&K<=Y.now()&&Y.now()-K<W),O=await Y.loadAccounts(Y.configPath).catch(()=>{return}),B=O?.mainAccountId??Y.storageMainAccountId;if(!X.accountKey||X.accountKey==="main")try{let N=await Y.getAuth();if(N.type==="oauth"){let K=L&&B!==void 0&&L.main.mainAccountId===B?L.main.quota:void 0;if(V(Y.quotaManager.peekMainForPolicy(B)?.checkedAt,K?.primary?.checkedAt,K?.secondary?.checkedAt,K?.checkedAt))G({account:"main",ok:!0});else{if(!N.access||(N.expires??0)<Y.now()){let A=await Y.refreshMainWithLease();N={...N,access:A.access,expires:A.expires}}if(N.access)if(Y.respectBackoff&&Y.quotaManager.isBackedOff())G({account:"main",ok:!0});else{let A=await J({accessToken:N.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:B,accountKey:"main"});Y.quotaManager.setMain(N.access,{quota:A,refreshAfter:Y.now()+300000,checkedAt:Y.now()},B,!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(N){G({account:"main",ok:!1,error:t0(N)})}if(O)for(let N of O.accounts){if(X.accountKey&&(X.accountKey==="main"||N.id!==X.accountKey))continue;if(N.enabled===!1||!Y.isOAuthAccountFn(N)){if(X.accountKey)G({account:N.id,ok:!1,error:"account is not an enabled OAuth fallback"});continue}try{let K=H.get(N.id),j=N.accountId,A=K&&j!==void 0&&K.accountId===j?K.quota:void 0;if(V(Y.quotaManager.peekFallbackForPolicy(N.id,j)?.checkedAt,A?.primary?.checkedAt,A?.secondary?.checkedAt,A?.checkedAt)){G({account:N.id,ok:!0});continue}if(Y.respectBackoff&&Y.quotaManager.isFallbackBackedOff(N.id,N.access)){G({account:N.id,ok:!0});continue}let x=N.lastRefreshError;if(xY(x,N.refresh,Y.now())){G({account:N.id,ok:!1,error:vY(x,Y.now()),permanent:!0});continue}let E;try{E=await Y.fallbackManager.refreshAccount(N,O)}catch(y){h8.warn("fallback token refresh failed during quota poll",{pid:process.pid,accountId:N.id,error:t0(y)}),E=N}if(!E.access||(E.expires??0)<Y.now()){G({account:N.id,ok:!1,error:"no usable access token"});continue}let S;try{S=await J({accessToken:E.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:E.accountId,accountKey:N.id})}catch(y){if(!rz(y))throw y;if(h8.warn("quota endpoint rejected the token; forcing a refresh",{pid:process.pid,accountId:N.id}),E=await Y.fallbackManager.refreshAccount(N,O,{force:!0}),!E.access){G({account:N.id,ok:!1,error:"no usable access token after forced refresh"});continue}S=await J({accessToken:E.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:E.accountId,accountKey:N.id})}Y.quotaManager.setFallback(N.id,{quota:S,refreshAfter:Y.now()+300000,checkedAt:Y.now()},E.access,!0,E.accountId),U=!0,G({account:N.id,ok:!0})}catch(K){G({account:N.id,ok:!1,error:t0(K)})}}if(X.accountKey&&X.accountKey!=="main"&&!Q.some((N)=>N.account===X.accountKey))Q.push({account:X.accountKey,ok:!1,error:"account not found"});if(W===void 0||U){let N=await Y.loadAccounts(Y.configPath);await Y.writeSidebarState(Y.quotaManager,N)}return Q}var sz=300000,az=30000,tz=240000,ez="bg-quota-refresh",YU=120000;function XU(Y,X){return hY({name:ez,ttlMs:YU,path:Y,renew:!0,...X})}function tX(Y,X=h1,J=()=>XU(Y.configPath)){return JU(Y,X,J)}async function JU(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:tz})}finally{await Q?.release().catch(()=>{})}}class g8{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)*az);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=$},sz+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 y8(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 f8(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 gY(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"),y8(Y.body))X.set("x-openai-internal-codex-responses-lite","true");return{...Y,headers:X,body:f8(Y.body)}}function QJ(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 $J(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 eX(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 QU=300000,GJ=1800000,YJ=2*GJ+900000,$U=3600000,XJ=1800000,JJ=60000,GU=32,WU=8388608,m8=600000;function WJ(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 zU(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 UU(Y,X){return WJ(Y)?GJ:X}function c8(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function zJ(Y){if(!Y||typeof Y!=="object")return c8();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 LU(Y){try{let X=JSON.parse(Y);return zJ(X.usage)}catch{return c8()}}function HU(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=zJ(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??c8()}class u8{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??QU,this.tickIntervalMs=Y.tickIntervalMs??JJ,this.leadMs=Y.leadMs??this.tickIntervalMs+15000;let X=Y.maxIdleWarmMs??Y.maxDurationMs;this.maxIdleWarmMs=typeof X==="number"&&Number.isFinite(X)&&X>0?X:$U;let J=Y.maxSubagentIdleMs??XJ;this.maxSubagentIdleMs=typeof J==="number"&&Number.isFinite(J)&&J>0?J:XJ,this.tickIntervalMs=Y.tickIntervalMs??JJ,this.maxTargets=Y.maxTargets??GU,this.maxBytes=Y.maxBytes??WU,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&&!eX(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 V=this.targets.get(Y);if(V)this.totalBytes-=V.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 V,O=Number.POSITIVE_INFINITY;for(let[N,K]of this.targets){let j=Math.max(K.lastRealRequestAt,K.lastWarmedAt??0);if(j<O)V=N,O=j}if(V===void 0)break;let B=this.targets.get(V);if(B)this.totalBytes-=B.bodyText.length;this.targets.delete(V)}let L=UU(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:WJ(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-YJ;for(let[$,G]of this.targets){let W,U;if(this.isGpt56Subagent(G))W=Q,U=YJ;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&&!eX(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()+m8;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 $=zU(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=gY({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()+m8,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")??"",V=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:V}));let O=V?HU(L):LU(L),B=g1(U.headers),N=B.primary?.usedPercent??null,K=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:N,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()+m8,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",error:$ instanceof Error?$.message:String($)}))}}}var HJ=900000,NU=0.016666666666666666,UJ=0.000001;function l8(Y,X){for(let J of[Y?.primary?.checkedAt,Y?.checkedAt,X])if(typeof J==="number"&&Number.isFinite(J))return J;return}function d8(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let X=l8(Y.quota,Y.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||Y.now-X>HJ)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,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 VU(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,NU);return Q/G}function LJ(Y,X){if(Y<X)return-1;if(Y>X)return 1;return 0}function ZU(Y,X){if(!Y.quota)return;let J=l8(Y.quota,Y.quotaCheckedAt);if(J===void 0||X-J>HJ)return;let Q=p8(Y.quota).map(({key:G,window:W})=>{return VU(W,Y.reservePercent[G]??0,X)}),$=Q.length>0?Math.min(...Q):0;return $>0?{candidate:Y,quotaCheckedAt:J,weight:$}:void 0}function NJ(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(($)=>ZU($,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,UJ),L=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,UJ);return U-L||G.candidate.configuredOrder-W.candidate.configuredOrder||LJ(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||LJ($.accountId,G.accountId)})[0];if(!Q)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Q.accountId,quotaCheckedAt:l8(Q.quota,Q.quotaCheckedAt),source:"mode-fallback"}}import{createHash as BU}from"node:crypto";import{chmod as KU,mkdir as OU,readdir as FU,readFile as qU,writeFile as i8}from"node:fs/promises";import{join as KJ}from"node:path";var r8=H0("dump"),z1="x-cortexkit-openai-auth-dump-session",jU=["http","prewarm","main"],VJ=0,y1=new Map,DU=100;function n8(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function OJ(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 FJ(Y){return BU("sha256").update(Y).digest("hex")}function o8(Y){return FJ(JSON.stringify(Y))}function qJ(Y){try{let X=JSON.parse(Y);return X!=null&&typeof X==="object"&&!Array.isArray(X)?X:void 0}catch{return}}function PU(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 MU(Y,X){if(!y1.has(Y))while(y1.size>=DU){let J=y1.keys().next().value;if(J===void 0)break;y1.delete(J)}y1.set(Y,X)}var ZJ=new Set;async function EU(Y,X,J){let Q=OJ(X),$=jU.map((G)=>`-${Q}-${J}-${G}.body.json`);try{let W=(await FU(Y)).filter((U)=>$.some((L)=>U.endsWith(L))).sort().pop();if(!W)return;return await qU(KJ(Y,W),"utf8")}catch{return}}function AU(Y){if(Y===void 0)return;return Object.fromEntries(new Headers(Y).entries())}function s8(Y){if(Array.isArray(Y))return Y.map(s8);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]=s8(Q)}return X}function wU(Y){let X=qJ(Y);if(X===void 0)return Y;let J=BJ(X),Q=JSON.stringify(J);if(Q===void 0)return Y;return JSON.stringify(X)===Q?Y:Q}function TU(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function RU(Y){let X=qJ(Y);if(!X)return{parseable:!1};let J=Array.isArray(X.input)?X.input:[],Q=Array.isArray(X.tools)?X.tools:[],$=Q.map(TU),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:o8(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:o8(J[0]),toolsCount:Q.length,toolTypes:$,toolsHash:o8(Q),hasWebSearch:$.includes("web_search"),clientMetadataKeys:G?Object.keys(G).sort():[]}}async function f1(Y){let X=w0();if(!X.dump)return;VJ++;let J=Y.sessionID?.trim()||"session-unknown",Q=`${new Date().toISOString().replace(/[:.]/g,"-")}-${process.pid}-${String(VJ).padStart(5,"0")}-${OJ(J)}-${Y.transport}-${Y.phase}`,$=KJ(X.dumpDir,Q),G={body:`${$}.body.json`,metadata:`${$}.meta.json`,request:`${$}.request.json`},W=`${Y.transport}:${J}`,U=y1.get(W),L=U?"memory":void 0;if(U===void 0&&!ZJ.has(W)){if(ZJ.add(W),U=await EU(X.dumpDir,J,Y.transport),U!==void 0)L="disk"}try{await OU(X.dumpDir,{recursive:!0,mode:448}),await KU(X.dumpDir,448).catch(()=>{});let H=wU(Y.bodyText),V={id:Q,createdAt:new Date().toISOString(),session:n8(J),transport:Y.transport,phase:Y.phase,accountId:Y.accountId,status:Y.status,error:Y.error,bodyBytes:Y.bodyText.length,bodyHash:FJ(Y.bodyText),diff:PU(U,H),baselineSource:L,body:RU(Y.bodyText),files:G};await Promise.all([i8(G.body,H,{encoding:"utf8",mode:384}),i8(G.metadata,`${JSON.stringify(V,null,2)}
|
|
148
|
+
`,{encoding:"utf8",mode:384}),i8(G.request,`${JSON.stringify(s8({url:Y.url,method:Y.method,accountId:Y.accountId,headers:AU(Y.headers)}),null,2)}
|
|
149
|
+
`,{encoding:"utf8",mode:384})]),r8.debug("dumped request",{id:Q,session:n8(J),body:G.body,meta:G.metadata}),MU(W,H)}catch(H){r8.warn("request dump failed",{session:n8(J),error:H instanceof Error?H.message:String(H)})}}async function e0(Y){if(!w0().dump)return;r8.debug("diagnostic",Y)}import{tool as e1}from"@opencode-ai/plugin";var yY="ws_",PJ=new Map,MJ=e1({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:e1.schema.string().optional(),query:e1.schema.string().optional(),queries:e1.schema.array(e1.schema.string()).optional()},async execute(Y){return{title:"OpenAI Web Search",output:JSON.stringify({action:Y}),metadata:{action:Y}}}});function t8(Y){if(_U(Y))return;if(!IU(Y))return Y;let X=Y.item;return PJ.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 EJ(Y){if(!Y.body)return Y;if(!(Y.headers.get("content-type")??"").includes("text/event-stream"))return Y;return new Response(CU(Y.body),{status:Y.status,statusText:Y.statusText,headers:Y.headers})}function AJ(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(yY)){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(SU(W)){J.set(W.call_id,W),X=!0;continue}if(kU(W,J)){Q.push(a8(W.call_id,W.output,J.get(W.call_id))),X=!0;continue}if(bU(W)){let U=PJ.get(W.id);if(U)Q.push(a8(W.id,U));else{let L=$.get(W.id),H=G.get(W.id);if(L||H)Q.push(a8(W.id,H,L));else Q.push(W)}X=!0;continue}Q.push(W)}if(X)Y.input=Q;return X}function _U(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 CU(Y){let X=new TextDecoder,J=new TextEncoder,Q="";return Y.pipeThrough(new TransformStream({transform($,G){Q+=X.decode($,{stream:!0});let W=jJ(Q);while(W){let U=Q.slice(0,W.index);Q=Q.slice(W.index+W.length);let L=DJ(U);if(L)G.enqueue(J.encode(L));W=jJ(Q)}},flush($){if(Q+=X.decode(),!Q)return;let G=DJ(Q);if(G)$.enqueue(J.encode(G))}}))}function jJ(Y){let X=Y.indexOf(`
|
|
150
150
|
|
|
151
151
|
`),J=Y.indexOf(`\r
|
|
152
152
|
\r
|
|
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
|
|
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 DJ(Y){let X=Y.split(/\r?\n/).filter((J)=>J.startsWith("data:")).map((J)=>J.slice(5).trimStart()).join(`
|
|
154
154
|
`);if(!X)return`${Y}
|
|
155
155
|
|
|
156
156
|
`;if(X==="[DONE]")return`data: [DONE]
|
|
@@ -161,11 +161,11 @@ Unavailable: reset command runtime dependencies are not wired.`,knobs:{}};let Q=
|
|
|
161
161
|
|
|
162
162
|
`}catch{return`${Y}
|
|
163
163
|
|
|
164
|
-
`}}function RU(Y){return Y.type==="response.output_item.done"&&_(Y.item)&&Y.item.type==="web_search_call"&&typeof Y.item.id==="string"}function _U(Y){return _(Y)&&Y.type==="function_call"&&Y.name==="web_search"&&typeof Y.call_id==="string"&&Y.call_id.startsWith(yY)}function CU(Y,X){return _(Y)&&Y.type==="function_call_output"&&typeof Y.call_id==="string"&&typeof Y.output==="string"&&Y.call_id.startsWith(yY)&&X.has(Y.call_id)}function IU(Y){return _(Y)&&Y.type==="item_reference"&&typeof Y.id==="string"&&Y.id.startsWith(yY)}function a8(Y,X,J){let Q=SU(X),$=_(Q?.action)?Q.action:kU(J?.arguments);return{type:"web_search_call",status:"completed",...$?{action:$}:{}}}function SU(Y){if(_(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return _(X)?X:void 0}catch{return}}function kU(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 bU}from"node:fs/promises";import{homedir as xU}from"node:os";import{join as EJ}from"node:path";var vU="https://models.dev/api.json",hU="OPENCODE_OPENAI_AUTH_MODELS_CACHE",gU="OPENCODE_MODELS_PATH",yU="OPENCODE_DISABLE_MODELS_FETCH",fU=1e4,mU=300000;function U1(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function wJ(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function e8(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=wJ(Y.cache_read),$=wJ(Y.cache_write);if(Q===null||$===null)return null;return{input:X,output:J,cache:{read:Q,write:$}}}function cU(Y){let X=U1(Y);if(!X)return null;let J=e8(X);if(!J)return null;let Q=J;if(Array.isArray(X.tiers)){let W=[];for(let U of X.tiers){let L=U1(U);if(!L)continue;let H=U1(L.tier),V=H?.size;if(H?.type!=="context")continue;if(typeof V!=="number"||!Number.isFinite(V)||V<=0)continue;let O=e8(L);if(!O)continue;W.push({...O,tier:{type:"context",size:V}})}if(W.length>0)Q.tiers=W}let $=U1(X.context_over_200k),G=$?e8($):null;if(G)Q.experimentalOver200K=G;return Q}function AJ(Y){let X=U1(Y),J=U1(X?.openai),Q=U1(J?.models);if(!Q)return null;let $={};for(let[G,W]of Object.entries(Q)){let U=U1(W),L=cU(U?.cost);if(L)$[G]=L}return Object.keys($).length>0?$:null}function uU(){let Y=process.env[hU]?.trim();if(Y)return Y;let X=process.env[gU]?.trim();if(X)return X;let J=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||EJ(xU(),".cache");return EJ(J,"opencode","models.json")}function pU(){let Y=process.env[yU]?.toLowerCase();return Y==="true"||Y==="1"}async function lU(){try{let Y=AJ(JSON.parse(await bU(uU(),"utf8")));if(Y)return Y}catch{}if(pU())return null;try{let Y=await fetch(vU,{signal:AbortSignal.timeout(fU)});if(!Y.ok)return null;return AJ(await Y.json())}catch{return null}}var m1;function TJ(){let Y=Date.now();if(m1&&m1.expiresAt>Y)return m1.promise;let X={expiresAt:Y+mU,promise:lU()};return m1=X,X.promise.then((J)=>{if(J===null&&m1===X)m1=void 0}),X.promise}function c1(Y){return typeof Y==="object"&&Y!==null}function dU(Y){if(Array.isArray(Y))return Y;if(c1(Y)&&Array.isArray(Y.data))return Y.data;return[]}function iU(Y){if(!c1(Y)||!c1(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function RJ(Y){if(!c1(Y)||!c1(Y.info))return null;let X=Y.info,J=c1(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 _J(Y,X){return{agent:Y.agent??X.agent,model:Y.model??X.model,variant:Y.variant??X.variant}}function CJ(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function IJ(Y,X){if(!Y||!X)return null;let J=Y;if(typeof J.session?.messages!=="function")return null;let Q=[];try{Q=dU(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(iU(Q[G])!=="assistant")continue;let W=RJ(Q[G]);if(!W)continue;if($=_J($,W),CJ($))return $}for(let G=Q.length-1;G>=0;G--){let W=RJ(Q[G]);if(!W)continue;if($=_J($,W),CJ($))return $}if(!$.agent&&!$.model&&!$.variant)return null;return $}var L1=[],nU=1,Y9=0,SJ=new Map;function X9(Y,X){if(L1.push({id:nU++,type:"open-dialog",payload:Y,sessionId:X}),L1.length>100)L1=L1.slice(L1.length-100)}function kJ(Y=0,X){let J=Date.now();if(Y9=J,X!==void 0)SJ.set(X,J);let Q=($)=>X===void 0||$.sessionId===void 0||$.sessionId===X;if(Y>0)L1=L1.filter(($)=>{if($.id>Y)return!0;if(X===void 0)return!1;return $.sessionId!==X});return L1.filter(($)=>$.id>Y&&Q($))}function bJ(Y){let X=Date.now();if(Y!==void 0){let J=SJ.get(Y)??0;return J>0&&X-J<3000}return Y9>0&&X-Y9<3000}import{randomBytes as oU,timingSafeEqual as rU}from"node:crypto";import{unlink as sU}from"node:fs/promises";import{createServer as aU}from"node:http";import{join as tU}from"node:path";var xJ=V0("rpc");function eU(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 YL(Y,X){if(!Y?.startsWith("Bearer "))return!1;let J=Buffer.from(Y.slice(7)),Q=Buffer.from(X);return J.length===Q.length&&rU(J,Q)}async function gJ(Y){let X=oU(32).toString("hex"),J=Y.timeoutMs??90000,Q=Y.receiptTimeoutMs??2000,$=aU((U,L)=>{U.setTimeout(J,()=>{U.socket.destroy()}),G(U,L)});$.requestTimeout=Q,$.headersTimeout=Q;async function G(U,L){let H=(V,O)=>{if(L.headersSent||L.writableEnded||L.destroyed)return;L.writeHead(V,{"content-type":"application/json"}),L.end(JSON.stringify(O))};try{let V=U.url??"";if(U.method==="GET"&&V==="/health")return H(200,{ok:!0});if(U.method!=="POST"||!V.startsWith("/rpc/"))return H(404,{error:"not found"});if(!YL(U.headers.authorization,X))return H(401,{error:"unauthorized"});let O=V.slice(5),B=await eU(U),N=JSON.parse(B||"{}");if(O==="pending-notifications"){let K=Y.drain(Number(N.lastReceivedId??0),typeof N.sessionId==="string"?N.sessionId:void 0);return H(200,{messages:K})}if(O==="apply"){let K=await Y.apply(N);return H(200,K)}return H(404,{error:"unknown method"})}catch(V){H(500,{error:V instanceof Error?V.message:String(V)})}}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 hJ(Y.sweepRoot,Y.dir)}catch(U){xJ.warn("rpc state sweep failed",{pid:process.pid,error:U instanceof Error?U.message:String(U)})}try{await vJ(Y.dir,{port:W,token:X,pid:process.pid},{secureDir:Y.secureDir}),xJ.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 sU(tU(Y.dir,`port-${process.pid}.json`)).catch(()=>{})}}}function Y1(Y){return JSON.stringify(J9(Y))??"undefined"}function J9(Y){if(Array.isArray(Y))return Y.map(J9);if(!_(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((X)=>[X,J9(Y[X])]))}function A1(){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 F1={};G9(F1,{withoutInternalHeaders:()=>V4,sanitizeHttpFallbackBody:()=>f8,orderCodexBody:()=>qY,hasWebSocketResponsesLiteMetadata:()=>y8,createWebSocketFetch:()=>YZ,applyTurnId:()=>U4,advanceTurn:()=>JX,TITLE_HEADER:()=>XX,QUOTA_ACCOUNT_HEADER:()=>V8,OpenAIWebSocketPool:()=>F1,CODEX_BODY_KEY_ORDER:()=>W4});import{createHash as rV}from"node:crypto";var BQ="vercel.ai.error",XL=Symbol.for(BQ),yJ,fJ,D=class Y extends(fJ=Error,yJ=XL,fJ){constructor({name:X,message:J,cause:Q}){super(J);this[yJ]=!0,this.name=X,this.cause=Q}static isInstance(X){return Y.hasMarker(X,BQ)}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}},KQ="AI_APICallError",OQ=`vercel.ai.error.${KQ}`,JL=Symbol.for(OQ),mJ,cJ,YY=class extends(cJ=D,mJ=JL,cJ){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:KQ,message:Y,cause:W});this[mJ]=!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 D.hasMarker(Y,OQ)}},FQ="AI_EmptyResponseBodyError",qQ=`vercel.ai.error.${FQ}`,QL=Symbol.for(qQ),uJ,pJ,$L=class extends(pJ=D,uJ=QL,pJ){constructor({message:Y="Empty response body"}={}){super({name:FQ,message:Y});this[uJ]=!0}static isInstance(Y){return D.hasMarker(Y,qQ)}};function T1(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 jQ="AI_InvalidArgumentError",DQ=`vercel.ai.error.${jQ}`,GL=Symbol.for(DQ),lJ,dJ,PQ=class extends(dJ=D,lJ=GL,dJ){constructor({message:Y,cause:X,argument:J}){super({name:jQ,message:Y,cause:X});this[lJ]=!0,this.argument=J}static isInstance(Y){return D.hasMarker(Y,DQ)}},MQ="AI_InvalidPromptError",EQ=`vercel.ai.error.${MQ}`,WL=Symbol.for(EQ),iJ,nJ,zL=class extends(nJ=D,iJ=WL,nJ){constructor({prompt:Y,message:X,cause:J}){super({name:MQ,message:`Invalid prompt: ${X}`,cause:J});this[iJ]=!0,this.prompt=Y}static isInstance(Y){return D.hasMarker(Y,EQ)}},wQ="AI_InvalidResponseDataError",AQ=`vercel.ai.error.${wQ}`,UL=Symbol.for(AQ),oJ,rJ,LL=class extends(rJ=D,oJ=UL,rJ){constructor({data:Y,message:X=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:wQ,message:X});this[oJ]=!0,this.data=Y}static isInstance(Y){return D.hasMarker(Y,AQ)}},TQ="AI_JSONParseError",RQ=`vercel.ai.error.${TQ}`,HL=Symbol.for(RQ),sJ,aJ,fY=class extends(aJ=D,sJ=HL,aJ){constructor({text:Y,cause:X}){super({name:TQ,message:`JSON parsing failed: Text: ${Y}.
|
|
165
|
-
Error message: ${T1(X)}`,cause:X});this[
|
|
166
|
-
Error message: ${T1(J)}`,cause:J});this[HQ]=!0,this.value=X,this.context=Q}static isInstance(X){return D.hasMarker(X,cQ)}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})}},uQ="AI_UnsupportedFunctionalityError",pQ=`vercel.ai.error.${uQ}`,EL=Symbol.for(pQ),VQ,ZQ,wL=class extends(ZQ=D,VQ=EL,ZQ){constructor({functionality:Y,message:X=`'${Y}' functionality not supported.`}){super({name:uQ,message:X});this[VQ]=!0,this.functionality=Y}static isInstance(Y){return D.hasMarker(Y,pQ)}};var FK=Object.freeze({status:"aborted"});function q(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 V in W.prototype)if(!(V in U))Object.defineProperty(U,V,{value:W.prototype[V].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 V of H._zod.deferred)V();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 qK=Symbol("zod_brand");class X1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class XY extends Error{constructor(Y){super(`Encountered unidirectional transform during encode: ${Y}`);this.name="ZodEncodeError"}}var mY={};function l0(Y){if(Y)Object.assign(mY,Y);return mY}var c={};G9(c,{unwrapMessage:()=>JY,uint8ArrayToHex:()=>sL,uint8ArrayToBase64url:()=>oL,uint8ArrayToBase64:()=>aQ,stringifyPrimitive:()=>nQ,shallowClone:()=>dQ,safeExtend:()=>uL,required:()=>dL,randomString:()=>vL,propertyKeyTypes:()=>U9,promiseAllObject:()=>xL,primitiveTypes:()=>iQ,prefixIssues:()=>Q1,pick:()=>fL,partial:()=>lL,optionalKeys:()=>L9,omit:()=>mL,objectClone:()=>SL,numKeys:()=>hL,nullish:()=>$Y,normalizeParams:()=>h,mergeDefs:()=>N1,merge:()=>pL,jsonStringifyReplacer:()=>u1,joinValues:()=>IL,issue:()=>l1,isPlainObject:()=>V1,isObject:()=>R1,hexToUint8Array:()=>rL,getSizableOrigin:()=>rQ,getParsedType:()=>gL,getLengthableOrigin:()=>WY,getEnumValues:()=>QY,getElementAtPath:()=>bL,floatSafeRemainder:()=>W9,finalizeIssue:()=>x0,extend:()=>cL,escapeRegex:()=>J1,esc:()=>cY,defineLazy:()=>p,createTransparentProxy:()=>yL,cloneDef:()=>kL,clone:()=>b0,cleanRegex:()=>GY,cleanEnum:()=>iL,captureStackTrace:()=>uY,cached:()=>p1,base64urlToUint8Array:()=>nL,base64ToUint8Array:()=>sQ,assignProp:()=>H1,assertNotEqual:()=>TL,assertNever:()=>_L,assertIs:()=>RL,assertEqual:()=>AL,assert:()=>CL,allowsEval:()=>z9,aborted:()=>Z1,NUMBER_FORMAT_RANGES:()=>H9,Class:()=>tQ,BIGINT_FORMAT_RANGES:()=>oQ});function AL(Y){return Y}function TL(Y){return Y}function RL(Y){}function _L(Y){throw Error()}function CL(Y){}function QY(Y){let X=Object.values(Y).filter((Q)=>typeof Q==="number");return Object.entries(Y).filter(([Q,$])=>X.indexOf(+Q)===-1).map(([Q,$])=>$)}function IL(Y,X="|"){return Y.map((J)=>nQ(J)).join(X)}function u1(Y,X){if(typeof X==="bigint")return X.toString();return X}function p1(Y){return{get value(){{let J=Y();return Object.defineProperty(this,"value",{value:J}),J}throw Error("cached value already set")}}}function $Y(Y){return Y===null||Y===void 0}function GY(Y){let X=Y.startsWith("^")?1:0,J=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(X,J)}function W9(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 lQ=Symbol("evaluating");function p(Y,X,J){let Q=void 0;Object.defineProperty(Y,X,{get(){if(Q===lQ)return;if(Q===void 0)Q=lQ,Q=J();return Q},set($){Object.defineProperty(Y,X,{value:$})},configurable:!0})}function SL(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function H1(Y,X,J){Object.defineProperty(Y,X,{value:J,writable:!0,enumerable:!0,configurable:!0})}function N1(...Y){let X={};for(let J of Y){let Q=Object.getOwnPropertyDescriptors(J);Object.assign(X,Q)}return Object.defineProperties({},X)}function kL(Y){return N1(Y._zod.def)}function bL(Y,X){if(!X)return Y;return X.reduce((J,Q)=>J?.[Q],Y)}function xL(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 vL(Y=10){let J="";for(let Q=0;Q<Y;Q++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function cY(Y){return JSON.stringify(Y)}var uY="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function R1(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var z9=p1(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function V1(Y){if(R1(Y)===!1)return!1;let X=Y.constructor;if(X===void 0)return!0;let J=X.prototype;if(R1(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function dQ(Y){if(V1(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function hL(Y){let X=0;for(let J in Y)if(Object.prototype.hasOwnProperty.call(Y,J))X++;return X}var gL=(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}`)}},U9=new Set(["string","number","symbol"]),iQ=new Set(["string","number","bigint","boolean","symbol","undefined"]);function J1(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function b0(Y,X,J){let Q=new Y._zod.constr(X??Y._zod.def);if(!X||J?.parent)Q._zod.parent=Y;return Q}function h(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 yL(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 nQ(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function L9(Y){return Object.keys(Y).filter((X)=>{return Y[X]._zod.optin==="optional"&&Y[X]._zod.optout==="optional"})}var H9={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]},oQ={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function fL(Y,X){let J=Y._zod.def,Q=N1(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 H1(this,"shape",$),$},checks:[]});return b0(Y,Q)}function mL(Y,X){let J=Y._zod.def,Q=N1(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 H1(this,"shape",$),$},checks:[]});return b0(Y,Q)}function cL(Y,X){if(!V1(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 $=N1(Y._zod.def,{get shape(){let G={...Y._zod.def.shape,...X};return H1(this,"shape",G),G},checks:[]});return b0(Y,$)}function uL(Y,X){if(!V1(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 H1(this,"shape",Q),Q},checks:Y._zod.def.checks};return b0(Y,J)}function pL(Y,X){let J=N1(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape,...X._zod.def.shape};return H1(this,"shape",Q),Q},get catchall(){return X._zod.def.catchall},checks:[]});return b0(Y,J)}function lL(Y,X,J){let Q=N1(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 H1(this,"shape",G),G},checks:[]});return b0(X,Q)}function dL(Y,X,J){let Q=N1(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 H1(this,"shape",G),G},checks:[]});return b0(X,Q)}function Z1(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 Q1(Y,X){return X.map((J)=>{var Q;return(Q=J).path??(Q.path=[]),J.path.unshift(Y),J})}function JY(Y){return typeof Y==="string"?Y:Y?.message}function x0(Y,X,J){let Q={...Y,path:Y.path??[]};if(!Y.message){let $=JY(Y.inst?._zod.def?.error?.(Y))??JY(X?.error?.(Y))??JY(J.customError?.(Y))??JY(J.localeError?.(Y))??"Invalid input";Q.message=$}if(delete Q.inst,delete Q.continue,!X?.reportInput)delete Q.input;return Q}function rQ(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function WY(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function l1(...Y){let[X,J,Q]=Y;if(typeof X==="string")return{message:X,code:"custom",input:J,inst:Q};return{...X}}function iL(Y){return Object.entries(Y).filter(([X,J])=>{return Number.isNaN(Number.parseInt(X,10))}).map((X)=>X[1])}function sQ(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 aQ(Y){let X="";for(let J=0;J<Y.length;J++)X+=String.fromCharCode(Y[J]);return btoa(X)}function nL(Y){let X=Y.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-X.length%4)%4);return sQ(X+J)}function oL(Y){return aQ(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function rL(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 sL(Y){return Array.from(Y).map((X)=>X.toString(16).padStart(2,"0")).join("")}class tQ{constructor(...Y){}}var eQ=(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,u1,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},pY=q("$ZodError",eQ),N9=q("$ZodError",eQ,{Parent:Error});function Y$(Y,X=(J)=>J.message){let J={},Q=[];for(let $ of Y.issues)if($.path.length>0)J[$.path[0]]=J[$.path[0]]||[],J[$.path[0]].push(X($));else Q.push(X($));return{formErrors:Q,fieldErrors:J}}function X$(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 lY=(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 X1;if(W.issues.length){let U=new($?.Err??Y)(W.issues.map((L)=>x0(L,G,l0())));throw uY(U,$?.callee),U}return W.value};var dY=(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)=>x0(L,G,l0())));throw uY(U,$?.callee),U}return W.value};var zY=(Y)=>(X,J,Q)=>{let $=Q?{...Q,async:!1}:{async:!1},G=X._zod.run({value:J,issues:[]},$);if(G instanceof Promise)throw new X1;return G.issues.length?{success:!1,error:new(Y??pY)(G.issues.map((W)=>x0(W,$,l0())))}:{success:!0,data:G.value}},J$=zY(N9),UY=(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)=>x0(W,$,l0())))}:{success:!0,data:G.value}},Q$=UY(N9),$$=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return lY(Y)(X,J,$)};var G$=(Y)=>(X,J,Q)=>{return lY(Y)(X,J,Q)};var W$=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return dY(Y)(X,J,$)};var z$=(Y)=>async(X,J,Q)=>{return dY(Y)(X,J,Q)};var U$=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return zY(Y)(X,J,$)};var L$=(Y)=>(X,J,Q)=>{return zY(Y)(X,J,Q)};var H$=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return UY(Y)(X,J,$)};var N$=(Y)=>async(X,J,Q)=>{return UY(Y)(X,J,Q)};var V$=/^[cC][^\s-]{8,}$/,Z$=/^[0-9a-z]+$/,B$=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,K$=/^[0-9a-vA-V]{20}$/,O$=/^[A-Za-z0-9]{27}$/,F$=/^[a-zA-Z0-9_-]{21}$/,q$=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var j$=/^([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})$/,V9=(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 D$=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function P$(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var M$=/^(?:(?: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])$/,E$=/^(([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}|:))$/,w$=/^((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])$/,A$=/^(([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])$/,T$=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Z9=/^[A-Za-z0-9_-]*$/,R$=/^(?=.{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 _$=/^\+(?:[0-9]){6,14}[0-9]$/,C$="(?:(?:\\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])))",I$=new RegExp(`^${C$}$`);function S$(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 k$(Y){return new RegExp(`^${S$(Y)}$`)}function b$(Y){let X=S$({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(`^${C$}T(?:${Q})$`)}var x$=(Y)=>{let X=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${X}$`)};var v$=/^-?\d+$/,h$=/^-?\d+(?:\.\d+)?/,g$=/^(?:true|false)$/i,y$=/^null$/i;var f$=/^[^A-Z]*$/,m$=/^[^a-z]*$/;var Z0=q("$ZodCheck",(Y,X)=>{var J;Y._zod??(Y._zod={}),Y._zod.def=X,(J=Y._zod).onattach??(J.onattach=[])}),c$={number:"number",bigint:"bigint",object:"date"},B9=q("$ZodCheckLessThan",(Y,X)=>{Z0.init(Y,X);let J=c$[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})}}),K9=q("$ZodCheckGreaterThan",(Y,X)=>{Z0.init(Y,X);let J=c$[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})}}),u$=q("$ZodCheckMultipleOf",(Y,X)=>{Z0.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):W9(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})}}),p$=q("$ZodCheckNumberFormat",(Y,X)=>{Z0.init(Y,X),X.format=X.format||"float64";let J=X.format?.includes("int"),Q=J?"int":"number",[$,G]=H9[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=v$}),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 l$=q("$ZodCheckMaxLength",(Y,X)=>{var J;Z0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!$Y($)&&$.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=WY($);Q.issues.push({origin:W,code:"too_big",maximum:X.maximum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),d$=q("$ZodCheckMinLength",(Y,X)=>{var J;Z0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!$Y($)&&$.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=WY($);Q.issues.push({origin:W,code:"too_small",minimum:X.minimum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),i$=q("$ZodCheckLengthEquals",(Y,X)=>{var J;Z0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!$Y($)&&$.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=WY($),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})}}),LY=q("$ZodCheckStringFormat",(Y,X)=>{var J,Q;if(Z0.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=()=>{})}),n$=q("$ZodCheckRegex",(Y,X)=>{LY.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})}}),o$=q("$ZodCheckLowerCase",(Y,X)=>{X.pattern??(X.pattern=f$),LY.init(Y,X)}),r$=q("$ZodCheckUpperCase",(Y,X)=>{X.pattern??(X.pattern=m$),LY.init(Y,X)}),s$=q("$ZodCheckIncludes",(Y,X)=>{Z0.init(Y,X);let J=J1(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})}}),a$=q("$ZodCheckStartsWith",(Y,X)=>{Z0.init(Y,X);let J=new RegExp(`^${J1(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})}}),t$=q("$ZodCheckEndsWith",(Y,X)=>{Z0.init(Y,X);let J=new RegExp(`.*${J1(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 e$=q("$ZodCheckOverwrite",(Y,X)=>{Z0.init(Y,X),Y._zod.check=(J)=>{J.value=X.tx(J.value)}});class O9{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 IU(Y){return Y.type==="response.output_item.done"&&_(Y.item)&&Y.item.type==="web_search_call"&&typeof Y.item.id==="string"}function SU(Y){return _(Y)&&Y.type==="function_call"&&Y.name==="web_search"&&typeof Y.call_id==="string"&&Y.call_id.startsWith(yY)}function kU(Y,X){return _(Y)&&Y.type==="function_call_output"&&typeof Y.call_id==="string"&&typeof Y.output==="string"&&Y.call_id.startsWith(yY)&&X.has(Y.call_id)}function bU(Y){return _(Y)&&Y.type==="item_reference"&&typeof Y.id==="string"&&Y.id.startsWith(yY)}function a8(Y,X,J){let Q=xU(X),$=_(Q?.action)?Q.action:vU(J?.arguments);return{type:"web_search_call",status:"completed",...$?{action:$}:{}}}function xU(Y){if(_(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return _(X)?X:void 0}catch{return}}function vU(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 hU}from"node:fs/promises";import{homedir as gU}from"node:os";import{join as wJ}from"node:path";var yU="https://models.dev/api.json",fU="OPENCODE_OPENAI_AUTH_MODELS_CACHE",mU="OPENCODE_MODELS_PATH",cU="OPENCODE_DISABLE_MODELS_FETCH",uU=1e4,pU=300000;function U1(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function TJ(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function e8(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=TJ(Y.cache_read),$=TJ(Y.cache_write);if(Q===null||$===null)return null;return{input:X,output:J,cache:{read:Q,write:$}}}function lU(Y){let X=U1(Y);if(!X)return null;let J=e8(X);if(!J)return null;let Q=J;if(Array.isArray(X.tiers)){let W=[];for(let U of X.tiers){let L=U1(U);if(!L)continue;let H=U1(L.tier),V=H?.size;if(H?.type!=="context")continue;if(typeof V!=="number"||!Number.isFinite(V)||V<=0)continue;let O=e8(L);if(!O)continue;W.push({...O,tier:{type:"context",size:V}})}if(W.length>0)Q.tiers=W}let $=U1(X.context_over_200k),G=$?e8($):null;if(G)Q.experimentalOver200K=G;return Q}function RJ(Y){let X=U1(Y),J=U1(X?.openai),Q=U1(J?.models);if(!Q)return null;let $={};for(let[G,W]of Object.entries(Q)){let U=U1(W),L=lU(U?.cost);if(L)$[G]=L}return Object.keys($).length>0?$:null}function dU(){let Y=process.env[fU]?.trim();if(Y)return Y;let X=process.env[mU]?.trim();if(X)return X;let J=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||wJ(gU(),".cache");return wJ(J,"opencode","models.json")}function iU(){let Y=process.env[cU]?.toLowerCase();return Y==="true"||Y==="1"}async function nU(){try{let Y=RJ(JSON.parse(await hU(dU(),"utf8")));if(Y)return Y}catch{}if(iU())return null;try{let Y=await fetch(yU,{signal:AbortSignal.timeout(uU)});if(!Y.ok)return null;return RJ(await Y.json())}catch{return null}}var m1;function _J(){let Y=Date.now();if(m1&&m1.expiresAt>Y)return m1.promise;let X={expiresAt:Y+pU,promise:nU()};return m1=X,X.promise.then((J)=>{if(J===null&&m1===X)m1=void 0}),X.promise}function c1(Y){return typeof Y==="object"&&Y!==null}function oU(Y){if(Array.isArray(Y))return Y;if(c1(Y)&&Array.isArray(Y.data))return Y.data;return[]}function rU(Y){if(!c1(Y)||!c1(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function CJ(Y){if(!c1(Y)||!c1(Y.info))return null;let X=Y.info,J=c1(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 IJ(Y,X){return{agent:Y.agent??X.agent,model:Y.model??X.model,variant:Y.variant??X.variant}}function SJ(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function kJ(Y,X){if(!Y||!X)return null;let J=Y;if(typeof J.session?.messages!=="function")return null;let Q=[];try{Q=oU(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(rU(Q[G])!=="assistant")continue;let W=CJ(Q[G]);if(!W)continue;if($=IJ($,W),SJ($))return $}for(let G=Q.length-1;G>=0;G--){let W=CJ(Q[G]);if(!W)continue;if($=IJ($,W),SJ($))return $}if(!$.agent&&!$.model&&!$.variant)return null;return $}var L1=[],sU=1,Y9=0,bJ=new Map;function X9(Y,X){if(L1.push({id:sU++,type:"open-dialog",payload:Y,sessionId:X}),L1.length>100)L1=L1.slice(L1.length-100)}function xJ(Y=0,X){let J=Date.now();if(Y9=J,X!==void 0)bJ.set(X,J);let Q=($)=>X===void 0||$.sessionId===void 0||$.sessionId===X;if(Y>0)L1=L1.filter(($)=>{if($.id>Y)return!0;if(X===void 0)return!1;return $.sessionId!==X});return L1.filter(($)=>$.id>Y&&Q($))}function vJ(Y){let X=Date.now();if(Y!==void 0){let J=bJ.get(Y)??0;return J>0&&X-J<3000}return Y9>0&&X-Y9<3000}import{randomBytes as aU,timingSafeEqual as tU}from"node:crypto";import{unlink as eU}from"node:fs/promises";import{createServer as YL}from"node:http";import{join as XL}from"node:path";var hJ=H0("rpc");function JL(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 QL(Y,X){if(!Y?.startsWith("Bearer "))return!1;let J=Buffer.from(Y.slice(7)),Q=Buffer.from(X);return J.length===Q.length&&tU(J,Q)}async function fJ(Y){let X=aU(32).toString("hex"),J=Y.timeoutMs??90000,Q=Y.receiptTimeoutMs??2000,$=YL((U,L)=>{U.setTimeout(J,()=>{U.socket.destroy()}),G(U,L)});$.requestTimeout=Q,$.headersTimeout=Q;async function G(U,L){let H=(V,O)=>{if(L.headersSent||L.writableEnded||L.destroyed)return;L.writeHead(V,{"content-type":"application/json"}),L.end(JSON.stringify(O))};try{let V=U.url??"";if(U.method==="GET"&&V==="/health")return H(200,{ok:!0});if(U.method!=="POST"||!V.startsWith("/rpc/"))return H(404,{error:"not found"});if(!QL(U.headers.authorization,X))return H(401,{error:"unauthorized"});let O=V.slice(5),B=await JL(U),N=JSON.parse(B||"{}");if(O==="pending-notifications"){let K=Y.drain(Number(N.lastReceivedId??0),typeof N.sessionId==="string"?N.sessionId:void 0);return H(200,{messages:K})}if(O==="apply"){let K=await Y.apply(N);return H(200,K)}return H(404,{error:"unknown method"})}catch(V){H(500,{error:V instanceof Error?V.message:String(V)})}}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 yJ(Y.sweepRoot,Y.dir)}catch(U){hJ.warn("rpc state sweep failed",{pid:process.pid,error:U instanceof Error?U.message:String(U)})}try{await gJ(Y.dir,{port:W,token:X,pid:process.pid},{secureDir:Y.secureDir}),hJ.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 eU(XL(Y.dir,`port-${process.pid}.json`)).catch(()=>{})}}}function Y1(Y){return JSON.stringify(J9(Y))??"undefined"}function J9(Y){if(Array.isArray(Y))return Y.map(J9);if(!_(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((X)=>[X,J9(Y[X])]))}function w1(){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 F1={};G9(F1,{withoutInternalHeaders:()=>K4,sanitizeHttpFallbackBody:()=>f8,orderCodexBody:()=>qY,hasWebSocketResponsesLiteMetadata:()=>y8,createWebSocketFetch:()=>QZ,applyTurnId:()=>N4,advanceTurn:()=>JX,TITLE_HEADER:()=>XX,QUOTA_ACCOUNT_HEADER:()=>V8,OpenAIWebSocketPool:()=>F1,CODEX_BODY_KEY_ORDER:()=>L4});import{createHash as tV}from"node:crypto";var OQ="vercel.ai.error",$L=Symbol.for(OQ),mJ,cJ,D=class Y extends(cJ=Error,mJ=$L,cJ){constructor({name:X,message:J,cause:Q}){super(J);this[mJ]=!0,this.name=X,this.cause=Q}static isInstance(X){return Y.hasMarker(X,OQ)}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}},FQ="AI_APICallError",qQ=`vercel.ai.error.${FQ}`,GL=Symbol.for(qQ),uJ,pJ,YY=class extends(pJ=D,uJ=GL,pJ){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:FQ,message:Y,cause:W});this[uJ]=!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 D.hasMarker(Y,qQ)}},jQ="AI_EmptyResponseBodyError",DQ=`vercel.ai.error.${jQ}`,WL=Symbol.for(DQ),lJ,dJ,zL=class extends(dJ=D,lJ=WL,dJ){constructor({message:Y="Empty response body"}={}){super({name:jQ,message:Y});this[lJ]=!0}static isInstance(Y){return D.hasMarker(Y,DQ)}};function T1(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 PQ="AI_InvalidArgumentError",MQ=`vercel.ai.error.${PQ}`,UL=Symbol.for(MQ),iJ,nJ,EQ=class extends(nJ=D,iJ=UL,nJ){constructor({message:Y,cause:X,argument:J}){super({name:PQ,message:Y,cause:X});this[iJ]=!0,this.argument=J}static isInstance(Y){return D.hasMarker(Y,MQ)}},AQ="AI_InvalidPromptError",wQ=`vercel.ai.error.${AQ}`,LL=Symbol.for(wQ),oJ,rJ,HL=class extends(rJ=D,oJ=LL,rJ){constructor({prompt:Y,message:X,cause:J}){super({name:AQ,message:`Invalid prompt: ${X}`,cause:J});this[oJ]=!0,this.prompt=Y}static isInstance(Y){return D.hasMarker(Y,wQ)}},TQ="AI_InvalidResponseDataError",RQ=`vercel.ai.error.${TQ}`,NL=Symbol.for(RQ),sJ,aJ,VL=class extends(aJ=D,sJ=NL,aJ){constructor({data:Y,message:X=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:TQ,message:X});this[sJ]=!0,this.data=Y}static isInstance(Y){return D.hasMarker(Y,RQ)}},_Q="AI_JSONParseError",CQ=`vercel.ai.error.${_Q}`,ZL=Symbol.for(CQ),tJ,eJ,fY=class extends(eJ=D,tJ=ZL,eJ){constructor({text:Y,cause:X}){super({name:_Q,message:`JSON parsing failed: Text: ${Y}.
|
|
165
|
+
Error message: ${T1(X)}`,cause:X});this[tJ]=!0,this.text=Y}static isInstance(Y){return D.hasMarker(Y,CQ)}},IQ="AI_LoadAPIKeyError",SQ=`vercel.ai.error.${IQ}`,BL=Symbol.for(SQ),YQ,XQ,KL=class extends(XQ=D,YQ=BL,XQ){constructor({message:Y}){super({name:IQ,message:Y});this[YQ]=!0}static isInstance(Y){return D.hasMarker(Y,SQ)}},kQ="AI_LoadSettingError",bQ=`vercel.ai.error.${kQ}`,OL=Symbol.for(bQ),JQ,QQ,FL=class extends(QQ=D,JQ=OL,QQ){constructor({message:Y}){super({name:kQ,message:Y});this[JQ]=!0}static isInstance(Y){return D.hasMarker(Y,bQ)}},xQ="AI_NoContentGeneratedError",vQ=`vercel.ai.error.${xQ}`,qL=Symbol.for(vQ),$Q,GQ,jL=class extends(GQ=D,$Q=qL,GQ){constructor({message:Y="No content generated."}={}){super({name:xQ,message:Y});this[$Q]=!0}static isInstance(Y){return D.hasMarker(Y,vQ)}},hQ="AI_NoSuchModelError",gQ=`vercel.ai.error.${hQ}`,DL=Symbol.for(gQ),WQ,zQ,Q9=class extends(zQ=D,WQ=DL,zQ){constructor({errorName:Y=hQ,modelId:X,modelType:J,message:Q=`No such ${J}: ${X}`}){super({name:Y,message:Q});this[WQ]=!0,this.modelId=X,this.modelType=J}static isInstance(Y){return D.hasMarker(Y,gQ)}},yQ="AI_NoSuchProviderReferenceError",fQ=`vercel.ai.error.${yQ}`,PL=Symbol.for(fQ),UQ,LQ,ML=class extends(LQ=D,UQ=PL,LQ){constructor({provider:Y,reference:X,message:J=`No provider reference found for provider '${Y}'. Available providers: ${Object.keys(X).join(", ")}`}){super({name:yQ,message:J});this[UQ]=!0,this.provider=Y,this.reference=X}static isInstance(Y){return D.hasMarker(Y,fQ)}},mQ="AI_TooManyEmbeddingValuesForCallError",cQ=`vercel.ai.error.${mQ}`,EL=Symbol.for(cQ),HQ,NQ,AL=class extends(NQ=D,HQ=EL,NQ){constructor(Y){super({name:mQ,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[HQ]=!0,this.provider=Y.provider,this.modelId=Y.modelId,this.maxEmbeddingsPerCall=Y.maxEmbeddingsPerCall,this.values=Y.values}static isInstance(Y){return D.hasMarker(Y,cQ)}},uQ="AI_TypeValidationError",pQ=`vercel.ai.error.${uQ}`,wL=Symbol.for(pQ),VQ,ZQ,p0=class Y extends(ZQ=D,VQ=wL,ZQ){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:uQ,message:`${$}: Value: ${JSON.stringify(X)}.
|
|
166
|
+
Error message: ${T1(J)}`,cause:J});this[VQ]=!0,this.value=X,this.context=Q}static isInstance(X){return D.hasMarker(X,pQ)}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})}},lQ="AI_UnsupportedFunctionalityError",dQ=`vercel.ai.error.${lQ}`,TL=Symbol.for(dQ),BQ,KQ,RL=class extends(KQ=D,BQ=TL,KQ){constructor({functionality:Y,message:X=`'${Y}' functionality not supported.`}){super({name:lQ,message:X});this[BQ]=!0,this.functionality=Y}static isInstance(Y){return D.hasMarker(Y,dQ)}};var DK=Object.freeze({status:"aborted"});function q(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 V in W.prototype)if(!(V in U))Object.defineProperty(U,V,{value:W.prototype[V].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 V of H._zod.deferred)V();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 PK=Symbol("zod_brand");class X1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class XY extends Error{constructor(Y){super(`Encountered unidirectional transform during encode: ${Y}`);this.name="ZodEncodeError"}}var mY={};function l0(Y){if(Y)Object.assign(mY,Y);return mY}var c={};G9(c,{unwrapMessage:()=>JY,uint8ArrayToHex:()=>eL,uint8ArrayToBase64url:()=>aL,uint8ArrayToBase64:()=>eQ,stringifyPrimitive:()=>rQ,shallowClone:()=>nQ,safeExtend:()=>dL,required:()=>oL,randomString:()=>yL,propertyKeyTypes:()=>U9,promiseAllObject:()=>gL,primitiveTypes:()=>oQ,prefixIssues:()=>Q1,pick:()=>uL,partial:()=>nL,optionalKeys:()=>L9,omit:()=>pL,objectClone:()=>xL,numKeys:()=>fL,nullish:()=>$Y,normalizeParams:()=>h,mergeDefs:()=>N1,merge:()=>iL,jsonStringifyReplacer:()=>u1,joinValues:()=>bL,issue:()=>l1,isPlainObject:()=>V1,isObject:()=>R1,hexToUint8Array:()=>tL,getSizableOrigin:()=>aQ,getParsedType:()=>mL,getLengthableOrigin:()=>WY,getEnumValues:()=>QY,getElementAtPath:()=>hL,floatSafeRemainder:()=>W9,finalizeIssue:()=>x0,extend:()=>lL,escapeRegex:()=>J1,esc:()=>cY,defineLazy:()=>p,createTransparentProxy:()=>cL,cloneDef:()=>vL,clone:()=>b0,cleanRegex:()=>GY,cleanEnum:()=>rL,captureStackTrace:()=>uY,cached:()=>p1,base64urlToUint8Array:()=>sL,base64ToUint8Array:()=>tQ,assignProp:()=>H1,assertNotEqual:()=>CL,assertNever:()=>SL,assertIs:()=>IL,assertEqual:()=>_L,assert:()=>kL,allowsEval:()=>z9,aborted:()=>Z1,NUMBER_FORMAT_RANGES:()=>H9,Class:()=>Y$,BIGINT_FORMAT_RANGES:()=>sQ});function _L(Y){return Y}function CL(Y){return Y}function IL(Y){}function SL(Y){throw Error()}function kL(Y){}function QY(Y){let X=Object.values(Y).filter((Q)=>typeof Q==="number");return Object.entries(Y).filter(([Q,$])=>X.indexOf(+Q)===-1).map(([Q,$])=>$)}function bL(Y,X="|"){return Y.map((J)=>rQ(J)).join(X)}function u1(Y,X){if(typeof X==="bigint")return X.toString();return X}function p1(Y){return{get value(){{let J=Y();return Object.defineProperty(this,"value",{value:J}),J}throw Error("cached value already set")}}}function $Y(Y){return Y===null||Y===void 0}function GY(Y){let X=Y.startsWith("^")?1:0,J=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(X,J)}function W9(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 iQ=Symbol("evaluating");function p(Y,X,J){let Q=void 0;Object.defineProperty(Y,X,{get(){if(Q===iQ)return;if(Q===void 0)Q=iQ,Q=J();return Q},set($){Object.defineProperty(Y,X,{value:$})},configurable:!0})}function xL(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function H1(Y,X,J){Object.defineProperty(Y,X,{value:J,writable:!0,enumerable:!0,configurable:!0})}function N1(...Y){let X={};for(let J of Y){let Q=Object.getOwnPropertyDescriptors(J);Object.assign(X,Q)}return Object.defineProperties({},X)}function vL(Y){return N1(Y._zod.def)}function hL(Y,X){if(!X)return Y;return X.reduce((J,Q)=>J?.[Q],Y)}function gL(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 yL(Y=10){let J="";for(let Q=0;Q<Y;Q++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function cY(Y){return JSON.stringify(Y)}var uY="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function R1(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var z9=p1(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function V1(Y){if(R1(Y)===!1)return!1;let X=Y.constructor;if(X===void 0)return!0;let J=X.prototype;if(R1(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function nQ(Y){if(V1(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function fL(Y){let X=0;for(let J in Y)if(Object.prototype.hasOwnProperty.call(Y,J))X++;return X}var mL=(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}`)}},U9=new Set(["string","number","symbol"]),oQ=new Set(["string","number","bigint","boolean","symbol","undefined"]);function J1(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function b0(Y,X,J){let Q=new Y._zod.constr(X??Y._zod.def);if(!X||J?.parent)Q._zod.parent=Y;return Q}function h(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 cL(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 rQ(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function L9(Y){return Object.keys(Y).filter((X)=>{return Y[X]._zod.optin==="optional"&&Y[X]._zod.optout==="optional"})}var H9={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]},sQ={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function uL(Y,X){let J=Y._zod.def,Q=N1(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 H1(this,"shape",$),$},checks:[]});return b0(Y,Q)}function pL(Y,X){let J=Y._zod.def,Q=N1(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 H1(this,"shape",$),$},checks:[]});return b0(Y,Q)}function lL(Y,X){if(!V1(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 $=N1(Y._zod.def,{get shape(){let G={...Y._zod.def.shape,...X};return H1(this,"shape",G),G},checks:[]});return b0(Y,$)}function dL(Y,X){if(!V1(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 H1(this,"shape",Q),Q},checks:Y._zod.def.checks};return b0(Y,J)}function iL(Y,X){let J=N1(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape,...X._zod.def.shape};return H1(this,"shape",Q),Q},get catchall(){return X._zod.def.catchall},checks:[]});return b0(Y,J)}function nL(Y,X,J){let Q=N1(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 H1(this,"shape",G),G},checks:[]});return b0(X,Q)}function oL(Y,X,J){let Q=N1(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 H1(this,"shape",G),G},checks:[]});return b0(X,Q)}function Z1(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 Q1(Y,X){return X.map((J)=>{var Q;return(Q=J).path??(Q.path=[]),J.path.unshift(Y),J})}function JY(Y){return typeof Y==="string"?Y:Y?.message}function x0(Y,X,J){let Q={...Y,path:Y.path??[]};if(!Y.message){let $=JY(Y.inst?._zod.def?.error?.(Y))??JY(X?.error?.(Y))??JY(J.customError?.(Y))??JY(J.localeError?.(Y))??"Invalid input";Q.message=$}if(delete Q.inst,delete Q.continue,!X?.reportInput)delete Q.input;return Q}function aQ(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function WY(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function l1(...Y){let[X,J,Q]=Y;if(typeof X==="string")return{message:X,code:"custom",input:J,inst:Q};return{...X}}function rL(Y){return Object.entries(Y).filter(([X,J])=>{return Number.isNaN(Number.parseInt(X,10))}).map((X)=>X[1])}function tQ(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 eQ(Y){let X="";for(let J=0;J<Y.length;J++)X+=String.fromCharCode(Y[J]);return btoa(X)}function sL(Y){let X=Y.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-X.length%4)%4);return tQ(X+J)}function aL(Y){return eQ(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function tL(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 eL(Y){return Array.from(Y).map((X)=>X.toString(16).padStart(2,"0")).join("")}class Y${constructor(...Y){}}var X$=(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,u1,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},pY=q("$ZodError",X$),N9=q("$ZodError",X$,{Parent:Error});function J$(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 Q$(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 lY=(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 X1;if(W.issues.length){let U=new($?.Err??Y)(W.issues.map((L)=>x0(L,G,l0())));throw uY(U,$?.callee),U}return W.value};var dY=(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)=>x0(L,G,l0())));throw uY(U,$?.callee),U}return W.value};var zY=(Y)=>(X,J,Q)=>{let $=Q?{...Q,async:!1}:{async:!1},G=X._zod.run({value:J,issues:[]},$);if(G instanceof Promise)throw new X1;return G.issues.length?{success:!1,error:new(Y??pY)(G.issues.map((W)=>x0(W,$,l0())))}:{success:!0,data:G.value}},$$=zY(N9),UY=(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)=>x0(W,$,l0())))}:{success:!0,data:G.value}},G$=UY(N9),W$=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return lY(Y)(X,J,$)};var z$=(Y)=>(X,J,Q)=>{return lY(Y)(X,J,Q)};var U$=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return dY(Y)(X,J,$)};var L$=(Y)=>async(X,J,Q)=>{return dY(Y)(X,J,Q)};var H$=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return zY(Y)(X,J,$)};var N$=(Y)=>(X,J,Q)=>{return zY(Y)(X,J,Q)};var V$=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return UY(Y)(X,J,$)};var Z$=(Y)=>async(X,J,Q)=>{return UY(Y)(X,J,Q)};var B$=/^[cC][^\s-]{8,}$/,K$=/^[0-9a-z]+$/,O$=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,F$=/^[0-9a-vA-V]{20}$/,q$=/^[A-Za-z0-9]{27}$/,j$=/^[a-zA-Z0-9_-]{21}$/,D$=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var P$=/^([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})$/,V9=(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 M$=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function E$(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var A$=/^(?:(?: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])$/,w$=/^(([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}|:))$/,T$=/^((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])$/,R$=/^(([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])$/,_$=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Z9=/^[A-Za-z0-9_-]*$/,C$=/^(?=.{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 I$=/^\+(?:[0-9]){6,14}[0-9]$/,S$="(?:(?:\\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])))",k$=new RegExp(`^${S$}$`);function b$(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 x$(Y){return new RegExp(`^${b$(Y)}$`)}function v$(Y){let X=b$({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(`^${S$}T(?:${Q})$`)}var h$=(Y)=>{let X=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${X}$`)};var g$=/^-?\d+$/,y$=/^-?\d+(?:\.\d+)?/,f$=/^(?:true|false)$/i,m$=/^null$/i;var c$=/^[^A-Z]*$/,u$=/^[^a-z]*$/;var Z0=q("$ZodCheck",(Y,X)=>{var J;Y._zod??(Y._zod={}),Y._zod.def=X,(J=Y._zod).onattach??(J.onattach=[])}),p$={number:"number",bigint:"bigint",object:"date"},B9=q("$ZodCheckLessThan",(Y,X)=>{Z0.init(Y,X);let J=p$[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})}}),K9=q("$ZodCheckGreaterThan",(Y,X)=>{Z0.init(Y,X);let J=p$[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})}}),l$=q("$ZodCheckMultipleOf",(Y,X)=>{Z0.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):W9(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})}}),d$=q("$ZodCheckNumberFormat",(Y,X)=>{Z0.init(Y,X),X.format=X.format||"float64";let J=X.format?.includes("int"),Q=J?"int":"number",[$,G]=H9[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=g$}),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 i$=q("$ZodCheckMaxLength",(Y,X)=>{var J;Z0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!$Y($)&&$.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=WY($);Q.issues.push({origin:W,code:"too_big",maximum:X.maximum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),n$=q("$ZodCheckMinLength",(Y,X)=>{var J;Z0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!$Y($)&&$.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=WY($);Q.issues.push({origin:W,code:"too_small",minimum:X.minimum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),o$=q("$ZodCheckLengthEquals",(Y,X)=>{var J;Z0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!$Y($)&&$.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=WY($),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})}}),LY=q("$ZodCheckStringFormat",(Y,X)=>{var J,Q;if(Z0.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=()=>{})}),r$=q("$ZodCheckRegex",(Y,X)=>{LY.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})}}),s$=q("$ZodCheckLowerCase",(Y,X)=>{X.pattern??(X.pattern=c$),LY.init(Y,X)}),a$=q("$ZodCheckUpperCase",(Y,X)=>{X.pattern??(X.pattern=u$),LY.init(Y,X)}),t$=q("$ZodCheckIncludes",(Y,X)=>{Z0.init(Y,X);let J=J1(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})}}),e$=q("$ZodCheckStartsWith",(Y,X)=>{Z0.init(Y,X);let J=new RegExp(`^${J1(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})}}),YG=q("$ZodCheckEndsWith",(Y,X)=>{Z0.init(Y,X);let J=new RegExp(`.*${J1(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 XG=q("$ZodCheckOverwrite",(Y,X)=>{Z0.init(Y,X),Y._zod.check=(J)=>{J.value=X.tx(J.value)}});class O9{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(`
|
|
167
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(`
|
|
168
|
-
`))}}var
|
|
168
|
+
`))}}var QG={major:4,minor:1,patch:8};var o=q("$ZodType",(Y,X)=>{var J;Y??(Y={}),Y._zod.def=X,Y._zod.bag=Y._zod.bag||{},Y._zod.version=QG;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=Z1(W),V;for(let O of U){if(O._zod.def.when){if(!O._zod.def.when(W))continue}else if(H)continue;let B=W.issues.length,N=O._zod.check(W);if(N instanceof Promise&&L?.async===!1)throw new X1;if(V||N instanceof Promise)V=(V??Promise.resolve()).then(async()=>{if(await N,W.issues.length===B)return;if(!H)H=Z1(W,B)});else{if(W.issues.length===B)continue;if(!H)H=Z1(W,B)}}if(V)return V.then(()=>{return W});return W},G=(W,U,L)=>{if(Z1(W))return W.aborted=!0,W;let H=$(U,Q,L);if(H instanceof Promise){if(L.async===!1)throw new X1;return H.then((V)=>Y._zod.parse(V,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((V)=>{return G(V,W,U)});return G(H,W,U)}let L=Y._zod.parse(W,U);if(L instanceof Promise){if(U.async===!1)throw new X1;return L.then((H)=>$(H,Q,U))}return $(L,Q,U)}}Y["~standard"]={validate:($)=>{try{let G=$$(Y,$);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return G$(Y,$).then((W)=>W.success?{value:W.data}:{issues:W.error?.issues})}},vendor:"zod",version:1}}),rY=q("$ZodString",(Y,X)=>{o.init(Y,X),Y._zod.pattern=[...Y?._zod.bag?.patterns??[]].pop()??h$(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=q("$ZodStringFormat",(Y,X)=>{LY.init(Y,X),rY.init(Y,X)}),VG=q("$ZodGUID",(Y,X)=>{X.pattern??(X.pattern=P$),s.init(Y,X)}),ZG=q("$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=V9(Q))}else X.pattern??(X.pattern=V9());s.init(Y,X)}),BG=q("$ZodEmail",(Y,X)=>{X.pattern??(X.pattern=M$),s.init(Y,X)}),KG=q("$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:C$.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})}}}),OG=q("$ZodEmoji",(Y,X)=>{X.pattern??(X.pattern=E$()),s.init(Y,X)}),FG=q("$ZodNanoID",(Y,X)=>{X.pattern??(X.pattern=j$),s.init(Y,X)}),qG=q("$ZodCUID",(Y,X)=>{X.pattern??(X.pattern=B$),s.init(Y,X)}),jG=q("$ZodCUID2",(Y,X)=>{X.pattern??(X.pattern=K$),s.init(Y,X)}),DG=q("$ZodULID",(Y,X)=>{X.pattern??(X.pattern=O$),s.init(Y,X)}),PG=q("$ZodXID",(Y,X)=>{X.pattern??(X.pattern=F$),s.init(Y,X)}),MG=q("$ZodKSUID",(Y,X)=>{X.pattern??(X.pattern=q$),s.init(Y,X)}),EG=q("$ZodISODateTime",(Y,X)=>{X.pattern??(X.pattern=v$(X)),s.init(Y,X)}),AG=q("$ZodISODate",(Y,X)=>{X.pattern??(X.pattern=k$),s.init(Y,X)}),wG=q("$ZodISOTime",(Y,X)=>{X.pattern??(X.pattern=x$(X)),s.init(Y,X)}),TG=q("$ZodISODuration",(Y,X)=>{X.pattern??(X.pattern=D$),s.init(Y,X)}),RG=q("$ZodIPv4",(Y,X)=>{X.pattern??(X.pattern=A$),s.init(Y,X),Y._zod.onattach.push((J)=>{let Q=J._zod.bag;Q.format="ipv4"})}),_G=q("$ZodIPv6",(Y,X)=>{X.pattern??(X.pattern=w$),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})}}}),CG=q("$ZodCIDRv4",(Y,X)=>{X.pattern??(X.pattern=T$),s.init(Y,X)}),IG=q("$ZodCIDRv6",(Y,X)=>{X.pattern??(X.pattern=R$),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 SG(Y){if(Y==="")return!0;if(Y.length%4!==0)return!1;try{return atob(Y),!0}catch{return!1}}var kG=q("$ZodBase64",(Y,X)=>{X.pattern??(X.pattern=_$),s.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64"}),Y._zod.check=(J)=>{if(SG(J.value))return;J.issues.push({code:"invalid_format",format:"base64",input:J.value,inst:Y,continue:!X.abort})}});function XH(Y){if(!Z9.test(Y))return!1;let X=Y.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),J=X.padEnd(Math.ceil(X.length/4)*4,"=");return SG(J)}var bG=q("$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(XH(J.value))return;J.issues.push({code:"invalid_format",format:"base64url",input:J.value,inst:Y,continue:!X.abort})}}),xG=q("$ZodE164",(Y,X)=>{X.pattern??(X.pattern=I$),s.init(Y,X)});function JH(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 vG=q("$ZodJWT",(Y,X)=>{s.init(Y,X),Y._zod.check=(J)=>{if(JH(J.value,X.alg))return;J.issues.push({code:"invalid_format",format:"jwt",input:J.value,inst:Y,continue:!X.abort})}});var q9=q("$ZodNumber",(Y,X)=>{o.init(Y,X),Y._zod.pattern=Y._zod.bag.pattern??y$,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}}),hG=q("$ZodNumber",(Y,X)=>{d$.init(Y,X),q9.init(Y,X)}),gG=q("$ZodBoolean",(Y,X)=>{o.init(Y,X),Y._zod.pattern=f$,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 yG=q("$ZodNull",(Y,X)=>{o.init(Y,X),Y._zod.pattern=m$,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 fG=q("$ZodUnknown",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J)=>J}),mG=q("$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 $G(Y,X,J){if(Y.issues.length)X.issues.push(...Q1(J,Y.issues));X.value[J]=Y.value}var cG=q("$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)=>$G(H,J,W)));else $G(L,J,W)}if(G.length)return Promise.all(G).then(()=>J);return J}});function oY(Y,X,J,Q){if(Y.issues.length)X.issues.push(...Q1(J,Y.issues));if(Y.value===void 0){if(J in Q)X.value[J]=void 0}else X.value[J]=Y.value}function uG(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=L9(Y.shape);return{...Y,keys:X,keySet:new Set(X),numKeys:X.length,optionalKeys:new Set(J)}}function pG(Y,X,J,Q,$,G){let W=[],U=$.keySet,L=$.catchall._zod,H=L.def.type;for(let V of Object.keys(X)){if(U.has(V))continue;if(H==="never"){W.push(V);continue}let O=L.run({value:X[V],issues:[]},Q);if(O instanceof Promise)Y.push(O.then((B)=>oY(B,J,V,X)));else oY(O,J,V,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 QH=q("$ZodObject",(Y,X)=>{o.init(Y,X);let J=p1(()=>uG(X));p(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 V of H.values)U[L].add(V)}}return U});let Q=R1,$=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=[],V=G.shape;for(let O of G.keys){let N=V[O]._zod.run({value:L[O],issues:[]},U);if(N instanceof Promise)H.push(N.then((K)=>oY(K,W,O,L)));else oY(N,W,O,L)}if(!$)return H.length?Promise.all(H).then(()=>W):W;return pG(H,L,W,U,J.value,Y)}}),lG=q("$ZodObjectJIT",(Y,X)=>{QH.init(Y,X);let J=Y._zod.parse,Q=p1(()=>uG(X)),$=(B)=>{let N=new O9(["shape","payload","ctx"]),K=Q.value,j=(S)=>{let y=cY(S);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};N.write("const input = payload.value;");let A=Object.create(null),x=0;for(let S of K.keys)A[S]=`key_${x++}`;N.write("const newResult = {};");for(let S of K.keys){let y=A[S],l=cY(S);N.write(`const ${y} = ${j(S)};`),N.write(`
|
|
169
169
|
if (${y}.issues.length) {
|
|
170
170
|
payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
|
|
171
171
|
...iss,
|
|
@@ -182,37 +182,37 @@ Error message: ${T1(J)}`,cause:J});this[HQ]=!0,this.value=X,this.context=Q}stati
|
|
|
182
182
|
newResult[${l}] = ${y}.value;
|
|
183
183
|
}
|
|
184
184
|
|
|
185
|
-
`)}N.write("payload.value = newResult;"),N.write("return payload;");let E=N.compile();return(S,y)=>E(B,S,y)},G,W=R1,U=!mY.jitless,H=U&&z9.value,V=X.catchall,O;Y._zod.parse=(B,N)=>{O??(O=Q.value);let K=B.value;if(!W(K))return B.issues.push({expected:"object",code:"invalid_type",input:K,inst:Y}),B;if(U&&H&&N?.async===!1&&N.jitless!==!0){if(!G)G=$(X.shape);if(B=G(B,N),!V)return B;return cG([],K,B,N,O,Y)}return J(B,N)}});function QG(Y,X,J,Q){for(let G of Y)if(G.issues.length===0)return X.value=G.value,X;let $=Y.filter((G)=>!Z1(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)=>x0(W,Q,l0())))}),X}var j9=q("$ZodUnion",(Y,X)=>{o.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)=>GY(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 QG(U,$,Y,G);return Promise.all(U).then((L)=>{return QG(L,$,Y,G)})}}),pG=q("$ZodDiscriminatedUnion",(Y,X)=>{j9.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[U,L]of Object.entries(W)){if(!$[U])$[U]=new Set;for(let H of L)$[U].add(H)}}return $});let Q=p1(()=>{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(!R1(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}),$}}),lG=q("$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 $G(J,L,H)});return $G(J,G,W)}});function F9(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(V1(Y)&&V1(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=F9(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=F9($,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 $G(Y,X,J){if(X.issues.length)Y.issues.push(...X.issues);if(J.issues.length)Y.issues.push(...J.issues);if(Z1(Y))return Y;let Q=F9(X.value,J.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return Y.value=Q.data,Y}var dG=q("$ZodRecord",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value;if(!V1($))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((V)=>{if(V.issues.length)J.issues.push(...Q1(L,V.issues));J.value[L]=V.value}));else{if(H.issues.length)J.issues.push(...Q1(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)=>x0(H,Q,l0())),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(...Q1(W,H.issues));J.value[U.value]=H.value}));else{if(L.issues.length)J.issues.push(...Q1(W,L.issues));J.value[U.value]=L.value}}}if(G.length)return Promise.all(G).then(()=>J);return J}});var iG=q("$ZodEnum",(Y,X)=>{o.init(Y,X);let J=QY(X.entries),Q=new Set(J);Y._zod.values=Q,Y._zod.pattern=new RegExp(`^(${J.filter(($)=>U9.has(typeof $)).map(($)=>typeof $==="string"?J1($):$.toString()).join("|")})$`),Y._zod.parse=($,G)=>{let W=$.value;if(Q.has(W))return $;return $.issues.push({code:"invalid_value",values:J,input:W,inst:Y}),$}}),nG=q("$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"?J1(J):J?J1(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 oG=q("$ZodTransform",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new XY(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 X1;return J.value=$,J}});function GG(Y,X){if(Y.issues.length&&X===void 0)return{issues:[],value:void 0};return Y}var rG=q("$ZodOptional",(Y,X)=>{o.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(`^(${GY(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)=>GG(G,J.value));return GG($,J.value)}if(J.value===void 0)return J;return X.innerType._zod.run(J,Q)}}),sG=q("$ZodNullable",(Y,X)=>{o.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(`^(${GY(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)}}),aG=q("$ZodDefault",(Y,X)=>{o.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)=>WG(G,X));return WG($,X)}});function WG(Y,X){if(Y.value===void 0)Y.value=X.defaultValue;return Y}var tG=q("$ZodPrefault",(Y,X)=>{o.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)}}),eG=q("$ZodNonOptional",(Y,X)=>{o.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)=>zG(G,Y));return zG($,Y)}});function zG(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 Y5=q("$ZodCatch",(Y,X)=>{o.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)=>x0(W,Q,l0()))},input:J.value}),J.issues=[];return J});if(J.value=$.value,$.issues.length)J.value=X.catchValue({...J,error:{issues:$.issues.map((G)=>x0(G,Q,l0()))},input:J.value}),J.issues=[];return J}});var X5=q("$ZodPipe",(Y,X)=>{o.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)=>nY(W,X.in,Q));return nY(G,X.in,Q)}let $=X.in._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>nY(G,X.out,Q));return nY($,X.out,Q)}});function nY(Y,X,J){if(Y.issues.length)return Y.aborted=!0,Y;return X._zod.run({value:Y.value,issues:Y.issues},J)}var J5=q("$ZodReadonly",(Y,X)=>{o.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(UG);return UG($)}});function UG(Y){return Y.value=Object.freeze(Y.value),Y}var Q5=q("$ZodLazy",(Y,X)=>{o.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)}}),$5=q("$ZodCustom",(Y,X)=>{Z0.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)=>LG(G,J,Q,Y));LG($,J,Q,Y);return}});function LG(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(l1($))}}var bK=Symbol("ZodOutput"),xK=Symbol("ZodInput");class sY{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 XH(){return new sY}var _1=XH();function G5(Y,X){return new Y({type:"string",...h(X)})}function W5(Y,X){return new Y({type:"string",format:"email",check:"string_format",abort:!1,...h(X)})}function D9(Y,X){return new Y({type:"string",format:"guid",check:"string_format",abort:!1,...h(X)})}function z5(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...h(X)})}function U5(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...h(X)})}function L5(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...h(X)})}function H5(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...h(X)})}function N5(Y,X){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...h(X)})}function V5(Y,X){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...h(X)})}function Z5(Y,X){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...h(X)})}function B5(Y,X){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...h(X)})}function K5(Y,X){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...h(X)})}function O5(Y,X){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...h(X)})}function F5(Y,X){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...h(X)})}function q5(Y,X){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...h(X)})}function j5(Y,X){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...h(X)})}function D5(Y,X){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...h(X)})}function P5(Y,X){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...h(X)})}function M5(Y,X){return new Y({type:"string",format:"cidrv6",check:"string_format",abort:!1,...h(X)})}function E5(Y,X){return new Y({type:"string",format:"base64",check:"string_format",abort:!1,...h(X)})}function w5(Y,X){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...h(X)})}function A5(Y,X){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...h(X)})}function T5(Y,X){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...h(X)})}function R5(Y,X){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...h(X)})}function _5(Y,X){return new Y({type:"string",format:"date",check:"string_format",...h(X)})}function C5(Y,X){return new Y({type:"string",format:"time",check:"string_format",precision:null,...h(X)})}function I5(Y,X){return new Y({type:"string",format:"duration",check:"string_format",...h(X)})}function S5(Y,X){return new Y({type:"number",checks:[],...h(X)})}function k5(Y,X){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...h(X)})}function b5(Y,X){return new Y({type:"boolean",...h(X)})}function x5(Y,X){return new Y({type:"null",...h(X)})}function v5(Y){return new Y({type:"unknown"})}function h5(Y,X){return new Y({type:"never",...h(X)})}function aY(Y,X){return new B9({check:"less_than",...h(X),value:Y,inclusive:!1})}function HY(Y,X){return new B9({check:"less_than",...h(X),value:Y,inclusive:!0})}function tY(Y,X){return new K9({check:"greater_than",...h(X),value:Y,inclusive:!1})}function NY(Y,X){return new K9({check:"greater_than",...h(X),value:Y,inclusive:!0})}function eY(Y,X){return new u$({check:"multiple_of",...h(X),value:Y})}function Y8(Y,X){return new l$({check:"max_length",...h(X),maximum:Y})}function d1(Y,X){return new d$({check:"min_length",...h(X),minimum:Y})}function X8(Y,X){return new i$({check:"length_equals",...h(X),length:Y})}function P9(Y,X){return new n$({check:"string_format",format:"regex",...h(X),pattern:Y})}function M9(Y){return new o$({check:"string_format",format:"lowercase",...h(Y)})}function E9(Y){return new r$({check:"string_format",format:"uppercase",...h(Y)})}function w9(Y,X){return new s$({check:"string_format",format:"includes",...h(X),includes:Y})}function A9(Y,X){return new a$({check:"string_format",format:"starts_with",...h(X),prefix:Y})}function T9(Y,X){return new t$({check:"string_format",format:"ends_with",...h(X),suffix:Y})}function C1(Y){return new e$({check:"overwrite",tx:Y})}function R9(Y){return C1((X)=>X.normalize(Y))}function _9(){return C1((Y)=>Y.trim())}function C9(){return C1((Y)=>Y.toLowerCase())}function I9(){return C1((Y)=>Y.toUpperCase())}function g5(Y,X,J){return new Y({type:"array",element:X,...h(J)})}function y5(Y,X,J){let Q=h(J);return Q.abort??(Q.abort=!0),new Y({type:"custom",check:"custom",fn:X,...Q})}function f5(Y,X,J){return new Y({type:"custom",check:"custom",fn:X,...h(J)})}function m5(Y){let X=JH((J)=>{return J.addIssue=(Q)=>{if(typeof Q==="string")J.issues.push(l1(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(l1($))}},Y(J.value,J)});return X}function JH(Y,X){let J=new Z0({check:"custom",...h(X)});return J._zod.check=Y,J}class S9{constructor(Y){this.counter=0,this.metadataRegistry=Y?.metadata??_1,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 V={...X,schemaPath:[...X.schemaPath,Y],path:X.path},O=Y._zod.parent;if(O)W.ref=O,this.process(O,V),this.seen.get(O).isParent=!0;else{let B=W.schema;switch(Q.type){case"string":{let N=B;N.type="string";let{minimum:K,maximum:j,format:w,patterns:x,contentEncoding:E}=Y._zod.bag;if(typeof K==="number")N.minLength=K;if(typeof j==="number")N.maxLength=j;if(w){if(N.format=$[w]??w,N.format==="")delete N.format}if(E)N.contentEncoding=E;if(x&&x.size>0){let S=[...x];if(S.length===1)N.pattern=S[0].source;else if(S.length>1)W.schema.allOf=[...S.map((y)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:y.source}))]}break}case"number":{let N=B,{minimum:K,maximum:j,format:w,multipleOf:x,exclusiveMaximum:E,exclusiveMinimum:S}=Y._zod.bag;if(typeof w==="string"&&w.includes("int"))N.type="integer";else N.type="number";if(typeof S==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")N.minimum=S,N.exclusiveMinimum=!0;else N.exclusiveMinimum=S;if(typeof K==="number"){if(N.minimum=K,typeof S==="number"&&this.target!=="draft-4")if(S>=K)delete N.minimum;else delete N.exclusiveMinimum}if(typeof E==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")N.maximum=E,N.exclusiveMaximum=!0;else N.exclusiveMaximum=E;if(typeof j==="number"){if(N.maximum=j,typeof E==="number"&&this.target!=="draft-4")if(E<=j)delete N.maximum;else delete N.exclusiveMaximum}if(typeof x==="number")N.multipleOf=x;break}case"boolean":{let N=B;N.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 N=B,{minimum:K,maximum:j}=Y._zod.bag;if(typeof K==="number")N.minItems=K;if(typeof j==="number")N.maxItems=j;N.type="array",N.items=this.process(Q.element,{...V,path:[...V.path,"items"]});break}case"object":{let N=B;N.type="object",N.properties={};let K=Q.shape;for(let x in K)N.properties[x]=this.process(K[x],{...V,path:[...V.path,"properties",x]});let j=new Set(Object.keys(K)),w=new Set([...j].filter((x)=>{let E=Q.shape[x]._zod;if(this.io==="input")return E.optin===void 0;else return E.optout===void 0}));if(w.size>0)N.required=Array.from(w);if(Q.catchall?._zod.def.type==="never")N.additionalProperties=!1;else if(!Q.catchall){if(this.io==="output")N.additionalProperties=!1}else if(Q.catchall)N.additionalProperties=this.process(Q.catchall,{...V,path:[...V.path,"additionalProperties"]});break}case"union":{let N=B,K=Q.options.map((j,w)=>this.process(j,{...V,path:[...V.path,"anyOf",w]}));N.anyOf=K;break}case"intersection":{let N=B,K=this.process(Q.left,{...V,path:[...V.path,"allOf",0]}),j=this.process(Q.right,{...V,path:[...V.path,"allOf",1]}),w=(E)=>("allOf"in E)&&Object.keys(E).length===1,x=[...w(K)?K.allOf:[K],...w(j)?j.allOf:[j]];N.allOf=x;break}case"tuple":{let N=B;N.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",w=Q.items.map((y,l)=>this.process(y,{...V,path:[...V.path,K,l]})),x=Q.rest?this.process(Q.rest,{...V,path:[...V.path,j,...this.target==="openapi-3.0"?[Q.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(N.prefixItems=w,x)N.items=x}else if(this.target==="openapi-3.0"){if(N.items={anyOf:w},x)N.items.anyOf.push(x);if(N.minItems=w.length,!x)N.maxItems=w.length}else if(N.items=w,x)N.additionalItems=x;let{minimum:E,maximum:S}=Y._zod.bag;if(typeof E==="number")N.minItems=E;if(typeof S==="number")N.maxItems=S;break}case"record":{let N=B;if(N.type="object",this.target==="draft-7"||this.target==="draft-2020-12")N.propertyNames=this.process(Q.keyType,{...V,path:[...V.path,"propertyNames"]});N.additionalProperties=this.process(Q.valueType,{...V,path:[...V.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let N=B,K=QY(Q.entries);if(K.every((j)=>typeof j==="number"))N.type="number";if(K.every((j)=>typeof j==="string"))N.type="string";N.enum=K;break}case"literal":{let N=B,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(N.type=j===null?"null":typeof j,this.target==="draft-4"||this.target==="openapi-3.0")N.enum=[j];else N.const=j}else{if(K.every((j)=>typeof j==="number"))N.type="number";if(K.every((j)=>typeof j==="string"))N.type="string";if(K.every((j)=>typeof j==="boolean"))N.type="string";if(K.every((j)=>j===null))N.type="null";N.enum=K}break}case"file":{let N=B,K={type:"string",format:"binary",contentEncoding:"binary"},{minimum:j,maximum:w,mime:x}=Y._zod.bag;if(j!==void 0)K.minLength=j;if(w!==void 0)K.maxLength=w;if(x)if(x.length===1)K.contentMediaType=x[0],Object.assign(N,K);else N.anyOf=x.map((E)=>{return{...K,contentMediaType:E}});else Object.assign(N,K);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let N=this.process(Q.innerType,V);if(this.target==="openapi-3.0")W.ref=Q.innerType,B.nullable=!0;else B.anyOf=[N,{type:"null"}];break}case"nonoptional":{this.process(Q.innerType,V),W.ref=Q.innerType;break}case"success":{let N=B;N.type="boolean";break}case"default":{this.process(Q.innerType,V),W.ref=Q.innerType,B.default=JSON.parse(JSON.stringify(Q.defaultValue));break}case"prefault":{if(this.process(Q.innerType,V),W.ref=Q.innerType,this.io==="input")B._prefault=JSON.parse(JSON.stringify(Q.defaultValue));break}case"catch":{this.process(Q.innerType,V),W.ref=Q.innerType;let N;try{N=Q.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}B.default=N;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let N=B,K=Y._zod.pattern;if(!K)throw Error("Pattern not found in template literal");N.type="string",N.pattern=K.source;break}case"pipe":{let N=this.io==="input"?Q.in._zod.def.type==="transform"?Q.out:Q.in:Q.out;this.process(N,V),W.ref=N;break}case"readonly":{this.process(Q.innerType,V),W.ref=Q.innerType,B.readOnly=!0;break}case"promise":{this.process(Q.innerType,V),W.ref=Q.innerType;break}case"optional":{this.process(Q.innerType,V),W.ref=Q.innerType;break}case"lazy":{let N=Y._zod.innerType;this.process(N,V),W.ref=N;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"&&U0(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 V=this.target==="draft-2020-12"?"$defs":"definitions";if(J.external){let K=J.external.registry.get(H[0])?.id,j=J.external.uri??((x)=>x);if(K)return{ref:j(K)};let w=H[1].defId??H[1].schema.id??`schema${this.counter++}`;return H[1].defId=w,{defId:w,ref:`${j("__shared")}#/${V}/${w}`}}if(H[1]===Q)return{ref:"#"};let B=`${"#"}/${V}/`,N=H[1].schema.id??`__schema${this.counter++}`;return{defId:N,ref:B+N}},G=(H)=>{if(H[1].schema.$ref)return;let V=H[1],{ref:O,defId:B}=$(H);if(V.def={...V.schema},B)V.defId=B;let N=V.schema;for(let K in N)delete N[K];N.$ref=O};if(J.cycles==="throw")for(let H of this.seen.entries()){let V=H[1];if(V.cycle)throw Error(`Cycle detected: #/${V.cycle?.join("/")}/<root>
|
|
185
|
+
`)}N.write("payload.value = newResult;"),N.write("return payload;");let E=N.compile();return(S,y)=>E(B,S,y)},G,W=R1,U=!mY.jitless,H=U&&z9.value,V=X.catchall,O;Y._zod.parse=(B,N)=>{O??(O=Q.value);let K=B.value;if(!W(K))return B.issues.push({expected:"object",code:"invalid_type",input:K,inst:Y}),B;if(U&&H&&N?.async===!1&&N.jitless!==!0){if(!G)G=$(X.shape);if(B=G(B,N),!V)return B;return pG([],K,B,N,O,Y)}return J(B,N)}});function GG(Y,X,J,Q){for(let G of Y)if(G.issues.length===0)return X.value=G.value,X;let $=Y.filter((G)=>!Z1(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)=>x0(W,Q,l0())))}),X}var j9=q("$ZodUnion",(Y,X)=>{o.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)=>GY(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 GG(U,$,Y,G);return Promise.all(U).then((L)=>{return GG(L,$,Y,G)})}}),dG=q("$ZodDiscriminatedUnion",(Y,X)=>{j9.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[U,L]of Object.entries(W)){if(!$[U])$[U]=new Set;for(let H of L)$[U].add(H)}}return $});let Q=p1(()=>{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(!R1(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}),$}}),iG=q("$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 WG(J,L,H)});return WG(J,G,W)}});function F9(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(V1(Y)&&V1(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=F9(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=F9($,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 WG(Y,X,J){if(X.issues.length)Y.issues.push(...X.issues);if(J.issues.length)Y.issues.push(...J.issues);if(Z1(Y))return Y;let Q=F9(X.value,J.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return Y.value=Q.data,Y}var nG=q("$ZodRecord",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value;if(!V1($))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((V)=>{if(V.issues.length)J.issues.push(...Q1(L,V.issues));J.value[L]=V.value}));else{if(H.issues.length)J.issues.push(...Q1(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)=>x0(H,Q,l0())),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(...Q1(W,H.issues));J.value[U.value]=H.value}));else{if(L.issues.length)J.issues.push(...Q1(W,L.issues));J.value[U.value]=L.value}}}if(G.length)return Promise.all(G).then(()=>J);return J}});var oG=q("$ZodEnum",(Y,X)=>{o.init(Y,X);let J=QY(X.entries),Q=new Set(J);Y._zod.values=Q,Y._zod.pattern=new RegExp(`^(${J.filter(($)=>U9.has(typeof $)).map(($)=>typeof $==="string"?J1($):$.toString()).join("|")})$`),Y._zod.parse=($,G)=>{let W=$.value;if(Q.has(W))return $;return $.issues.push({code:"invalid_value",values:J,input:W,inst:Y}),$}}),rG=q("$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"?J1(J):J?J1(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 sG=q("$ZodTransform",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new XY(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 X1;return J.value=$,J}});function zG(Y,X){if(Y.issues.length&&X===void 0)return{issues:[],value:void 0};return Y}var aG=q("$ZodOptional",(Y,X)=>{o.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(`^(${GY(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)=>zG(G,J.value));return zG($,J.value)}if(J.value===void 0)return J;return X.innerType._zod.run(J,Q)}}),tG=q("$ZodNullable",(Y,X)=>{o.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(`^(${GY(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)}}),eG=q("$ZodDefault",(Y,X)=>{o.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)=>UG(G,X));return UG($,X)}});function UG(Y,X){if(Y.value===void 0)Y.value=X.defaultValue;return Y}var Y5=q("$ZodPrefault",(Y,X)=>{o.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)}}),X5=q("$ZodNonOptional",(Y,X)=>{o.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)=>LG(G,Y));return LG($,Y)}});function LG(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 J5=q("$ZodCatch",(Y,X)=>{o.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)=>x0(W,Q,l0()))},input:J.value}),J.issues=[];return J});if(J.value=$.value,$.issues.length)J.value=X.catchValue({...J,error:{issues:$.issues.map((G)=>x0(G,Q,l0()))},input:J.value}),J.issues=[];return J}});var Q5=q("$ZodPipe",(Y,X)=>{o.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)=>nY(W,X.in,Q));return nY(G,X.in,Q)}let $=X.in._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>nY(G,X.out,Q));return nY($,X.out,Q)}});function nY(Y,X,J){if(Y.issues.length)return Y.aborted=!0,Y;return X._zod.run({value:Y.value,issues:Y.issues},J)}var $5=q("$ZodReadonly",(Y,X)=>{o.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(HG);return HG($)}});function HG(Y){return Y.value=Object.freeze(Y.value),Y}var G5=q("$ZodLazy",(Y,X)=>{o.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)}}),W5=q("$ZodCustom",(Y,X)=>{Z0.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)=>NG(G,J,Q,Y));NG($,J,Q,Y);return}});function NG(Y,X,J,Q){if(!Y){let $={code:"custom",input:J,inst:Q,path:[...Q._zod.def.path??[]],continue:!Q._zod.def.abort};if(Q._zod.def.params)$.params=Q._zod.def.params;X.issues.push(l1($))}}var hK=Symbol("ZodOutput"),gK=Symbol("ZodInput");class sY{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 $H(){return new sY}var _1=$H();function z5(Y,X){return new Y({type:"string",...h(X)})}function U5(Y,X){return new Y({type:"string",format:"email",check:"string_format",abort:!1,...h(X)})}function D9(Y,X){return new Y({type:"string",format:"guid",check:"string_format",abort:!1,...h(X)})}function L5(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...h(X)})}function H5(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...h(X)})}function N5(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...h(X)})}function V5(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...h(X)})}function Z5(Y,X){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...h(X)})}function B5(Y,X){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...h(X)})}function K5(Y,X){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...h(X)})}function O5(Y,X){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...h(X)})}function F5(Y,X){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...h(X)})}function q5(Y,X){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...h(X)})}function j5(Y,X){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...h(X)})}function D5(Y,X){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...h(X)})}function P5(Y,X){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...h(X)})}function M5(Y,X){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...h(X)})}function E5(Y,X){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...h(X)})}function A5(Y,X){return new Y({type:"string",format:"cidrv6",check:"string_format",abort:!1,...h(X)})}function w5(Y,X){return new Y({type:"string",format:"base64",check:"string_format",abort:!1,...h(X)})}function T5(Y,X){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...h(X)})}function R5(Y,X){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...h(X)})}function _5(Y,X){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...h(X)})}function C5(Y,X){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...h(X)})}function I5(Y,X){return new Y({type:"string",format:"date",check:"string_format",...h(X)})}function S5(Y,X){return new Y({type:"string",format:"time",check:"string_format",precision:null,...h(X)})}function k5(Y,X){return new Y({type:"string",format:"duration",check:"string_format",...h(X)})}function b5(Y,X){return new Y({type:"number",checks:[],...h(X)})}function x5(Y,X){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...h(X)})}function v5(Y,X){return new Y({type:"boolean",...h(X)})}function h5(Y,X){return new Y({type:"null",...h(X)})}function g5(Y){return new Y({type:"unknown"})}function y5(Y,X){return new Y({type:"never",...h(X)})}function aY(Y,X){return new B9({check:"less_than",...h(X),value:Y,inclusive:!1})}function HY(Y,X){return new B9({check:"less_than",...h(X),value:Y,inclusive:!0})}function tY(Y,X){return new K9({check:"greater_than",...h(X),value:Y,inclusive:!1})}function NY(Y,X){return new K9({check:"greater_than",...h(X),value:Y,inclusive:!0})}function eY(Y,X){return new l$({check:"multiple_of",...h(X),value:Y})}function Y8(Y,X){return new i$({check:"max_length",...h(X),maximum:Y})}function d1(Y,X){return new n$({check:"min_length",...h(X),minimum:Y})}function X8(Y,X){return new o$({check:"length_equals",...h(X),length:Y})}function P9(Y,X){return new r$({check:"string_format",format:"regex",...h(X),pattern:Y})}function M9(Y){return new s$({check:"string_format",format:"lowercase",...h(Y)})}function E9(Y){return new a$({check:"string_format",format:"uppercase",...h(Y)})}function A9(Y,X){return new t$({check:"string_format",format:"includes",...h(X),includes:Y})}function w9(Y,X){return new e$({check:"string_format",format:"starts_with",...h(X),prefix:Y})}function T9(Y,X){return new YG({check:"string_format",format:"ends_with",...h(X),suffix:Y})}function C1(Y){return new XG({check:"overwrite",tx:Y})}function R9(Y){return C1((X)=>X.normalize(Y))}function _9(){return C1((Y)=>Y.trim())}function C9(){return C1((Y)=>Y.toLowerCase())}function I9(){return C1((Y)=>Y.toUpperCase())}function f5(Y,X,J){return new Y({type:"array",element:X,...h(J)})}function m5(Y,X,J){let Q=h(J);return Q.abort??(Q.abort=!0),new Y({type:"custom",check:"custom",fn:X,...Q})}function c5(Y,X,J){return new Y({type:"custom",check:"custom",fn:X,...h(J)})}function u5(Y){let X=GH((J)=>{return J.addIssue=(Q)=>{if(typeof Q==="string")J.issues.push(l1(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(l1($))}},Y(J.value,J)});return X}function GH(Y,X){let J=new Z0({check:"custom",...h(X)});return J._zod.check=Y,J}class S9{constructor(Y){this.counter=0,this.metadataRegistry=Y?.metadata??_1,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 V={...X,schemaPath:[...X.schemaPath,Y],path:X.path},O=Y._zod.parent;if(O)W.ref=O,this.process(O,V),this.seen.get(O).isParent=!0;else{let B=W.schema;switch(Q.type){case"string":{let N=B;N.type="string";let{minimum:K,maximum:j,format:A,patterns:x,contentEncoding:E}=Y._zod.bag;if(typeof K==="number")N.minLength=K;if(typeof j==="number")N.maxLength=j;if(A){if(N.format=$[A]??A,N.format==="")delete N.format}if(E)N.contentEncoding=E;if(x&&x.size>0){let S=[...x];if(S.length===1)N.pattern=S[0].source;else if(S.length>1)W.schema.allOf=[...S.map((y)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:y.source}))]}break}case"number":{let N=B,{minimum:K,maximum:j,format:A,multipleOf:x,exclusiveMaximum:E,exclusiveMinimum:S}=Y._zod.bag;if(typeof A==="string"&&A.includes("int"))N.type="integer";else N.type="number";if(typeof S==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")N.minimum=S,N.exclusiveMinimum=!0;else N.exclusiveMinimum=S;if(typeof K==="number"){if(N.minimum=K,typeof S==="number"&&this.target!=="draft-4")if(S>=K)delete N.minimum;else delete N.exclusiveMinimum}if(typeof E==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")N.maximum=E,N.exclusiveMaximum=!0;else N.exclusiveMaximum=E;if(typeof j==="number"){if(N.maximum=j,typeof E==="number"&&this.target!=="draft-4")if(E<=j)delete N.maximum;else delete N.exclusiveMaximum}if(typeof x==="number")N.multipleOf=x;break}case"boolean":{let N=B;N.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 N=B,{minimum:K,maximum:j}=Y._zod.bag;if(typeof K==="number")N.minItems=K;if(typeof j==="number")N.maxItems=j;N.type="array",N.items=this.process(Q.element,{...V,path:[...V.path,"items"]});break}case"object":{let N=B;N.type="object",N.properties={};let K=Q.shape;for(let x in K)N.properties[x]=this.process(K[x],{...V,path:[...V.path,"properties",x]});let j=new Set(Object.keys(K)),A=new Set([...j].filter((x)=>{let E=Q.shape[x]._zod;if(this.io==="input")return E.optin===void 0;else return E.optout===void 0}));if(A.size>0)N.required=Array.from(A);if(Q.catchall?._zod.def.type==="never")N.additionalProperties=!1;else if(!Q.catchall){if(this.io==="output")N.additionalProperties=!1}else if(Q.catchall)N.additionalProperties=this.process(Q.catchall,{...V,path:[...V.path,"additionalProperties"]});break}case"union":{let N=B,K=Q.options.map((j,A)=>this.process(j,{...V,path:[...V.path,"anyOf",A]}));N.anyOf=K;break}case"intersection":{let N=B,K=this.process(Q.left,{...V,path:[...V.path,"allOf",0]}),j=this.process(Q.right,{...V,path:[...V.path,"allOf",1]}),A=(E)=>("allOf"in E)&&Object.keys(E).length===1,x=[...A(K)?K.allOf:[K],...A(j)?j.allOf:[j]];N.allOf=x;break}case"tuple":{let N=B;N.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",A=Q.items.map((y,l)=>this.process(y,{...V,path:[...V.path,K,l]})),x=Q.rest?this.process(Q.rest,{...V,path:[...V.path,j,...this.target==="openapi-3.0"?[Q.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(N.prefixItems=A,x)N.items=x}else if(this.target==="openapi-3.0"){if(N.items={anyOf:A},x)N.items.anyOf.push(x);if(N.minItems=A.length,!x)N.maxItems=A.length}else if(N.items=A,x)N.additionalItems=x;let{minimum:E,maximum:S}=Y._zod.bag;if(typeof E==="number")N.minItems=E;if(typeof S==="number")N.maxItems=S;break}case"record":{let N=B;if(N.type="object",this.target==="draft-7"||this.target==="draft-2020-12")N.propertyNames=this.process(Q.keyType,{...V,path:[...V.path,"propertyNames"]});N.additionalProperties=this.process(Q.valueType,{...V,path:[...V.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let N=B,K=QY(Q.entries);if(K.every((j)=>typeof j==="number"))N.type="number";if(K.every((j)=>typeof j==="string"))N.type="string";N.enum=K;break}case"literal":{let N=B,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(N.type=j===null?"null":typeof j,this.target==="draft-4"||this.target==="openapi-3.0")N.enum=[j];else N.const=j}else{if(K.every((j)=>typeof j==="number"))N.type="number";if(K.every((j)=>typeof j==="string"))N.type="string";if(K.every((j)=>typeof j==="boolean"))N.type="string";if(K.every((j)=>j===null))N.type="null";N.enum=K}break}case"file":{let N=B,K={type:"string",format:"binary",contentEncoding:"binary"},{minimum:j,maximum:A,mime:x}=Y._zod.bag;if(j!==void 0)K.minLength=j;if(A!==void 0)K.maxLength=A;if(x)if(x.length===1)K.contentMediaType=x[0],Object.assign(N,K);else N.anyOf=x.map((E)=>{return{...K,contentMediaType:E}});else Object.assign(N,K);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let N=this.process(Q.innerType,V);if(this.target==="openapi-3.0")W.ref=Q.innerType,B.nullable=!0;else B.anyOf=[N,{type:"null"}];break}case"nonoptional":{this.process(Q.innerType,V),W.ref=Q.innerType;break}case"success":{let N=B;N.type="boolean";break}case"default":{this.process(Q.innerType,V),W.ref=Q.innerType,B.default=JSON.parse(JSON.stringify(Q.defaultValue));break}case"prefault":{if(this.process(Q.innerType,V),W.ref=Q.innerType,this.io==="input")B._prefault=JSON.parse(JSON.stringify(Q.defaultValue));break}case"catch":{this.process(Q.innerType,V),W.ref=Q.innerType;let N;try{N=Q.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}B.default=N;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let N=B,K=Y._zod.pattern;if(!K)throw Error("Pattern not found in template literal");N.type="string",N.pattern=K.source;break}case"pipe":{let N=this.io==="input"?Q.in._zod.def.type==="transform"?Q.out:Q.in:Q.out;this.process(N,V),W.ref=N;break}case"readonly":{this.process(Q.innerType,V),W.ref=Q.innerType,B.readOnly=!0;break}case"promise":{this.process(Q.innerType,V),W.ref=Q.innerType;break}case"optional":{this.process(Q.innerType,V),W.ref=Q.innerType;break}case"lazy":{let N=Y._zod.innerType;this.process(N,V),W.ref=N;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"&&U0(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 V=this.target==="draft-2020-12"?"$defs":"definitions";if(J.external){let K=J.external.registry.get(H[0])?.id,j=J.external.uri??((x)=>x);if(K)return{ref:j(K)};let A=H[1].defId??H[1].schema.id??`schema${this.counter++}`;return H[1].defId=A,{defId:A,ref:`${j("__shared")}#/${V}/${A}`}}if(H[1]===Q)return{ref:"#"};let B=`${"#"}/${V}/`,N=H[1].schema.id??`__schema${this.counter++}`;return{defId:N,ref:B+N}},G=(H)=>{if(H[1].schema.$ref)return;let V=H[1],{ref:O,defId:B}=$(H);if(V.def={...V.schema},B)V.defId=B;let N=V.schema;for(let K in N)delete N[K];N.$ref=O};if(J.cycles==="throw")for(let H of this.seen.entries()){let V=H[1];if(V.cycle)throw Error(`Cycle detected: #/${V.cycle?.join("/")}/<root>
|
|
186
186
|
|
|
187
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let H of this.seen.entries()){let V=H[1];if(Y===H[0]){G(H);continue}if(J.external){let B=J.external.registry.get(H[0])?.id;if(Y!==H[0]&&B){G(H);continue}}if(this.metadataRegistry.get(H[0])?.id){G(H);continue}if(V.cycle){G(H);continue}if(V.count>1){if(J.reused==="ref"){G(H);continue}}}let W=(H,V)=>{let O=this.seen.get(H),B=O.def??O.schema,N={...B};if(O.ref===null)return;let K=O.ref;if(O.ref=null,K){W(K,V);let j=this.seen.get(K).schema;if(j.$ref&&(V.target==="draft-7"||V.target==="draft-4"||V.target==="openapi-3.0"))B.allOf=B.allOf??[],B.allOf.push(j);else Object.assign(B,j),Object.assign(B,N)}if(!O.isParent)this.override({zodSchema:H,jsonSchema:B,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 V=H[1];if(V.def&&V.defId)L[V.defId]=V.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 c5(Y,X){if(Y instanceof sY){let Q=new S9(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 S9(X);return J.process(Y),J.emit(Y,X)}function U0(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 U0($.element,J);case"object":{for(let G in $.shape)if(U0($.shape[G],J))return!0;return!1}case"union":{for(let G of $.options)if(U0(G,J))return!0;return!1}case"intersection":return U0($.left,J)||U0($.right,J);case"tuple":{for(let G of $.items)if(U0(G,J))return!0;if($.rest&&U0($.rest,J))return!0;return!1}case"record":return U0($.keyType,J)||U0($.valueType,J);case"map":return U0($.keyType,J)||U0($.valueType,J);case"set":return U0($.valueType,J);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return U0($.innerType,J);case"lazy":return U0($.getter(),J);case"default":return U0($.innerType,J);case"prefault":return U0($.innerType,J);case"custom":return!1;case"transform":return!0;case"pipe":return U0($.in,J)||U0($.out,J);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${$.type}`)}var UH=q("ZodISODateTime",(Y,X)=>{PG.init(Y,X),a.init(Y,X)});function u5(Y){return R5(UH,Y)}var LH=q("ZodISODate",(Y,X)=>{MG.init(Y,X),a.init(Y,X)});function p5(Y){return _5(LH,Y)}var HH=q("ZodISOTime",(Y,X)=>{EG.init(Y,X),a.init(Y,X)});function l5(Y){return C5(HH,Y)}var NH=q("ZodISODuration",(Y,X)=>{wG.init(Y,X),a.init(Y,X)});function d5(Y){return I5(NH,Y)}var i5=(Y,X)=>{pY.init(Y,X),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(J)=>X$(Y,J)},flatten:{value:(J)=>Y$(Y,J)},addIssue:{value:(J)=>{Y.issues.push(J),Y.message=JSON.stringify(Y.issues,u1,2)}},addIssues:{value:(J)=>{Y.issues.push(...J),Y.message=JSON.stringify(Y.issues,u1,2)}},isEmpty:{get(){return Y.issues.length===0}}})},HO=q("ZodError",i5),R0=q("ZodError",i5,{Parent:Error});var n5=lY(R0),o5=dY(R0),r5=zY(R0),Q8=UY(R0),s5=$$(R0),a5=G$(R0),t5=W$(R0),e5=z$(R0),Y7=U$(R0),X7=L$(R0),J7=H$(R0),Q7=N$(R0);var t=q("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)=>b0(Y,J,Q),Y.brand=()=>Y,Y.register=(J,Q)=>{return J.add(Y,Q),Y},Y.parse=(J,Q)=>n5(Y,J,Q,{callee:Y.parse}),Y.safeParse=(J,Q)=>r5(Y,J,Q),Y.parseAsync=async(J,Q)=>o5(Y,J,Q,{callee:Y.parseAsync}),Y.safeParseAsync=async(J,Q)=>Q8(Y,J,Q),Y.spa=Y.safeParseAsync,Y.encode=(J,Q)=>s5(Y,J,Q),Y.decode=(J,Q)=>a5(Y,J,Q),Y.encodeAsync=async(J,Q)=>t5(Y,J,Q),Y.decodeAsync=async(J,Q)=>e5(Y,J,Q),Y.safeEncode=(J,Q)=>Y7(Y,J,Q),Y.safeDecode=(J,Q)=>X7(Y,J,Q),Y.safeEncodeAsync=async(J,Q)=>J7(Y,J,Q),Y.safeDecodeAsync=async(J,Q)=>Q7(Y,J,Q),Y.refine=(J,Q)=>Y.check($N(J,Q)),Y.superRefine=(J)=>Y.check(GN(J)),Y.overwrite=(J)=>Y.check(C1(J)),Y.optional=()=>W7(Y),Y.nullable=()=>z7(Y),Y.nullish=()=>W7(z7(Y)),Y.nonoptional=(J)=>aH(Y,J),Y.array=()=>x9(Y),Y.or=(J)=>v9([Y,J]),Y.and=(J)=>cH(Y,J),Y.transform=(J)=>U7(Y,dH(J)),Y.default=(J)=>oH(Y,J),Y.prefault=(J)=>sH(Y,J),Y.catch=(J)=>eH(Y,J),Y.pipe=(J)=>U7(Y,J),Y.readonly=()=>JN(Y),Y.describe=(J)=>{let Q=Y.clone();return _1.add(Q,{description:J}),Q},Object.defineProperty(Y,"description",{get(){return _1.get(Y)?.description},configurable:!0}),Y.meta=(...J)=>{if(J.length===0)return _1.get(Y);let Q=Y.clone();return _1.add(Q,J[0]),Q},Y.isOptional=()=>Y.safeParse(void 0).success,Y.isNullable=()=>Y.safeParse(null).success,Y}),L7=q("_ZodString",(Y,X)=>{rY.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(P9(...Q)),Y.includes=(...Q)=>Y.check(w9(...Q)),Y.startsWith=(...Q)=>Y.check(A9(...Q)),Y.endsWith=(...Q)=>Y.check(T9(...Q)),Y.min=(...Q)=>Y.check(d1(...Q)),Y.max=(...Q)=>Y.check(Y8(...Q)),Y.length=(...Q)=>Y.check(X8(...Q)),Y.nonempty=(...Q)=>Y.check(d1(1,...Q)),Y.lowercase=(Q)=>Y.check(M9(Q)),Y.uppercase=(Q)=>Y.check(E9(Q)),Y.trim=()=>Y.check(_9()),Y.normalize=(...Q)=>Y.check(R9(...Q)),Y.toLowerCase=()=>Y.check(C9()),Y.toUpperCase=()=>Y.check(I9())}),KH=q("ZodString",(Y,X)=>{rY.init(Y,X),L7.init(Y,X),Y.email=(J)=>Y.check(W5(OH,J)),Y.url=(J)=>Y.check(N5(FH,J)),Y.jwt=(J)=>Y.check(T5(kH,J)),Y.emoji=(J)=>Y.check(V5(qH,J)),Y.guid=(J)=>Y.check(D9($7,J)),Y.uuid=(J)=>Y.check(z5($8,J)),Y.uuidv4=(J)=>Y.check(U5($8,J)),Y.uuidv6=(J)=>Y.check(L5($8,J)),Y.uuidv7=(J)=>Y.check(H5($8,J)),Y.nanoid=(J)=>Y.check(Z5(jH,J)),Y.guid=(J)=>Y.check(D9($7,J)),Y.cuid=(J)=>Y.check(B5(DH,J)),Y.cuid2=(J)=>Y.check(K5(PH,J)),Y.ulid=(J)=>Y.check(O5(MH,J)),Y.base64=(J)=>Y.check(E5(CH,J)),Y.base64url=(J)=>Y.check(w5(IH,J)),Y.xid=(J)=>Y.check(F5(EH,J)),Y.ksuid=(J)=>Y.check(q5(wH,J)),Y.ipv4=(J)=>Y.check(j5(AH,J)),Y.ipv6=(J)=>Y.check(D5(TH,J)),Y.cidrv4=(J)=>Y.check(P5(RH,J)),Y.cidrv6=(J)=>Y.check(M5(_H,J)),Y.e164=(J)=>Y.check(A5(SH,J)),Y.datetime=(J)=>Y.check(u5(J)),Y.date=(J)=>Y.check(p5(J)),Y.time=(J)=>Y.check(l5(J)),Y.duration=(J)=>Y.check(d5(J))});function H7(Y){return G5(KH,Y)}var a=q("ZodStringFormat",(Y,X)=>{s.init(Y,X),L7.init(Y,X)}),OH=q("ZodEmail",(Y,X)=>{VG.init(Y,X),a.init(Y,X)});var $7=q("ZodGUID",(Y,X)=>{HG.init(Y,X),a.init(Y,X)});var $8=q("ZodUUID",(Y,X)=>{NG.init(Y,X),a.init(Y,X)});var FH=q("ZodURL",(Y,X)=>{ZG.init(Y,X),a.init(Y,X)});var qH=q("ZodEmoji",(Y,X)=>{BG.init(Y,X),a.init(Y,X)});var jH=q("ZodNanoID",(Y,X)=>{KG.init(Y,X),a.init(Y,X)});var DH=q("ZodCUID",(Y,X)=>{OG.init(Y,X),a.init(Y,X)});var PH=q("ZodCUID2",(Y,X)=>{FG.init(Y,X),a.init(Y,X)});var MH=q("ZodULID",(Y,X)=>{qG.init(Y,X),a.init(Y,X)});var EH=q("ZodXID",(Y,X)=>{jG.init(Y,X),a.init(Y,X)});var wH=q("ZodKSUID",(Y,X)=>{DG.init(Y,X),a.init(Y,X)});var AH=q("ZodIPv4",(Y,X)=>{AG.init(Y,X),a.init(Y,X)});var TH=q("ZodIPv6",(Y,X)=>{TG.init(Y,X),a.init(Y,X)});var RH=q("ZodCIDRv4",(Y,X)=>{RG.init(Y,X),a.init(Y,X)});var _H=q("ZodCIDRv6",(Y,X)=>{_G.init(Y,X),a.init(Y,X)});var CH=q("ZodBase64",(Y,X)=>{IG.init(Y,X),a.init(Y,X)});var IH=q("ZodBase64URL",(Y,X)=>{SG.init(Y,X),a.init(Y,X)});var SH=q("ZodE164",(Y,X)=>{kG.init(Y,X),a.init(Y,X)});var kH=q("ZodJWT",(Y,X)=>{bG.init(Y,X),a.init(Y,X)});var N7=q("ZodNumber",(Y,X)=>{q9.init(Y,X),t.init(Y,X),Y.gt=(Q,$)=>Y.check(tY(Q,$)),Y.gte=(Q,$)=>Y.check(NY(Q,$)),Y.min=(Q,$)=>Y.check(NY(Q,$)),Y.lt=(Q,$)=>Y.check(aY(Q,$)),Y.lte=(Q,$)=>Y.check(HY(Q,$)),Y.max=(Q,$)=>Y.check(HY(Q,$)),Y.int=(Q)=>Y.check(G7(Q)),Y.safe=(Q)=>Y.check(G7(Q)),Y.positive=(Q)=>Y.check(tY(0,Q)),Y.nonnegative=(Q)=>Y.check(NY(0,Q)),Y.negative=(Q)=>Y.check(aY(0,Q)),Y.nonpositive=(Q)=>Y.check(HY(0,Q)),Y.multipleOf=(Q,$)=>Y.check(eY(Q,$)),Y.step=(Q,$)=>Y.check(eY(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 V7(Y){return S5(N7,Y)}var bH=q("ZodNumberFormat",(Y,X)=>{xG.init(Y,X),N7.init(Y,X)});function G7(Y){return k5(bH,Y)}var xH=q("ZodBoolean",(Y,X)=>{vG.init(Y,X),t.init(Y,X)});function Z7(Y){return b5(xH,Y)}var vH=q("ZodNull",(Y,X)=>{hG.init(Y,X),t.init(Y,X)});function B7(Y){return x5(vH,Y)}var hH=q("ZodUnknown",(Y,X)=>{gG.init(Y,X),t.init(Y,X)});function VY(){return v5(hH)}var gH=q("ZodNever",(Y,X)=>{yG.init(Y,X),t.init(Y,X)});function b9(Y){return h5(gH,Y)}var yH=q("ZodArray",(Y,X)=>{fG.init(Y,X),t.init(Y,X),Y.element=X.element,Y.min=(J,Q)=>Y.check(d1(J,Q)),Y.nonempty=(J)=>Y.check(d1(1,J)),Y.max=(J,Q)=>Y.check(Y8(J,Q)),Y.length=(J,Q)=>Y.check(X8(J,Q)),Y.unwrap=()=>Y.element});function x9(Y,X){return g5(yH,Y,X)}var K7=q("ZodObject",(Y,X)=>{uG.init(Y,X),t.init(Y,X),c.defineLazy(Y,"shape",()=>X.shape),Y.keyof=()=>h9(Object.keys(Y._zod.def.shape)),Y.catchall=(J)=>Y.clone({...Y._zod.def,catchall:J}),Y.passthrough=()=>Y.clone({...Y._zod.def,catchall:VY()}),Y.loose=()=>Y.clone({...Y._zod.def,catchall:VY()}),Y.strict=()=>Y.clone({...Y._zod.def,catchall:b9()}),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(M7,Y,J[0]),Y.required=(...J)=>c.required(E7,Y,J[0])});function O7(Y,X){let J={type:"object",get shape(){return c.assignProp(this,"shape",Y?c.objectClone(Y):{}),this.shape},...c.normalizeParams(X)};return new K7(J)}function F7(Y,X){return new K7({type:"object",get shape(){return c.assignProp(this,"shape",c.objectClone(Y)),this.shape},catchall:VY(),...c.normalizeParams(X)})}var q7=q("ZodUnion",(Y,X)=>{j9.init(Y,X),t.init(Y,X),Y.options=X.options});function v9(Y,X){return new q7({type:"union",options:Y,...c.normalizeParams(X)})}var fH=q("ZodDiscriminatedUnion",(Y,X)=>{q7.init(Y,X),pG.init(Y,X)});function j7(Y,X,J){return new fH({type:"union",options:X,discriminator:Y,...c.normalizeParams(J)})}var mH=q("ZodIntersection",(Y,X)=>{lG.init(Y,X),t.init(Y,X)});function cH(Y,X){return new mH({type:"intersection",left:Y,right:X})}var uH=q("ZodRecord",(Y,X)=>{dG.init(Y,X),t.init(Y,X),Y.keyType=X.keyType,Y.valueType=X.valueType});function D7(Y,X,J){return new uH({type:"record",keyType:Y,valueType:X,...c.normalizeParams(J)})}var k9=q("ZodEnum",(Y,X)=>{iG.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 k9({...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 k9({...X,checks:[],...c.normalizeParams($),entries:G})}});function h9(Y,X){let J=Array.isArray(Y)?Object.fromEntries(Y.map((Q)=>[Q,Q])):Y;return new k9({type:"enum",entries:J,...c.normalizeParams(X)})}var pH=q("ZodLiteral",(Y,X)=>{nG.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 P7(Y,X){return new pH({type:"literal",values:Array.isArray(Y)?Y:[Y],...c.normalizeParams(X)})}var lH=q("ZodTransform",(Y,X)=>{oG.init(Y,X),t.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new XY(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 dH(Y){return new lH({type:"transform",transform:Y})}var M7=q("ZodOptional",(Y,X)=>{rG.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function W7(Y){return new M7({type:"optional",innerType:Y})}var iH=q("ZodNullable",(Y,X)=>{sG.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function z7(Y){return new iH({type:"nullable",innerType:Y})}var nH=q("ZodDefault",(Y,X)=>{aG.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function oH(Y,X){return new nH({type:"default",innerType:Y,get defaultValue(){return typeof X==="function"?X():c.shallowClone(X)}})}var rH=q("ZodPrefault",(Y,X)=>{tG.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function sH(Y,X){return new rH({type:"prefault",innerType:Y,get defaultValue(){return typeof X==="function"?X():c.shallowClone(X)}})}var E7=q("ZodNonOptional",(Y,X)=>{eG.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function aH(Y,X){return new E7({type:"nonoptional",innerType:Y,...c.normalizeParams(X)})}var tH=q("ZodCatch",(Y,X)=>{Y5.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function eH(Y,X){return new tH({type:"catch",innerType:Y,catchValue:typeof X==="function"?X:()=>X})}var YN=q("ZodPipe",(Y,X)=>{X5.init(Y,X),t.init(Y,X),Y.in=X.in,Y.out=X.out});function U7(Y,X){return new YN({type:"pipe",in:Y,out:X})}var XN=q("ZodReadonly",(Y,X)=>{J5.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function JN(Y){return new XN({type:"readonly",innerType:Y})}var QN=q("ZodLazy",(Y,X)=>{Q5.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.getter()});function w7(Y){return new QN({type:"lazy",getter:Y})}var g9=q("ZodCustom",(Y,X)=>{$5.init(Y,X),t.init(Y,X)});function A7(Y,X){return y5(g9,Y??(()=>!0),X)}function $N(Y,X={}){return f5(g9,Y,X)}function GN(Y){return m5(Y)}function T7(Y,X={error:`Input not instance of ${Y.name}`}){let J=new g9({type:"custom",check:"custom",fn:(Q)=>Q instanceof Y,abort:!0,...c.normalizeParams(X)});return J._zod.bag.Class=Y,J}function h7(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 WN(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 i1(Y,...X){let J=new Headers(WN(Y)),Q=J.get("user-agent")||"";return J.set("user-agent",[Q,...X].filter(Boolean).join(" ")),Object.fromEntries(J.entries())}var zN=[{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]}],aO=[...zN,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];var UN=12,LN=131072,tO=LN+UN;async function G8(Y){var X;try{await((X=Y.body)==null?void 0:X.cancel())}catch(J){}}var g7="AI_DownloadError",y7=`vercel.ai.error.${g7}`,HN=Symbol.for(y7),R7,_7,j0=class extends(_7=D,R7=HN,_7){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:g7,message:$,cause:Q});this[R7]=!0,this.url=Y,this.statusCode=X,this.statusText=J}static isInstance(Y){return D.hasMarker(Y,y7)}};function NN(Y=globalThis){return Y.window!=null}function C7(Y,X){try{return new URL(Y).origin===new URL(X).origin}catch(J){return!1}}function VN(Y){let X;try{X=new URL(Y)}catch(Q){throw new j0({url:Y,message:`Invalid URL: ${Y}`})}if(X.protocol==="data:")return;if(X.protocol!=="http:"&&X.protocol!=="https:")throw new j0({url:Y,message:`URL scheme must be http, https, or data, got ${X.protocol}`});let J=X.hostname.toLowerCase().replace(/\.+$/,"");if(!J)throw new j0({url:Y,message:"URL must have a hostname"});if(J==="localhost"||J.endsWith(".local")||J.endsWith(".localhost"))throw new j0({url:Y,message:`URL with hostname ${J} is not allowed`});if(J.startsWith("[")&&J.endsWith("]")){let Q=J.slice(1,-1);if(f7(Q))throw new j0({url:Y,message:`URL with IPv6 address ${J} is not allowed`});return}if(p9(J)){if(l9(J))throw new j0({url:Y,message:`URL with IP address ${J} is not allowed`});return}}function ZN({address:Y,family:X,hostname:J}){if(X===4?!p9(Y)||l9(Y):X===6?f7(Y):!0)throw new j0({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 l9(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 BN(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 V=L[H];if(V.includes(".")){if(H!==L.length-1||!p9(V))return null;let[O,B,N,K]=V.split(".").map(Number);U.push(O<<8|B,N<<8|K);continue}if(!/^[0-9a-f]{1,4}$/.test(V))return null;U.push(parseInt(V,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 f7(Y){let X=BN(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 l9(`${$}.${G}.${W}.${U}`)}return!1}function KN(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)ZN({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 y9,m7=globalThis.fetch,ON=jN(m7);function FN(){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 qN(){if(!FN()||!ON||globalThis.fetch!==m7)return globalThis.fetch;return y9!=null?y9:y9=Promise.resolve().then(DN)}function jN(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 DN(){let{createRequire:Y}=I7("node:module"),{lookup:X}=I7("node:dns"),{Agent:J,fetch:Q}=Y(c7())("undici"),$=new J({connect:{lookup:KN(X)}});return(G,W)=>Q(G,{...W,dispatcher:$})}function I7(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 c7(){let Y=Error.prepareStackTrace;try{Error.prepareStackTrace=($,G)=>G;let X=Error("Capture current module path");Error.captureStackTrace(X,c7);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 PN=["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 MN(Y){let X=new Headers(Y);for(let J of PN)X.delete(J);return X}var EN=10,wN=new Set([301,302,303,307,308]);async function u7({url:Y,headers:X,abortSignal:J,maxRedirects:Q=EN,fetch:$,trustedOrigin:G}){let W=X===void 0?void 0:MN(X),U=(H)=>{let V={signal:J,redirect:H};if(W!==void 0)V.headers=new Headers(W);return V},L=Y;for(let H=0;H<=Q;H++){let V=G!==void 0&&C7(L,G);if(!V)VN(L);let O=$!=null?$:V?globalThis.fetch:await qN(),B=await O(L,U("manual"));if(B.type==="opaqueredirect"){if(!NN())throw new j0({url:Y,message:`Redirect from ${L} could not be validated and was blocked`});return await O(L,U("follow"))}let N=B.headers.get("location");if(wN.has(B.status)&&N){await G8(B);let K=new URL(N,L).toString();if(W!==void 0&&!C7(K,L)){let j=W.get("user-agent");W=new Headers(j==null?void 0:{"user-agent":j})}L=K;continue}return B}throw new j0({url:Y,message:`Too many redirects (max ${Q})`})}var d9=2147483648;async function p7({response:Y,url:X,maxBytes:J=d9}){let Q=Y.headers.get("content-length");if(Q!=null){let V=parseInt(Q,10);if(!isNaN(V)&&V>J)throw await G8(Y),new j0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes (Content-Length: ${V}).`})}let $=Y.body;if($==null)return new Uint8Array(0);let G=$.getReader(),W=[],U=0;try{while(!0){let{done:V,value:O}=await G.read();if(V)break;if(U+=O.length,U>J)throw new j0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes.`});W.push(O)}}finally{try{await G.cancel()}catch(V){}finally{G.releaseLock()}}let L=new Uint8Array(U),H=0;for(let V of W)L.set(V,H),H+=V.length;return L}var W0=({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 PQ({argument:"separator",message:`The separator "${Q}" must not be part of the alphabet "${J}".`});return()=>`${Y}${Q}${$()}`},XF=W0();function l7(Y){var X,J;return(J=(X=globalThis.Buffer)==null?void 0:X.isBuffer(Y))!=null?J:!1}var AN=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,TN=/"(?: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 S7(Y){let X=JSON.parse(Y);if(X===null||typeof X!=="object")return X;if(AN.test(Y)===!1&&TN.test(Y)===!1)return X;return RN(X)}function RN(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 _N(Y){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(J){return S7(Y)}try{return S7(Y)}finally{Error.stackTraceLimit=X}}function i9(Y){if(Y.type==="object"||Array.isArray(Y.type)&&Y.type.includes("object")){let{additionalProperties:J}=Y;Y.additionalProperties=J!=null&&typeof J!=="boolean"?B1(J):!1;let{properties:Q}=Y;if(Q!=null)for(let $ of Object.keys(Q))Q[$]=B1(Q[$])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(B1):B1(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(B1);if(Y.allOf!=null)Y.allOf=Y.allOf.map(B1);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(B1);let{definitions:X}=Y;if(X!=null)for(let J of Object.keys(X))X[J]=B1(X[J]);return Y}function B1(Y){if(typeof Y==="boolean")return Y;return i9(Y)}var CN=Symbol("Let zodToJsonSchema decide on which parser to use"),k7={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"},IN=(Y)=>typeof Y==="string"?{...k7,name:Y}:{...k7,...Y};function _0(){return{}}function SN(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 kN(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 bN(){return{type:"boolean"}}function d7(Y,X){return n(Y.type._def,X)}var xN=(Y,X)=>{return n(Y.innerType._def,X)};function i7(Y,X,J){let Q=J!=null?J:X.dateStrategy;if(Array.isArray(Q))return{anyOf:Q.map(($)=>i7(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 vN(Y)}}var vN=(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 hN(Y,X){return{...n(Y.innerType._def,X),default:Y.defaultValue()}}function gN(Y,X){return X.effectStrategy==="input"?n(Y.schema._def,X):_0()}function yN(Y){return{type:"string",enum:Array.from(Y.values)}}var fN=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function mN(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(fN($))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 cN(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,v0={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 n7(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":h0(J,"email",Q.message,X);break;case"format:idn-email":h0(J,"idn-email",Q.message,X);break;case"pattern:zod":q0(J,v0.email,Q.message,X);break}break;case"url":h0(J,"uri",Q.message,X);break;case"uuid":h0(J,"uuid",Q.message,X);break;case"regex":q0(J,Q.regex,Q.message,X);break;case"cuid":q0(J,v0.cuid,Q.message,X);break;case"cuid2":q0(J,v0.cuid2,Q.message,X);break;case"startsWith":q0(J,RegExp(`^${m9(Q.value,X)}`),Q.message,X);break;case"endsWith":q0(J,RegExp(`${m9(Q.value,X)}$`),Q.message,X);break;case"datetime":h0(J,"date-time",Q.message,X);break;case"date":h0(J,"date",Q.message,X);break;case"time":h0(J,"time",Q.message,X);break;case"duration":h0(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":{q0(J,RegExp(m9(Q.value,X)),Q.message,X);break}case"ip":{if(Q.version!=="v6")h0(J,"ipv4",Q.message,X);if(Q.version!=="v4")h0(J,"ipv6",Q.message,X);break}case"base64url":q0(J,v0.base64url,Q.message,X);break;case"jwt":q0(J,v0.jwt,Q.message,X);break;case"cidr":{if(Q.version!=="v6")q0(J,v0.ipv4Cidr,Q.message,X);if(Q.version!=="v4")q0(J,v0.ipv6Cidr,Q.message,X);break}case"emoji":q0(J,v0.emoji(),Q.message,X);break;case"ulid":{q0(J,v0.ulid,Q.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{h0(J,"binary",Q.message,X);break}case"contentEncoding:base64":{J.contentEncoding="base64";break}case"pattern:zod":{q0(J,v0.base64,Q.message,X);break}}break}case"nanoid":q0(J,v0.nanoid,Q.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return J}function m9(Y,X){return X.patternStrategy==="escape"?pN(Y):Y}var uN=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function pN(Y){let X="";for(let J=0;J<Y.length;J++){if(!uN.has(Y[J]))X+="\\";X+=Y[J]}return X}function h0(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 q0(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:b7(X,Q),...J&&Q.errorMessages&&{errorMessage:{pattern:J}}})}else Y.pattern=b7(X,Q)}function b7(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
|
|
187
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let H of this.seen.entries()){let V=H[1];if(Y===H[0]){G(H);continue}if(J.external){let B=J.external.registry.get(H[0])?.id;if(Y!==H[0]&&B){G(H);continue}}if(this.metadataRegistry.get(H[0])?.id){G(H);continue}if(V.cycle){G(H);continue}if(V.count>1){if(J.reused==="ref"){G(H);continue}}}let W=(H,V)=>{let O=this.seen.get(H),B=O.def??O.schema,N={...B};if(O.ref===null)return;let K=O.ref;if(O.ref=null,K){W(K,V);let j=this.seen.get(K).schema;if(j.$ref&&(V.target==="draft-7"||V.target==="draft-4"||V.target==="openapi-3.0"))B.allOf=B.allOf??[],B.allOf.push(j);else Object.assign(B,j),Object.assign(B,N)}if(!O.isParent)this.override({zodSchema:H,jsonSchema:B,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 V=H[1];if(V.def&&V.defId)L[V.defId]=V.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 p5(Y,X){if(Y instanceof sY){let Q=new S9(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 S9(X);return J.process(Y),J.emit(Y,X)}function U0(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 U0($.element,J);case"object":{for(let G in $.shape)if(U0($.shape[G],J))return!0;return!1}case"union":{for(let G of $.options)if(U0(G,J))return!0;return!1}case"intersection":return U0($.left,J)||U0($.right,J);case"tuple":{for(let G of $.items)if(U0(G,J))return!0;if($.rest&&U0($.rest,J))return!0;return!1}case"record":return U0($.keyType,J)||U0($.valueType,J);case"map":return U0($.keyType,J)||U0($.valueType,J);case"set":return U0($.valueType,J);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return U0($.innerType,J);case"lazy":return U0($.getter(),J);case"default":return U0($.innerType,J);case"prefault":return U0($.innerType,J);case"custom":return!1;case"transform":return!0;case"pipe":return U0($.in,J)||U0($.out,J);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${$.type}`)}var NH=q("ZodISODateTime",(Y,X)=>{EG.init(Y,X),a.init(Y,X)});function l5(Y){return C5(NH,Y)}var VH=q("ZodISODate",(Y,X)=>{AG.init(Y,X),a.init(Y,X)});function d5(Y){return I5(VH,Y)}var ZH=q("ZodISOTime",(Y,X)=>{wG.init(Y,X),a.init(Y,X)});function i5(Y){return S5(ZH,Y)}var BH=q("ZodISODuration",(Y,X)=>{TG.init(Y,X),a.init(Y,X)});function n5(Y){return k5(BH,Y)}var o5=(Y,X)=>{pY.init(Y,X),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(J)=>Q$(Y,J)},flatten:{value:(J)=>J$(Y,J)},addIssue:{value:(J)=>{Y.issues.push(J),Y.message=JSON.stringify(Y.issues,u1,2)}},addIssues:{value:(J)=>{Y.issues.push(...J),Y.message=JSON.stringify(Y.issues,u1,2)}},isEmpty:{get(){return Y.issues.length===0}}})},ZO=q("ZodError",o5),R0=q("ZodError",o5,{Parent:Error});var r5=lY(R0),s5=dY(R0),a5=zY(R0),Q8=UY(R0),t5=W$(R0),e5=z$(R0),Y7=U$(R0),X7=L$(R0),J7=H$(R0),Q7=N$(R0),$7=V$(R0),G7=Z$(R0);var t=q("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)=>b0(Y,J,Q),Y.brand=()=>Y,Y.register=(J,Q)=>{return J.add(Y,Q),Y},Y.parse=(J,Q)=>r5(Y,J,Q,{callee:Y.parse}),Y.safeParse=(J,Q)=>a5(Y,J,Q),Y.parseAsync=async(J,Q)=>s5(Y,J,Q,{callee:Y.parseAsync}),Y.safeParseAsync=async(J,Q)=>Q8(Y,J,Q),Y.spa=Y.safeParseAsync,Y.encode=(J,Q)=>t5(Y,J,Q),Y.decode=(J,Q)=>e5(Y,J,Q),Y.encodeAsync=async(J,Q)=>Y7(Y,J,Q),Y.decodeAsync=async(J,Q)=>X7(Y,J,Q),Y.safeEncode=(J,Q)=>J7(Y,J,Q),Y.safeDecode=(J,Q)=>Q7(Y,J,Q),Y.safeEncodeAsync=async(J,Q)=>$7(Y,J,Q),Y.safeDecodeAsync=async(J,Q)=>G7(Y,J,Q),Y.refine=(J,Q)=>Y.check(zN(J,Q)),Y.superRefine=(J)=>Y.check(UN(J)),Y.overwrite=(J)=>Y.check(C1(J)),Y.optional=()=>U7(Y),Y.nullable=()=>L7(Y),Y.nullish=()=>U7(L7(Y)),Y.nonoptional=(J)=>YN(Y,J),Y.array=()=>x9(Y),Y.or=(J)=>v9([Y,J]),Y.and=(J)=>lH(Y,J),Y.transform=(J)=>H7(Y,oH(J)),Y.default=(J)=>aH(Y,J),Y.prefault=(J)=>eH(Y,J),Y.catch=(J)=>JN(Y,J),Y.pipe=(J)=>H7(Y,J),Y.readonly=()=>GN(Y),Y.describe=(J)=>{let Q=Y.clone();return _1.add(Q,{description:J}),Q},Object.defineProperty(Y,"description",{get(){return _1.get(Y)?.description},configurable:!0}),Y.meta=(...J)=>{if(J.length===0)return _1.get(Y);let Q=Y.clone();return _1.add(Q,J[0]),Q},Y.isOptional=()=>Y.safeParse(void 0).success,Y.isNullable=()=>Y.safeParse(null).success,Y}),N7=q("_ZodString",(Y,X)=>{rY.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(P9(...Q)),Y.includes=(...Q)=>Y.check(A9(...Q)),Y.startsWith=(...Q)=>Y.check(w9(...Q)),Y.endsWith=(...Q)=>Y.check(T9(...Q)),Y.min=(...Q)=>Y.check(d1(...Q)),Y.max=(...Q)=>Y.check(Y8(...Q)),Y.length=(...Q)=>Y.check(X8(...Q)),Y.nonempty=(...Q)=>Y.check(d1(1,...Q)),Y.lowercase=(Q)=>Y.check(M9(Q)),Y.uppercase=(Q)=>Y.check(E9(Q)),Y.trim=()=>Y.check(_9()),Y.normalize=(...Q)=>Y.check(R9(...Q)),Y.toLowerCase=()=>Y.check(C9()),Y.toUpperCase=()=>Y.check(I9())}),qH=q("ZodString",(Y,X)=>{rY.init(Y,X),N7.init(Y,X),Y.email=(J)=>Y.check(U5(jH,J)),Y.url=(J)=>Y.check(Z5(DH,J)),Y.jwt=(J)=>Y.check(_5(vH,J)),Y.emoji=(J)=>Y.check(B5(PH,J)),Y.guid=(J)=>Y.check(D9(W7,J)),Y.uuid=(J)=>Y.check(L5($8,J)),Y.uuidv4=(J)=>Y.check(H5($8,J)),Y.uuidv6=(J)=>Y.check(N5($8,J)),Y.uuidv7=(J)=>Y.check(V5($8,J)),Y.nanoid=(J)=>Y.check(K5(MH,J)),Y.guid=(J)=>Y.check(D9(W7,J)),Y.cuid=(J)=>Y.check(O5(EH,J)),Y.cuid2=(J)=>Y.check(F5(AH,J)),Y.ulid=(J)=>Y.check(q5(wH,J)),Y.base64=(J)=>Y.check(w5(kH,J)),Y.base64url=(J)=>Y.check(T5(bH,J)),Y.xid=(J)=>Y.check(j5(TH,J)),Y.ksuid=(J)=>Y.check(D5(RH,J)),Y.ipv4=(J)=>Y.check(P5(_H,J)),Y.ipv6=(J)=>Y.check(M5(CH,J)),Y.cidrv4=(J)=>Y.check(E5(IH,J)),Y.cidrv6=(J)=>Y.check(A5(SH,J)),Y.e164=(J)=>Y.check(R5(xH,J)),Y.datetime=(J)=>Y.check(l5(J)),Y.date=(J)=>Y.check(d5(J)),Y.time=(J)=>Y.check(i5(J)),Y.duration=(J)=>Y.check(n5(J))});function V7(Y){return z5(qH,Y)}var a=q("ZodStringFormat",(Y,X)=>{s.init(Y,X),N7.init(Y,X)}),jH=q("ZodEmail",(Y,X)=>{BG.init(Y,X),a.init(Y,X)});var W7=q("ZodGUID",(Y,X)=>{VG.init(Y,X),a.init(Y,X)});var $8=q("ZodUUID",(Y,X)=>{ZG.init(Y,X),a.init(Y,X)});var DH=q("ZodURL",(Y,X)=>{KG.init(Y,X),a.init(Y,X)});var PH=q("ZodEmoji",(Y,X)=>{OG.init(Y,X),a.init(Y,X)});var MH=q("ZodNanoID",(Y,X)=>{FG.init(Y,X),a.init(Y,X)});var EH=q("ZodCUID",(Y,X)=>{qG.init(Y,X),a.init(Y,X)});var AH=q("ZodCUID2",(Y,X)=>{jG.init(Y,X),a.init(Y,X)});var wH=q("ZodULID",(Y,X)=>{DG.init(Y,X),a.init(Y,X)});var TH=q("ZodXID",(Y,X)=>{PG.init(Y,X),a.init(Y,X)});var RH=q("ZodKSUID",(Y,X)=>{MG.init(Y,X),a.init(Y,X)});var _H=q("ZodIPv4",(Y,X)=>{RG.init(Y,X),a.init(Y,X)});var CH=q("ZodIPv6",(Y,X)=>{_G.init(Y,X),a.init(Y,X)});var IH=q("ZodCIDRv4",(Y,X)=>{CG.init(Y,X),a.init(Y,X)});var SH=q("ZodCIDRv6",(Y,X)=>{IG.init(Y,X),a.init(Y,X)});var kH=q("ZodBase64",(Y,X)=>{kG.init(Y,X),a.init(Y,X)});var bH=q("ZodBase64URL",(Y,X)=>{bG.init(Y,X),a.init(Y,X)});var xH=q("ZodE164",(Y,X)=>{xG.init(Y,X),a.init(Y,X)});var vH=q("ZodJWT",(Y,X)=>{vG.init(Y,X),a.init(Y,X)});var Z7=q("ZodNumber",(Y,X)=>{q9.init(Y,X),t.init(Y,X),Y.gt=(Q,$)=>Y.check(tY(Q,$)),Y.gte=(Q,$)=>Y.check(NY(Q,$)),Y.min=(Q,$)=>Y.check(NY(Q,$)),Y.lt=(Q,$)=>Y.check(aY(Q,$)),Y.lte=(Q,$)=>Y.check(HY(Q,$)),Y.max=(Q,$)=>Y.check(HY(Q,$)),Y.int=(Q)=>Y.check(z7(Q)),Y.safe=(Q)=>Y.check(z7(Q)),Y.positive=(Q)=>Y.check(tY(0,Q)),Y.nonnegative=(Q)=>Y.check(NY(0,Q)),Y.negative=(Q)=>Y.check(aY(0,Q)),Y.nonpositive=(Q)=>Y.check(HY(0,Q)),Y.multipleOf=(Q,$)=>Y.check(eY(Q,$)),Y.step=(Q,$)=>Y.check(eY(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 B7(Y){return b5(Z7,Y)}var hH=q("ZodNumberFormat",(Y,X)=>{hG.init(Y,X),Z7.init(Y,X)});function z7(Y){return x5(hH,Y)}var gH=q("ZodBoolean",(Y,X)=>{gG.init(Y,X),t.init(Y,X)});function K7(Y){return v5(gH,Y)}var yH=q("ZodNull",(Y,X)=>{yG.init(Y,X),t.init(Y,X)});function O7(Y){return h5(yH,Y)}var fH=q("ZodUnknown",(Y,X)=>{fG.init(Y,X),t.init(Y,X)});function VY(){return g5(fH)}var mH=q("ZodNever",(Y,X)=>{mG.init(Y,X),t.init(Y,X)});function b9(Y){return y5(mH,Y)}var cH=q("ZodArray",(Y,X)=>{cG.init(Y,X),t.init(Y,X),Y.element=X.element,Y.min=(J,Q)=>Y.check(d1(J,Q)),Y.nonempty=(J)=>Y.check(d1(1,J)),Y.max=(J,Q)=>Y.check(Y8(J,Q)),Y.length=(J,Q)=>Y.check(X8(J,Q)),Y.unwrap=()=>Y.element});function x9(Y,X){return f5(cH,Y,X)}var F7=q("ZodObject",(Y,X)=>{lG.init(Y,X),t.init(Y,X),c.defineLazy(Y,"shape",()=>X.shape),Y.keyof=()=>h9(Object.keys(Y._zod.def.shape)),Y.catchall=(J)=>Y.clone({...Y._zod.def,catchall:J}),Y.passthrough=()=>Y.clone({...Y._zod.def,catchall:VY()}),Y.loose=()=>Y.clone({...Y._zod.def,catchall:VY()}),Y.strict=()=>Y.clone({...Y._zod.def,catchall:b9()}),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(A7,Y,J[0]),Y.required=(...J)=>c.required(w7,Y,J[0])});function q7(Y,X){let J={type:"object",get shape(){return c.assignProp(this,"shape",Y?c.objectClone(Y):{}),this.shape},...c.normalizeParams(X)};return new F7(J)}function j7(Y,X){return new F7({type:"object",get shape(){return c.assignProp(this,"shape",c.objectClone(Y)),this.shape},catchall:VY(),...c.normalizeParams(X)})}var D7=q("ZodUnion",(Y,X)=>{j9.init(Y,X),t.init(Y,X),Y.options=X.options});function v9(Y,X){return new D7({type:"union",options:Y,...c.normalizeParams(X)})}var uH=q("ZodDiscriminatedUnion",(Y,X)=>{D7.init(Y,X),dG.init(Y,X)});function P7(Y,X,J){return new uH({type:"union",options:X,discriminator:Y,...c.normalizeParams(J)})}var pH=q("ZodIntersection",(Y,X)=>{iG.init(Y,X),t.init(Y,X)});function lH(Y,X){return new pH({type:"intersection",left:Y,right:X})}var dH=q("ZodRecord",(Y,X)=>{nG.init(Y,X),t.init(Y,X),Y.keyType=X.keyType,Y.valueType=X.valueType});function M7(Y,X,J){return new dH({type:"record",keyType:Y,valueType:X,...c.normalizeParams(J)})}var k9=q("ZodEnum",(Y,X)=>{oG.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 k9({...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 k9({...X,checks:[],...c.normalizeParams($),entries:G})}});function h9(Y,X){let J=Array.isArray(Y)?Object.fromEntries(Y.map((Q)=>[Q,Q])):Y;return new k9({type:"enum",entries:J,...c.normalizeParams(X)})}var iH=q("ZodLiteral",(Y,X)=>{rG.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 E7(Y,X){return new iH({type:"literal",values:Array.isArray(Y)?Y:[Y],...c.normalizeParams(X)})}var nH=q("ZodTransform",(Y,X)=>{sG.init(Y,X),t.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new XY(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 oH(Y){return new nH({type:"transform",transform:Y})}var A7=q("ZodOptional",(Y,X)=>{aG.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function U7(Y){return new A7({type:"optional",innerType:Y})}var rH=q("ZodNullable",(Y,X)=>{tG.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function L7(Y){return new rH({type:"nullable",innerType:Y})}var sH=q("ZodDefault",(Y,X)=>{eG.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function aH(Y,X){return new sH({type:"default",innerType:Y,get defaultValue(){return typeof X==="function"?X():c.shallowClone(X)}})}var tH=q("ZodPrefault",(Y,X)=>{Y5.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function eH(Y,X){return new tH({type:"prefault",innerType:Y,get defaultValue(){return typeof X==="function"?X():c.shallowClone(X)}})}var w7=q("ZodNonOptional",(Y,X)=>{X5.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function YN(Y,X){return new w7({type:"nonoptional",innerType:Y,...c.normalizeParams(X)})}var XN=q("ZodCatch",(Y,X)=>{J5.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function JN(Y,X){return new XN({type:"catch",innerType:Y,catchValue:typeof X==="function"?X:()=>X})}var QN=q("ZodPipe",(Y,X)=>{Q5.init(Y,X),t.init(Y,X),Y.in=X.in,Y.out=X.out});function H7(Y,X){return new QN({type:"pipe",in:Y,out:X})}var $N=q("ZodReadonly",(Y,X)=>{$5.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function GN(Y){return new $N({type:"readonly",innerType:Y})}var WN=q("ZodLazy",(Y,X)=>{G5.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.getter()});function T7(Y){return new WN({type:"lazy",getter:Y})}var g9=q("ZodCustom",(Y,X)=>{W5.init(Y,X),t.init(Y,X)});function R7(Y,X){return m5(g9,Y??(()=>!0),X)}function zN(Y,X={}){return c5(g9,Y,X)}function UN(Y){return u5(Y)}function _7(Y,X={error:`Input not instance of ${Y.name}`}){let J=new g9({type:"custom",check:"custom",fn:(Q)=>Q instanceof Y,abort:!0,...c.normalizeParams(X)});return J._zod.bag.Class=Y,J}function y7(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 LN(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 i1(Y,...X){let J=new Headers(LN(Y)),Q=J.get("user-agent")||"";return J.set("user-agent",[Q,...X].filter(Boolean).join(" ")),Object.fromEntries(J.entries())}var HN=[{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]}],YF=[...HN,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];var NN=12,VN=131072,XF=VN+NN;async function G8(Y){var X;try{await((X=Y.body)==null?void 0:X.cancel())}catch(J){}}var f7="AI_DownloadError",m7=`vercel.ai.error.${f7}`,ZN=Symbol.for(m7),C7,I7,j0=class extends(I7=D,C7=ZN,I7){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:f7,message:$,cause:Q});this[C7]=!0,this.url=Y,this.statusCode=X,this.statusText=J}static isInstance(Y){return D.hasMarker(Y,m7)}};function BN(Y=globalThis){return Y.window!=null}function S7(Y,X){try{return new URL(Y).origin===new URL(X).origin}catch(J){return!1}}function KN(Y){let X;try{X=new URL(Y)}catch(Q){throw new j0({url:Y,message:`Invalid URL: ${Y}`})}if(X.protocol==="data:")return;if(X.protocol!=="http:"&&X.protocol!=="https:")throw new j0({url:Y,message:`URL scheme must be http, https, or data, got ${X.protocol}`});let J=X.hostname.toLowerCase().replace(/\.+$/,"");if(!J)throw new j0({url:Y,message:"URL must have a hostname"});if(J==="localhost"||J.endsWith(".local")||J.endsWith(".localhost"))throw new j0({url:Y,message:`URL with hostname ${J} is not allowed`});if(J.startsWith("[")&&J.endsWith("]")){let Q=J.slice(1,-1);if(c7(Q))throw new j0({url:Y,message:`URL with IPv6 address ${J} is not allowed`});return}if(p9(J)){if(l9(J))throw new j0({url:Y,message:`URL with IP address ${J} is not allowed`});return}}function ON({address:Y,family:X,hostname:J}){if(X===4?!p9(Y)||l9(Y):X===6?c7(Y):!0)throw new j0({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 l9(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 FN(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 V=L[H];if(V.includes(".")){if(H!==L.length-1||!p9(V))return null;let[O,B,N,K]=V.split(".").map(Number);U.push(O<<8|B,N<<8|K);continue}if(!/^[0-9a-f]{1,4}$/.test(V))return null;U.push(parseInt(V,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 c7(Y){let X=FN(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 l9(`${$}.${G}.${W}.${U}`)}return!1}function qN(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)ON({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 y9,u7=globalThis.fetch,jN=MN(u7);function DN(){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 PN(){if(!DN()||!jN||globalThis.fetch!==u7)return globalThis.fetch;return y9!=null?y9:y9=Promise.resolve().then(EN)}function MN(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 EN(){let{createRequire:Y}=k7("node:module"),{lookup:X}=k7("node:dns"),{Agent:J,fetch:Q}=Y(p7())("undici"),$=new J({connect:{lookup:qN(X)}});return(G,W)=>Q(G,{...W,dispatcher:$})}function k7(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 p7(){let Y=Error.prepareStackTrace;try{Error.prepareStackTrace=($,G)=>G;let X=Error("Capture current module path");Error.captureStackTrace(X,p7);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 AN=["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 wN(Y){let X=new Headers(Y);for(let J of AN)X.delete(J);return X}var TN=10,RN=new Set([301,302,303,307,308]);async function l7({url:Y,headers:X,abortSignal:J,maxRedirects:Q=TN,fetch:$,trustedOrigin:G}){let W=X===void 0?void 0:wN(X),U=(H)=>{let V={signal:J,redirect:H};if(W!==void 0)V.headers=new Headers(W);return V},L=Y;for(let H=0;H<=Q;H++){let V=G!==void 0&&S7(L,G);if(!V)KN(L);let O=$!=null?$:V?globalThis.fetch:await PN(),B=await O(L,U("manual"));if(B.type==="opaqueredirect"){if(!BN())throw new j0({url:Y,message:`Redirect from ${L} could not be validated and was blocked`});return await O(L,U("follow"))}let N=B.headers.get("location");if(RN.has(B.status)&&N){await G8(B);let K=new URL(N,L).toString();if(W!==void 0&&!S7(K,L)){let j=W.get("user-agent");W=new Headers(j==null?void 0:{"user-agent":j})}L=K;continue}return B}throw new j0({url:Y,message:`Too many redirects (max ${Q})`})}var d9=2147483648;async function d7({response:Y,url:X,maxBytes:J=d9}){let Q=Y.headers.get("content-length");if(Q!=null){let V=parseInt(Q,10);if(!isNaN(V)&&V>J)throw await G8(Y),new j0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes (Content-Length: ${V}).`})}let $=Y.body;if($==null)return new Uint8Array(0);let G=$.getReader(),W=[],U=0;try{while(!0){let{done:V,value:O}=await G.read();if(V)break;if(U+=O.length,U>J)throw new j0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes.`});W.push(O)}}finally{try{await G.cancel()}catch(V){}finally{G.releaseLock()}}let L=new Uint8Array(U),H=0;for(let V of W)L.set(V,H),H+=V.length;return L}var W0=({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 EQ({argument:"separator",message:`The separator "${Q}" must not be part of the alphabet "${J}".`});return()=>`${Y}${Q}${$()}`},$F=W0();function i7(Y){var X,J;return(J=(X=globalThis.Buffer)==null?void 0:X.isBuffer(Y))!=null?J:!1}var _N=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,CN=/"(?: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 b7(Y){let X=JSON.parse(Y);if(X===null||typeof X!=="object")return X;if(_N.test(Y)===!1&&CN.test(Y)===!1)return X;return IN(X)}function IN(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 SN(Y){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(J){return b7(Y)}try{return b7(Y)}finally{Error.stackTraceLimit=X}}function i9(Y){if(Y.type==="object"||Array.isArray(Y.type)&&Y.type.includes("object")){let{additionalProperties:J}=Y;Y.additionalProperties=J!=null&&typeof J!=="boolean"?B1(J):!1;let{properties:Q}=Y;if(Q!=null)for(let $ of Object.keys(Q))Q[$]=B1(Q[$])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(B1):B1(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(B1);if(Y.allOf!=null)Y.allOf=Y.allOf.map(B1);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(B1);let{definitions:X}=Y;if(X!=null)for(let J of Object.keys(X))X[J]=B1(X[J]);return Y}function B1(Y){if(typeof Y==="boolean")return Y;return i9(Y)}var kN=Symbol("Let zodToJsonSchema decide on which parser to use"),x7={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"},bN=(Y)=>typeof Y==="string"?{...x7,name:Y}:{...x7,...Y};function _0(){return{}}function xN(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 vN(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 hN(){return{type:"boolean"}}function n7(Y,X){return n(Y.type._def,X)}var gN=(Y,X)=>{return n(Y.innerType._def,X)};function o7(Y,X,J){let Q=J!=null?J:X.dateStrategy;if(Array.isArray(Q))return{anyOf:Q.map(($)=>o7(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 yN(Y)}}var yN=(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 fN(Y,X){return{...n(Y.innerType._def,X),default:Y.defaultValue()}}function mN(Y,X){return X.effectStrategy==="input"?n(Y.schema._def,X):_0()}function cN(Y){return{type:"string",enum:Array.from(Y.values)}}var uN=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function pN(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(uN($))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 lN(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,v0={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 r7(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":h0(J,"email",Q.message,X);break;case"format:idn-email":h0(J,"idn-email",Q.message,X);break;case"pattern:zod":q0(J,v0.email,Q.message,X);break}break;case"url":h0(J,"uri",Q.message,X);break;case"uuid":h0(J,"uuid",Q.message,X);break;case"regex":q0(J,Q.regex,Q.message,X);break;case"cuid":q0(J,v0.cuid,Q.message,X);break;case"cuid2":q0(J,v0.cuid2,Q.message,X);break;case"startsWith":q0(J,RegExp(`^${m9(Q.value,X)}`),Q.message,X);break;case"endsWith":q0(J,RegExp(`${m9(Q.value,X)}$`),Q.message,X);break;case"datetime":h0(J,"date-time",Q.message,X);break;case"date":h0(J,"date",Q.message,X);break;case"time":h0(J,"time",Q.message,X);break;case"duration":h0(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":{q0(J,RegExp(m9(Q.value,X)),Q.message,X);break}case"ip":{if(Q.version!=="v6")h0(J,"ipv4",Q.message,X);if(Q.version!=="v4")h0(J,"ipv6",Q.message,X);break}case"base64url":q0(J,v0.base64url,Q.message,X);break;case"jwt":q0(J,v0.jwt,Q.message,X);break;case"cidr":{if(Q.version!=="v6")q0(J,v0.ipv4Cidr,Q.message,X);if(Q.version!=="v4")q0(J,v0.ipv6Cidr,Q.message,X);break}case"emoji":q0(J,v0.emoji(),Q.message,X);break;case"ulid":{q0(J,v0.ulid,Q.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{h0(J,"binary",Q.message,X);break}case"contentEncoding:base64":{J.contentEncoding="base64";break}case"pattern:zod":{q0(J,v0.base64,Q.message,X);break}}break}case"nanoid":q0(J,v0.nanoid,Q.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return J}function m9(Y,X){return X.patternStrategy==="escape"?iN(Y):Y}var dN=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function iN(Y){let X="";for(let J=0;J<Y.length;J++){if(!dN.has(Y[J]))X+="\\";X+=Y[J]}return X}function h0(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 q0(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:v7(X,Q),...J&&Q.errorMessages&&{errorMessage:{pattern:J}}})}else Y.pattern=v7(X,Q)}function v7(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
188
|
]))`;continue}else if($[H]==="$"){G+=`($|(?=[\r
|
|
189
189
|
]))`;continue}}if(Q.s&&$[H]==="."){G+=U?`${$[H]}\r
|
|
190
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 o7(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,...V}=n7(Y.keyType._def,X);return{...L,propertyNames:V}}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,...V}=d7(Y.keyType._def,X);return{...L,propertyNames:V}}return L}function lN(Y,X){if(X.mapStrategy==="record")return o7(Y,X);let J=n(Y.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||_0(),Q=n(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||_0();return{type:"array",maxItems:125,items:{type:"array",items:[J,Q],minItems:2,maxItems:2}}}function dN(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 iN(){return{not:_0()}}function nN(){return{type:"null"}}var c9={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function oN(Y,X){let J=Y.options instanceof Map?Array.from(Y.options.values()):Y.options;if(J.every((Q)=>(Q._def.typeName in c9)&&(!Q._def.checks||!Q._def.checks.length))){let Q=J.reduce(($,G)=>{let W=c9[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 rN(Y,X)}var rN=(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 sN(Y,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Y.innerType._def.typeName)&&(!Y.innerType._def.checks||!Y.innerType._def.checks.length))return{type:[c9[Y.innerType._def.typeName],"null"]};let J=n(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return J&&{anyOf:[J,{type:"null"}]}}function aN(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 tN(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=Y6(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=eN(Y,X);if(G!==void 0)J.additionalProperties=G;return J}function eN(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 Y6(Y){try{return Y.isOptional()}catch(X){return!0}}var X6=(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:_0()},Q]}:_0()},J6=(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 Q6(Y,X){return n(Y.type._def,X)}function $6(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 G6(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 W6(){return{not:_0()}}function z6(){return _0()}var U6=(Y,X)=>{return n(Y.innerType._def,X)},L6=(Y,X,J)=>{switch(X){case"ZodString":return n7(Y,J);case"ZodNumber":return aN(Y);case"ZodObject":return tN(Y,J);case"ZodBigInt":return kN(Y);case"ZodBoolean":return bN();case"ZodDate":return i7(Y,J);case"ZodUndefined":return W6();case"ZodNull":return nN();case"ZodArray":return SN(Y,J);case"ZodUnion":case"ZodDiscriminatedUnion":return oN(Y,J);case"ZodIntersection":return mN(Y,J);case"ZodTuple":return G6(Y,J);case"ZodRecord":return o7(Y,J);case"ZodLiteral":return cN(Y);case"ZodEnum":return yN(Y);case"ZodNativeEnum":return dN(Y);case"ZodNullable":return sN(Y,J);case"ZodOptional":return X6(Y,J);case"ZodMap":return lN(Y,J);case"ZodSet":return $6(Y,J);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return Q6(Y,J);case"ZodNaN":case"ZodNever":return iN();case"ZodEffects":return gN(Y,J);case"ZodAny":return _0();case"ZodUnknown":return z6();case"ZodDefault":return hN(Y,J);case"ZodBranded":return d7(Y,J);case"ZodReadonly":return U6(Y,J);case"ZodCatch":return xN(Y,J);case"ZodPipeline":return J6(Y,J);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Q)=>{return})(X)}},H6=(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!==CN)return L}if($&&!J){let L=N6($,X);if(L!==void 0)return L}let G={def:Y,path:X.currentPath,jsonSchema:void 0};X.seen.set(Y,G);let W=L6(Y,Y.typeName,X),U=typeof W==="function"?n(W(),X):W;if(U)V6(Y,X,U);if(X.postProcess){let L=X.postProcess(U,Y,X);return G.jsonSchema=U,L}return G.jsonSchema=U,U}var N6=(Y,X)=>{switch(X.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:H6(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`),_0();return X.$refStrategy==="seen"?_0():void 0}}},V6=(Y,X,J)=>{if(Y.description)J.description=Y.description;return J},Z6=(Y)=>{let X=IN(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}]))}},B6=(Y,X)=>{var J;let Q=Z6(X),$=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((H,[V,O])=>{var B;return{...H,[V]:(B=n(O._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,V]},!0))!=null?B:_0()}},{}):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:_0(),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},u9=Symbol.for("vercel.ai.schema");function W8(Y){let X;return()=>{if(X==null)X=Y();return X}}function z8(Y,{validate:X}={}){return{[u9]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:X}}function K6(Y){return typeof Y==="object"&&Y!==null&&u9 in Y&&Y[u9]===!0&&"jsonSchema"in Y&&"validate"in Y}function U8(Y){return Y==null?z8({type:"object",properties:{},additionalProperties:!1}):K6(Y)?Y:("~standard"in Y)?Y["~standard"].vendor==="zod"?ZY(Y):O6(Y):Y()}function O6(Y){return z8(()=>{if(!F6(Y))throw Error(`Standard schema vendor '${Y["~standard"].vendor}' does not support JSON Schema conversion.`);return i9(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 p0({value:X,cause:J.issues})}}})}function F6(Y){return Y["~standard"].jsonSchema!=null}function q6(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return z8(()=>B6(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 j6(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return z8(()=>i9(c5(Y,{target:"draft-7",io:"input",reused:Q?"ref":"inline"})),{validate:async($)=>{let G=await Q8(Y,$);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function D6(Y){return"_zod"in Y}function ZY(Y,X){if(D6(Y))return j6(Y,X);else return q6(Y,X)}async function n1({value:Y,schema:X,context:J}){let Q=U8(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:p0.wrap({value:Y,cause:$.error,context:J}),rawValue:Y}}catch($){return{success:!1,error:p0.wrap({value:Y,cause:$,context:J}),rawValue:Y}}}async function K1({text:Y,schema:X}){try{let J=_N(Y);if(X==null)return{success:!0,value:J,rawValue:J};return await n1({value:J,schema:X})}catch(J){return{success:!1,error:fY.isInstance(J)?J:new fY({text:Y,cause:J}),rawValue:void 0}}}async function n9(Y){if(typeof Y==="function")Y=Y();return Promise.resolve(Y)}var r7="AI_SerializationError",s7=`vercel.ai.error.${r7}`,P6=Symbol.for(s7),x7,v7,UF=class extends(v7=D,x7=P6,v7){constructor({message:Y="Failed to serialize value.",cause:X}={}){super({name:r7,message:Y,cause:X});this[x7]=!0}static isInstance(Y){return D.hasMarker(Y,s7)}};var w6=Object.defineProperty,A6=(Y,X)=>{for(var J in X)w6(Y,J,{get:X[J],enumerable:!0})},dW="AI_InvalidArgumentError",iW=`vercel.ai.error.${dW}`,T6=Symbol.for(iW),a7,t7,jF=class extends(t7=D,a7=T6,t7){constructor({parameter:Y,value:X,message:J}){super({name:dW,message:`Invalid argument for parameter ${Y}: ${J}`});this[a7]=!0,this.parameter=Y,this.value=X}static isInstance(Y){return D.hasMarker(Y,iW)}},nW="AI_InvalidStreamPartError",oW=`vercel.ai.error.${nW}`,R6=Symbol.for(oW),e7,YW,PF=class extends(YW=D,e7=R6,YW){constructor({chunk:Y,message:X}){super({name:nW,message:X});this[e7]=!0,this.chunk=Y}static isInstance(Y){return D.hasMarker(Y,oW)}},rW="AI_InvalidToolApprovalError",sW=`vercel.ai.error.${rW}`,_6=Symbol.for(sW),XW,JW,EF=class extends(JW=D,XW=_6,JW){constructor({approvalId:Y}){super({name:rW,message:`Tool approval response references unknown approvalId: "${Y}". No matching tool-approval-request found in message history.`});this[XW]=!0,this.approvalId=Y}static isInstance(Y){return D.hasMarker(Y,sW)}},aW="AI_InvalidToolApprovalSignatureError",tW=`vercel.ai.error.${aW}`,C6=Symbol.for(tW),QW,$W,AF=class extends($W=D,QW=C6,$W){constructor({approvalId:Y,toolCallId:X,reason:J}){super({name:aW,message:`Tool approval signature verification failed for approval "${Y}" (tool call "${X}"): ${J}`});this[QW]=!0,this.approvalId=Y,this.toolCallId=X}static isInstance(Y){return D.hasMarker(Y,tW)}},eW="AI_InvalidToolInputError",Y2=`vercel.ai.error.${eW}`,I6=Symbol.for(Y2),GW,WW,RF=class extends(WW=D,GW=I6,WW){constructor({toolInput:Y,toolName:X,cause:J,message:Q=`Invalid input for tool ${X}: ${T1(J)}`}){super({name:eW,message:Q,cause:J});this[GW]=!0,this.toolInput=Y,this.toolName=X}static isInstance(Y){return D.hasMarker(Y,Y2)}},X2="AI_ToolCallNotFoundForApprovalError",J2=`vercel.ai.error.${X2}`,S6=Symbol.for(J2),zW,UW,CF=class extends(UW=D,zW=S6,UW){constructor({toolCallId:Y,approvalId:X}){super({name:X2,message:`Tool call "${Y}" not found for approval request "${X}".`});this[zW]=!0,this.toolCallId=Y,this.approvalId=X}static isInstance(Y){return D.hasMarker(Y,J2)}},Q2="AI_MissingToolResultsError",$2=`vercel.ai.error.${Q2}`,k6=Symbol.for($2),LW,HW,SF=class extends(HW=D,LW=k6,HW){constructor({toolCallIds:Y}){super({name:Q2,message:`Tool result${Y.length>1?"s are":" is"} missing for tool call${Y.length>1?"s":""} ${Y.join(", ")}.`});this[LW]=!0,this.toolCallIds=Y}static isInstance(Y){return D.hasMarker(Y,$2)}},G2="AI_NoImageGeneratedError",W2=`vercel.ai.error.${G2}`,b6=Symbol.for(W2),NW,VW,bF=class extends(VW=D,NW=b6,VW){constructor({message:Y="No image generated.",cause:X,responses:J}){super({name:G2,message:Y,cause:X});this[NW]=!0,this.responses=J}static isInstance(Y){return D.hasMarker(Y,W2)}},z2="AI_NoObjectGeneratedError",U2=`vercel.ai.error.${z2}`,x6=Symbol.for(U2),ZW,BW,O1=class extends(BW=D,ZW=x6,BW){constructor({message:Y="No object generated.",cause:X,text:J,response:Q,usage:$,finishReason:G}){super({name:z2,message:Y,cause:X});this[ZW]=!0,this.text=J,this.response=Q,this.usage=$,this.finishReason=G}static isInstance(Y){return D.hasMarker(Y,U2)}},L2="AI_NoOutputGeneratedError",H2=`vercel.ai.error.${L2}`,v6=Symbol.for(H2),KW,OW,hF=class extends(OW=D,KW=v6,OW){constructor({message:Y="No output generated.",cause:X}={}){super({name:L2,message:Y,cause:X});this[KW]=!0}static isInstance(Y){return D.hasMarker(Y,H2)}},N2="AI_NoSpeechGeneratedError",V2=`vercel.ai.error.${N2}`,h6=Symbol.for(V2),FW,qW,yF=class extends(qW=D,FW=h6,qW){constructor(Y){super({name:N2,message:"No speech audio generated."});this[FW]=!0,this.responses=Y.responses}static isInstance(Y){return D.hasMarker(Y,V2)}},Z2="AI_NoTranscriptGeneratedError",B2=`vercel.ai.error.${Z2}`,g6=Symbol.for(B2),jW,DW,mF=class extends(DW=D,jW=g6,DW){constructor(Y){super({name:Z2,message:"No transcript generated."});this[jW]=!0,this.responses=Y.responses}static isInstance(Y){return D.hasMarker(Y,B2)}},K2="AI_NoTranslationGeneratedError",O2=`vercel.ai.error.${K2}`,y6=Symbol.for(O2),PW,MW,uF=class extends(MW=D,PW=y6,MW){constructor(Y){super({name:K2,message:"No translation generated."});this[PW]=!0,this.response=Y.response}static isInstance(Y){return D.hasMarker(Y,O2)}},o9="AI_NoVideoGeneratedError",F2=`vercel.ai.error.${o9}`,f6=Symbol.for(F2),EW,wW,lF=class extends(wW=D,EW=f6,wW){constructor({message:Y="No video generated.",cause:X,responses:J}){super({name:o9,message:Y,cause:X});this[EW]=!0,this.responses=J}static isInstance(Y){return D.hasMarker(Y,F2)}static isNoVideoGeneratedError(Y){return Y instanceof Error&&Y.name===o9&&typeof Y.responses<"u"?!0:!1}toJSON(){return{name:this.name,message:this.message,stack:this.stack,cause:this.cause,responses:this.responses}}},q2="AI_NoSuchToolError",j2=`vercel.ai.error.${q2}`,m6=Symbol.for(j2),AW,TW,iF=class extends(TW=D,AW=m6,TW){constructor({toolName:Y,availableTools:X=void 0,message:J=`Model tried to call unavailable tool '${Y}'. ${X===void 0?"No tools are available.":`Available tools: ${X.join(", ")}.`}`}){super({name:q2,message:J});this[AW]=!0,this.toolName=Y,this.availableTools=X}static isInstance(Y){return D.hasMarker(Y,j2)}},D2="AI_StreamProviderError",P2=`vercel.ai.error.${D2}`,c6=Symbol.for(P2),RW,_W,oF=class extends(_W=D,RW=c6,_W){constructor({message:Y,type:X,code:J,statusCode:Q,isRetryable:$=u6(Q),data:G,cause:W}){super({name:D2,message:Y,cause:W});this[RW]=!0,this.type=X,this.code=J,this.statusCode=Q,this.isRetryable=$,this.data=G}static isInstance(Y){return D.hasMarker(Y,P2)}};function u6(Y){return Y!=null&&(Y===408||Y===409||Y===429||Y>=500)}var M2="AI_ToolCallRepairError",E2=`vercel.ai.error.${M2}`,p6=Symbol.for(E2),CW,IW,sF=class extends(IW=D,CW=p6,IW){constructor({cause:Y,originalError:X,message:J=`Error repairing tool call: ${T1(Y)}`}){super({name:M2,message:J,cause:Y});this[CW]=!0,this.originalError=X}static isInstance(Y){return D.hasMarker(Y,E2)}},w2="AI_ToolChoiceViolationError",A2=`vercel.ai.error.${w2}`,l6=Symbol.for(A2),SW,kW,tF=class extends(kW=D,SW=l6,kW){constructor({toolChoice:Y,finishReason:X,provider:J,modelId:Q,content:$,message:G=Y.type==="required"?"Model response did not contain a tool call even though tool choice was required.":`Model response did not contain a call to the required tool '${Y.toolName}'.`}){super({name:w2,message:G});this[SW]=!0,this.toolChoice=Y,this.finishReason=X,this.provider=J,this.modelId=Q,this.content=$}static isInstance(Y){return D.hasMarker(Y,A2)}};var T2="AI_UIMessageStreamError",R2=`vercel.ai.error.${T2}`,d6=Symbol.for(R2),bW,xW,Yq=class extends(xW=D,bW=d6,xW){constructor({chunkType:Y,chunkId:X,message:J}){super({name:T2,message:J});this[bW]=!0,this.chunkType=Y,this.chunkId=X}static isInstance(Y){return D.hasMarker(Y,R2)}},_2="AI_InvalidDataContentError",C2=`vercel.ai.error.${_2}`,i6=Symbol.for(C2),vW,hW,Jq=class extends(hW=D,vW=i6,hW){constructor({content:Y,cause:X,message:J=`Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof Y}.`}){super({name:_2,message:J,cause:X});this[vW]=!0,this.content=Y}static isInstance(Y){return D.hasMarker(Y,C2)}},I2="AI_InvalidMessageRoleError",S2=`vercel.ai.error.${I2}`,n6=Symbol.for(S2),gW,yW,$q=class extends(yW=D,gW=n6,yW){constructor({role:Y,message:X=`Invalid message role: '${Y}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:I2,message:X});this[gW]=!0,this.role=Y}static isInstance(Y){return D.hasMarker(Y,S2)}},k2="AI_MessageConversionError",b2=`vercel.ai.error.${k2}`,o6=Symbol.for(b2),fW,mW,Wq=class extends(mW=D,fW=o6,mW){constructor({originalMessage:Y,message:X}){super({name:k2,message:X});this[fW]=!0,this.originalMessage=Y}static isInstance(Y){return D.hasMarker(Y,b2)}},x2="AI_RetryError",v2=`vercel.ai.error.${x2}`,r6=Symbol.for(v2),cW,uW,Uq=class extends(uW=D,cW=r6,uW){constructor({message:Y,reason:X,errors:J}){super({name:x2,message:Y});this[cW]=!0,this.reason=X,this.errors=J,this.lastError=J[J.length-1]}static isInstance(Y){return D.hasMarker(Y,v2)}};var s6="7.0.90",a6=async({url:Y,maxBytes:X,abortSignal:J})=>{var Q;let $=Y.toString();try{let G=i1({},`ai-sdk/${s6}`,h7()),W=await u7({url:$,headers:G,abortSignal:J});if(!W.ok)throw await G8(W),new j0({url:$,statusCode:W.status,statusText:W.statusText});return{data:await p7({response:W,url:$,maxBytes:X!=null?X:d9}),mediaType:(Q=W.headers.get("content-type"))!=null?Q:void 0}}catch(G){if(j0.isInstance(G))throw G;throw new j0({url:$,cause:G})}};var z={array:x9,boolean:Z7,custom:A7,discriminatedUnion:j7,enum:h9,instanceof:T7,lazy:w7,literal:P7,looseObject:F7,never:b9,null:B7,number:V7,object:O7,record:D7,string:H7,union:v9,unknown:VY},I1=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),I1.optional()),z.array(I1)])),T=z.record(z.string(),z.record(z.string(),I1.optional())),KY=z.union([z.string(),z.instanceof(Uint8Array),z.instanceof(ArrayBuffer),z.custom(l7,{message:"Must be a Buffer"})]),r9=z.record(z.string(),z.string()),h2=z.object({type:z.literal("text"),text:z.string(),providerOptions:T.optional()}),t6=z.object({type:z.literal("image"),image:z.union([KY,z.instanceof(URL),r9]),mediaType:z.string().optional(),providerOptions:T.optional()}),g2=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:KY}),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()})]),e6=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:KY}),z.object({type:z.literal("url"),url:z.instanceof(URL)})]),y2=z.object({type:z.literal("file"),data:z.union([g2,KY,z.instanceof(URL),r9]),filename:z.string().optional(),mediaType:z.string(),providerOptions:T.optional()}),YV=z.object({type:z.literal("reasoning"),text:z.string(),providerOptions:T.optional()}),XV=z.object({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerOptions:T.optional()}),JV=z.object({type:z.literal("reasoning-file"),data:z.union([e6,KY,z.instanceof(URL)]),mediaType:z.string(),providerOptions:T.optional()}),QV=z.object({type:z.literal("tool-call"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerOptions:T.optional(),providerExecuted:z.boolean().optional()}),$V=z.discriminatedUnion("type",[z.object({type:z.literal("text"),value:z.string(),providerOptions:T.optional()}),z.object({type:z.literal("json"),value:I1,providerOptions:T.optional()}),z.object({type:z.literal("execution-denied"),reason:z.string().optional(),providerOptions:T.optional()}),z.object({type:z.literal("error-text"),value:z.string(),providerOptions:T.optional()}),z.object({type:z.literal("error-json"),value:I1,providerOptions:T.optional()}),z.object({type:z.literal("content"),value:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),providerOptions:T.optional()}),z.object({type:z.literal("file"),data:g2,mediaType:z.string(),filename:z.string().optional(),providerOptions:T.optional()}),z.object({type:z.literal("file-data"),data:z.string(),mediaType:z.string(),filename:z.string().optional(),providerOptions:T.optional()}),z.object({type:z.literal("file-url"),url:z.string(),mediaType:z.string().optional(),providerOptions:T.optional()}),z.object({type:z.literal("file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:T.optional()}),z.object({type:z.literal("file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:T.optional()}),z.object({type:z.literal("image-data"),data:z.string(),mediaType:z.string(),providerOptions:T.optional()}),z.object({type:z.literal("image-url"),url:z.string(),providerOptions:T.optional()}),z.object({type:z.literal("image-file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:T.optional()}),z.object({type:z.literal("image-file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:T.optional()}),z.object({type:z.literal("custom"),providerOptions:T.optional()})]))})]),f2=z.object({type:z.literal("tool-result"),toolCallId:z.string(),toolName:z.string(),output:$V,providerOptions:T.optional()}),GV=z.object({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string(),reason:z.string().optional()}),WV=z.object({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional()}),zV=z.object({role:z.literal("system"),content:z.string(),providerOptions:T.optional()}),UV=z.object({role:z.literal("user"),content:z.union([z.string(),z.array(z.union([h2,t6,y2]))]),providerOptions:T.optional()}),LV=z.object({role:z.literal("assistant"),content:z.union([z.string(),z.array(z.union([h2,XV,y2,YV,JV,QV,f2,GV]))]),providerOptions:T.optional()}),HV=z.object({role:z.literal("tool"),content:z.array(z.union([f2,WV])),providerOptions:T.optional()}),Vq=z.union([zV,UV,LV,HV]);var NV={};A6(NV,{array:()=>KV,choice:()=>OV,json:()=>FV,object:()=>BV,text:()=>ZV});function VV(Y){let X=["ROOT"],J=-1,Q=null,$=0;function G(V){return V>="0"&&V<="9"||V>="A"&&V<="F"||V>="a"&&V<="f"}function W(V,O,B){switch(V){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 U(V,O){switch(V){case",":{X.pop(),X.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{J=O,X.pop();break}}}function L(V,O){switch(V){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=O,X.pop();break}}}for(let V=0;V<Y.length;V++){let O=Y[V];switch(X[X.length-1]){case"ROOT":W(O,V,"FINISH");break;case"INSIDE_OBJECT_START":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}case"}":{J=V,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,V,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{U(O,V);break}case"INSIDE_STRING":{switch(O){case'"':{X.pop(),J=V;break}case"\\":{X.push("INSIDE_STRING_ESCAPE");break}default:J=V}break}case"INSIDE_ARRAY_START":{switch(O){case"]":{J=V,X.pop();break}default:{J=V,W(O,V,"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=V,X.pop();break}default:{J=V;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{W(O,V,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{if(X.pop(),O==="u")$=0,X.push("INSIDE_STRING_UNICODE_ESCAPE");else J=V;break}case"INSIDE_STRING_UNICODE_ESCAPE":{if(G(O)){if($++,$===4)X.pop(),J=V}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=V;break}case"e":case"E":case"-":case".":break;case",":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")L(O,V);if(X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")U(O,V);break}case"}":{if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")U(O,V);break}case"]":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")L(O,V);break}default:{X.pop();break}}break}case"INSIDE_LITERAL":{let N=Y.substring(Q,V+1);if(!"false".startsWith(N)&&!"true".startsWith(N)&&!"null".startsWith(N)){if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")U(O,V);else if(X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")L(O,V)}else J=V;break}}}let H=Y.slice(0,J+1);for(let V=X.length-1;V>=0;V--)switch(X[V]){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 B=Y.substring(Q,Y.length);if("true".startsWith(B))H+="true".slice(B.length);else if("false".startsWith(B))H+="false".slice(B.length);else if("null".startsWith(B))H+="null".slice(B.length)}}return H}async function L8(Y){if(Y===void 0)return{value:void 0,state:"undefined-input"};let X=await K1({text:Y});if(X.success)return{value:X.value,state:"successful-parse"};if(X=await K1({text:VV(Y)}),X.success)return{value:X.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var ZV=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:Y}){return Y},async parsePartialOutput({text:Y}){return{partial:Y}},createElementStreamTransform(){return}}),BV=({schema:Y,name:X,description:J})=>{let Q=U8(Y);return{name:"object",responseFormat:n9(Q.jsonSchema).then(($)=>({type:"json",schema:$,...X!=null&&{name:X},...J!=null&&{description:J}})),async parseCompleteOutput({text:$},G){let W=await K1({text:$});if(!W.success)throw new O1({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 n1({value:W.value,schema:Q});if(!U.success)throw new O1({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 L8($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:G.value}}},createElementStreamTransform(){return}}},KV=({element:Y,name:X,description:J})=>{let Q=U8(Y);return{name:"array",responseFormat:n9(Q.jsonSchema).then(($)=>{let{$schema:G,definitions:W,$defs:U,...L}=$;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",...W!=null&&{definitions:W},...U!=null&&{$defs:U},type:"object",properties:{elements:{type:"array",items:L}},required:["elements"],additionalProperties:!1},...X!=null&&{name:X},...J!=null&&{description:J}}}),async parseCompleteOutput({text:$},G){let W=await K1({text:$});if(!W.success)throw new O1({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 O1({message:"No object generated: response did not match schema.",cause:new p0({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 V=await n1({value:H,schema:Q});if(!V.success)throw new O1({message:"No object generated: response did not match schema.",cause:V.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});L.push(V.value)}return L},async parsePartialOutput({text:$}){let G=await L8($);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 V=await n1({value:H,schema:Q});if(V.success)L.push(V.value)}return{partial:L}}}},createElementStreamTransform(){let $=0;return new TransformStream({transform({partialOutput:G},W){if(G!=null)for(;$<G.length;$++)W.enqueue(G[$])}})}}},OV=({options:Y,name:X,description:J})=>{return{name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:Y}},required:["result"],additionalProperties:!1},...X!=null&&{name:X},...J!=null&&{description:J}}),async parseCompleteOutput({text:Q},$){let G=await K1({text:Q});if(!G.success)throw new O1({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 O1({message:"No object generated: response did not match schema.",cause:new p0({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 L8(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}}},FV=({name:Y,description:X}={})=>{return{name:"json",responseFormat:Promise.resolve({type:"json",...Y!=null&&{name:Y},...X!=null&&{description:X}}),async parseCompleteOutput({text:J},Q){let $=await K1({text:J});if(!$.success)throw new O1({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 L8(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 Oq=W0({prefix:"aitxt",size:24}),Fq=W0({prefix:"call",size:24});var jq=class extends TransformStream{constructor(){super({transform(Y,X){X.enqueue(`data: ${JSON.stringify(Y)}
|
|
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 s7(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,...V}=r7(Y.keyType._def,X);return{...L,propertyNames:V}}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,...V}=n7(Y.keyType._def,X);return{...L,propertyNames:V}}return L}function nN(Y,X){if(X.mapStrategy==="record")return s7(Y,X);let J=n(Y.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||_0(),Q=n(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||_0();return{type:"array",maxItems:125,items:{type:"array",items:[J,Q],minItems:2,maxItems:2}}}function oN(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 rN(){return{not:_0()}}function sN(){return{type:"null"}}var c9={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function aN(Y,X){let J=Y.options instanceof Map?Array.from(Y.options.values()):Y.options;if(J.every((Q)=>(Q._def.typeName in c9)&&(!Q._def.checks||!Q._def.checks.length))){let Q=J.reduce(($,G)=>{let W=c9[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 tN(Y,X)}var tN=(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 eN(Y,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Y.innerType._def.typeName)&&(!Y.innerType._def.checks||!Y.innerType._def.checks.length))return{type:[c9[Y.innerType._def.typeName],"null"]};let J=n(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return J&&{anyOf:[J,{type:"null"}]}}function Y6(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 X6(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=Q6(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=J6(Y,X);if(G!==void 0)J.additionalProperties=G;return J}function J6(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 Q6(Y){try{return Y.isOptional()}catch(X){return!0}}var $6=(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:_0()},Q]}:_0()},G6=(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 W6(Y,X){return n(Y.type._def,X)}function z6(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 U6(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 L6(){return{not:_0()}}function H6(){return _0()}var N6=(Y,X)=>{return n(Y.innerType._def,X)},V6=(Y,X,J)=>{switch(X){case"ZodString":return r7(Y,J);case"ZodNumber":return Y6(Y);case"ZodObject":return X6(Y,J);case"ZodBigInt":return vN(Y);case"ZodBoolean":return hN();case"ZodDate":return o7(Y,J);case"ZodUndefined":return L6();case"ZodNull":return sN();case"ZodArray":return xN(Y,J);case"ZodUnion":case"ZodDiscriminatedUnion":return aN(Y,J);case"ZodIntersection":return pN(Y,J);case"ZodTuple":return U6(Y,J);case"ZodRecord":return s7(Y,J);case"ZodLiteral":return lN(Y);case"ZodEnum":return cN(Y);case"ZodNativeEnum":return oN(Y);case"ZodNullable":return eN(Y,J);case"ZodOptional":return $6(Y,J);case"ZodMap":return nN(Y,J);case"ZodSet":return z6(Y,J);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return W6(Y,J);case"ZodNaN":case"ZodNever":return rN();case"ZodEffects":return mN(Y,J);case"ZodAny":return _0();case"ZodUnknown":return H6();case"ZodDefault":return fN(Y,J);case"ZodBranded":return n7(Y,J);case"ZodReadonly":return N6(Y,J);case"ZodCatch":return gN(Y,J);case"ZodPipeline":return G6(Y,J);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Q)=>{return})(X)}},Z6=(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!==kN)return L}if($&&!J){let L=B6($,X);if(L!==void 0)return L}let G={def:Y,path:X.currentPath,jsonSchema:void 0};X.seen.set(Y,G);let W=V6(Y,Y.typeName,X),U=typeof W==="function"?n(W(),X):W;if(U)K6(Y,X,U);if(X.postProcess){let L=X.postProcess(U,Y,X);return G.jsonSchema=U,L}return G.jsonSchema=U,U}var B6=(Y,X)=>{switch(X.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:Z6(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`),_0();return X.$refStrategy==="seen"?_0():void 0}}},K6=(Y,X,J)=>{if(Y.description)J.description=Y.description;return J},O6=(Y)=>{let X=bN(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}]))}},F6=(Y,X)=>{var J;let Q=O6(X),$=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((H,[V,O])=>{var B;return{...H,[V]:(B=n(O._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,V]},!0))!=null?B:_0()}},{}):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:_0(),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},u9=Symbol.for("vercel.ai.schema");function W8(Y){let X;return()=>{if(X==null)X=Y();return X}}function z8(Y,{validate:X}={}){return{[u9]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:X}}function q6(Y){return typeof Y==="object"&&Y!==null&&u9 in Y&&Y[u9]===!0&&"jsonSchema"in Y&&"validate"in Y}function U8(Y){return Y==null?z8({type:"object",properties:{},additionalProperties:!1}):q6(Y)?Y:("~standard"in Y)?Y["~standard"].vendor==="zod"?ZY(Y):j6(Y):Y()}function j6(Y){return z8(()=>{if(!D6(Y))throw Error(`Standard schema vendor '${Y["~standard"].vendor}' does not support JSON Schema conversion.`);return i9(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 p0({value:X,cause:J.issues})}}})}function D6(Y){return Y["~standard"].jsonSchema!=null}function P6(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return z8(()=>F6(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 M6(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return z8(()=>i9(p5(Y,{target:"draft-7",io:"input",reused:Q?"ref":"inline"})),{validate:async($)=>{let G=await Q8(Y,$);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function E6(Y){return"_zod"in Y}function ZY(Y,X){if(E6(Y))return M6(Y,X);else return P6(Y,X)}async function n1({value:Y,schema:X,context:J}){let Q=U8(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:p0.wrap({value:Y,cause:$.error,context:J}),rawValue:Y}}catch($){return{success:!1,error:p0.wrap({value:Y,cause:$,context:J}),rawValue:Y}}}async function K1({text:Y,schema:X}){try{let J=SN(Y);if(X==null)return{success:!0,value:J,rawValue:J};return await n1({value:J,schema:X})}catch(J){return{success:!1,error:fY.isInstance(J)?J:new fY({text:Y,cause:J}),rawValue:void 0}}}async function n9(Y){if(typeof Y==="function")Y=Y();return Promise.resolve(Y)}var a7="AI_SerializationError",t7=`vercel.ai.error.${a7}`,A6=Symbol.for(t7),h7,g7,NF=class extends(g7=D,h7=A6,g7){constructor({message:Y="Failed to serialize value.",cause:X}={}){super({name:a7,message:Y,cause:X});this[h7]=!0}static isInstance(Y){return D.hasMarker(Y,t7)}};var R6=Object.defineProperty,_6=(Y,X)=>{for(var J in X)R6(Y,J,{get:X[J],enumerable:!0})},nW="AI_InvalidArgumentError",oW=`vercel.ai.error.${nW}`,C6=Symbol.for(oW),e7,YW,MF=class extends(YW=D,e7=C6,YW){constructor({parameter:Y,value:X,message:J}){super({name:nW,message:`Invalid argument for parameter ${Y}: ${J}`});this[e7]=!0,this.parameter=Y,this.value=X}static isInstance(Y){return D.hasMarker(Y,oW)}},rW="AI_InvalidStreamPartError",sW=`vercel.ai.error.${rW}`,I6=Symbol.for(sW),XW,JW,AF=class extends(JW=D,XW=I6,JW){constructor({chunk:Y,message:X}){super({name:rW,message:X});this[XW]=!0,this.chunk=Y}static isInstance(Y){return D.hasMarker(Y,sW)}},aW="AI_InvalidToolApprovalError",tW=`vercel.ai.error.${aW}`,S6=Symbol.for(tW),QW,$W,TF=class extends($W=D,QW=S6,$W){constructor({approvalId:Y}){super({name:aW,message:`Tool approval response references unknown approvalId: "${Y}". No matching tool-approval-request found in message history.`});this[QW]=!0,this.approvalId=Y}static isInstance(Y){return D.hasMarker(Y,tW)}},eW="AI_InvalidToolApprovalSignatureError",Y2=`vercel.ai.error.${eW}`,k6=Symbol.for(Y2),GW,WW,_F=class extends(WW=D,GW=k6,WW){constructor({approvalId:Y,toolCallId:X,reason:J}){super({name:eW,message:`Tool approval signature verification failed for approval "${Y}" (tool call "${X}"): ${J}`});this[GW]=!0,this.approvalId=Y,this.toolCallId=X}static isInstance(Y){return D.hasMarker(Y,Y2)}},X2="AI_InvalidToolInputError",J2=`vercel.ai.error.${X2}`,b6=Symbol.for(J2),zW,UW,IF=class extends(UW=D,zW=b6,UW){constructor({toolInput:Y,toolName:X,cause:J,message:Q=`Invalid input for tool ${X}: ${T1(J)}`}){super({name:X2,message:Q,cause:J});this[zW]=!0,this.toolInput=Y,this.toolName=X}static isInstance(Y){return D.hasMarker(Y,J2)}},Q2="AI_ToolCallNotFoundForApprovalError",$2=`vercel.ai.error.${Q2}`,x6=Symbol.for($2),LW,HW,kF=class extends(HW=D,LW=x6,HW){constructor({toolCallId:Y,approvalId:X}){super({name:Q2,message:`Tool call "${Y}" not found for approval request "${X}".`});this[LW]=!0,this.toolCallId=Y,this.approvalId=X}static isInstance(Y){return D.hasMarker(Y,$2)}},G2="AI_MissingToolResultsError",W2=`vercel.ai.error.${G2}`,v6=Symbol.for(W2),NW,VW,xF=class extends(VW=D,NW=v6,VW){constructor({toolCallIds:Y}){super({name:G2,message:`Tool result${Y.length>1?"s are":" is"} missing for tool call${Y.length>1?"s":""} ${Y.join(", ")}.`});this[NW]=!0,this.toolCallIds=Y}static isInstance(Y){return D.hasMarker(Y,W2)}},z2="AI_NoImageGeneratedError",U2=`vercel.ai.error.${z2}`,h6=Symbol.for(U2),ZW,BW,hF=class extends(BW=D,ZW=h6,BW){constructor({message:Y="No image generated.",cause:X,responses:J}){super({name:z2,message:Y,cause:X});this[ZW]=!0,this.responses=J}static isInstance(Y){return D.hasMarker(Y,U2)}},L2="AI_NoObjectGeneratedError",H2=`vercel.ai.error.${L2}`,g6=Symbol.for(H2),KW,OW,O1=class extends(OW=D,KW=g6,OW){constructor({message:Y="No object generated.",cause:X,text:J,response:Q,usage:$,finishReason:G}){super({name:L2,message:Y,cause:X});this[KW]=!0,this.text=J,this.response=Q,this.usage=$,this.finishReason=G}static isInstance(Y){return D.hasMarker(Y,H2)}},N2="AI_NoOutputGeneratedError",V2=`vercel.ai.error.${N2}`,y6=Symbol.for(V2),FW,qW,fF=class extends(qW=D,FW=y6,qW){constructor({message:Y="No output generated.",cause:X}={}){super({name:N2,message:Y,cause:X});this[FW]=!0}static isInstance(Y){return D.hasMarker(Y,V2)}},Z2="AI_NoSpeechGeneratedError",B2=`vercel.ai.error.${Z2}`,f6=Symbol.for(B2),jW,DW,cF=class extends(DW=D,jW=f6,DW){constructor(Y){super({name:Z2,message:"No speech audio generated."});this[jW]=!0,this.responses=Y.responses}static isInstance(Y){return D.hasMarker(Y,B2)}},K2="AI_NoTranscriptGeneratedError",O2=`vercel.ai.error.${K2}`,m6=Symbol.for(O2),PW,MW,pF=class extends(MW=D,PW=m6,MW){constructor(Y){super({name:K2,message:"No transcript generated."});this[PW]=!0,this.responses=Y.responses}static isInstance(Y){return D.hasMarker(Y,O2)}},F2="AI_NoTranslationGeneratedError",q2=`vercel.ai.error.${F2}`,c6=Symbol.for(q2),EW,AW,dF=class extends(AW=D,EW=c6,AW){constructor(Y){super({name:F2,message:"No translation generated."});this[EW]=!0,this.response=Y.response}static isInstance(Y){return D.hasMarker(Y,q2)}},o9="AI_NoVideoGeneratedError",j2=`vercel.ai.error.${o9}`,u6=Symbol.for(j2),wW,TW,nF=class extends(TW=D,wW=u6,TW){constructor({message:Y="No video generated.",cause:X,responses:J}){super({name:o9,message:Y,cause:X});this[wW]=!0,this.responses=J}static isInstance(Y){return D.hasMarker(Y,j2)}static isNoVideoGeneratedError(Y){return Y instanceof Error&&Y.name===o9&&typeof Y.responses<"u"?!0:!1}toJSON(){return{name:this.name,message:this.message,stack:this.stack,cause:this.cause,responses:this.responses}}},D2="AI_NoSuchToolError",P2=`vercel.ai.error.${D2}`,p6=Symbol.for(P2),RW,_W,rF=class extends(_W=D,RW=p6,_W){constructor({toolName:Y,availableTools:X=void 0,message:J=`Model tried to call unavailable tool '${Y}'. ${X===void 0?"No tools are available.":`Available tools: ${X.join(", ")}.`}`}){super({name:D2,message:J});this[RW]=!0,this.toolName=Y,this.availableTools=X}static isInstance(Y){return D.hasMarker(Y,P2)}},M2="AI_StreamProviderError",E2=`vercel.ai.error.${M2}`,l6=Symbol.for(E2),CW,IW,aF=class extends(IW=D,CW=l6,IW){constructor({message:Y,type:X,code:J,statusCode:Q,isRetryable:$=d6(Q),data:G,cause:W}){super({name:M2,message:Y,cause:W});this[CW]=!0,this.type=X,this.code=J,this.statusCode=Q,this.isRetryable=$,this.data=G}static isInstance(Y){return D.hasMarker(Y,E2)}};function d6(Y){return Y!=null&&(Y===408||Y===409||Y===429||Y>=500)}var A2="AI_ToolCallRepairError",w2=`vercel.ai.error.${A2}`,i6=Symbol.for(w2),SW,kW,eF=class extends(kW=D,SW=i6,kW){constructor({cause:Y,originalError:X,message:J=`Error repairing tool call: ${T1(Y)}`}){super({name:A2,message:J,cause:Y});this[SW]=!0,this.originalError=X}static isInstance(Y){return D.hasMarker(Y,w2)}},T2="AI_ToolChoiceViolationError",R2=`vercel.ai.error.${T2}`,n6=Symbol.for(R2),bW,xW,Xq=class extends(xW=D,bW=n6,xW){constructor({toolChoice:Y,finishReason:X,provider:J,modelId:Q,content:$,message:G=Y.type==="required"?"Model response did not contain a tool call even though tool choice was required.":`Model response did not contain a call to the required tool '${Y.toolName}'.`}){super({name:T2,message:G});this[bW]=!0,this.toolChoice=Y,this.finishReason=X,this.provider=J,this.modelId=Q,this.content=$}static isInstance(Y){return D.hasMarker(Y,R2)}};var _2="AI_UIMessageStreamError",C2=`vercel.ai.error.${_2}`,o6=Symbol.for(C2),vW,hW,Qq=class extends(hW=D,vW=o6,hW){constructor({chunkType:Y,chunkId:X,message:J}){super({name:_2,message:J});this[vW]=!0,this.chunkType=Y,this.chunkId=X}static isInstance(Y){return D.hasMarker(Y,C2)}},I2="AI_InvalidDataContentError",S2=`vercel.ai.error.${I2}`,r6=Symbol.for(S2),gW,yW,Gq=class extends(yW=D,gW=r6,yW){constructor({content:Y,cause:X,message:J=`Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof Y}.`}){super({name:I2,message:J,cause:X});this[gW]=!0,this.content=Y}static isInstance(Y){return D.hasMarker(Y,S2)}},k2="AI_InvalidMessageRoleError",b2=`vercel.ai.error.${k2}`,s6=Symbol.for(b2),fW,mW,zq=class extends(mW=D,fW=s6,mW){constructor({role:Y,message:X=`Invalid message role: '${Y}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:k2,message:X});this[fW]=!0,this.role=Y}static isInstance(Y){return D.hasMarker(Y,b2)}},x2="AI_MessageConversionError",v2=`vercel.ai.error.${x2}`,a6=Symbol.for(v2),cW,uW,Lq=class extends(uW=D,cW=a6,uW){constructor({originalMessage:Y,message:X}){super({name:x2,message:X});this[cW]=!0,this.originalMessage=Y}static isInstance(Y){return D.hasMarker(Y,v2)}},h2="AI_RetryError",g2=`vercel.ai.error.${h2}`,t6=Symbol.for(g2),pW,lW,Nq=class extends(lW=D,pW=t6,lW){constructor({message:Y,reason:X,errors:J}){super({name:h2,message:Y});this[pW]=!0,this.reason=X,this.errors=J,this.lastError=J[J.length-1]}static isInstance(Y){return D.hasMarker(Y,g2)}};var e6="7.0.90",YV=async({url:Y,maxBytes:X,abortSignal:J})=>{var Q;let $=Y.toString();try{let G=i1({},`ai-sdk/${e6}`,y7()),W=await l7({url:$,headers:G,abortSignal:J});if(!W.ok)throw await G8(W),new j0({url:$,statusCode:W.status,statusText:W.statusText});return{data:await d7({response:W,url:$,maxBytes:X!=null?X:d9}),mediaType:(Q=W.headers.get("content-type"))!=null?Q:void 0}}catch(G){if(j0.isInstance(G))throw G;throw new j0({url:$,cause:G})}};var z={array:x9,boolean:K7,custom:R7,discriminatedUnion:P7,enum:h9,instanceof:_7,lazy:T7,literal:E7,looseObject:j7,never:b9,null:O7,number:B7,object:q7,record:M7,string:V7,union:v9,unknown:VY},I1=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),I1.optional()),z.array(I1)])),T=z.record(z.string(),z.record(z.string(),I1.optional())),KY=z.union([z.string(),z.instanceof(Uint8Array),z.instanceof(ArrayBuffer),z.custom(i7,{message:"Must be a Buffer"})]),r9=z.record(z.string(),z.string()),y2=z.object({type:z.literal("text"),text:z.string(),providerOptions:T.optional()}),XV=z.object({type:z.literal("image"),image:z.union([KY,z.instanceof(URL),r9]),mediaType:z.string().optional(),providerOptions:T.optional()}),f2=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:KY}),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()})]),JV=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:KY}),z.object({type:z.literal("url"),url:z.instanceof(URL)})]),m2=z.object({type:z.literal("file"),data:z.union([f2,KY,z.instanceof(URL),r9]),filename:z.string().optional(),mediaType:z.string(),providerOptions:T.optional()}),QV=z.object({type:z.literal("reasoning"),text:z.string(),providerOptions:T.optional()}),$V=z.object({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerOptions:T.optional()}),GV=z.object({type:z.literal("reasoning-file"),data:z.union([JV,KY,z.instanceof(URL)]),mediaType:z.string(),providerOptions:T.optional()}),WV=z.object({type:z.literal("tool-call"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerOptions:T.optional(),providerExecuted:z.boolean().optional()}),zV=z.discriminatedUnion("type",[z.object({type:z.literal("text"),value:z.string(),providerOptions:T.optional()}),z.object({type:z.literal("json"),value:I1,providerOptions:T.optional()}),z.object({type:z.literal("execution-denied"),reason:z.string().optional(),providerOptions:T.optional()}),z.object({type:z.literal("error-text"),value:z.string(),providerOptions:T.optional()}),z.object({type:z.literal("error-json"),value:I1,providerOptions:T.optional()}),z.object({type:z.literal("content"),value:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),providerOptions:T.optional()}),z.object({type:z.literal("file"),data:f2,mediaType:z.string(),filename:z.string().optional(),providerOptions:T.optional()}),z.object({type:z.literal("file-data"),data:z.string(),mediaType:z.string(),filename:z.string().optional(),providerOptions:T.optional()}),z.object({type:z.literal("file-url"),url:z.string(),mediaType:z.string().optional(),providerOptions:T.optional()}),z.object({type:z.literal("file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:T.optional()}),z.object({type:z.literal("file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:T.optional()}),z.object({type:z.literal("image-data"),data:z.string(),mediaType:z.string(),providerOptions:T.optional()}),z.object({type:z.literal("image-url"),url:z.string(),providerOptions:T.optional()}),z.object({type:z.literal("image-file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:T.optional()}),z.object({type:z.literal("image-file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:T.optional()}),z.object({type:z.literal("custom"),providerOptions:T.optional()})]))})]),c2=z.object({type:z.literal("tool-result"),toolCallId:z.string(),toolName:z.string(),output:zV,providerOptions:T.optional()}),UV=z.object({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string(),reason:z.string().optional()}),LV=z.object({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional()}),HV=z.object({role:z.literal("system"),content:z.string(),providerOptions:T.optional()}),NV=z.object({role:z.literal("user"),content:z.union([z.string(),z.array(z.union([y2,XV,m2]))]),providerOptions:T.optional()}),VV=z.object({role:z.literal("assistant"),content:z.union([z.string(),z.array(z.union([y2,$V,m2,QV,GV,WV,c2,UV]))]),providerOptions:T.optional()}),ZV=z.object({role:z.literal("tool"),content:z.array(z.union([c2,LV])),providerOptions:T.optional()}),Kq=z.union([HV,NV,VV,ZV]);var BV={};_6(BV,{array:()=>qV,choice:()=>jV,json:()=>DV,object:()=>FV,text:()=>OV});function KV(Y){let X=["ROOT"],J=-1,Q=null,$=0;function G(V){return V>="0"&&V<="9"||V>="A"&&V<="F"||V>="a"&&V<="f"}function W(V,O,B){switch(V){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 U(V,O){switch(V){case",":{X.pop(),X.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{J=O,X.pop();break}}}function L(V,O){switch(V){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=O,X.pop();break}}}for(let V=0;V<Y.length;V++){let O=Y[V];switch(X[X.length-1]){case"ROOT":W(O,V,"FINISH");break;case"INSIDE_OBJECT_START":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}case"}":{J=V,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,V,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{U(O,V);break}case"INSIDE_STRING":{switch(O){case'"':{X.pop(),J=V;break}case"\\":{X.push("INSIDE_STRING_ESCAPE");break}default:J=V}break}case"INSIDE_ARRAY_START":{switch(O){case"]":{J=V,X.pop();break}default:{J=V,W(O,V,"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=V,X.pop();break}default:{J=V;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{W(O,V,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{if(X.pop(),O==="u")$=0,X.push("INSIDE_STRING_UNICODE_ESCAPE");else J=V;break}case"INSIDE_STRING_UNICODE_ESCAPE":{if(G(O)){if($++,$===4)X.pop(),J=V}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=V;break}case"e":case"E":case"-":case".":break;case",":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")L(O,V);if(X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")U(O,V);break}case"}":{if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")U(O,V);break}case"]":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")L(O,V);break}default:{X.pop();break}}break}case"INSIDE_LITERAL":{let N=Y.substring(Q,V+1);if(!"false".startsWith(N)&&!"true".startsWith(N)&&!"null".startsWith(N)){if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")U(O,V);else if(X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")L(O,V)}else J=V;break}}}let H=Y.slice(0,J+1);for(let V=X.length-1;V>=0;V--)switch(X[V]){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 B=Y.substring(Q,Y.length);if("true".startsWith(B))H+="true".slice(B.length);else if("false".startsWith(B))H+="false".slice(B.length);else if("null".startsWith(B))H+="null".slice(B.length)}}return H}async function L8(Y){if(Y===void 0)return{value:void 0,state:"undefined-input"};let X=await K1({text:Y});if(X.success)return{value:X.value,state:"successful-parse"};if(X=await K1({text:KV(Y)}),X.success)return{value:X.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var OV=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:Y}){return Y},async parsePartialOutput({text:Y}){return{partial:Y}},createElementStreamTransform(){return}}),FV=({schema:Y,name:X,description:J})=>{let Q=U8(Y);return{name:"object",responseFormat:n9(Q.jsonSchema).then(($)=>({type:"json",schema:$,...X!=null&&{name:X},...J!=null&&{description:J}})),async parseCompleteOutput({text:$},G){let W=await K1({text:$});if(!W.success)throw new O1({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 n1({value:W.value,schema:Q});if(!U.success)throw new O1({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 L8($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:G.value}}},createElementStreamTransform(){return}}},qV=({element:Y,name:X,description:J})=>{let Q=U8(Y);return{name:"array",responseFormat:n9(Q.jsonSchema).then(($)=>{let{$schema:G,definitions:W,$defs:U,...L}=$;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",...W!=null&&{definitions:W},...U!=null&&{$defs:U},type:"object",properties:{elements:{type:"array",items:L}},required:["elements"],additionalProperties:!1},...X!=null&&{name:X},...J!=null&&{description:J}}}),async parseCompleteOutput({text:$},G){let W=await K1({text:$});if(!W.success)throw new O1({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 O1({message:"No object generated: response did not match schema.",cause:new p0({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 V=await n1({value:H,schema:Q});if(!V.success)throw new O1({message:"No object generated: response did not match schema.",cause:V.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});L.push(V.value)}return L},async parsePartialOutput({text:$}){let G=await L8($);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 V=await n1({value:H,schema:Q});if(V.success)L.push(V.value)}return{partial:L}}}},createElementStreamTransform(){let $=0;return new TransformStream({transform({partialOutput:G},W){if(G!=null)for(;$<G.length;$++)W.enqueue(G[$])}})}}},jV=({options:Y,name:X,description:J})=>{return{name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:Y}},required:["result"],additionalProperties:!1},...X!=null&&{name:X},...J!=null&&{description:J}}),async parseCompleteOutput({text:Q},$){let G=await K1({text:Q});if(!G.success)throw new O1({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 O1({message:"No object generated: response did not match schema.",cause:new p0({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 L8(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}}},DV=({name:Y,description:X}={})=>{return{name:"json",responseFormat:Promise.resolve({type:"json",...Y!=null&&{name:Y},...X!=null&&{description:X}}),async parseCompleteOutput({text:J},Q){let $=await K1({text:J});if(!$.success)throw new O1({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 L8(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 jq=W0({prefix:"aitxt",size:24}),Dq=W0({prefix:"call",size:24});var Mq=class extends TransformStream{constructor(){super({transform(Y,X){X.enqueue(`data: ${JSON.stringify(Y)}
|
|
192
192
|
|
|
193
193
|
`)},flush(Y){Y.enqueue(`data: [DONE]
|
|
194
194
|
|
|
195
|
-
`)}})}};var BY=z.record(z.string(),I1.optional()),Pq=W8(()=>ZY(z.union([z.looseObject({type:z.literal("text-start"),id:z.string(),providerMetadata:T.optional()}),z.looseObject({type:z.literal("text-delta"),id:z.string(),delta:z.string(),providerMetadata:T.optional()}),z.looseObject({type:z.literal("text-end"),id:z.string(),providerMetadata:T.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:T.optional(),toolMetadata:BY.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:T.optional(),toolMetadata:BY.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:T.optional(),toolMetadata:BY.optional(),dynamic:z.boolean().optional(),errorText:z.string(),title:z.string().optional()}),z.looseObject({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string(),approvalDescriptor:z.unknown().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}),z.looseObject({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional(),providerExecuted:z.boolean().optional(),providerMetadata:T.optional()}),z.looseObject({type:z.literal("tool-output-available"),toolCallId:z.string(),output:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:T.optional(),toolMetadata:BY.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:T.optional(),toolMetadata:BY.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:T.optional()}),z.looseObject({type:z.literal("reasoning-delta"),id:z.string(),delta:z.string(),providerMetadata:T.optional()}),z.looseObject({type:z.literal("reasoning-end"),id:z.string(),providerMetadata:T.optional()}),z.looseObject({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerMetadata:T.optional()}),z.looseObject({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:T.optional()}),z.looseObject({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:T.optional()}),z.looseObject({type:z.literal("file"),url:z.string(),mediaType:z.string(),providerMetadata:T.optional()}),z.looseObject({type:z.literal("reasoning-file"),url:z.string(),mediaType:z.string(),providerMetadata:T.optional()}),z.looseObject({type:z.custom((Y)=>typeof Y==="string"&&Y.startsWith("data-"),{message:'Type must start with "data-"'}),id:z.string().optional(),data:z.unknown(),transient:z.boolean().optional()}),z.looseObject({type:z.literal("start-step")}),z.looseObject({type:z.literal("finish-step")}),z.looseObject({type:z.literal("reset-step")}),z.looseObject({type:z.literal("start"),messageId:z.string().optional(),messageMetadata:z.unknown().optional()}),z.looseObject({type:z.literal("finish"),finishReason:z.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:z.unknown().optional()}),z.looseObject({type:z.literal("abort"),reason:z.string().optional()}),z.looseObject({type:z.literal("message-metadata"),messageMetadata:z.unknown()})])));var Eq=W0({prefix:"aitxt",size:24}),wq=W0({prefix:"call",size:24});var Aq=W0({prefix:"aitxt",size:24}),Tq=W0({prefix:"call",size:24});var M0=z.record(z.string(),I1.optional()),qV=z.record(z.string(),z.string());var _q=W8(()=>ZY(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:T.optional()}),z.object({type:z.literal("reasoning"),id:z.string().optional(),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:T.optional()}),z.object({type:z.literal("custom"),kind:z.string(),providerMetadata:T.optional()}),z.object({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:T.optional()}),z.object({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:T.optional()}),z.object({type:z.literal("file"),mediaType:z.string(),filename:z.string().optional(),url:z.string(),providerReference:qV.optional(),providerMetadata:T.optional()}),z.object({type:z.literal("reasoning-file"),mediaType:z.string(),url:z.string(),providerMetadata:T.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:M0.optional(),state:z.literal("input-streaming"),input:z.unknown().optional(),providerExecuted:z.boolean().optional(),callProviderMetadata:T.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:M0.optional(),state:z.literal("input-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:T.optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:T.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.never().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:T.optional(),approval:z.object({id:z.string(),approved:z.boolean(),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("output-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:T.optional(),resultProviderMetadata:T.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("output-error"),input:z.unknown().optional(),rawInput:z.unknown().optional(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.string(),callProviderMetadata:T.optional(),resultProviderMetadata:T.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("output-denied"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:T.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("input-streaming"),providerExecuted:z.boolean().optional(),callProviderMetadata:T.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:M0.optional(),state:z.literal("input-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:T.optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:T.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.never().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:T.optional(),approval:z.object({id:z.string(),approved:z.boolean(),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("output-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:T.optional(),resultProviderMetadata:T.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("output-error"),providerExecuted:z.boolean().optional(),input:z.unknown().optional(),rawInput:z.unknown().optional(),output:z.never().optional(),errorText:z.string(),callProviderMetadata:T.optional(),resultProviderMetadata:T.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("output-denied"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:T.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})})]))}).superRefine((Y,X)=>{if(Y.role!=="assistant"&&Y.parts.length===0)X.addIssue({origin:"array",code:"too_small",minimum:1,inclusive:!0,input:Y.parts,path:["parts"],message:"Message must contain at least one part"})})).nonempty("Messages array must not be empty")));var Iq=W0({prefix:"call",size:24});var kq=W0({prefix:"call",size:24});var xq=W0({prefix:"aiobj",size:24});function m2(Y){return({url:X,abortSignal:J})=>a6({url:X,maxBytes:Y==null?void 0:Y.maxBytes,abortSignal:J})}var hq=W0({prefix:"aiobj",size:24});var gq=m2();var c2="AI_NoSuchProviderError",u2=`vercel.ai.error.${c2}`,jV=Symbol.for(u2),pW,lW,fq=class extends(lW=Q9,pW=jV,lW){constructor({modelId:Y,modelType:X,providerId:J,availableProviders:Q,message:$=`No such provider: ${J} (available providers: ${Q.join()})`}){super({errorName:c2,modelId:Y,modelType:X,message:$});this[pW]=!0,this.providerId=J,this.availableProviders=Q}static isInstance(Y){return D.hasMarker(Y,u2)}};var cq=W0({prefix:"call",size:24});var uq=m2();class C0 extends YY{name="ProviderResponseStreamError";constructor(Y,X){super({message:Y,url:"",requestBodyValues:void 0,cause:X?.cause,isRetryable:!0})}}var E0={};G9(E0,{toWebSocketUrl:()=>gV,streamResponsesWebSocket:()=>cV,parseRateLimitSignal:()=>FY,normalizeHeaders:()=>yV,isUpgradeFailure:()=>fV,isAbortError:()=>e9,connectResponsesWebSocket:()=>mV,PROTOCOL_HEADER:()=>s2,OpenAIWebSocket:()=>E0});function OY(Y){let X=Number(Y.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(X)?X:void 0}function H8(Y,X,J=!1){let $=Buffer.from(Y.slice(0,X)).toString("latin1").split(`\r
|
|
196
|
-
`),G=$[0]??"",W=OY(G);if(W===void 0||W===101)return;let U=Object.fromEntries($.slice(1).flatMap((N)=>{let K=N.indexOf(":");return K===-1?[]:[[N.slice(0,K).trim().toLowerCase(),N.slice(K+1).trim()]]})),L=Y.slice(X+4),H=U["content-length"],V=Number(H);if(!J&&(H===void 0||Number.isFinite(V)&&L.length<V))return;let O=Buffer.from(L).toString("utf8"),B=(()=>{try{let N=JSON.parse(O);return _(N)?N:void 0}catch{return}})();return{message:`WS upgrade failed: ${G}`,status:W,status_code:W,headers:U,body:O,..._(B?.error)?{error:B.error}:{}}}var
|
|
195
|
+
`)}})}};var BY=z.record(z.string(),I1.optional()),Aq=W8(()=>ZY(z.union([z.looseObject({type:z.literal("text-start"),id:z.string(),providerMetadata:T.optional()}),z.looseObject({type:z.literal("text-delta"),id:z.string(),delta:z.string(),providerMetadata:T.optional()}),z.looseObject({type:z.literal("text-end"),id:z.string(),providerMetadata:T.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:T.optional(),toolMetadata:BY.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:T.optional(),toolMetadata:BY.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:T.optional(),toolMetadata:BY.optional(),dynamic:z.boolean().optional(),errorText:z.string(),title:z.string().optional()}),z.looseObject({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string(),approvalDescriptor:z.unknown().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}),z.looseObject({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional(),providerExecuted:z.boolean().optional(),providerMetadata:T.optional()}),z.looseObject({type:z.literal("tool-output-available"),toolCallId:z.string(),output:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:T.optional(),toolMetadata:BY.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:T.optional(),toolMetadata:BY.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:T.optional()}),z.looseObject({type:z.literal("reasoning-delta"),id:z.string(),delta:z.string(),providerMetadata:T.optional()}),z.looseObject({type:z.literal("reasoning-end"),id:z.string(),providerMetadata:T.optional()}),z.looseObject({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerMetadata:T.optional()}),z.looseObject({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:T.optional()}),z.looseObject({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:T.optional()}),z.looseObject({type:z.literal("file"),url:z.string(),mediaType:z.string(),providerMetadata:T.optional()}),z.looseObject({type:z.literal("reasoning-file"),url:z.string(),mediaType:z.string(),providerMetadata:T.optional()}),z.looseObject({type:z.custom((Y)=>typeof Y==="string"&&Y.startsWith("data-"),{message:'Type must start with "data-"'}),id:z.string().optional(),data:z.unknown(),transient:z.boolean().optional()}),z.looseObject({type:z.literal("start-step")}),z.looseObject({type:z.literal("finish-step")}),z.looseObject({type:z.literal("reset-step")}),z.looseObject({type:z.literal("start"),messageId:z.string().optional(),messageMetadata:z.unknown().optional()}),z.looseObject({type:z.literal("finish"),finishReason:z.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:z.unknown().optional()}),z.looseObject({type:z.literal("abort"),reason:z.string().optional()}),z.looseObject({type:z.literal("message-metadata"),messageMetadata:z.unknown()})])));var Tq=W0({prefix:"aitxt",size:24}),Rq=W0({prefix:"call",size:24});var _q=W0({prefix:"aitxt",size:24}),Cq=W0({prefix:"call",size:24});var M0=z.record(z.string(),I1.optional()),PV=z.record(z.string(),z.string());var Sq=W8(()=>ZY(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:T.optional()}),z.object({type:z.literal("reasoning"),id:z.string().optional(),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:T.optional()}),z.object({type:z.literal("custom"),kind:z.string(),providerMetadata:T.optional()}),z.object({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:T.optional()}),z.object({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:T.optional()}),z.object({type:z.literal("file"),mediaType:z.string(),filename:z.string().optional(),url:z.string(),providerReference:PV.optional(),providerMetadata:T.optional()}),z.object({type:z.literal("reasoning-file"),mediaType:z.string(),url:z.string(),providerMetadata:T.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:M0.optional(),state:z.literal("input-streaming"),input:z.unknown().optional(),providerExecuted:z.boolean().optional(),callProviderMetadata:T.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:M0.optional(),state:z.literal("input-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:T.optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:T.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.never().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:T.optional(),approval:z.object({id:z.string(),approved:z.boolean(),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("output-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:T.optional(),resultProviderMetadata:T.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("output-error"),input:z.unknown().optional(),rawInput:z.unknown().optional(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.string(),callProviderMetadata:T.optional(),resultProviderMetadata:T.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("output-denied"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:T.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("input-streaming"),providerExecuted:z.boolean().optional(),callProviderMetadata:T.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:M0.optional(),state:z.literal("input-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:T.optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:T.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.never().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:T.optional(),approval:z.object({id:z.string(),approved:z.boolean(),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("output-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:T.optional(),resultProviderMetadata:T.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("output-error"),providerExecuted:z.boolean().optional(),input:z.unknown().optional(),rawInput:z.unknown().optional(),output:z.never().optional(),errorText:z.string(),callProviderMetadata:T.optional(),resultProviderMetadata:T.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("output-denied"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:T.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})})]))}).superRefine((Y,X)=>{if(Y.role!=="assistant"&&Y.parts.length===0)X.addIssue({origin:"array",code:"too_small",minimum:1,inclusive:!0,input:Y.parts,path:["parts"],message:"Message must contain at least one part"})})).nonempty("Messages array must not be empty")));var bq=W0({prefix:"call",size:24});var vq=W0({prefix:"call",size:24});var gq=W0({prefix:"aiobj",size:24});function u2(Y){return({url:X,abortSignal:J})=>YV({url:X,maxBytes:Y==null?void 0:Y.maxBytes,abortSignal:J})}var fq=W0({prefix:"aiobj",size:24});var mq=u2();var p2="AI_NoSuchProviderError",l2=`vercel.ai.error.${p2}`,MV=Symbol.for(l2),dW,iW,uq=class extends(iW=Q9,dW=MV,iW){constructor({modelId:Y,modelType:X,providerId:J,availableProviders:Q,message:$=`No such provider: ${J} (available providers: ${Q.join()})`}){super({errorName:p2,modelId:Y,modelType:X,message:$});this[dW]=!0,this.providerId=J,this.availableProviders=Q}static isInstance(Y){return D.hasMarker(Y,l2)}};var lq=W0({prefix:"call",size:24});var dq=u2();class C0 extends YY{name="ProviderResponseStreamError";constructor(Y,X){super({message:Y,url:"",requestBodyValues:void 0,cause:X?.cause,isRetryable:!0})}}var E0={};G9(E0,{toWebSocketUrl:()=>mV,streamResponsesWebSocket:()=>lV,parseRateLimitSignal:()=>FY,normalizeHeaders:()=>cV,isUpgradeFailure:()=>uV,isAbortError:()=>e9,connectResponsesWebSocket:()=>pV,PROTOCOL_HEADER:()=>e2,OpenAIWebSocket:()=>E0});function OY(Y){let X=Number(Y.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(X)?X:void 0}function H8(Y,X,J=!1){let $=Buffer.from(Y.slice(0,X)).toString("latin1").split(`\r
|
|
196
|
+
`),G=$[0]??"",W=OY(G);if(W===void 0||W===101)return;let U=Object.fromEntries($.slice(1).flatMap((N)=>{let K=N.indexOf(":");return K===-1?[]:[[N.slice(0,K).trim().toLowerCase(),N.slice(K+1).trim()]]})),L=Y.slice(X+4),H=U["content-length"],V=Number(H);if(!J&&(H===void 0||Number.isFinite(V)&&L.length<V))return;let O=Buffer.from(L).toString("utf8"),B=(()=>{try{let N=JSON.parse(O);return _(N)?N:void 0}catch{return}})();return{message:`WS upgrade failed: ${G}`,status:W,status_code:W,headers:U,body:O,..._(B?.error)?{error:B.error}:{}}}var EV="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",d2=["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 s9{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+EV));this.expectedAccept=Buffer.from(new Uint8Array(L)).toString("base64");let H={};for(let[B,N]of Object.entries(X))H[B.toLowerCase()]=N;let V=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${U}`];for(let B of d2)if(H[B]!==void 0)V.push(`${AV(B)}: ${H[B]}`);for(let[B,N]of Object.entries(X))if(!d2.includes(B.toLowerCase())&&B.toLowerCase()!=="content-length")V.push(`${B}: ${N}`);let O=`${V.join(`\r
|
|
197
197
|
`)}\r
|
|
198
198
|
\r
|
|
199
|
-
`;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let B=globalThis.Bun?.connect;if(!B)throw Error("Bun.connect is not available");this.socket=await B({hostname:Q,port:$,tls:J.protocol==="https:"?{serverName:Q}:void 0,socket:{open:(N)=>{this.socket=N,this.enqueueWrite(new TextEncoder().encode(O))},data:(N,K)=>this.onData(K),drain:()=>this.flushWrites(),error:(N,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(B){this.readyState=3;let N=B instanceof Error?B.message:String(B);this.log("connect_exception",{message:N}),this.emit("error",{message:N})}}onData(Y){if(this.rxBuffer=
|
|
199
|
+
`;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let B=globalThis.Bun?.connect;if(!B)throw Error("Bun.connect is not available");this.socket=await B({hostname:Q,port:$,tls:J.protocol==="https:"?{serverName:Q}:void 0,socket:{open:(N)=>{this.socket=N,this.enqueueWrite(new TextEncoder().encode(O))},data:(N,K)=>this.onData(K),drain:()=>this.flushWrites(),error:(N,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(B){this.readyState=3;let N=B instanceof Error?B.message:String(B);this.log("connect_exception",{message:N}),this.emit("error",{message:N})}}onData(Y){if(this.rxBuffer=wV(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
|
|
200
200
|
\r
|
|
201
201
|
`);if(J===-1)return;let Q=X.slice(0,J),$=Q.split(`\r
|
|
202
202
|
`)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=OY($);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
|
|
203
203
|
\r
|
|
204
|
-
`);if(X===-1)return!1;let J=H8(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=
|
|
204
|
+
`);if(X===-1)return!1;let J=H8(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=TV(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 e0({component:"raw-ws-bun",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function AV(Y){return Y}function wV(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function TV(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 RV}from"node:net";import{connect as _V}from"node:tls";var CV="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",i2=["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 a9{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+CV));this.expectedAccept=Buffer.from(new Uint8Array(L)).toString("base64");let H={};for(let[B,N]of Object.entries(X))H[B.toLowerCase()]=N;let V=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${U}`];for(let B of i2)if(H[B]!==void 0)V.push(`${IV(B)}: ${H[B]}`);for(let[B,N]of Object.entries(X))if(!i2.includes(B.toLowerCase())&&B.toLowerCase()!=="content-length")V.push(`${B}: ${N}`);let O=`${V.join(`\r
|
|
205
205
|
`)}\r
|
|
206
206
|
\r
|
|
207
|
-
`;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let B=()=>{this.socket?.write(O)},N=J.protocol==="https:"?
|
|
207
|
+
`;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let B=()=>{this.socket?.write(O)},N=J.protocol==="https:"?_V({host:Q,port:$,servername:Q},B):RV({host:Q,port:$},B);this.socket=N,N.on("data",(K)=>{this.onData(typeof K==="string"?Buffer.from(K,"binary"):K)}),N.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})}),N.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(B){this.readyState=3,this.log("connect_exception",{message:B instanceof Error?B.message:String(B)}),this.emit("error",{message:B instanceof Error?B.message:String(B)})}}onData(Y){if(this.rxBuffer=SV(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
|
|
208
208
|
\r
|
|
209
209
|
`);if(J===-1)return;let Q=X.slice(0,J),$=Q.split(`\r
|
|
210
210
|
`)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=OY($);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
|
|
211
211
|
\r
|
|
212
|
-
`);if(X===-1)return!1;let J=H8(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=
|
|
212
|
+
`);if(X===-1)return!1;let J=H8(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=kV(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 e0({component:"raw-ws-node",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function IV(Y){return Y}function SV(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function kV(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 bV(){return typeof globalThis.Bun?.connect==="function"}var n2=bV()?s9:a9;function N8(Y){return process.env[Y]??process.env[Y.toLowerCase()]}function xV(Y){let X=N8("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 vV(Y){let X=new URL(Y);if(xV(X))return;if(X.protocol==="http:")return N8("HTTP_PROXY");if(X.protocol==="https:")return N8("HTTPS_PROXY")??N8("HTTP_PROXY");return}var o2={getProxyForUrl:vV};var hV=H0("quota"),r2=H0("transport"),e2="responses_websockets=2026-02-06",s2=["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"],gV=new Set([z1,"x-opencode-title"]);function yV(Y){let X=new Map;for(let Q of Object.keys(Y))X.set(Q.toLowerCase(),Q);let J={};for(let Q of s2){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(!s2.includes(Q.toLowerCase()))J[Q]=$;return J}function fV(Y){let X={};for(let[J,Q]of Object.entries(Y)){if(gV.has(J.toLowerCase()))continue;X[J]=Q}return X}function mV(Y){return Y.replace(/^http/,"ws")}function cV(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 e9(Y){return Y instanceof DOMException&&Y.name==="AbortError"}var Y4=new WeakSet;function uV(Y){return typeof Y==="object"&&Y!==null&&Y4.has(Y)}function a2(Y,X){let J=Error(Y,X===void 0?void 0:{cause:X});return Y4.add(J),J}function pV(Y){return new Promise((X,J)=>{if(Y.signal?.aborted){J(t9(Y.signal));return}let Q={...Y.headers,"openai-beta":Y.headers["openai-beta"]??e2},$=Q[z1]??Q["session-id"];delete Q["content-length"],Q=yV(fV(Q));let G=typeof Bun>"u"?void 0:o2.getProxyForUrl(Y.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),W=!0,U=Y.rawWebSocket?new n2(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",V),U.removeEventListener("error",O),U.removeEventListener("close",B),Y.signal?.removeEventListener("abort",N)}function V(){H(),X(U)}function O(K){H(),J(a2(t0(K),K))}function B(K){H(),J(a2(J4("WebSocket closed before open",K.code,K.reason)))}function N(){H(),U.close(),J(t9(Y.signal))}U.addEventListener("open",V,{once:!0}),U.addEventListener("error",O,{once:!0}),U.addEventListener("close",B,{once:!0}),Y.signal?.addEventListener("abort",N,{once:!0})})}function lV(Y){let X=new TextEncoder,J=Y.socket,Q,$=()=>{},G=!1,W=!1,U=!1,L,H=new Set;function V(){if(L)clearTimeout(L);$(),Y.signal?.removeEventListener("abort",y)}function O(v=J){v.close()}function B(){V(),Q?.enqueue(X.encode(`data: [DONE]
|
|
213
213
|
|
|
214
|
-
`)),Q?.close()}function N(v){j(v,v)}function K(v){if(U){
|
|
214
|
+
`)),Q?.close()}function N(v){j(v,v)}function K(v){if(U){let f=`${v.message} (not retried: output already emitted)`;r2.warn("stream failed after output; not retried",{reason:v.message,emittedOutput:!0}),j(Error(f,{cause:v}),new C0(f,{cause:v}));return}r2.warn("stream failed before output; retryable",{reason:v.message,emittedOutput:!1}),N(v)}function j(v,f){if(G)return;G=!0,V(),Y.onConnectionInvalid?.(f),Q?.error(v)}function A(v){if(G)return;if(!Y.idleTimeout)return;if(L)clearTimeout(L);L=setTimeout(()=>K(new C0(v)),Y.idleTimeout)}async function x(v){if(G)return;if(typeof v.data!=="string"){K(new C0("Unexpected binary WebSocket frame"));return}let f=v.data,u=(()=>{try{let d=JSON.parse(f);return typeof d==="object"&&d!==null?d:void 0}catch{return}})();if(u?.type==="codex.rate_limits"){hV.debug("codex.rate_limits frame received",{pid:process.pid}),A("idle timeout waiting for websocket");let d=t2(u);Y.onQuota?.(d);return}let N0=!U?FY(u):void 0;if(N0&&u){G=!0,V(),Y.onRateLimitReached?.(N0.window,N0.resetAt),Y.onTerminal?.(u),Y.onFirstEvent?.(),Q?.error(new C0(`OpenAI account rate limit reached at admission (${N0.window})`));return}if(u?.type==="error"&&Y.onRetryableTerminal){if($(),L)clearTimeout(L);L=void 0;try{let d=await Y.onRetryableTerminal(u);if(G){if(d)O(d);return}if(d){K0(d);return}}catch(d){K(new C0(d instanceof Error?d.message:String(d),{cause:d}));return}}let Y0=rV(u,f);if(Y0&&u){if(!W)Y.onFirstEvent?.(Y0);G=!0,V(),Y.onTerminal?.(u);let d=new YY({message:Y0.message,url:J.url,requestBodyValues:Y.body,statusCode:Y0.status,responseHeaders:Y0.headers,responseBody:Y0.body});Q?.error(U?Error(d.message,{cause:d}):d);return}if(_(u)&&u.type==="response.failed"){let d=_(u.response)?u.response.failed:void 0,g0=_(d)?d.rate_limit_reached_type:void 0;if(typeof g0==="string"){if(G=!0,V(),Y.onRateLimitReached?.(g0),Y.onTerminal?.(u),!U)Y.onFirstEvent?.(),Q?.error(new C0(`OpenAI account rate limit reached mid-stream (${g0})`));else B();return}}if(u)dV(u,Y.sessionID),nV(u,H);let Q0=u?t8(u):u;if(!Q0){if(!W)Y.onFirstEvent?.();A("idle timeout waiting for websocket");return}let q1=Q0===u?f:JSON.stringify(Q0);if(!W)Y.onFirstEvent?.();if(Q?.enqueue(X.encode(`${q1.split(/\r?\n/).map((d)=>`data: ${d}`).join(`
|
|
215
215
|
`)}
|
|
216
216
|
|
|
217
|
-
`)),W=!0,Q0.type!=="response.created"&&Q0.type!=="response.in_progress")U=!0;if(w("idle timeout waiting for websocket"),!Q0)return;if(Q0.type==="response.completed"||Q0.type==="response.done"){G=!0,dV(Q0,H),Y.onComplete?.(Q0,H),Y.onTerminal?.(Q0),B();return}if(Q0.type==="response.failed"||Q0.type==="response.incomplete"||Q0.type==="error")G=!0,Y.onTerminal?.(Q0),B()}function E(v){K(new C0(t0(v),{cause:v}))}function S(v){if(G)return;K(new C0(e2("WebSocket closed before response.completed",v.code,v.reason)))}function y(){let v=t9(Y.signal);if(G)return;G=!0,V(),O(),Y.onAbort?.(v),Q?.error(v)}function l(v){if(G)return;G=!0,V(),O(),Y.onAbort?.(nV(v))}function K0(v){$(),J=v,J.addEventListener("message",x),J.addEventListener("error",E,{once:!0}),J.addEventListener("close",S,{once:!0}),$=()=>{J.removeEventListener("message",x),J.removeEventListener("error",E),J.removeEventListener("close",S)};let{background:m,...u}=Y.body;w("idle timeout sending websocket request");try{J.send(JSON.stringify({type:"response.create",...u})),w("idle timeout waiting for websocket")}catch(H0){if(G)return;N(new C0(H0 instanceof Error?H0.message:String(H0),{cause:H0}))}}return new Response(new ReadableStream({start(v){if(Q=v,Y.signal?.addEventListener("abort",y,{once:!0}),Y.signal?.aborted){y();return}K0(J)},cancel(v){l(v)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function uV(Y,X){if(!pV(Y))return;await e0({component:"ws",event:"provider_native_web_search_event",sessionID:X,serverEventType:Y.type,itemType:_(Y.item)?Y.item.type:void 0,serverEvent:Y})}function pV(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 lV(Y,X){if(Y.type!=="response.output_item.done")return;if(!_(Y.item))return;t2(Y.item,X)}function dV(Y,X){let J=Y.response;if(!_(J)||!Array.isArray(J.output))return;for(let Q of J.output)if(_(Q))t2(Q,X)}function t2(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 iV(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 FY(Y){if(typeof Y==="string")try{return FY(JSON.parse(Y))}catch{return}if(!_(Y))return;let X=FY(Y.cause);if(X)return X;let J=FY(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 nV(Y){if(e9(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function t9(Y){let X=Y?.reason;if(e9(X))return X;if(oV(X))return X;return new DOMException(X instanceof Error?X.message:"Aborted","AbortError")}function oV(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function e2(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 XX="x-opencode-title",V8="x-openai-auth-quota-account",YX=new Set([XX,z1,V8,"x-opencode-session"]),sV=15000,aV=300000,tV=3300000,Y4="websocket_connection_limit_reached";function eV(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 rV("sha256").update(Q).digest("hex").slice(0,12)}function YZ(Y){let X=Y?.httpFetch??globalThis.fetch,J=new Map,Q=Y?.connectTimeout??sV,$=Y?.idleTimeout??aV,G=Y?.maxConnectionAge??tV,W=Y?.streamRetries??5,U=Y?.firstEventGraceMs??250,L=Y?.rawWebSocket??!1,H=Y?.onQuota,V=Y?.onRateLimitReached,O=setInterval(()=>j(),Math.min($,60000));if(typeof O==="object"&&"unref"in O&&typeof O.unref==="function")O.unref();function B(E,S,y){if(!S||!y)return y;JX(E,X4(S));let l=new Headers(y.headers),K0=l.get("x-codex-turn-metadata");if(!K0)return y;let v=L4(K0,E.turnID,E.turnStartedAt);if(!v)return y;return l.set("x-codex-turn-metadata",v),{...y,headers:l}}async function N(E,S){let y=E instanceof URL?E.toString():typeof E==="string"?E:E.url,l=E0.normalizeHeaders(S?.headers),K0=V4(S),v=gY(K0);if(S?.method!=="POST"||!new URL(y).pathname.endsWith("/responses"))return X(E,v);let m=(()=>{try{if(typeof S?.body!=="string")return;let r=JSON.parse(S.body);return typeof r==="object"&&r!==null?r:void 0}catch{return}})();if(!m?.stream)return X(E,v);if(l[XX]==="true")return X(E,v);let u=l[z1]??l["x-session-affinity"]??l["session-id"],H0=u;if(!u)return X(E,v);let Y0=E0.normalizeHeaders(K0?.headers),Q0=eV(Y0),q1=`${u}:${Q0}:conversation`,d=typeof l[V8]==="string"?l[V8]:void 0,g0=V?(r,O0)=>V(r,d,O0):void 0,g=J.get(q1)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};if(J.set(q1,g),g.fallback)return X(E,B(g,m,v));if(g.busy)return X(E,B(g,m,v));g.busy=!0,g.lastUsedAt=Date.now();try{let r=X4(m),O0=E0.normalizeHeaders(K0?.headers),O8=typeof O0.authorization==="string"&&O0.authorization.startsWith("Bearer ")?O0.authorization.slice(7):"",k1=typeof O0["chatgpt-account-id"]==="string"?O0["chatgpt-account-id"]:void 0,wY=H?($0)=>H($0,O8,d,k1):void 0,n0=!g.socket&&!g.continuation?UZ(O0):O0;if(g.socket=await QZ(g,Y?.url??y,n0,Q,G,L,S?.signal),VZ(g,r))await $Z(g,r,$,{signal:S?.signal??void 0,sessionID:H0,url:Y?.url??y,headers:K0?.headers,onRateLimitReached:g0});let G1=()=>{},o0=()=>{},j1=new Promise(($0,I0)=>{G1=$0,o0=I0}),F8=NZ(g,r),r0=qY(U4(g,F8,r)),P0=typeof r0.previous_response_id==="string";await f1({sessionID:H0,transport:"websocket",phase:"main",bodyText:JSON.stringify(r0),url:Y?.url??y,method:K0?.method,headers:K0?.headers});let y0=E0.streamResponsesWebSocket({socket:g.socket,body:r0,sessionID:H0??void 0,idleTimeout:$,signal:S?.signal??void 0,onQuota:wY,onRateLimitReached:g0,onFirstEvent:($0)=>G1($0??!0),onComplete:($0,I0)=>{let b1=$4($0);e0({component:"ws-pool",event:"main_completed",sessionID:H0,responseID:Q4($0),usage:b1}),z4(g,r,$0,I0,P0)},onTerminal:($0)=>{if(g.busy=!1,g.lastUsedAt=Date.now(),g.streamFailures=0,$0.type!=="response.completed"&&$0.type!=="response.done")g.continuation=void 0,$1(g)},onConnectionInvalid:()=>{if(g.busy=!1,g.lastUsedAt=Date.now(),!g.fallback)K(g);g.continuation=void 0,$1(g),G1(!1)},onAbort:($0)=>{g.busy=!1,g.lastUsedAt=Date.now(),g.streamFailures=0,g.continuation=void 0,$1(g),o0($0)},onRetryableTerminal:async($0)=>{let I0=J4($0);if(!I0)return;throw g.fallback=!0,I0}}),f0=await XZ(j1,U);if(f0!==!1){if(f0===!0||f0.status<200||f0.status>599)return y0;return new Response(f0.body,{status:f0.status,headers:{"content-type":"application/json",...f0.headers}})}if(!g.fallback)return y0;return X(E,B(g,m,v))}catch(r){if(g.busy=!1,g.lastUsedAt=Date.now(),E0.isAbortError(r))throw g.streamFailures=0,g.continuation=void 0,$1(g),r;let O0=E0.parseRateLimitSignal(r);if(O0)g0?.(O0.window,O0.resetAt);if(E0.isUpgradeFailure(r)&&!L)g.fallback=!0;if(K(g),g.continuation=void 0,$1(g),g.fallback)return X(E,B(g,m,v));return JZ(new C0(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[S,y]of J){if(y.busy)continue;if(E-y.lastUsedAt<$)continue;$1(y),J.delete(S)}}function w(){clearInterval(O);for(let E of J.values())$1(E);J.clear()}function x(E){let S=`${E}:`;for(let[y,l]of J){if(!y.startsWith(S))continue;$1(l),J.delete(y)}}return Object.assign(N,{close:w,remove:x})}function J4(Y){if(Y.type!=="error"||!_(Y.error)||Y.error.code!==Y4)return;return Error(typeof Y.error.message==="string"?Y.error.message:Y4)}async function XZ(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 JZ(Y){return new Response(new ReadableStream({start(X){X.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function QZ(Y,X,J,Q,$,G,W){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<$)return Y.socket;$1(Y);let U=await E0.connectResponsesWebSocket({url:E0.toWebSocketUrl(X),headers:J,timeout:Q,rawWebSocket:G,signal:W??void 0});return Y.connectedAt=Date.now(),U}function $1(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function $Z(Y,X,J,Q){if(!Y.socket||!Array.isArray(X.input)||X.input.length===0)return;let $=WZ(X);await f1({sessionID:Q.sessionID,transport:"websocket",phase:"prewarm",bodyText:JSON.stringify($),url:Q.url,method:"POST",headers:Q.headers});let G=E0.streamResponsesWebSocket({socket:Y.socket,body:$,sessionID:Q.sessionID,idleTimeout:J,signal:Q.signal,onRateLimitReached:Q.onRateLimitReached,onComplete:(W,U)=>{e0({component:"ws-pool",event:"prewarm_completed",sessionID:Q.sessionID,responseID:Q4(W),usage:$4(W)}),z4(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=J4(W);if(!U)return;throw Y.fallback=!0,U}});await GZ(G)}function Q4(Y){let X=Y.response;if(!_(X))return;return typeof X.id==="string"?X.id:void 0}function $4(Y){let X=Y.response;if(!_(X))return;return _(X.usage)?X.usage:void 0}async function GZ(Y){let X=Y.body?.getReader();if(!X)return;while(!0)if((await X.read()).done)return}function WZ(Y){return qY({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:zZ(Y.client_metadata)})}function G4(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 zZ(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":G4(X),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function UZ(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":G4(J)}}catch{return Y}}var W4=["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 X4(Y){let X={...Y};if(Array.isArray(Y.input))X.input=Y.input.map(LZ);return X}function qY(Y){let X={};for(let J of W4)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 LZ(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 z4(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:QX(X),finalizedCallIds:U}}function JX(Y,X,J=X){let Q=Array.isArray(X.input)?X.input:[],$=Array.isArray(J.input)?J.input:Q,G=QX(J),W=Y.turnInput&&Y.turnSignature===G?HZ(Y.turnInput,$):void 0,U=W===void 0?Q:$.slice(W);if(U.length>0&&U.some(H4)||!Y.turnID)Y.turnID=A1(),Y.turnStartedAt=Date.now();Y.turnInput=$.slice(),Y.turnSignature=G}function U4(Y,X,J=X){JX(Y,X,J);let Q=X.client_metadata;if(!_(Q)||typeof Q["x-codex-turn-metadata"]!=="string")return X;let $=L4(Q["x-codex-turn-metadata"],Y.turnID,Y.turnStartedAt);if(!$)return X;return{...X,client_metadata:{...Q,"x-codex-turn-metadata":$}}}function L4(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 HZ(Y,X){if(Y.length>X.length)return;for(let J=0;J<Y.length;J++)if(Y1(Y[J])!==Y1(X[J]))return;return Y.length}function NZ(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!J||!Y.continuation)return X;if(Y.continuation.signature!==QX(X))return Y.continuation=void 0,X;if(!N4(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),$=ZZ(Q,Y.continuation.finalizedCallIds);if($.length===0)return X;return{...X,previous_response_id:Y.continuation.responseID,input:$}}function VZ(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!Y.continuation)return!0;if(!J)return!1;if(!N4(Y.continuation.input,J))return!0;return J.slice(Y.continuation.input.length).some(H4)}function H4(Y){if(!_(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function ZZ(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 QX(Y){return Y1(BZ(Object.fromEntries(Object.entries(Y).filter(([X])=>X!=="input"&&X!=="stream"&&X!=="background"&&X!=="previous_response_id"&&X!=="generate"))))}function BZ(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 N4(Y,X){if(Y.length>=X.length)return!1;for(let J=0;J<Y.length;J++)if(Y1(Y[J])!==Y1(X[J]))return!1;return!0}function V4(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let X=new Headers(Y.headers);for(let J of YX)X.delete(J);return{...Y,headers:X}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((X)=>!YX.has(X[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([X])=>!YX.has(X.toLowerCase())))}}var PZ=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),MZ=new Set(["gpt-5.6"]),EZ=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),wZ="opencode-oauth-dummy-key",AZ="terminal_resize_reflow",zX="0.144.0",TZ=`codex_exec/${zX} (Debian 12.0.0; aarch64) unknown (codex_exec; ${zX})`,RZ="seccomp",_Z="main-refresh",CZ=120000,IZ=90000,SZ=4000,Z4=50,B4=3,kZ=25,bZ=60000,xZ="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",K4=!1,O4=V0("models"),F4=!1,q4=!1;class LX 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 d0 extends Error{code;constructor(Y,X){super(X);this.name="ResetTargetResolutionError",this.code=Y}}function j4(Y,X,J,Q){let $=(J?.refresh?.refreshBeforeExpiryMinutes??240)*60000;return!Y||!X||X-Q<=$}function vZ(Y){return async(X)=>{if(X==="main"){let U=await Y.loadAccounts(Y.accountStoragePath),L=await Y.getAuth();if(L.type!=="oauth")throw new d0("non_oauth_account","Main OpenAI account is not authenticated with OAuth.");if(j4(L.access,L.expires,U,Y.now()))L={type:"oauth",...await Y.refreshMainWithLease()};if(!L.access)throw new d0("token_unavailable","Main OpenAI account has no usable access token.");let H=o1(L.access),V=H?r1(H):void 0,O=await Y.loadAccounts(Y.accountStoragePath);return{accountKey:X,label:"Main account",accessToken:L.access,chatgptAccountId:V??O?.mainAccountId}}let J=await Y.loadAccounts(Y.accountStoragePath),Q=J?.accounts.find((U)=>U.id===X);if(!J||!Q)throw new d0("unknown_account",`Fallback account ${X} was not found.`);if(Q.enabled===!1)throw new d0("disabled_account",`Fallback account ${X} is disabled.`);if(!i0(Q))throw new d0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);let $=Q;if(j4($.access,$.expires,J,Y.now()))$=await Y.refreshFallbackAccount($,J);if(!$.access)throw new d0("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 d0("unknown_account",`Fallback account ${X} was not found.`);if(W.enabled===!1)throw new d0("disabled_account",`Fallback account ${X} is disabled.`);if(!i0(W))throw new d0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);return{accountKey:X,label:$.label??X,accessToken:$.access,chatgptAccountId:W.accountId}}}function hZ(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function GX(Y){return Y instanceof LX}function D4(){throw Error(xZ)}function gZ(Y){return Math.floor(Math.random()*Y)}function yZ(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 fZ(Y,X,J){let Q=Y.get(X);if(Q)return Q;let $=A1(),G={threadID:$,turnID:A1(),windowID:`${$}:0`};return Y.set(X,G),J?.(),G}function t4(){return DZ(CY(),"openai-auth-sessions.json")}function mZ(){let Y=new Map;try{let X=JSON.parse(OZ(t4(),"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:A1(),windowID:`${Q.threadID}:0`})}}catch{}return Y}function cZ(Y){let X=t4(),J=`${X}.tmp-${process.pid}`;try{KZ(CY(),{recursive:!0});let Q={version:1,sessions:Object.fromEntries([...Y.entries()].map(([$,G])=>[$,{threadID:G.threadID}]))};jZ(J,`${JSON.stringify(Q,null,2)}
|
|
218
|
-
`,"utf8"),FZ(J,X)}catch{}}function P4(Y,X){return _(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===X}function uZ(Y,X){if(Y.length>X.length)return!1;for(let J=0;J<Y.length;J++)if(Y1(Y[J])!==Y1(X[J]))return!1;return!0}function pZ(Y,X){if(!Y.input)return X.length>0;if(!uZ(Y.input,X))return!0;return X.slice(Y.input.length).some((Q)=>P4(Q,"user")||P4(Q,"developer"))}function lZ(Y,X){let J=Array.isArray(X?.input)?X.input:void 0;if(J&&(pZ(Y,J)||!Y.turnID))Y.turnID=A1(),Y.turnStartedAt=Date.now();else if(!Y.turnStartedAt)Y.turnStartedAt=Date.now();if(J)Y.input=J}function dZ(Y){if(!Y.metadata)return{init:Y.init};let X=yZ(Y.init?.body);if(!Y.websocket)lZ(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:RZ,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",AZ),Y.headers.set("x-codex-turn-metadata",J),Y.headers.set("user-agent",TZ),Y.headers.set("version",zX),Y.dumpSessionID)Y.headers.set(z1,Y.dumpSessionID);let Q=X;if(!Q)return{init:Y.init};let $=Y.responsesLite&&typeof Q.model==="string"&&EZ.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(tZ);if(sZ(Q),aZ(Q),MJ(Q),oZ(Q),$)rZ(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(qY(Q))}}}function iZ(Y,X){return Y.find((J)=>J.enabled!==!1&&i0(J)&&(J.id===X||J.accountId===X))}function M4(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 Z8(Y,X){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:X}}function e4(Y,X,J=Date.now(),Q=X.mainAccountId){let $=Y.getMain(),G=$?.quota;return{main:{quota:G?{...G,checkedAt:$.checkedAt,primary:Z8(G.primary,$.checkedAt),secondary:Z8(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:Z8(L.primary,U.checkedAt),secondary:Z8(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 TD(Y,X,J,Q=Date.now()){return{...e4(Y,X,Q),activeId:J}}function E4(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 nZ(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 w4(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}function oZ(Y){if(!A0().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 UX(Y){if(Array.isArray(Y)){for(let X of Y)UX(X);return}if(!_(Y))return;if(Y.type==="input_image")delete Y.detail;for(let X of Object.values(Y))UX(X)}function rZ(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:[];UX(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 sZ(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(_(X)&&X.type==="function"&&X.name==="web_search"))}function aZ(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(_(X)&&X.type==="function"&&X.name==="websearch_web_search_exa"))}function tZ(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 eZ(Y,X={}){let J=X.codexApiEndpoint??A0().codexApiEndpoint,Q=crypto.randomUUID(),$=mZ(),G=()=>cZ($),W=!1,U=[],L=null,H=null,V,O=new g8;async function B(N,K){let j=Y.client.session;if(typeof j?.promptAsync==="function"){let w=await IJ(Y.client,N),x={noReply:!0,parts:[{type:"text",text:K,ignored:!0}]};if(w?.agent)x.agent=w.agent;if(w?.model)x.model=w.model;if(w?.variant)x.variant=w.variant;await j.promptAsync({path:{id:N},body:x});return}}return{async dispose(){O.stop();for(let N of U)N.close();if(U.length=0,H){await H.stop().catch(()=>{});let N=globalThis;if(N.__openaiAuthRpcServer===H)N.__openaiAuthRpcServer=void 0;H=null}},async event(N){if(N.event.type!=="session.deleted")return;let K=N.event.properties.info,j=$.get(K.id);if(j)L?.cacheKeepManager?.remove(j.threadID);if($.delete(K.id))G();if(V){let w=(await D0(G0()))?.accounts;await o4(K.id,w,V)}for(let w of U)w.remove(K.id)},provider:{id:"openai",async models(N,K){if(K.auth?.type!=="oauth")return N.models;let j=await D0(G0()),w=!j||y4(j),x=w?null:await TJ();if(!w&&x&&!F4)F4=!0,O4.debug("restoring OAuth model costs from models.dev catalog");if(!w&&!x&&!q4)q4=!0,O4.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(N.models).filter(([,E])=>{if(E.options.reasoningMode==="pro")return!1;if(PZ.has(E.api.id))return!0;if(MZ.has(E.api.id))return!1;let y=E.api.id.match(/^gpt-(\d+\.\d+)/)?.[1];return y?parseFloat(y)>5.4:!1}).map(([E,S])=>[E,{...S,cost:w?{input:0,output:0,cache:{read:0,write:0}}:x?.[S.api.id]??x?.[E]??S.cost,limit:S.id.includes("gpt-5.5")?{context:400000,input:272000,output:128000}:S.id.includes("gpt-5.6")?{context:372000,input:244000,output:128000}:S.limit}]))}},tool:{web_search:DJ},auth:{provider:"openai",async loader(N){let K=await N();if(K.type!=="oauth")return{};await m4({type:"oauth",access:K.access??"",refresh:K.refresh??"",expires:K.expires??0},G0());let j=await D0(G0()).catch((Z)=>{let F=G0();throw Error(`OpenAI auth store at ${F} is corrupt or unreadable: ${Z instanceof Error?Z.message:String(Z)}. Fix or remove it to continue.`,{cause:Z})}),w;async function x(){let Z=G0();try{let F=qZ(Z);if(w?.path===Z&&w.mtimeMs===F.mtimeMs&&w.size===F.size)return w.storage;let P=await D0(Z);return w={path:Z,mtimeMs:F.mtimeMs,size:F.size,storage:P},P}catch{return w=void 0,D0(Z)}}function E(){w=void 0}if(j&&K.access){let Z=B8({id_token:"",access_token:K.access,refresh_token:K.refresh??""});if(Z&&Z!==j.mainAccountId)await J0((F)=>{return F.mainAccountId=Z,F},G0()),j.mainAccountId=Z,E()}let S=j?.logging?.level;if(S&&typeof S==="string")bY(S);let y=V0("transport"),l=V0("quota"),K0=V0("refresh"),v=V0("accounts");y.info("codex auth loader ready",{codexApiEndpoint:J,transport:A0().rawWebSocket?"raw-websocket":A0().webSockets?"websocket":"http",webSearch:A0().webSearch});let m=new g4({storage:j,fetchQuotaFn:void 0}),u,H0=0,Y0=new c4({refreshFn:(Z)=>S1({refreshToken:Z.refreshToken,fetchImpl:Z.fetchImpl,now:Z.now}),quotaManager:m,onFallbackStorageChanged:E});if(j&&j.accounts.length>0)Y0.startBackgroundRefresh();let Q0=V0("cachekeep"),q1=j?.cachekeep?.enabled===!0,d=j?.cachekeep?.subagents===!0,g0=j?.cachekeep?.sustain===!0,g=JJ(j),r;async function O0(Z){await new Promise((F)=>setTimeout(F,Z))}async function O8(Z){let F;for(let P=1;P<=B4;P++)try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:Z.refresh,access:Z.access,expires:Z.expires}});return}catch(R){if(F=R,P<B4)await O0(kZ*P)}throw new LX(F)}async function k1(Z){await J0((F)=>{return F.refresh=F.refresh??{},Z(F),F},G0()),E()}async function wY(Z){let F=Date.now()+SZ;while(Date.now()<F){await new Promise((k)=>setTimeout(k,Z4+gZ(Z4)));let P=await N();if(P.type!=="oauth"||!P.access)continue;if((P.access!==Z.access||P.refresh!==Z.refresh||(P.expires??0)>(Z.expires??0)+60000)&&(!P.expires||P.expires>Date.now()))return K0.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:P.expires?P.expires-Date.now():void 0}),{access:P.access,refresh:P.refresh??Z.refresh??"",expires:P.expires??0}}return null}async function n0(){if(!r)r=(async()=>{let Z=await N();if(Z.type!=="oauth")throw Error("not oauth");if(!Z.refresh)throw Error("Token refresh failed: missing refresh token");let F=A4(Z.refresh),P=await D0(G0()),R=P?.refresh?.mainLastRefreshError;if(R&&xY(R,Z.refresh,Date.now()))throw Error(vY(R,Date.now()));if(P?.refresh?.mainRefreshLeaseUntil&&P.refresh.mainRefreshLeaseUntil>Date.now()&&P.refresh.mainRefreshLeaseTokenHash===F){let I=await wY(Z);if(I)return I;throw Error("Codex OAuth refresh is already in progress")}let k=await hY({name:_Z,ttlMs:CZ,path:G0(),renew:!0});if(!k){let I=await wY(Z);if(I)return I;throw Error("Codex OAuth refresh is already in progress")}let C=crypto.randomUUID(),A=F;try{await k1((f)=>{f.refresh=f.refresh??{},f.refresh.mainRefreshLeaseId=C,f.refresh.mainRefreshLeaseUntil=Date.now()+IZ,f.refresh.mainRefreshLeaseTokenHash=F});let I=await D0(G0());if(I?.refresh?.mainRefreshLeaseId!==C||I.refresh.mainRefreshLeaseTokenHash!==F)throw Error("Codex OAuth refresh is already in progress");let M=await S1({refreshToken:Z.refresh,fetchImpl:fetch,now:Date.now});return await O8(M),await k1((f)=>{if(f.refresh=f.refresh??{},f.refresh.mainLastRefreshError=void 0,f.refresh.mainRefreshLeaseId===C)f.refresh.mainRefreshLeaseId=void 0,f.refresh.mainRefreshLeaseUntil=void 0,f.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),A=void 0,M}catch(I){if(Z.refresh&&!GX(I))await k1((M)=>{M.refresh=M.refresh??{},M.refresh.mainLastRefreshError=T4({error:I,now:Date.now(),refreshToken:Z.refresh??"",previous:M.refresh.mainLastRefreshError})}).catch(()=>{});throw I}finally{if(A)await k1((I)=>{if(I.refresh?.mainRefreshLeaseId===C&&I.refresh.mainRefreshLeaseTokenHash===A)I.refresh.mainRefreshLeaseId=void 0,I.refresh.mainRefreshLeaseUntil=void 0,I.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await k.release().catch(()=>{})}})().finally(()=>{r=void 0});return r}let G1=globalThis;G1.__openaiAuthCacheKeepManager?.stop();let o0=new u8({fetchImpl:fetch,getMainToken:async()=>{let Z=await N();if(Z.type!=="oauth")throw Error("not oauth");if(!Z.access||(Z.expires??0)<Date.now())try{return(await n0()).access}catch(F){if(GX(F))throw F;if(Z.access)return Z.access;throw Error("main token refresh failed")}return Z.access},refreshFallback:async(Z)=>{let F=await x(),P=F?iZ(F.accounts,Z):void 0;if(!P)throw Error(`fallback account ${Z} not found`);let R=await Y0.refreshAccount(P,F??{version:1,accounts:[P]});if(!R.access)throw Error(`no access token for ${Z}`);return R.access},codexResponsesUrl:J,logger:Q0,now:Date.now,getWindow:()=>g,getSustain:()=>g0});G1.__openaiAuthCacheKeepManager=o0;async function j1(Z,F,P,R,k=!1){if(Object.keys(Z).length===0&&!k)return;let C=Date.now(),A=Z,I={quota:A,refreshAfter:C+300000,checkedAt:C},M;if(P&&P!=="main"){let b=F?o1(F):null,X0=b?r1(b):void 0,F0=m.peekFallbackForPolicy(P)?.quota,m0=M4(A,F0);I={...I,quota:m0},m.setFallback(P,I,F,k,X0)}else{if(M=R,!M&&F){let F0=o1(F);M=F0?r1(F0):void 0}if(M&&u&&M!==u){l.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:M,currentMainIdentity:u});return}let b=m.peekMainForPolicy(M)?.quota,X0=M4(A,b);I={...I,quota:X0},m.setMain(F,I,M,k)}l.debug("quota pushed",{pid:process.pid,accountId:P??"main",snapshot:I.quota});let f=await x();await y0(m,f,P&&P!=="main"?f?.mainAccountId:M)}function F8(Z,F,P){let R=Z==="main"?m.peekMainForPolicy()?.quota:m.peekFallbackForPolicy(Z)?.quota;return h4(R,F,Date.now(),bZ,P)}let r0=X.experimentalWebSockets?F1.createWebSocketFetch({httpFetch:fetch,rawWebSocket:A0().rawWebSocket,onQuota:(Z,F,P,R)=>{j1(Z,F,P,!P||P==="main"?R:void 0,!0)},onRateLimitReached:(Z,F,P)=>{if(!F)l.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:Z});let R=F??"main",k=F8(R,Z,P);m.markRateLimited(R,k),l.debug("mid-stream rate limit mark",{pid:process.pid,accountId:R,window:Z})}}):void 0;if(r0)U.push(r0),W=!0;let P0=u4();V=P0;async function y0(Z,F,P=F?.mainAccountId){if(!F)return;await i4(e4(Z,F,Date.now(),P),P0)}async function f0(Z,F,P,R,k){let C={activeId:P,route:R,updatedAt:Date.now()};if(Z){if(await K8({sessionId:Z,...C},k,P0),F&&F!==Z){if(R==="sticky-balanced"){let A=(await w1(P0)).stickyAssignments?.[EY(F)]?.accountId,I=k===void 0||A==="main"||k.some((M)=>M.enabled!==!1&&M.id===A);if(!A||!I)return;await K8({sessionId:F,activeId:A,route:R,updatedAt:Date.now()},k,P0);return}await K8({sessionId:F,...C},k,P0)}return}await n4(C,P0)}L={accountStoragePath:G0(),quotaManager:m,loadAccounts:D0,client:Y.client,resolveResetTarget:vZ({getAuth:N,refreshMainWithLease:n0,refreshFallbackAccount:(Z,F)=>Y0.refreshAccount(Z,F),loadAccounts:D0,accountStoragePath:G0(),now:Date.now}),...hZ(),cacheKeepManager:o0,setCacheKeepEnabled:(Z)=>{q1=Z},setCacheKeepSubagents:(Z)=>{d=Z},setCacheKeepSustain:(Z)=>{g0=Z},setCacheKeepWindow:(Z)=>{g=Z},clearStickyRouting:(Z)=>s4(Z,P0),getStickyRouting:async(Z)=>d4(await w1(P0),Z),refreshSidebar:async()=>{let Z=await D0(G0());await y0(m,Z)},refreshAllQuota:async()=>h1({getAuth:N,codexRefreshFn:S1,refreshMainWithLease:n0,fallbackManager:Y0,quotaManager:m,loadAccounts:D0,writeSidebarState:y0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:G0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:i0,whamFn:W1}),refreshResetTargetQuota:async(Z)=>{return(await h1({getAuth:N,codexRefreshFn:S1,refreshMainWithLease:n0,fallbackManager:Y0,quotaManager:m,loadAccounts:D0,writeSidebarState:y0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:G0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:i0,whamFn:W1,respectBackoff:!1},{accountKey:Z})).find((P)=>P.account===Z)??{account:Z,ok:!1,error:"targeted quota refresh returned no result"}}};let $0=null;if(Y.directory){let Z=await a4(Y.directory),F=globalThis;if(F.__openaiAuthRpcServer)await F.__openaiAuthRpcServer.stop().catch(()=>{}),F.__openaiAuthRpcServer=void 0;try{$0=await gJ({dir:Z.dir,secureDir:Z.secureDir,sweepRoot:Z.sweepRoot,drain:kJ,apply:async(P)=>{let R={...L,sessionId:P.sessionId},k=await v8(P.command,P.arguments,R);return{text:k.text,knobs:k.knobs}}}),F.__openaiAuthRpcServer=$0,H=$0}catch{}}async function I0(Z,F,P,R,k="main"){let C=E4(Z,F);if(C.delete("x-api-key"),C.delete("api-key"),C.set("authorization",`Bearer ${P}`),R)C.set("ChatGPT-Account-Id",R);C.set(F1.QUOTA_ACCOUNT_HEADER,k);let A=w4(C),I=A?fZ($,A,G):void 0,M=Z instanceof URL?Z:new URL(typeof Z==="string"?Z:Z.url),f=M.pathname.includes("/v1/responses")||M.pathname.includes("/chat/completions")?new URL(J):M,X0=dZ({init:{...F,headers:C},headers:C,metadata:I,installationID:Q,websocket:Boolean(r0&&M.pathname.endsWith("/responses")),responsesLite:X.responsesLite??!1,dumpSessionID:A}).init,F0=q1,m0=new Headers(X0?.headers),z0=XJ({enabled:F0,includeSubagents:d,headers:m0,body:X0?.body});if(F0)Q0.trace("cachekeep headers",{pid:process.pid,hasParent:m0.has("x-parent-session-id"),sessionKey:z0?.sessionKey,captured:Boolean(z0),affinity:m0.get("x-session-affinity"),opencodeSession:m0.get("x-opencode-session"),sessionId:m0.get("session-id")});if(r0&&M.pathname.endsWith("/responses")){if(y.debug("WS transport",{pid:process.pid,pathname:M.pathname,accountId:k}),z0)o0.track(z0.sessionKey,z0.bodyText,k,R,z0.replayHeaders,z0.isSubagent);return r0(f,X0)}let B0=F1.withoutInternalHeaders(X0);if(typeof B0?.body!=="string")return fetch(f,B0);if(z0)o0.track(z0.sessionKey,z0.bodyText,k,R,z0.replayHeaders,z0.isSubagent);y.debug("HTTP transport",{pid:process.pid,pathname:M.pathname,accountId:k});try{let S0=await fetch(f,B0);return await f1({sessionID:A,transport:"http",phase:"http",bodyText:B0.body,accountId:k,url:f.toString(),method:B0.method,headers:B0.headers,status:S0.status}),PJ(S0)}catch(S0){throw await f1({sessionID:A,transport:"http",phase:"http",bodyText:B0.body,accountId:k,url:f.toString(),method:B0.method,headers:B0.headers,error:S0 instanceof Error?S0.message:String(S0)}),S0}}function b1(Z,F){if((F?.method??(Z instanceof Request?Z.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof F?.body!=="string")return!1;try{let R=Z instanceof URL?Z.toString():typeof Z==="string"?Z:Z.url;return new URL(R).pathname.endsWith("/responses")}catch{return!1}}function Yz(Z){return m.peekMainForPolicy(Z)?.quota}function HX(Z,F){for(let P of[Z?.primary?.checkedAt,Z?.secondary?.checkedAt,Z?.checkedAt,F])if(typeof P==="number"&&Number.isFinite(P))return P;return}function s1(Z,F,P,R,k){let C=HX(Z,F),A=HX(P),I=R===k&&P!=null&&(Z===void 0||A!==void 0&&(C===void 0||A>C));return{quota:I?P:Z,quotaCheckedAt:I?A:C,source:I?"file":"memory"}}function NX(Z,F,P,R,k){let C=Z?.quota,A=s1(C,Z?.checkedAt,F,R,k),I=A.source,M=A.quota;if(!l4(M,P))return{exhausted:!1};let f=p4(M,P);if(!f)return{exhausted:!1};return{exhausted:!0,source:I,...f}}function VX(Z,F){l.debug("admission skip: exhausted account",{accountId:Z,source:F.source,resetsAt:F.resetsAt})}function Xz(Z,F="killswitch",P){let R=Date.now(),k=m.getMain()?.quota,C=(Z?.accounts??[]).filter((b)=>b.enabled!==!1&&i0(b)).map((b)=>({accountId:b.id,quota:m.getFallback(b.id)?.quota})),A=f4(k,C,R,Z);if(F==="quota-exhausted"&&P!==void 0)A=Math.max(1,Math.ceil((P-R)/1000));else if(F==="mid-stream-rate-limit"&&P!==void 0){let b=Math.max(1,Math.ceil((P-R)/1000));A=Math.min(A,b)}let I=Math.floor(A/60),M=A%60,f=F==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${I}m ${M}s.`:F==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${I}m ${M}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${I}m ${M}s.`;return new Response(JSON.stringify({error:{message:f,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(A)}})}function ZX(Z){let F=Z?.resetCreditsAvailable;return typeof F==="number"&&Number.isFinite(F)?F:void 0}async function Jz(Z){let F=PY(Z.storage),P=Date.now(),R=m.peekMainForPolicy(Z.mainAccountIdentity),k=s1(R?.quota,R?.checkedAt,Z.sidebarState.main.quota,Z.sidebarState.main.mainAccountId,Z.mainAccountIdentity),C=F?MY(R?.quota,Z.storage,void 0,P):void 0,A=[{accountId:"main",wireAccountId:Z.mainAccountIdentity,access:Z.primaryAccess,keepwarmAccountKey:"main",quota:k.quota,quotaCheckedAt:k.quotaCheckedAt,reservePercent:WX(Z.storage),configuredOrder:0,resetCreditsApplicable:ZX(k.quota),killswitchPasses:C}],I=await Y0.getUsableFallbackAccounts(Z.storage);for(let M of I){if(!M.access)continue;let f=Z.sidebarState.fallbacks.find((m0)=>m0.id===M.id),b=m.peekFallbackForPolicy(M.id,M.accountId),X0=s1(b?.quota,b?.checkedAt,f?.quota,f?.accountId,M.accountId),F0=F?MY(b?.quota,Z.storage,M.id,P):void 0;A.push({accountId:M.id,wireAccountId:M.accountId,access:M.access,keepwarmAccountKey:M.id,fallback:M,quota:X0.quota,quotaCheckedAt:X0.quotaCheckedAt,reservePercent:WX(Z.storage,M.id),configuredOrder:A.length,resetCreditsApplicable:ZX(X0.quota),killswitchPasses:F0})}return A}function BX(Z,F,P,R,k){let C=PY(k)?Z.killswitchPasses:void 0;if(Z.accountId==="main"){let f=m.peekMainForPolicy(Z.wireAccountId),b=s1(f?.quota,f?.checkedAt,F.main.quota,F.main.mainAccountId,Z.wireAccountId);return d8({quota:b.quota,quotaCheckedAt:b.quotaCheckedAt,status:P,now:R,killswitchPasses:C})}let A=F.fallbacks.find((f)=>f.id===Z.accountId),I=m.peekFallbackForPolicy(Z.accountId,Z.wireAccountId),M=s1(I?.quota,I?.checkedAt,A?.quota,A?.accountId,Z.wireAccountId);return d8({quota:M.quota,quotaCheckedAt:M.quotaCheckedAt,status:P,now:R,killswitchPasses:C})}function Qz(Z){return Z.accountId==="main"?"main":Z.keepwarmAccountKey}function KX(Z){return m.isRateLimited(Qz(Z))}async function q8(Z){let F=Z.candidates.filter((M)=>!KX(M)),P=new Map(F.map((M)=>[M.accountId,M])),R=Object.fromEntries(F.map((M)=>[M.accountId,M.quotaCheckedAt])),k=Object.fromEntries(F.map((M)=>[M.accountId,M.wireAccountId])),C=new Set(Z.excludeAccountIds),A,I=await r4({sessionId:Z.sessionId,requestBytes:Z.requestBytes,now:Z.now,validPinnedAccountIds:[...P.keys()],excludeAccountIds:Z.excludeAccountIds,quotaCheckedAtByAccount:R,wireAccountIdByAccount:k,choose:(M)=>{let f=F.filter((X0)=>!C.has(X0.accountId));if(f.length===0)return;let b=LJ({candidates:f,pendingBytes:M,requestBytes:Z.requestBytes,now:Z.now,onEmptyWeightedSet:()=>{v.debug("sticky routing: no fresh weighted candidates; using configured order")}});if(!b)return;return A={accountId:b.accountId,source:b.source,pendingBytes:M.get(b.accountId)??0},b}},P0);if(A&&I?.accountId===A.accountId)v.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:EY(Z.sessionId),accountId:A.accountId,source:A.source,requestBytes:Z.requestBytes,pendingBytes:A.pendingBytes});return I?P.get(I.accountId):void 0}async function $z(Z,F){let P=await Y0.getUsableFallbackAccounts(Z),R=[];for(let b of P)if(b.access)R.push({access:b.access,accountId:b.accountId,keepwarmAccountKey:b.id,quotaAccountId:b.id,fallback:b});let k=R.filter((b)=>!m.isRateLimited(b.quotaAccountId)),C=PY(Z)?k.filter((b)=>MY(m.peekFallbackForPolicy(b.quotaAccountId,b.accountId)?.quota,Z,b.quotaAccountId,Date.now())):k,A=new Map(F.fallbacks.map((b)=>[b.id,{quota:b.quota,accountId:b.accountId}])),I=[],M=[],f=Date.now();for(let b of C){let X0=A.get(b.quotaAccountId),F0=NX(m.peekFallbackForPolicy(b.quotaAccountId,b.accountId),X0?.quota,f,X0?.accountId,b.accountId);if(F0.exhausted)M.push({candidate:b,decision:F0});else I.push(b)}return{current:C,retained:I,skipped:M}}function OX(Z,F){if(Z.retained.length===0&&!F)return Z.current;for(let{candidate:P,decision:R}of Z.skipped)VX(P.quotaAccountId,R);return Z.retained}async function FX(Z,F){try{let P=g1(Z.headers);await j1(P,F.access,F.quotaAccountId,void 0,jY(Z.headers))}catch{}}async function Gz(Z,F,P,R){for(let k of R){let C;try{C=await I0(Z,F,k.access,k.accountId,k.keepwarmAccountKey)}catch(A){if(A instanceof DOMException&&A.name==="AbortError")throw A;if(F?.signal?.aborted)throw A;throw v.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:k.quotaAccountId}),A}if(!DY(C.status,P))return Y0.markUsed(k.fallback),{response:C,accessToken:k.access,quotaAccountId:k.quotaAccountId,activeId:k.keepwarmAccountKey};await FX(C,k),C.body?.cancel().catch(()=>{})}return}async function Wz(Z,F,P,R,k){if(!b1(Z,F))return{response:P};if(!k.length)return{response:P};let C=P,A;for(let I of k){let M;try{M=await I0(Z,F,I.access,I.accountId,I.keepwarmAccountKey)}catch(f){if(f instanceof DOMException&&f.name==="AbortError")throw f;if(F?.signal?.aborted)throw f;return v.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:I.quotaAccountId}),{response:C,...A}}if(C.body?.cancel().catch(()=>{}),C=M,A={accessToken:I.access,accountId:I.quotaAccountId},!DY(M.status,R))return Y0.markUsed(I.fallback),{response:M,...A};await FX(M,I)}return{response:C,...A}}if(!K4){if(K4=!0,j){let Z=[];for(let F of j.accounts)if(i0(F))Z.push(F);m.seedFallbacksFromAccounts(Z)}y0(m,j).catch(()=>{}),h1({getAuth:N,codexRefreshFn:S1,refreshMainWithLease:n0,fallbackManager:Y0,quotaManager:m,loadAccounts:D0,writeSidebarState:y0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:G0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:i0,whamFn:W1,respectBackoff:!0}).catch((Z)=>l.warn("boot quota seed failed",{pid:process.pid,error:t0(Z)}))}return O.start(async()=>{let F=(await sX({getAuth:N,codexRefreshFn:S1,refreshMainWithLease:n0,fallbackManager:Y0,quotaManager:m,loadAccounts:D0,writeSidebarState:(P,R)=>O.isStopped()?Promise.resolve():y0(P,R),client:Y.client,fetchImpl:fetch,now:Date.now,configPath:G0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:i0,whamFn:W1,readSidebarState:()=>w1(P0)})).filter((P)=>!P.ok);if(F.length>0)l.warn("background quota refresh completed with failures",{pid:process.pid,failures:F})},(Z)=>{l.warn("background quota refresh failed",{pid:process.pid,error:Z instanceof Error?Z.message:String(Z)})}),{apiKey:wZ,async fetch(Z,F){let P=E4(Z,F),R=w4(P),k=P.get("x-parent-session-id")?.trim()||void 0,C=await x(),A=await N(),I=++H0;if(A.type!=="oauth")return fetch(Z,F);F=await nZ(Z,F);let M=A.access??"";if(!A.access||(A.expires??0)<Date.now()){K0.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(A.access),expiresInMs:A.expires?A.expires-Date.now():void 0});try{let e=await n0();A.access=e.access,A.refresh=e.refresh,A.expires=e.expires}catch(e){if(GX(e))throw e}}M=A.access??"";let b=A.accountId??(M?r1(o1(M)??{}):void 0);if(I===H0)u=b;let X0=C?.routing?.mode??"main-first",F0,z0=await(()=>{return F0??=w1(P0),F0})();if(X0==="sticky-balanced"&&R&&b1(Z,F)&&typeof F?.body==="string"){let e=Buffer.byteLength(F.body,"utf8"),N0=await Jz({storage:C,sidebarState:z0,primaryAccess:M,mainAccountIdentity:b}),L0=await q8({sessionId:R,requestBytes:e,candidates:N0,now:Date.now()});if(L0){let wX=KX(L0)?{action:"migrate",reason:"exhausted"}:BX(L0,z0,void 0,Date.now(),C);if(wX.action==="migrate"){let w0=await q8({sessionId:R,requestBytes:e,candidates:N0,excludeAccountIds:[L0.accountId],now:Date.now()});if(w0)v.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:EY(R),fromAccountId:L0.accountId,toAccountId:w0.accountId,reason:wX.reason}),L0=w0}let c0=await I0(Z,F,L0.access,L0.wireAccountId,L0.keepwarmAccountKey),AX=async(w0,D1)=>{try{let zz=g1(w0.headers);await j1(zz,D1.access,D1.accountId==="main"?void 0:D1.accountId,D1.accountId==="main"?D1.wireAccountId:void 0,jY(w0.headers))}catch{}};await AX(c0,L0);let TX=BX(L0,z0,c0.status,Date.now(),C);if((c0.status===401||c0.status===403||c0.status===429)&&TX.action==="migrate"){let w0=await q8({sessionId:R,requestBytes:e,candidates:N0,excludeAccountIds:[L0.accountId],now:Date.now()});if(w0){v.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:EY(R),fromAccountId:L0.accountId,toAccountId:w0.accountId,reason:TX.reason});let D1=c0;c0=await I0(Z,F,w0.access,w0.wireAccountId,w0.keepwarmAccountKey),D1.body?.cancel().catch(()=>{}),L0=w0,await AX(c0,L0)}}if(L0.fallback&&!DY(c0.status,C))Y0.markUsed(L0.fallback);return await f0(R,k,L0.accountId,X0,C?.accounts).catch(()=>{}),c0}}let B0=NX(m.peekMainForPolicy(b),z0.main.quota,Date.now(),z0.main.mainAccountId,b),S0=PY(C)&&!MY(Yz(b),C,void 0,Date.now()),AY=m.isRateLimited("main"),qX,j8=()=>{return qX??=$z(C,z0),qX},s0,x1,jX=!1,TY;if(X0==="fallback-first"&&b1(Z,F)){jX=!0;let e=await j8();TY=OX(e,!S0&&!AY&&!B0.exhausted);let N0=await Gz(Z,F,C,TY);if(N0)s0=N0.response,x1={accessToken:N0.accessToken,accountId:N0.quotaAccountId,activeId:N0.activeId}}if(!s0){let e=B0.exhausted&&b1(Z,F)&&(await j8()).retained.length>0;if(S0||AY||e){let N0=S0?"killswitch":AY?"mid-stream-rate-limit":"quota-exhausted";if(N0==="quota-exhausted"&&B0.exhausted)VX("main",B0);v.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:N0}),s0=Xz(C,N0,N0==="quota-exhausted"&&B0.exhausted?B0.resetAtMs:AY?m.rateLimitedUntil("main"):void 0)}else s0=await I0(Z,F,M,b,"main")}let DX=Boolean(x1),a1=s0,PX=x1?.accessToken??M,MX=x1?.accountId,EX=x1?.activeId??"main";if(!x1&&!jX&&DY(s0.status,C)){v.debug("reactive fallback triggered",{pid:process.pid,status:s0.status}),TY??=OX(await j8(),!1);let e=await Wz(Z,F,s0,C,TY),N0=e.response;if(N0!==s0){if(DX=!0,a1=N0,PX=e.accessToken??M,MX=e.accountId,e.accountId)EX=e.accountId}}try{let e=g1(a1.headers);if(DX)await j1(e,PX,MX,void 0,jY(a1.headers));else await j1(e,M,void 0,b,jY(a1.headers))}catch{}return await f0(R,k,EX,X0,C?.accounts).catch(()=>{}),a1},async dispose(){if(O.stop(),o0.stop(),G1.__openaiAuthCacheKeepManager===o0)G1.__openaiAuthCacheKeepManager=void 0;if(Y0.stopBackgroundRefresh(),H){await H.stop().catch(()=>{});let Z=globalThis;if(Z.__openaiAuthRpcServer===H)Z.__openaiAuthRpcServer=void 0;H=null}}}},methods:[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:async()=>{let{redirectUri:N}=await k4(),K=await C4(),j=_4(crypto.getRandomValues(new Uint8Array(32)).buffer),w=I4(N,K,j),x=b4(K,j);return{url:w,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let E=await x,S=B8(E);return{type:"success",refresh:E.refresh_token,access:E.access_token,expires:Date.now()+(E.expires_in??3600)*1000,accountId:S}}finally{S4(j)}}}}},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:async()=>{let{deviceData:N,url:K,instructions:j}=await x4();return{url:K,instructions:j,method:"auto",async callback(){try{let w=await v4(N);return{type:"success",refresh:w.refresh_token,access:w.access_token,expires:Date.now()+(w.expires_in??3600)*1000,accountId:B8(w)}}catch{return{type:"failed"}}}}}},{label:"Manually enter API Key",type:"api"}]},"chat.headers":async(N,K)=>{if(N.model.providerID!=="openai")return;if(K.headers.originator="opencode",K.headers["User-Agent"]=`${R4} (${$X.platform()} ${$X.release()}; ${$X.arch()})`,K.headers["session-id"]=N.sessionID,W&&N.agent==="title")K.headers[F1.TITLE_HEADER]="true"},"chat.params":async(N,K)=>{if(N.model.providerID!=="openai")return;K.maxOutputTokens=void 0},config:async(N)=>{N.command={...N.command??{},[_8]:{template:_8,description:"Show current OpenAI Codex OAuth quota usage for all accounts."},[C8]:{template:C8,description:"Manage OpenAI accounts — add, switch, remove, or reorder."},[I8]:{template:I8,description:"Show or change OpenAI account routing between main-first, fallback-first, and sticky-balanced."},[S8]:{template:S8,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."},[k8]:{template:k8,description:"Show or toggle OpenAI Codex request dump capture for debugging."},[b8]:{template:b8,description:"Show or change the plugin log level (error, warn, info, debug, trace)."},[x8]:{template:x8,description:"Keep Codex prompt cache alive during idle by shadow-replaying the last request."},[E1]:{template:E1,description:"Spend one reset credit on an exhausted Codex account."}}},"command.execute.before":async(N)=>{if(!oX.includes(N.command))return;if(!L)await B(N.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),D4();let K=N.command,j={...L,sessionId:N.sessionID,notify:(x)=>{X9(x,N.sessionID)}},w=await v8(K,N.arguments,j);if(bJ(N.sessionID))X9(w,N.sessionID);else await B(N.sessionID,w.text);D4()}}}var YB=async(Y)=>{let X=A0();return eZ(Y,{codexApiEndpoint:X.codexApiEndpoint,experimentalWebSockets:X.webSockets,responsesLite:X.responsesLite})},RD={id:"cortexkit-openai-auth",server:YB};export{w4 as resolveSidebarSessionId,o1 as parseJwtClaims,M4 as mergePushedQuotaMetadata,iZ as findCachekeepFallbackAccount,r1 as extractAccountIdFromClaims,RD as default,vZ as createResetTargetResolver,TD as buildSidebarState,e4 as buildSidebarMachineState,hZ as buildResetRedemptionDeps,d0 as ResetTargetResolutionError,YB as OpenAIAuthPlugin,CZ as MAIN_REFRESH_LOCK_TTL_MS,IZ as MAIN_REFRESH_LEASE_TTL_MS,eZ as CodexAuthPlugin,LX as AuthPersistError};
|
|
217
|
+
`)),W=!0,Q0.type!=="response.created"&&Q0.type!=="response.in_progress")U=!0;if(A("idle timeout waiting for websocket"),!Q0)return;if(Q0.type==="response.completed"||Q0.type==="response.done"){G=!0,oV(Q0,H),Y.onComplete?.(Q0,H),Y.onTerminal?.(Q0),B();return}if(Q0.type==="response.failed"||Q0.type==="response.incomplete"||Q0.type==="error")G=!0,Y.onTerminal?.(Q0),B()}function E(v){K(new C0(t0(v),{cause:v}))}function S(v){if(G)return;K(new C0(J4("WebSocket closed before response.completed",v.code,v.reason)))}function y(){let v=t9(Y.signal);if(G)return;G=!0,V(),O(),Y.onAbort?.(v),Q?.error(v)}function l(v){if(G)return;G=!0,V(),O(),Y.onAbort?.(sV(v))}function K0(v){$(),J=v,J.addEventListener("message",x),J.addEventListener("error",E,{once:!0}),J.addEventListener("close",S,{once:!0}),$=()=>{J.removeEventListener("message",x),J.removeEventListener("error",E),J.removeEventListener("close",S)};let{background:f,...u}=Y.body;A("idle timeout sending websocket request");try{J.send(JSON.stringify({type:"response.create",...u})),A("idle timeout waiting for websocket")}catch(N0){if(G)return;N(new C0(N0 instanceof Error?N0.message:String(N0),{cause:N0}))}}return new Response(new ReadableStream({start(v){if(Q=v,Y.signal?.addEventListener("abort",y,{once:!0}),Y.signal?.aborted){y();return}K0(J)},cancel(v){l(v)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function dV(Y,X){if(!iV(Y))return;await e0({component:"ws",event:"provider_native_web_search_event",sessionID:X,serverEventType:Y.type,itemType:_(Y.item)?Y.item.type:void 0,serverEvent:Y})}function iV(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 nV(Y,X){if(Y.type!=="response.output_item.done")return;if(!_(Y.item))return;X4(Y.item,X)}function oV(Y,X){let J=Y.response;if(!_(J)||!Array.isArray(J.output))return;for(let Q of J.output)if(_(Q))X4(Q,X)}function X4(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 rV(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 FY(Y){if(typeof Y==="string")try{return FY(JSON.parse(Y))}catch{return}if(!_(Y))return;let X=FY(Y.cause);if(X)return X;let J=FY(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 sV(Y){if(e9(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function t9(Y){let X=Y?.reason;if(e9(X))return X;if(aV(X))return X;return new DOMException(X instanceof Error?X.message:"Aborted","AbortError")}function aV(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function J4(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 XX="x-opencode-title",V8="x-openai-auth-quota-account",YX=new Set([XX,z1,V8,"x-opencode-session"]),eV=15000,YZ=300000,XZ=3300000,Q4="websocket_connection_limit_reached";function JZ(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 tV("sha256").update(Q).digest("hex").slice(0,12)}function QZ(Y){let X=Y?.httpFetch??globalThis.fetch,J=new Map,Q=Y?.connectTimeout??eV,$=Y?.idleTimeout??YZ,G=Y?.maxConnectionAge??XZ,W=Y?.streamRetries??5,U=Y?.firstEventGraceMs??250,L=Y?.rawWebSocket??!1,H=Y?.onQuota,V=Y?.onRateLimitReached,O=setInterval(()=>j(),Math.min($,60000));if(typeof O==="object"&&"unref"in O&&typeof O.unref==="function")O.unref();function B(E,S,y){if(!S||!y)return y;JX(E,$4(S));let l=new Headers(y.headers),K0=l.get("x-codex-turn-metadata");if(!K0)return y;let v=V4(K0,E.turnID,E.turnStartedAt);if(!v)return y;return l.set("x-codex-turn-metadata",v),{...y,headers:l}}async function N(E,S){let y=E instanceof URL?E.toString():typeof E==="string"?E:E.url,l=E0.normalizeHeaders(S?.headers),K0=K4(S),v=gY(K0);if(S?.method!=="POST"||!new URL(y).pathname.endsWith("/responses"))return X(E,v);let f=(()=>{try{if(typeof S?.body!=="string")return;let r=JSON.parse(S.body);return typeof r==="object"&&r!==null?r:void 0}catch{return}})();if(!f?.stream)return X(E,v);if(l[XX]==="true")return X(E,v);let u=l[z1]??l["x-session-affinity"]??l["session-id"],N0=u;if(!u)return X(E,v);let Y0=E0.normalizeHeaders(K0?.headers),Q0=JZ(Y0),q1=`${u}:${Q0}:conversation`,d=typeof l[V8]==="string"?l[V8]:void 0,g0=V?(r,O0)=>V(r,d,O0):void 0,g=J.get(q1)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};if(J.set(q1,g),g.fallback)return X(E,B(g,f,v));if(g.busy)return X(E,B(g,f,v));g.busy=!0,g.lastUsedAt=Date.now();try{let r=$4(f),O0=E0.normalizeHeaders(K0?.headers),O8=typeof O0.authorization==="string"&&O0.authorization.startsWith("Bearer ")?O0.authorization.slice(7):"",k1=typeof O0["chatgpt-account-id"]==="string"?O0["chatgpt-account-id"]:void 0,AY=H?($0)=>H($0,O8,d,k1):void 0,n0=!g.socket&&!g.continuation?NZ(O0):O0;if(g.socket=await WZ(g,Y?.url??y,n0,Q,G,L,S?.signal),KZ(g,r))await zZ(g,r,$,{signal:S?.signal??void 0,sessionID:N0,url:Y?.url??y,headers:K0?.headers,onRateLimitReached:g0});let G1=()=>{},o0=()=>{},j1=new Promise(($0,I0)=>{G1=$0,o0=I0}),F8=BZ(g,r),r0=qY(N4(g,F8,r)),P0=typeof r0.previous_response_id==="string";await f1({sessionID:N0,transport:"websocket",phase:"main",bodyText:JSON.stringify(r0),url:Y?.url??y,method:K0?.method,headers:K0?.headers});let y0=E0.streamResponsesWebSocket({socket:g.socket,body:r0,sessionID:N0??void 0,idleTimeout:$,signal:S?.signal??void 0,onQuota:AY,onRateLimitReached:g0,onFirstEvent:($0)=>G1($0??!0),onComplete:($0,I0)=>{let b1=z4($0);e0({component:"ws-pool",event:"main_completed",sessionID:N0,responseID:W4($0),usage:b1}),H4(g,r,$0,I0,P0)},onTerminal:($0)=>{if(g.busy=!1,g.lastUsedAt=Date.now(),g.streamFailures=0,$0.type!=="response.completed"&&$0.type!=="response.done")g.continuation=void 0,$1(g)},onConnectionInvalid:()=>{if(g.busy=!1,g.lastUsedAt=Date.now(),!g.fallback)K(g);g.continuation=void 0,$1(g),G1(!1)},onAbort:($0)=>{g.busy=!1,g.lastUsedAt=Date.now(),g.streamFailures=0,g.continuation=void 0,$1(g),o0($0)},onRetryableTerminal:async($0)=>{let I0=G4($0);if(!I0)return;throw g.fallback=!0,I0}}),f0=await $Z(j1,U);if(f0!==!1){if(f0===!0||f0.status<200||f0.status>599)return y0;return new Response(f0.body,{status:f0.status,headers:{"content-type":"application/json",...f0.headers}})}if(!g.fallback)return y0;return X(E,B(g,f,v))}catch(r){if(g.busy=!1,g.lastUsedAt=Date.now(),E0.isAbortError(r))throw g.streamFailures=0,g.continuation=void 0,$1(g),r;let O0=E0.parseRateLimitSignal(r);if(O0)g0?.(O0.window,O0.resetAt);if(E0.isUpgradeFailure(r)&&!L)g.fallback=!0;if(K(g),g.continuation=void 0,$1(g),g.fallback)return X(E,B(g,f,v));return GZ(new C0(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[S,y]of J){if(y.busy)continue;if(E-y.lastUsedAt<$)continue;$1(y),J.delete(S)}}function A(){clearInterval(O);for(let E of J.values())$1(E);J.clear()}function x(E){let S=`${E}:`;for(let[y,l]of J){if(!y.startsWith(S))continue;$1(l),J.delete(y)}}return Object.assign(N,{close:A,remove:x})}function G4(Y){if(Y.type!=="error"||!_(Y.error)||Y.error.code!==Q4)return;return Error(typeof Y.error.message==="string"?Y.error.message:Q4)}async function $Z(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 GZ(Y){return new Response(new ReadableStream({start(X){X.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function WZ(Y,X,J,Q,$,G,W){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<$)return Y.socket;$1(Y);let U=await E0.connectResponsesWebSocket({url:E0.toWebSocketUrl(X),headers:J,timeout:Q,rawWebSocket:G,signal:W??void 0});return Y.connectedAt=Date.now(),U}function $1(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function zZ(Y,X,J,Q){if(!Y.socket||!Array.isArray(X.input)||X.input.length===0)return;let $=LZ(X);await f1({sessionID:Q.sessionID,transport:"websocket",phase:"prewarm",bodyText:JSON.stringify($),url:Q.url,method:"POST",headers:Q.headers});let G=E0.streamResponsesWebSocket({socket:Y.socket,body:$,sessionID:Q.sessionID,idleTimeout:J,signal:Q.signal,onRateLimitReached:Q.onRateLimitReached,onComplete:(W,U)=>{e0({component:"ws-pool",event:"prewarm_completed",sessionID:Q.sessionID,responseID:W4(W),usage:z4(W)}),H4(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=G4(W);if(!U)return;throw Y.fallback=!0,U}});await UZ(G)}function W4(Y){let X=Y.response;if(!_(X))return;return typeof X.id==="string"?X.id:void 0}function z4(Y){let X=Y.response;if(!_(X))return;return _(X.usage)?X.usage:void 0}async function UZ(Y){let X=Y.body?.getReader();if(!X)return;while(!0)if((await X.read()).done)return}function LZ(Y){return qY({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:HZ(Y.client_metadata)})}function U4(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 HZ(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":U4(X),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function NZ(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":U4(J)}}catch{return Y}}var L4=["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 $4(Y){let X={...Y};if(Array.isArray(Y.input))X.input=Y.input.map(VZ);return X}function qY(Y){let X={};for(let J of L4)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 VZ(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 H4(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:QX(X),finalizedCallIds:U}}function JX(Y,X,J=X){let Q=Array.isArray(X.input)?X.input:[],$=Array.isArray(J.input)?J.input:Q,G=QX(J),W=Y.turnInput&&Y.turnSignature===G?ZZ(Y.turnInput,$):void 0,U=W===void 0?Q:$.slice(W);if(U.length>0&&U.some(Z4)||!Y.turnID)Y.turnID=w1(),Y.turnStartedAt=Date.now();Y.turnInput=$.slice(),Y.turnSignature=G}function N4(Y,X,J=X){JX(Y,X,J);let Q=X.client_metadata;if(!_(Q)||typeof Q["x-codex-turn-metadata"]!=="string")return X;let $=V4(Q["x-codex-turn-metadata"],Y.turnID,Y.turnStartedAt);if(!$)return X;return{...X,client_metadata:{...Q,"x-codex-turn-metadata":$}}}function V4(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 ZZ(Y,X){if(Y.length>X.length)return;for(let J=0;J<Y.length;J++)if(Y1(Y[J])!==Y1(X[J]))return;return Y.length}function BZ(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!J||!Y.continuation)return X;if(Y.continuation.signature!==QX(X))return Y.continuation=void 0,X;if(!B4(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),$=OZ(Q,Y.continuation.finalizedCallIds);if($.length===0)return X;return{...X,previous_response_id:Y.continuation.responseID,input:$}}function KZ(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!Y.continuation)return!0;if(!J)return!1;if(!B4(Y.continuation.input,J))return!0;return J.slice(Y.continuation.input.length).some(Z4)}function Z4(Y){if(!_(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function OZ(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 QX(Y){return Y1(FZ(Object.fromEntries(Object.entries(Y).filter(([X])=>X!=="input"&&X!=="stream"&&X!=="background"&&X!=="previous_response_id"&&X!=="generate"))))}function FZ(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 B4(Y,X){if(Y.length>=X.length)return!1;for(let J=0;J<Y.length;J++)if(Y1(Y[J])!==Y1(X[J]))return!1;return!0}function K4(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let X=new Headers(Y.headers);for(let J of YX)X.delete(J);return{...Y,headers:X}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((X)=>!YX.has(X[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([X])=>!YX.has(X.toLowerCase())))}}var AZ=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),wZ=new Set(["gpt-5.6","gpt-6"]),TZ=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-6-astra"]),RZ="opencode-oauth-dummy-key",_Z="terminal_resize_reflow",zX="0.153.0",CZ=`codex_exec/${zX} (Debian 12.0.0; aarch64) unknown (codex_exec; ${zX})`,IZ="seccomp",SZ="main-refresh",kZ=120000,bZ=90000,xZ=4000,O4=50,F4=3,vZ=25,hZ=60000,gZ="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",q4=!1,j4=H0("models"),D4=!1,P4=!1;class LX 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 d0 extends Error{code;constructor(Y,X){super(X);this.name="ResetTargetResolutionError",this.code=Y}}function M4(Y,X,J,Q){let $=(J?.refresh?.refreshBeforeExpiryMinutes??240)*60000;return!Y||!X||X-Q<=$}function yZ(Y){return async(X)=>{if(X==="main"){let U=await Y.loadAccounts(Y.accountStoragePath),L=await Y.getAuth();if(L.type!=="oauth")throw new d0("non_oauth_account","Main OpenAI account is not authenticated with OAuth.");if(M4(L.access,L.expires,U,Y.now()))L={type:"oauth",...await Y.refreshMainWithLease()};if(!L.access)throw new d0("token_unavailable","Main OpenAI account has no usable access token.");let H=o1(L.access),V=H?r1(H):void 0,O=await Y.loadAccounts(Y.accountStoragePath);return{accountKey:X,label:"Main account",accessToken:L.access,chatgptAccountId:V??O?.mainAccountId}}let J=await Y.loadAccounts(Y.accountStoragePath),Q=J?.accounts.find((U)=>U.id===X);if(!J||!Q)throw new d0("unknown_account",`Fallback account ${X} was not found.`);if(Q.enabled===!1)throw new d0("disabled_account",`Fallback account ${X} is disabled.`);if(!i0(Q))throw new d0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);let $=Q;if(M4($.access,$.expires,J,Y.now()))$=await Y.refreshFallbackAccount($,J);if(!$.access)throw new d0("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 d0("unknown_account",`Fallback account ${X} was not found.`);if(W.enabled===!1)throw new d0("disabled_account",`Fallback account ${X} is disabled.`);if(!i0(W))throw new d0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);return{accountKey:X,label:$.label??X,accessToken:$.access,chatgptAccountId:W.accountId}}}function fZ(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function GX(Y){return Y instanceof LX}function E4(){throw Error(gZ)}function mZ(Y){return Math.floor(Math.random()*Y)}function cZ(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 uZ(Y,X,J){let Q=Y.get(X);if(Q)return Q;let $=w1(),G={threadID:$,turnID:w1(),windowID:`${$}:0`};return Y.set(X,G),J?.(),G}function Xz(){return EZ(CY(),"openai-auth-sessions.json")}function pZ(){let Y=new Map;try{let X=JSON.parse(jZ(Xz(),"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:w1(),windowID:`${Q.threadID}:0`})}}catch{}return Y}function lZ(Y){let X=Xz(),J=`${X}.tmp-${process.pid}`;try{qZ(CY(),{recursive:!0});let Q={version:1,sessions:Object.fromEntries([...Y.entries()].map(([$,G])=>[$,{threadID:G.threadID}]))};MZ(J,`${JSON.stringify(Q,null,2)}
|
|
218
|
+
`,"utf8"),DZ(J,X)}catch{}}function A4(Y,X){return _(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===X}function dZ(Y,X){if(Y.length>X.length)return!1;for(let J=0;J<Y.length;J++)if(Y1(Y[J])!==Y1(X[J]))return!1;return!0}function iZ(Y,X){if(!Y.input)return X.length>0;if(!dZ(Y.input,X))return!0;return X.slice(Y.input.length).some((Q)=>A4(Q,"user")||A4(Q,"developer"))}function nZ(Y,X){let J=Array.isArray(X?.input)?X.input:void 0;if(J&&(iZ(Y,J)||!Y.turnID))Y.turnID=w1(),Y.turnStartedAt=Date.now();else if(!Y.turnStartedAt)Y.turnStartedAt=Date.now();if(J)Y.input=J}function oZ(Y){if(!Y.metadata)return{init:Y.init};let X=cZ(Y.init?.body);if(!Y.websocket)nZ(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:IZ,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",_Z),Y.headers.set("x-codex-turn-metadata",J),Y.headers.set("user-agent",CZ),Y.headers.set("version",zX),Y.dumpSessionID)Y.headers.set(z1,Y.dumpSessionID);let Q=X;if(!Q)return{init:Y.init};let $=Y.responsesLite&&typeof Q.model==="string"&&TZ.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(XB);if(eZ(Q),YB(Q),AJ(Q),aZ(Q),$)tZ(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(qY(Q))}}}function rZ(Y,X){return Y.find((J)=>J.enabled!==!1&&i0(J)&&(J.id===X||J.accountId===X))}function w4(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 Z8(Y,X){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:X}}function Jz(Y,X,J=Date.now(),Q=X.mainAccountId){let $=Y.getMain(),G=$?.quota;return{main:{quota:G?{...G,checkedAt:$.checkedAt,primary:Z8(G.primary,$.checkedAt),secondary:Z8(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:Z8(L.primary,U.checkedAt),secondary:Z8(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 CD(Y,X,J,Q=Date.now()){return{...Jz(Y,X,Q),activeId:J}}function T4(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 sZ(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 R4(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}function aZ(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 UX(Y){if(Array.isArray(Y)){for(let X of Y)UX(X);return}if(!_(Y))return;if(Y.type==="input_image")delete Y.detail;for(let X of Object.values(Y))UX(X)}function tZ(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:[];UX(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 eZ(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(_(X)&&X.type==="function"&&X.name==="web_search"))}function YB(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(_(X)&&X.type==="function"&&X.name==="websearch_web_search_exa"))}function XB(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 JB(Y,X={}){let J=X.codexApiEndpoint??w0().codexApiEndpoint,Q=crypto.randomUUID(),$=pZ(),G=()=>lZ($),W=!1,U=[],L=null,H=null,V,O=new g8;async function B(N,K){let j=Y.client.session;if(typeof j?.promptAsync==="function"){let A=await kJ(Y.client,N),x={noReply:!0,parts:[{type:"text",text:K,ignored:!0}]};if(A?.agent)x.agent=A.agent;if(A?.model)x.model=A.model;if(A?.variant)x.variant=A.variant;await j.promptAsync({path:{id:N},body:x});return}}return{async dispose(){O.stop();for(let N of U)N.close();if(U.length=0,H){await H.stop().catch(()=>{});let N=globalThis;if(N.__openaiAuthRpcServer===H)N.__openaiAuthRpcServer=void 0;H=null}},async event(N){if(N.event.type!=="session.deleted")return;let K=N.event.properties.info,j=$.get(K.id);if(j)L?.cacheKeepManager?.remove(j.threadID);if($.delete(K.id))G();if(V){let A=(await D0(G0()))?.accounts;await a4(K.id,A,V)}for(let A of U)A.remove(K.id)},provider:{id:"openai",async models(N,K){if(K.auth?.type!=="oauth")return N.models;let j=await D0(G0()),A=!j||c4(j),x=A?null:await _J();if(!A&&x&&!D4)D4=!0,j4.debug("restoring OAuth model costs from models.dev catalog");if(!A&&!x&&!P4)P4=!0,j4.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(N.models).filter(([,E])=>{if(E.options.reasoningMode==="pro")return!1;if(AZ.has(E.api.id))return!0;if(wZ.has(E.api.id))return!1;let y=E.api.id.match(/^gpt-(\d+(?:\.\d+)?)/)?.[1];return y?parseFloat(y)>5.4:!1}).map(([E,S])=>[E,{...S,cost:A?{input:0,output:0,cache:{read:0,write:0}}:x?.[S.api.id]??x?.[E]??S.cost,limit:S.id.includes("gpt-5.5")?{context:400000,input:272000,output:128000}:S.id.includes("gpt-6-astra")?{context:872000,input:744000,output:128000}:S.id.includes("gpt-5.6")?{context:372000,input:244000,output:128000}:S.limit}]))}},tool:{web_search:MJ},auth:{provider:"openai",async loader(N){let K=await N();if(K.type!=="oauth")return{};await p4({type:"oauth",access:K.access??"",refresh:K.refresh??"",expires:K.expires??0},G0());let j=await D0(G0()).catch((Z)=>{let F=G0();throw Error(`OpenAI auth store at ${F} is corrupt or unreadable: ${Z instanceof Error?Z.message:String(Z)}. Fix or remove it to continue.`,{cause:Z})}),A;async function x(){let Z=G0();try{let F=PZ(Z);if(A?.path===Z&&A.mtimeMs===F.mtimeMs&&A.size===F.size)return A.storage;let P=await D0(Z);return A={path:Z,mtimeMs:F.mtimeMs,size:F.size,storage:P},P}catch{return A=void 0,D0(Z)}}function E(){A=void 0}if(j&&K.access){let Z=B8({id_token:"",access_token:K.access,refresh_token:K.refresh??""});if(Z&&Z!==j.mainAccountId)await J0((F)=>{return F.mainAccountId=Z,F},G0()),j.mainAccountId=Z,E()}let S=j?.logging?.level;if(S&&typeof S==="string")bY(S);let y=H0("transport"),l=H0("quota"),K0=H0("refresh"),v=H0("accounts");y.info("codex auth loader ready",{codexApiEndpoint:J,transport:w0().rawWebSocket?"raw-websocket":w0().webSockets?"websocket":"http",webSearch:w0().webSearch});let f=new m4({storage:j,fetchQuotaFn:void 0}),u,N0=0,Y0=new l4({refreshFn:(Z)=>S1({refreshToken:Z.refreshToken,fetchImpl:Z.fetchImpl,now:Z.now}),quotaManager:f,onFallbackStorageChanged:E});if(j&&j.accounts.length>0)Y0.startBackgroundRefresh();let Q0=H0("cachekeep"),q1=j?.cachekeep?.enabled===!0,d=j?.cachekeep?.subagents===!0,g0=j?.cachekeep?.sustain===!0,g=$J(j),r;async function O0(Z){await new Promise((F)=>setTimeout(F,Z))}async function O8(Z){let F;for(let P=1;P<=F4;P++)try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:Z.refresh,access:Z.access,expires:Z.expires}});return}catch(R){if(F=R,P<F4)await O0(vZ*P)}throw new LX(F)}async function k1(Z){await J0((F)=>{return F.refresh=F.refresh??{},Z(F),F},G0()),E()}async function AY(Z){let F=Date.now()+xZ;while(Date.now()<F){await new Promise((k)=>setTimeout(k,O4+mZ(O4)));let P=await N();if(P.type!=="oauth"||!P.access)continue;if((P.access!==Z.access||P.refresh!==Z.refresh||(P.expires??0)>(Z.expires??0)+60000)&&(!P.expires||P.expires>Date.now()))return K0.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:P.expires?P.expires-Date.now():void 0}),{access:P.access,refresh:P.refresh??Z.refresh??"",expires:P.expires??0}}return null}async function n0(){if(!r)r=(async()=>{let Z=await N();if(Z.type!=="oauth")throw Error("not oauth");if(!Z.refresh)throw Error("Token refresh failed: missing refresh token");let F=_4(Z.refresh),P=await D0(G0()),R=P?.refresh?.mainLastRefreshError;if(R&&xY(R,Z.refresh,Date.now()))throw Error(vY(R,Date.now()));if(P?.refresh?.mainRefreshLeaseUntil&&P.refresh.mainRefreshLeaseUntil>Date.now()&&P.refresh.mainRefreshLeaseTokenHash===F){let I=await AY(Z);if(I)return I;throw Error("Codex OAuth refresh is already in progress")}let k=await hY({name:SZ,ttlMs:kZ,path:G0(),renew:!0});if(!k){let I=await AY(Z);if(I)return I;throw Error("Codex OAuth refresh is already in progress")}let C=crypto.randomUUID(),w=F;try{await k1((m)=>{m.refresh=m.refresh??{},m.refresh.mainRefreshLeaseId=C,m.refresh.mainRefreshLeaseUntil=Date.now()+bZ,m.refresh.mainRefreshLeaseTokenHash=F});let I=await D0(G0());if(I?.refresh?.mainRefreshLeaseId!==C||I.refresh.mainRefreshLeaseTokenHash!==F)throw Error("Codex OAuth refresh is already in progress");let M=await S1({refreshToken:Z.refresh,fetchImpl:fetch,now:Date.now});return await O8(M),await k1((m)=>{if(m.refresh=m.refresh??{},m.refresh.mainLastRefreshError=void 0,m.refresh.mainRefreshLeaseId===C)m.refresh.mainRefreshLeaseId=void 0,m.refresh.mainRefreshLeaseUntil=void 0,m.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),w=void 0,M}catch(I){if(Z.refresh&&!GX(I))await k1((M)=>{M.refresh=M.refresh??{},M.refresh.mainLastRefreshError=C4({error:I,now:Date.now(),refreshToken:Z.refresh??"",previous:M.refresh.mainLastRefreshError})}).catch(()=>{});throw I}finally{if(w)await k1((I)=>{if(I.refresh?.mainRefreshLeaseId===C&&I.refresh.mainRefreshLeaseTokenHash===w)I.refresh.mainRefreshLeaseId=void 0,I.refresh.mainRefreshLeaseUntil=void 0,I.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await k.release().catch(()=>{})}})().finally(()=>{r=void 0});return r}let G1=globalThis;G1.__openaiAuthCacheKeepManager?.stop();let o0=new u8({fetchImpl:fetch,getMainToken:async()=>{let Z=await N();if(Z.type!=="oauth")throw Error("not oauth");if(!Z.access||(Z.expires??0)<Date.now())try{return(await n0()).access}catch(F){if(GX(F))throw F;if(Z.access)return Z.access;throw Error("main token refresh failed")}return Z.access},refreshFallback:async(Z)=>{let F=await x(),P=F?rZ(F.accounts,Z):void 0;if(!P)throw Error(`fallback account ${Z} not found`);let R=await Y0.refreshAccount(P,F??{version:1,accounts:[P]});if(!R.access)throw Error(`no access token for ${Z}`);return R.access},codexResponsesUrl:J,logger:Q0,now:Date.now,getWindow:()=>g,getSustain:()=>g0});G1.__openaiAuthCacheKeepManager=o0;async function j1(Z,F,P,R,k=!1){if(Object.keys(Z).length===0&&!k)return;let C=Date.now(),w=Z,I={quota:w,refreshAfter:C+300000,checkedAt:C},M;if(P&&P!=="main"){let b=F?o1(F):null,X0=b?r1(b):void 0,F0=f.peekFallbackForPolicy(P)?.quota,m0=w4(w,F0);I={...I,quota:m0},f.setFallback(P,I,F,k,X0)}else{if(M=R,!M&&F){let F0=o1(F);M=F0?r1(F0):void 0}if(M&&u&&M!==u){l.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:M,currentMainIdentity:u});return}let b=f.peekMainForPolicy(M)?.quota,X0=w4(w,b);I={...I,quota:X0},f.setMain(F,I,M,k)}l.debug("quota pushed",{pid:process.pid,accountId:P??"main",snapshot:I.quota});let m=await x();await y0(f,m,P&&P!=="main"?m?.mainAccountId:M)}function F8(Z,F,P){let R=Z==="main"?f.peekMainForPolicy()?.quota:f.peekFallbackForPolicy(Z)?.quota;return f4(R,F,Date.now(),hZ,P)}let r0=X.experimentalWebSockets?F1.createWebSocketFetch({httpFetch:fetch,rawWebSocket:w0().rawWebSocket,onQuota:(Z,F,P,R)=>{j1(Z,F,P,!P||P==="main"?R:void 0,!0)},onRateLimitReached:(Z,F,P)=>{if(!F)l.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:Z});let R=F??"main",k=F8(R,Z,P);f.markRateLimited(R,k),l.debug("mid-stream rate limit mark",{pid:process.pid,accountId:R,window:Z})}}):void 0;if(r0)U.push(r0),W=!0;let P0=d4();V=P0;async function y0(Z,F,P=F?.mainAccountId){if(!F)return;await r4(Jz(Z,F,Date.now(),P),P0)}async function f0(Z,F,P,R,k){let C={activeId:P,route:R,updatedAt:Date.now()};if(Z){if(await K8({sessionId:Z,...C},k,P0),F&&F!==Z){if(R==="sticky-balanced"){let w=(await A1(P0)).stickyAssignments?.[EY(F)]?.accountId,I=k===void 0||w==="main"||k.some((M)=>M.enabled!==!1&&M.id===w);if(!w||!I)return;await K8({sessionId:F,activeId:w,route:R,updatedAt:Date.now()},k,P0);return}await K8({sessionId:F,...C},k,P0)}return}await s4(C,P0)}L={accountStoragePath:G0(),quotaManager:f,loadAccounts:D0,client:Y.client,resolveResetTarget:yZ({getAuth:N,refreshMainWithLease:n0,refreshFallbackAccount:(Z,F)=>Y0.refreshAccount(Z,F),loadAccounts:D0,accountStoragePath:G0(),now:Date.now}),...fZ(),cacheKeepManager:o0,setCacheKeepEnabled:(Z)=>{q1=Z},setCacheKeepSubagents:(Z)=>{d=Z},setCacheKeepSustain:(Z)=>{g0=Z},setCacheKeepWindow:(Z)=>{g=Z},clearStickyRouting:(Z)=>e4(Z,P0),getStickyRouting:async(Z)=>o4(await A1(P0),Z),refreshSidebar:async()=>{let Z=await D0(G0());await y0(f,Z)},refreshAllQuota:async()=>h1({getAuth:N,codexRefreshFn:S1,refreshMainWithLease:n0,fallbackManager:Y0,quotaManager:f,loadAccounts:D0,writeSidebarState:y0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:G0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:i0,whamFn:W1}),refreshResetTargetQuota:async(Z)=>{return(await h1({getAuth:N,codexRefreshFn:S1,refreshMainWithLease:n0,fallbackManager:Y0,quotaManager:f,loadAccounts:D0,writeSidebarState:y0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:G0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:i0,whamFn:W1,respectBackoff:!1},{accountKey:Z})).find((P)=>P.account===Z)??{account:Z,ok:!1,error:"targeted quota refresh returned no result"}}};let $0=null;if(Y.directory){let Z=await Yz(Y.directory),F=globalThis;if(F.__openaiAuthRpcServer)await F.__openaiAuthRpcServer.stop().catch(()=>{}),F.__openaiAuthRpcServer=void 0;try{$0=await fJ({dir:Z.dir,secureDir:Z.secureDir,sweepRoot:Z.sweepRoot,drain:xJ,apply:async(P)=>{let R={...L,sessionId:P.sessionId},k=await v8(P.command,P.arguments,R);return{text:k.text,knobs:k.knobs}}}),F.__openaiAuthRpcServer=$0,H=$0}catch{}}async function I0(Z,F,P,R,k="main"){let C=T4(Z,F);if(C.delete("x-api-key"),C.delete("api-key"),C.set("authorization",`Bearer ${P}`),R)C.set("ChatGPT-Account-Id",R);C.set(F1.QUOTA_ACCOUNT_HEADER,k);let w=R4(C),I=w?uZ($,w,G):void 0,M=Z instanceof URL?Z:new URL(typeof Z==="string"?Z:Z.url),m=M.pathname.includes("/v1/responses")||M.pathname.includes("/chat/completions")?new URL(J):M,X0=oZ({init:{...F,headers:C},headers:C,metadata:I,installationID:Q,websocket:Boolean(r0&&M.pathname.endsWith("/responses")),responsesLite:X.responsesLite??!1,dumpSessionID:w}).init,F0=q1,m0=new Headers(X0?.headers),z0=QJ({enabled:F0,includeSubagents:d,headers:m0,body:X0?.body});if(F0)Q0.trace("cachekeep headers",{pid:process.pid,hasParent:m0.has("x-parent-session-id"),sessionKey:z0?.sessionKey,captured:Boolean(z0),affinity:m0.get("x-session-affinity"),opencodeSession:m0.get("x-opencode-session"),sessionId:m0.get("session-id")});if(r0&&M.pathname.endsWith("/responses")){if(y.debug("WS transport",{pid:process.pid,pathname:M.pathname,accountId:k}),z0)o0.track(z0.sessionKey,z0.bodyText,k,R,z0.replayHeaders,z0.isSubagent);return r0(m,X0)}let B0=F1.withoutInternalHeaders(X0);if(typeof B0?.body!=="string")return fetch(m,B0);if(z0)o0.track(z0.sessionKey,z0.bodyText,k,R,z0.replayHeaders,z0.isSubagent);y.debug("HTTP transport",{pid:process.pid,pathname:M.pathname,accountId:k});try{let S0=await fetch(m,B0);return await f1({sessionID:w,transport:"http",phase:"http",bodyText:B0.body,accountId:k,url:m.toString(),method:B0.method,headers:B0.headers,status:S0.status}),EJ(S0)}catch(S0){throw await f1({sessionID:w,transport:"http",phase:"http",bodyText:B0.body,accountId:k,url:m.toString(),method:B0.method,headers:B0.headers,error:S0 instanceof Error?S0.message:String(S0)}),S0}}function b1(Z,F){if((F?.method??(Z instanceof Request?Z.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof F?.body!=="string")return!1;try{let R=Z instanceof URL?Z.toString():typeof Z==="string"?Z:Z.url;return new URL(R).pathname.endsWith("/responses")}catch{return!1}}function Qz(Z){return f.peekMainForPolicy(Z)?.quota}function HX(Z,F){for(let P of[Z?.primary?.checkedAt,Z?.secondary?.checkedAt,Z?.checkedAt,F])if(typeof P==="number"&&Number.isFinite(P))return P;return}function s1(Z,F,P,R,k){let C=HX(Z,F),w=HX(P),I=R===k&&P!=null&&(Z===void 0||w!==void 0&&(C===void 0||w>C));return{quota:I?P:Z,quotaCheckedAt:I?w:C,source:I?"file":"memory"}}function NX(Z,F,P,R,k){let C=Z?.quota,w=s1(C,Z?.checkedAt,F,R,k),I=w.source,M=w.quota;if(!n4(M,P))return{exhausted:!1};let m=i4(M,P);if(!m)return{exhausted:!1};return{exhausted:!0,source:I,...m}}function VX(Z,F){l.debug("admission skip: exhausted account",{accountId:Z,source:F.source,resetsAt:F.resetsAt})}function $z(Z,F="killswitch",P){let R=Date.now(),k=f.getMain()?.quota,C=(Z?.accounts??[]).filter((b)=>b.enabled!==!1&&i0(b)).map((b)=>({accountId:b.id,quota:f.getFallback(b.id)?.quota})),w=u4(k,C,R,Z);if(F==="quota-exhausted"&&P!==void 0)w=Math.max(1,Math.ceil((P-R)/1000));else if(F==="mid-stream-rate-limit"&&P!==void 0){let b=Math.max(1,Math.ceil((P-R)/1000));w=Math.min(w,b)}let I=Math.floor(w/60),M=w%60,m=F==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${I}m ${M}s.`:F==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${I}m ${M}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${I}m ${M}s.`;return new Response(JSON.stringify({error:{message:m,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(w)}})}function ZX(Z){let F=Z?.resetCreditsAvailable;return typeof F==="number"&&Number.isFinite(F)?F:void 0}async function Gz(Z){let F=PY(Z.storage),P=Date.now(),R=f.peekMainForPolicy(Z.mainAccountIdentity),k=s1(R?.quota,R?.checkedAt,Z.sidebarState.main.quota,Z.sidebarState.main.mainAccountId,Z.mainAccountIdentity),C=F?MY(R?.quota,Z.storage,void 0,P):void 0,w=[{accountId:"main",wireAccountId:Z.mainAccountIdentity,access:Z.primaryAccess,keepwarmAccountKey:"main",quota:k.quota,quotaCheckedAt:k.quotaCheckedAt,reservePercent:WX(Z.storage),configuredOrder:0,resetCreditsApplicable:ZX(k.quota),killswitchPasses:C}],I=await Y0.getUsableFallbackAccounts(Z.storage);for(let M of I){if(!M.access)continue;let m=Z.sidebarState.fallbacks.find((m0)=>m0.id===M.id),b=f.peekFallbackForPolicy(M.id,M.accountId),X0=s1(b?.quota,b?.checkedAt,m?.quota,m?.accountId,M.accountId),F0=F?MY(b?.quota,Z.storage,M.id,P):void 0;w.push({accountId:M.id,wireAccountId:M.accountId,access:M.access,keepwarmAccountKey:M.id,fallback:M,quota:X0.quota,quotaCheckedAt:X0.quotaCheckedAt,reservePercent:WX(Z.storage,M.id),configuredOrder:w.length,resetCreditsApplicable:ZX(X0.quota),killswitchPasses:F0})}return w}function BX(Z,F,P,R,k){let C=PY(k)?Z.killswitchPasses:void 0;if(Z.accountId==="main"){let m=f.peekMainForPolicy(Z.wireAccountId),b=s1(m?.quota,m?.checkedAt,F.main.quota,F.main.mainAccountId,Z.wireAccountId);return d8({quota:b.quota,quotaCheckedAt:b.quotaCheckedAt,status:P,now:R,killswitchPasses:C})}let w=F.fallbacks.find((m)=>m.id===Z.accountId),I=f.peekFallbackForPolicy(Z.accountId,Z.wireAccountId),M=s1(I?.quota,I?.checkedAt,w?.quota,w?.accountId,Z.wireAccountId);return d8({quota:M.quota,quotaCheckedAt:M.quotaCheckedAt,status:P,now:R,killswitchPasses:C})}function Wz(Z){return Z.accountId==="main"?"main":Z.keepwarmAccountKey}function KX(Z){return f.isRateLimited(Wz(Z))}async function q8(Z){let F=Z.candidates.filter((M)=>!KX(M)),P=new Map(F.map((M)=>[M.accountId,M])),R=Object.fromEntries(F.map((M)=>[M.accountId,M.quotaCheckedAt])),k=Object.fromEntries(F.map((M)=>[M.accountId,M.wireAccountId])),C=new Set(Z.excludeAccountIds),w,I=await t4({sessionId:Z.sessionId,requestBytes:Z.requestBytes,now:Z.now,validPinnedAccountIds:[...P.keys()],excludeAccountIds:Z.excludeAccountIds,quotaCheckedAtByAccount:R,wireAccountIdByAccount:k,choose:(M)=>{let m=F.filter((X0)=>!C.has(X0.accountId));if(m.length===0)return;let b=NJ({candidates:m,pendingBytes:M,requestBytes:Z.requestBytes,now:Z.now,onEmptyWeightedSet:()=>{v.debug("sticky routing: no fresh weighted candidates; using configured order")}});if(!b)return;return w={accountId:b.accountId,source:b.source,pendingBytes:M.get(b.accountId)??0},b}},P0);if(w&&I?.accountId===w.accountId)v.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:EY(Z.sessionId),accountId:w.accountId,source:w.source,requestBytes:Z.requestBytes,pendingBytes:w.pendingBytes});return I?P.get(I.accountId):void 0}async function zz(Z,F){let P=await Y0.getUsableFallbackAccounts(Z),R=[];for(let b of P)if(b.access)R.push({access:b.access,accountId:b.accountId,keepwarmAccountKey:b.id,quotaAccountId:b.id,fallback:b});let k=R.filter((b)=>!f.isRateLimited(b.quotaAccountId)),C=PY(Z)?k.filter((b)=>MY(f.peekFallbackForPolicy(b.quotaAccountId,b.accountId)?.quota,Z,b.quotaAccountId,Date.now())):k,w=new Map(F.fallbacks.map((b)=>[b.id,{quota:b.quota,accountId:b.accountId}])),I=[],M=[],m=Date.now();for(let b of C){let X0=w.get(b.quotaAccountId),F0=NX(f.peekFallbackForPolicy(b.quotaAccountId,b.accountId),X0?.quota,m,X0?.accountId,b.accountId);if(F0.exhausted)M.push({candidate:b,decision:F0});else I.push(b)}return{current:C,retained:I,skipped:M}}function OX(Z,F){if(Z.retained.length===0&&!F)return Z.current;for(let{candidate:P,decision:R}of Z.skipped)VX(P.quotaAccountId,R);return Z.retained}async function FX(Z,F){try{let P=g1(Z.headers);await j1(P,F.access,F.quotaAccountId,void 0,jY(Z.headers))}catch{}}async function Uz(Z,F,P,R){for(let k of R){let C;try{C=await I0(Z,F,k.access,k.accountId,k.keepwarmAccountKey)}catch(w){if(w instanceof DOMException&&w.name==="AbortError")throw w;if(F?.signal?.aborted)throw w;throw v.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:k.quotaAccountId}),w}if(!DY(C.status,P))return Y0.markUsed(k.fallback),{response:C,accessToken:k.access,quotaAccountId:k.quotaAccountId,activeId:k.keepwarmAccountKey};await FX(C,k),C.body?.cancel().catch(()=>{})}return}async function Lz(Z,F,P,R,k){if(!b1(Z,F))return{response:P};if(!k.length)return{response:P};let C=P,w;for(let I of k){let M;try{M=await I0(Z,F,I.access,I.accountId,I.keepwarmAccountKey)}catch(m){if(m instanceof DOMException&&m.name==="AbortError")throw m;if(F?.signal?.aborted)throw m;return v.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:I.quotaAccountId}),{response:C,...w}}if(C.body?.cancel().catch(()=>{}),C=M,w={accessToken:I.access,accountId:I.quotaAccountId},!DY(M.status,R))return Y0.markUsed(I.fallback),{response:M,...w};await FX(M,I)}return{response:C,...w}}if(!q4){if(q4=!0,j){let Z=[];for(let F of j.accounts)if(i0(F))Z.push(F);f.seedFallbacksFromAccounts(Z)}y0(f,j).catch(()=>{}),h1({getAuth:N,codexRefreshFn:S1,refreshMainWithLease:n0,fallbackManager:Y0,quotaManager:f,loadAccounts:D0,writeSidebarState:y0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:G0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:i0,whamFn:W1,respectBackoff:!0}).catch((Z)=>l.warn("boot quota seed failed",{pid:process.pid,error:t0(Z)}))}return O.start(async()=>{let F=(await tX({getAuth:N,codexRefreshFn:S1,refreshMainWithLease:n0,fallbackManager:Y0,quotaManager:f,loadAccounts:D0,writeSidebarState:(P,R)=>O.isStopped()?Promise.resolve():y0(P,R),client:Y.client,fetchImpl:fetch,now:Date.now,configPath:G0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:i0,whamFn:W1,readSidebarState:()=>A1(P0)})).filter((P)=>!P.ok);if(F.length>0)l.warn("background quota refresh completed with failures",{pid:process.pid,failures:F})},(Z)=>{l.warn("background quota refresh failed",{pid:process.pid,error:Z instanceof Error?Z.message:String(Z)})}),{apiKey:RZ,async fetch(Z,F){let P=T4(Z,F),R=R4(P),k=P.get("x-parent-session-id")?.trim()||void 0,C=await x(),w=await N(),I=++N0;if(w.type!=="oauth")return fetch(Z,F);F=await sZ(Z,F);let M=w.access??"";if(!w.access||(w.expires??0)<Date.now()){K0.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(w.access),expiresInMs:w.expires?w.expires-Date.now():void 0});try{let e=await n0();w.access=e.access,w.refresh=e.refresh,w.expires=e.expires}catch(e){if(GX(e))throw e}}M=w.access??"";let b=w.accountId??(M?r1(o1(M)??{}):void 0);if(I===N0)u=b;let X0=C?.routing?.mode??"main-first",F0,z0=await(()=>{return F0??=A1(P0),F0})();if(X0==="sticky-balanced"&&R&&b1(Z,F)&&typeof F?.body==="string"){let e=Buffer.byteLength(F.body,"utf8"),V0=await Gz({storage:C,sidebarState:z0,primaryAccess:M,mainAccountIdentity:b}),L0=await q8({sessionId:R,requestBytes:e,candidates:V0,now:Date.now()});if(L0){let AX=KX(L0)?{action:"migrate",reason:"exhausted"}:BX(L0,z0,void 0,Date.now(),C);if(AX.action==="migrate"){let A0=await q8({sessionId:R,requestBytes:e,candidates:V0,excludeAccountIds:[L0.accountId],now:Date.now()});if(A0)v.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:EY(R),fromAccountId:L0.accountId,toAccountId:A0.accountId,reason:AX.reason}),L0=A0}let c0=await I0(Z,F,L0.access,L0.wireAccountId,L0.keepwarmAccountKey),wX=async(A0,D1)=>{try{let Hz=g1(A0.headers);await j1(Hz,D1.access,D1.accountId==="main"?void 0:D1.accountId,D1.accountId==="main"?D1.wireAccountId:void 0,jY(A0.headers))}catch{}};await wX(c0,L0);let TX=BX(L0,z0,c0.status,Date.now(),C);if((c0.status===401||c0.status===403||c0.status===429)&&TX.action==="migrate"){let A0=await q8({sessionId:R,requestBytes:e,candidates:V0,excludeAccountIds:[L0.accountId],now:Date.now()});if(A0){v.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:EY(R),fromAccountId:L0.accountId,toAccountId:A0.accountId,reason:TX.reason});let D1=c0;c0=await I0(Z,F,A0.access,A0.wireAccountId,A0.keepwarmAccountKey),D1.body?.cancel().catch(()=>{}),L0=A0,await wX(c0,L0)}}if(L0.fallback&&!DY(c0.status,C))Y0.markUsed(L0.fallback);return await f0(R,k,L0.accountId,X0,C?.accounts).catch(()=>{}),c0}}let B0=NX(f.peekMainForPolicy(b),z0.main.quota,Date.now(),z0.main.mainAccountId,b),S0=PY(C)&&!MY(Qz(b),C,void 0,Date.now()),wY=f.isRateLimited("main"),qX,j8=()=>{return qX??=zz(C,z0),qX},s0,x1,jX=!1,TY;if(X0==="fallback-first"&&b1(Z,F)){jX=!0;let e=await j8();TY=OX(e,!S0&&!wY&&!B0.exhausted);let V0=await Uz(Z,F,C,TY);if(V0)s0=V0.response,x1={accessToken:V0.accessToken,accountId:V0.quotaAccountId,activeId:V0.activeId}}if(!s0){let e=B0.exhausted&&b1(Z,F)&&(await j8()).retained.length>0;if(S0||wY||e){let V0=S0?"killswitch":wY?"mid-stream-rate-limit":"quota-exhausted";if(V0==="quota-exhausted"&&B0.exhausted)VX("main",B0);v.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:V0}),s0=$z(C,V0,V0==="quota-exhausted"&&B0.exhausted?B0.resetAtMs:wY?f.rateLimitedUntil("main"):void 0)}else s0=await I0(Z,F,M,b,"main")}let DX=Boolean(x1),a1=s0,PX=x1?.accessToken??M,MX=x1?.accountId,EX=x1?.activeId??"main";if(!x1&&!jX&&DY(s0.status,C)){v.debug("reactive fallback triggered",{pid:process.pid,status:s0.status}),TY??=OX(await j8(),!1);let e=await Lz(Z,F,s0,C,TY),V0=e.response;if(V0!==s0){if(DX=!0,a1=V0,PX=e.accessToken??M,MX=e.accountId,e.accountId)EX=e.accountId}}try{let e=g1(a1.headers);if(DX)await j1(e,PX,MX,void 0,jY(a1.headers));else await j1(e,M,void 0,b,jY(a1.headers))}catch{}return await f0(R,k,EX,X0,C?.accounts).catch(()=>{}),a1},async dispose(){if(O.stop(),o0.stop(),G1.__openaiAuthCacheKeepManager===o0)G1.__openaiAuthCacheKeepManager=void 0;if(Y0.stopBackgroundRefresh(),H){await H.stop().catch(()=>{});let Z=globalThis;if(Z.__openaiAuthRpcServer===H)Z.__openaiAuthRpcServer=void 0;H=null}}}},methods:[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:async()=>{let{redirectUri:N}=await v4(),K=await k4(),j=S4(crypto.getRandomValues(new Uint8Array(32)).buffer),A=b4(N,K,j),x=h4(K,j);return{url:A,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let E=await x,S=B8(E);return{type:"success",refresh:E.refresh_token,access:E.access_token,expires:Date.now()+(E.expires_in??3600)*1000,accountId:S}}finally{x4(j)}}}}},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:async()=>{let{deviceData:N,url:K,instructions:j}=await g4();return{url:K,instructions:j,method:"auto",async callback(){try{let A=await y4(N);return{type:"success",refresh:A.refresh_token,access:A.access_token,expires:Date.now()+(A.expires_in??3600)*1000,accountId:B8(A)}}catch{return{type:"failed"}}}}}},{label:"Manually enter API Key",type:"api"}]},"chat.headers":async(N,K)=>{if(N.model.providerID!=="openai")return;if(K.headers.originator="opencode",K.headers["User-Agent"]=`${I4} (${$X.platform()} ${$X.release()}; ${$X.arch()})`,K.headers["session-id"]=N.sessionID,W&&N.agent==="title")K.headers[F1.TITLE_HEADER]="true"},"chat.params":async(N,K)=>{if(N.model.providerID!=="openai")return;K.maxOutputTokens=void 0},config:async(N)=>{N.command={...N.command??{},[_8]:{template:_8,description:"Show current OpenAI Codex OAuth quota usage for all accounts."},[C8]:{template:C8,description:"Manage OpenAI accounts — add, switch, remove, or reorder."},[I8]:{template:I8,description:"Show or change OpenAI account routing between main-first, fallback-first, and sticky-balanced."},[S8]:{template:S8,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."},[k8]:{template:k8,description:"Show or toggle OpenAI Codex request dump capture for debugging."},[b8]:{template:b8,description:"Show or change the plugin log level (error, warn, info, debug, trace)."},[x8]:{template:x8,description:"Keep Codex prompt cache alive during idle by shadow-replaying the last request."},[E1]:{template:E1,description:"Spend one reset credit on an exhausted Codex account."}}},"command.execute.before":async(N)=>{if(!sX.includes(N.command))return;if(!L)await B(N.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),E4();let K=N.command,j={...L,sessionId:N.sessionID,notify:(x)=>{X9(x,N.sessionID)}},A=await v8(K,N.arguments,j);if(vJ(N.sessionID))X9(A,N.sessionID);else await B(N.sessionID,A.text);E4()}}}var QB=async(Y)=>{let X=w0();return JB(Y,{codexApiEndpoint:X.codexApiEndpoint,experimentalWebSockets:X.webSockets,responsesLite:X.responsesLite})},ID={id:"cortexkit-openai-auth",server:QB};export{R4 as resolveSidebarSessionId,o1 as parseJwtClaims,w4 as mergePushedQuotaMetadata,rZ as findCachekeepFallbackAccount,r1 as extractAccountIdFromClaims,ID as default,yZ as createResetTargetResolver,CD as buildSidebarState,Jz as buildSidebarMachineState,fZ as buildResetRedemptionDeps,d0 as ResetTargetResolutionError,QB as OpenAIAuthPlugin,kZ as MAIN_REFRESH_LOCK_TTL_MS,bZ as MAIN_REFRESH_LEASE_TTL_MS,JB as CodexAuthPlugin,LX as AuthPersistError};
|