@cortexkit/opencode-openai-auth 0.6.3 → 0.6.4

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/index.js CHANGED
@@ -1,14 +1,14 @@
1
- import{d as h1,e as FY,f as JW}from"./index-87145jkw.js";import{A as W1,B as I1,C as $1,D as dW,E as iW,F as i0,G as nW,H as P1,I as u0,J as cX,K as D0,L as J0,M as jY,N as DY,O as XX,P as PY,Q as oW,R as rW,S as sW,h as kW,i as bW,j as xW,k as vW,l as hW,m as gW,n as yW,o as i1,p as n1,q as V8,s as fW,t as mW,u as cW,v as uW,w as pW,x as lW,y as fX,z as mX}from"./index-ng315c61.js";import{$ as w1,U as f8,X as MY,Y as aW,da as tW,ea as eW,fa as Y5,ka as X5,la as N8,ma as J5,na as Q5,oa as G5,pa as $5}from"./index-zbpt7v1a.js";import{wa as bY}from"./index-8f1200qx.js";import{xa as TJ,ya as RJ}from"./index-00rp531h.js";import{Aa as kY,Ba as $J,Ca as N0}from"./index-80gqxa1f.js";import{Fa as W5}from"./index-4agbg1ec.js";import{Ia as X9}from"./index-x55z0b3y.js";import{mkdirSync as CB,readFileSync as _B,renameSync as IB,statSync as SB,writeFileSync as kB}from"node:fs";import e9 from"node:os";import{join as bB}from"node:path";import{readFileSync as q5}from"node:fs";import{homedir as F5,tmpdir as j5}from"node:os";import{join as RY}from"node:path";var D5="https://chatgpt.com/backend-api/codex/responses",P5="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 RY(process.env.XDG_CONFIG_HOME||RY(F5(),".config"),"opencode")}function $0(){return process.env[a0.configFile]?.trim()||RY(CY(),P5)}function M5(){try{let Y=JSON.parse(q5($0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function MX(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 TY(Y,X,J){let Q=MX(Y);if(Q!==void 0)return Q;if(typeof X==="boolean")return X;return J}function w5(){let Y=M5(),X=MX(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:TY(a0.webSockets,Y.webSockets,!1),rawWebSocket:TY(a0.rawWebSocket,Y.rawWebSocket,!1),responsesLite:TY(a0.responsesLite,Y.responsesLite,!1),dump:TY(a0.dump,Q,!1),dumpDir:process.env[a0.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():RY(j5(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[a0.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():D5)}}var q8;function A0(){if(!q8)q8=w5();return q8}var F8="/backend-api/wham/rate-limit-reset-credits",E5=`https://chatgpt.com${F8}`,RX=`${F8}/consume`,A5=`https://chatgpt.com${RX}`,T5=300000,R5=60000,C5=15000,_5=60000;class k0 extends Error{kind;cooldownUntil;constructor(Y,X,J){super(X);this.name="ResetRedemptionError",this.kind=Y,this.cooldownUntil=J}}class D1 extends Error{kind;status;constructor(Y,X,J){super(X);this.name="ResetCreditError",this.kind=Y,this.status=J}}function CX(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 _Y(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}function _X(Y){if(!Y)return;return{...Y.inFlight?{inFlight:{...Y.inFlight}}:{},...Y.lastOutcome?{lastOutcome:{...Y.lastOutcome}}:{},...Y.cooldownUntil!==void 0?{cooldownUntil:Y.cooldownUntil}:{}}}function j8(Y){if(!_Y(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 IX(Y){return Boolean(Y&&Object.hasOwn(Y,"inFlight"))}function SX(Y,X){return X-Y.startedAt<T5}function IY(Y,X){if(!u0(X))return;return Y.reset?.[X]}function kX(Y){if(!Y.reset)Y.reset=Object.create(null);return Y.reset}function bX(Y,X,J){if(!u0(X))return;let Q=kX(Y),G=Q[X]??{},$=G.lastOutcome;delete G.inFlight,G.lastOutcome={code:"ambiguous_local",at:J,...$?{previousOutcome:{code:$.code,at:$.at}}:{}},Q[X]=G}function xX(Y,X){let J=_X(Y),Q=j8(Y?.inFlight);if(IX(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&&SX(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 I5(Y,X){if(!u0(X))return{kind:"fresh",beforeState:void 0};let J=await Y.loadAccountsFn(Y.configPath);return xX(J?IY(J,X):void 0,Y.now())}async function S5(Y,X){let J;if(await Y.mutateAccountsFn((Q)=>{let G=Y.now(),$=IY(Q,X);if(J=xX($,G),J.kind==="corrupt")bX(Q,X,G);return Q},Y.configPath),!J)throw Error("corrupt reset state mutation did not run");return J}async function k5(Y,X,J){if(!u0(X))return{kind:"fresh",beforeState:void 0};let Q;if(await Y.mutateAccountsFn((G)=>{let $=Y.now(),W=IY(G,X),U=_X(W),H=j8(W?.inFlight);if(IX(W)&&!H)return bX(G,X,$),Q={kind:"corrupt",beforeState:U},G;if(W?.cooldownUntil!==void 0&&W.cooldownUntil>$)return Q={kind:"cooldown",beforeState:U,cooldownUntil:W.cooldownUntil},G;if(H&&SX(H,$))return Q={kind:"claim",beforeState:U,claim:{inFlight:H,selectedCredit:{id:H.creditId}}},G;if(H)return Q={kind:"expired_unreconciled",beforeState:U,claim:{inFlight:H,selectedCredit:{id:H.creditId}}},G;let L=SY(J);if(!L)return Q={kind:"fresh",beforeState:U},G;let N={redeemRequestId:Y.randomUUID(),creditId:L.id,startedAt:$},O=kX(G);return O[X]={...W,inFlight:N},Q={kind:"claim",beforeState:U,claim:{inFlight:N,selectedCredit:L}},G},Y.configPath),!Q)throw Error("reset claim mutation did not run");return Q}async function b5(Y,X,J,Q){if(!u0(X))return;if(!M8(Q.kind))return;await Y.mutateAccountsFn((G)=>{let $=IY(G,X),W=j8($?.inFlight);if(!$||!W||W.redeemRequestId!==J.redeemRequestId||W.creditId!==J.creditId)return G;let U=Y.now();if(delete $.inFlight,$.lastOutcome={code:Q.kind,at:U},Q.kind==="reset"||Q.kind==="already_redeemed")$.cooldownUntil=U+_5;else delete $.cooldownUntil;return G},Y.configPath)}function s1(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 D8(Y,X,J,Q){if(!(X||s1(Y.primary,Q)||s1(Y.secondary,Q)))return{ok:!1,reason:"not exhausted"};if(J<=0)return{ok:!1,reason:"no applicable credits"};return{ok:!0}}function wX(Y,X){let J=Y[X];if(J===void 0||J===null)return;return typeof J==="string"?J:null}function x5(Y){if(!_Y(Y))return;let X=wX(Y,"granted_at"),J=wX(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 P8(Y,X,J){let Q;try{Q=await Y(E5,{method:"GET",headers:CX(X,F8,J),signal:AbortSignal.timeout(C5)})}catch{throw new D1("http_error","reset credit list request failed")}if(!Q.ok)throw new D1("http_error",`reset credit list request failed: ${Q.status}`,Q.status);let G;try{G=await Q.json()}catch{throw new D1("invalid_response","reset credit list response was not valid JSON",Q.status)}if(!_Y(G))throw new D1("invalid_response","reset credit list response was not an object",Q.status);return{credits:(Array.isArray(G.credits)?G.credits:[]).flatMap((W)=>{let U=x5(W);return U===void 0?[]:[U]}),availableCount:typeof G.available_count==="number"&&Number.isFinite(G.available_count)?G.available_count:void 0}}function SY(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 M8(Y){return Y==="reset"||Y==="already_redeemed"||Y==="nothing_to_reset"||Y==="no_credit"}async function v5(Y,X,J,Q,G){let $;try{$=await Y(A5,{method:"POST",headers:{...CX(X,RX,J),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:G,credit_id:Q}),signal:AbortSignal.timeout(R5)})}catch(L){return{kind:"ambiguous",raw:L}}let W;try{W=await $.text()}catch(L){return $.ok?{kind:"ambiguous",raw:L}:{kind:"http_error",raw:L,status:$.status}}let U=W,H=!1;try{U=JSON.parse(W),H=!0}catch{}if(!$.ok)return{kind:"http_error",raw:U,status:$.status};if(!H||!_Y(U)||!M8(U.code))return{kind:"ambiguous",raw:U};return{kind:U.code,raw:U}}function EX(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 AX(){throw new k0("expired_unreconciled","the previous reset attempt outcome is unknown")}function TX(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 h5(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 vX(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,G=await I5(Y,X.accountKey);if(G.kind==="corrupt"){if(G=await S5(Y,X.accountKey),G.kind==="corrupt")return TX(J,G.beforeState)}if(G.kind==="cooldown")EX(G);let $;if(G.kind==="claim")$=G.claim;else if(G.kind==="expired_unreconciled"){if(!X.retry)AX();$=G.claim}else{if(X.retry)throw new k0("retry_without_inflight","there is no active reset credit redemption to retry");let[H,L]=await Promise.all([Y.fetchUsage(J),P8(Y.fetchImpl,J.accessToken,Q)]),N=D8(H,Y.hasActiveRateLimitMark(X.accountKey),H.resetCreditsApplicable??0,Y.now());if(!N.ok)throw new k0(N.reason==="not exhausted"?"not_exhausted":"no_applicable_credits",N.reason);if(!SY(L.credits))throw new k0("no_eligible_credit","no eligible reset credit was returned");let O=await k5(Y,X.accountKey,L.credits);if(O.kind==="corrupt")return TX(J,O.beforeState);if(O.kind==="cooldown")EX(O);if(O.kind==="expired_unreconciled")AX();if(O.kind!=="claim")throw new k0("no_eligible_credit","no eligible reset credit was available while claiming");$=O.claim}let W=await v5(Y.fetchImpl,J.accessToken,Q,$.inFlight.creditId,$.inFlight.redeemRequestId),U=!1;try{await b5(Y,X.accountKey,$.inFlight,W)}catch{U=M8(W.kind)}return{target:J,selectedCredit:$.selectedCredit,beforeState:G.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.":h5(W),...U?{finalizeStateWriteFailed:!0}:{}}}function R(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var A8="openai-quota",T8="openai-account",R8="openai-routing",C8="openai-killswitch",_8="openai-dump",I8="openai-logging",S8="openai-cachekeep",M1="openai-reset",uX=["openai-quota","openai-account","openai-routing","openai-killswitch","openai-dump","openai-logging","openai-cachekeep","openai-reset"],i=N0("commands");function hX(Y){if(Y==="fallback-first")return"Try usable fallback accounts before the main account.";if(Y==="sticky-balanced")return"Keep each session on its assigned account while balancing new sessions.";return"Try the main account first. Use fallback accounts only when required."}async function g5(Y){let X=await Y.refreshAllQuota?.(),J=Y.quotaManager.getMain(),Q=["## OpenAI Quota",""];if(J?.quota){let W=J.quota;Q.push("### Main account");for(let U of["primary","secondary"]){let H=W[U];if(H){let L=Math.round(H.usedPercent),N="█".repeat(Math.max(0,Math.min(Math.round(L/10),10)))+"░".repeat(Math.max(0,10-Math.min(Math.round(L/10),10)));Q.push(`- ${U}: ${N} ${L}% used (${Math.round(H.remainingPercent)}% remaining)`)}}if(W.resetCreditsAvailable!==void 0)Q.push(`- resets: ${W.resetCreditsAvailable}`)}else Q.push("No main quota snapshot available. Send a request first.");let $=[...Y.quotaManager.getAllFallbacks().entries()].filter(([,W])=>W);if($.length>0){Q.push(""),Q.push("### Fallback accounts");for(let[W,U]of $){if(!U?.quota)continue;Q.push(`**${W}**`);for(let H of["primary","secondary"]){let L=U.quota[H];if(L){let N=Math.round(L.usedPercent);Q.push(` - ${H}: ${N}% used (${Math.round(L.remainingPercent)}% remaining)`)}}if(U.quota.resetCreditsAvailable!==void 0)Q.push(` - resets: ${U.quota.resetCreditsAvailable}`)}}if(X?.length){let W=X.filter((U)=>!U.ok);if(W.length>0){Q.push("");for(let U of W)Q.push(`- ${U.account}: fetch failed — Refresh to retry`)}}return{command:"openai-quota",text:Q.join(`
2
- `),knobs:{}}}function x1(Y){return{id:Y.id,type:Y.type??"oauth",enabled:Y.enabled,label:Y.label}}async function y5(Y,X){let J=Y.trim().split(/\s+/).filter(Boolean),Q=await X.loadAccounts(X.accountStoragePath)??{version:1,accounts:[]},G=Q.accounts??[];if(J.length===0){let $=["## OpenAI Accounts",""];if(G.length===0)$.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";$.push(`Routing: \`${W}\` (set with \`/openai-routing\`). Modes: main-first, fallback-first, or sticky-balanced. \`/openai-routing reset\` clears this session's pin.`),$.push("");for(let U of G){let H=U.type??"oauth";$.push(`- \`${U.id}\` (${H})`)}}return $.push(""),$.push("Commands: `/openai-account add [label]` | `/openai-account remove <id>`"),{command:"openai-account",text:$.join(`
3
- `),knobs:{accounts:G.map(x1)}}}if(J[0]==="remove"&&J[1]){let $=J[1],W=await cX(X.accountStoragePath),U=W?W.has($):!1,H=!1,L=await J0((O)=>{let Z=O.accounts.findIndex((V)=>V.id===$);if(Z===-1)return O;return O.accounts.splice(Z,1),H=!0,O},X.accountStoragePath,{allowDrop:[$]});if(!(H||U))return{command:"openai-account",text:`## Account Not Found
1
+ import{d as h1,e as FY,f as $W}from"./index-87145jkw.js";import{A as W1,B as I1,C as $1,D as oW,E as rW,F as i0,G as sW,H as P1,I as u0,J as cX,K as D0,L as J0,M as jY,N as DY,O as XX,P as PY,Q as aW,R as tW,S as eW,h as vW,i as hW,j as gW,k as yW,l as fW,m as mW,n as cW,o as i1,p as n1,q as V8,s as uW,t as pW,u as lW,v as dW,w as iW,x as nW,y as fX,z as mX}from"./index-z6mxjaar.js";import{$ as w1,U as f8,X as MY,Y as Y5,da as X5,ea as J5,fa as Q5,ka as G5,la as N8,ma as $5,na as W5,oa as z5,pa as U5}from"./index-zbpt7v1a.js";import{wa as bY}from"./index-8f1200qx.js";import{xa as _J,ya as IJ}from"./index-00rp531h.js";import{Aa as kY,Ba as WJ,Ca as N0}from"./index-80gqxa1f.js";import{Fa as H5}from"./index-4agbg1ec.js";import{Ia as X9}from"./index-x55z0b3y.js";import{mkdirSync as bB,readFileSync as xB,renameSync as vB,statSync as hB,writeFileSync as gB}from"node:fs";import e9 from"node:os";import{join as yB}from"node:path";import{readFileSync as D5}from"node:fs";import{homedir as P5,tmpdir as M5}from"node:os";import{join as RY}from"node:path";var w5="https://chatgpt.com/backend-api/codex/responses",E5="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 RY(process.env.XDG_CONFIG_HOME||RY(P5(),".config"),"opencode")}function $0(){return process.env[a0.configFile]?.trim()||RY(CY(),E5)}function A5(){try{let Y=JSON.parse(D5($0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function MX(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 TY(Y,X,J){let Q=MX(Y);if(Q!==void 0)return Q;if(typeof X==="boolean")return X;return J}function T5(){let Y=A5(),X=MX(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:TY(a0.webSockets,Y.webSockets,!1),rawWebSocket:TY(a0.rawWebSocket,Y.rawWebSocket,!1),responsesLite:TY(a0.responsesLite,Y.responsesLite,!1),dump:TY(a0.dump,Q,!1),dumpDir:process.env[a0.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():RY(M5(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[a0.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():w5)}}var q8;function A0(){if(!q8)q8=T5();return q8}var F8="/backend-api/wham/rate-limit-reset-credits",R5=`https://chatgpt.com${F8}`,RX=`${F8}/consume`,C5=`https://chatgpt.com${RX}`,_5=300000,I5=60000,S5=15000,k5=60000;class k0 extends Error{kind;cooldownUntil;constructor(Y,X,J){super(X);this.name="ResetRedemptionError",this.kind=Y,this.cooldownUntil=J}}class D1 extends Error{kind;status;constructor(Y,X,J){super(X);this.name="ResetCreditError",this.kind=Y,this.status=J}}function CX(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 _Y(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}function _X(Y){if(!Y)return;return{...Y.inFlight?{inFlight:{...Y.inFlight}}:{},...Y.lastOutcome?{lastOutcome:{...Y.lastOutcome}}:{},...Y.cooldownUntil!==void 0?{cooldownUntil:Y.cooldownUntil}:{}}}function j8(Y){if(!_Y(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 IX(Y){return Boolean(Y&&Object.hasOwn(Y,"inFlight"))}function SX(Y,X){return X-Y.startedAt<_5}function IY(Y,X){if(!u0(X))return;return Y.reset?.[X]}function kX(Y){if(!Y.reset)Y.reset=Object.create(null);return Y.reset}function bX(Y,X,J){if(!u0(X))return;let Q=kX(Y),G=Q[X]??{},$=G.lastOutcome;delete G.inFlight,G.lastOutcome={code:"ambiguous_local",at:J,...$?{previousOutcome:{code:$.code,at:$.at}}:{}},Q[X]=G}function xX(Y,X){let J=_X(Y),Q=j8(Y?.inFlight);if(IX(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&&SX(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 b5(Y,X){if(!u0(X))return{kind:"fresh",beforeState:void 0};let J=await Y.loadAccountsFn(Y.configPath);return xX(J?IY(J,X):void 0,Y.now())}async function x5(Y,X){let J;if(await Y.mutateAccountsFn((Q)=>{let G=Y.now(),$=IY(Q,X);if(J=xX($,G),J.kind==="corrupt")bX(Q,X,G);return Q},Y.configPath),!J)throw Error("corrupt reset state mutation did not run");return J}async function v5(Y,X,J){if(!u0(X))return{kind:"fresh",beforeState:void 0};let Q;if(await Y.mutateAccountsFn((G)=>{let $=Y.now(),W=IY(G,X),z=_X(W),L=j8(W?.inFlight);if(IX(W)&&!L)return bX(G,X,$),Q={kind:"corrupt",beforeState:z},G;if(W?.cooldownUntil!==void 0&&W.cooldownUntil>$)return Q={kind:"cooldown",beforeState:z,cooldownUntil:W.cooldownUntil},G;if(L&&SX(L,$))return Q={kind:"claim",beforeState:z,claim:{inFlight:L,selectedCredit:{id:L.creditId}}},G;if(L)return Q={kind:"expired_unreconciled",beforeState:z,claim:{inFlight:L,selectedCredit:{id:L.creditId}}},G;let H=SY(J);if(!H)return Q={kind:"fresh",beforeState:z},G;let N={redeemRequestId:Y.randomUUID(),creditId:H.id,startedAt:$},O=kX(G);return O[X]={...W,inFlight:N},Q={kind:"claim",beforeState:z,claim:{inFlight:N,selectedCredit:H}},G},Y.configPath),!Q)throw Error("reset claim mutation did not run");return Q}async function h5(Y,X,J,Q){if(!u0(X))return;if(!M8(Q.kind))return;await Y.mutateAccountsFn((G)=>{let $=IY(G,X),W=j8($?.inFlight);if(!$||!W||W.redeemRequestId!==J.redeemRequestId||W.creditId!==J.creditId)return G;let z=Y.now();if(delete $.inFlight,$.lastOutcome={code:Q.kind,at:z},Q.kind==="reset"||Q.kind==="already_redeemed")$.cooldownUntil=z+k5;else delete $.cooldownUntil;return G},Y.configPath)}function s1(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 D8(Y,X,J,Q){if(!(X||s1(Y.primary,Q)||s1(Y.secondary,Q)))return{ok:!1,reason:"not exhausted"};if(J<=0)return{ok:!1,reason:"no applicable credits"};return{ok:!0}}function wX(Y,X){let J=Y[X];if(J===void 0||J===null)return;return typeof J==="string"?J:null}function g5(Y){if(!_Y(Y))return;let X=wX(Y,"granted_at"),J=wX(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 P8(Y,X,J){let Q;try{Q=await Y(R5,{method:"GET",headers:CX(X,F8,J),signal:AbortSignal.timeout(S5)})}catch{throw new D1("http_error","reset credit list request failed")}if(!Q.ok)throw new D1("http_error",`reset credit list request failed: ${Q.status}`,Q.status);let G;try{G=await Q.json()}catch{throw new D1("invalid_response","reset credit list response was not valid JSON",Q.status)}if(!_Y(G))throw new D1("invalid_response","reset credit list response was not an object",Q.status);return{credits:(Array.isArray(G.credits)?G.credits:[]).flatMap((W)=>{let z=g5(W);return z===void 0?[]:[z]}),availableCount:typeof G.available_count==="number"&&Number.isFinite(G.available_count)?G.available_count:void 0}}function SY(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 M8(Y){return Y==="reset"||Y==="already_redeemed"||Y==="nothing_to_reset"||Y==="no_credit"}async function y5(Y,X,J,Q,G){let $;try{$=await Y(C5,{method:"POST",headers:{...CX(X,RX,J),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:G,credit_id:Q}),signal:AbortSignal.timeout(I5)})}catch(H){return{kind:"ambiguous",raw:H}}let W;try{W=await $.text()}catch(H){return $.ok?{kind:"ambiguous",raw:H}:{kind:"http_error",raw:H,status:$.status}}let z=W,L=!1;try{z=JSON.parse(W),L=!0}catch{}if(!$.ok)return{kind:"http_error",raw:z,status:$.status};if(!L||!_Y(z)||!M8(z.code))return{kind:"ambiguous",raw:z};return{kind:z.code,raw:z}}function EX(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 AX(){throw new k0("expired_unreconciled","the previous reset attempt outcome is unknown")}function TX(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 f5(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 vX(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,G=await b5(Y,X.accountKey);if(G.kind==="corrupt"){if(G=await x5(Y,X.accountKey),G.kind==="corrupt")return TX(J,G.beforeState)}if(G.kind==="cooldown")EX(G);let $;if(G.kind==="claim")$=G.claim;else if(G.kind==="expired_unreconciled"){if(!X.retry)AX();$=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),P8(Y.fetchImpl,J.accessToken,Q)]),N=D8(L,Y.hasActiveRateLimitMark(X.accountKey),L.resetCreditsApplicable??0,Y.now());if(!N.ok)throw new k0(N.reason==="not exhausted"?"not_exhausted":"no_applicable_credits",N.reason);if(!SY(H.credits))throw new k0("no_eligible_credit","no eligible reset credit was returned");let O=await v5(Y,X.accountKey,H.credits);if(O.kind==="corrupt")return TX(J,O.beforeState);if(O.kind==="cooldown")EX(O);if(O.kind==="expired_unreconciled")AX();if(O.kind!=="claim")throw new k0("no_eligible_credit","no eligible reset credit was available while claiming");$=O.claim}let W=await y5(Y.fetchImpl,J.accessToken,Q,$.inFlight.creditId,$.inFlight.redeemRequestId),z=!1;try{await h5(Y,X.accountKey,$.inFlight,W)}catch{z=M8(W.kind)}return{target:J,selectedCredit:$.selectedCredit,beforeState:G.beforeState,outcome:W,retrySafety:z?"The server returned a terminal result, but the state write failed. A retry within five minutes reuses the same request and credit identifiers.":f5(W),...z?{finalizeStateWriteFailed:!0}:{}}}function R(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var A8="openai-quota",T8="openai-account",R8="openai-routing",C8="openai-killswitch",_8="openai-dump",I8="openai-logging",S8="openai-cachekeep",M1="openai-reset",uX=["openai-quota","openai-account","openai-routing","openai-killswitch","openai-dump","openai-logging","openai-cachekeep","openai-reset"],i=N0("commands");function hX(Y){if(Y==="fallback-first")return"Try usable fallback accounts before the main account.";if(Y==="sticky-balanced")return"Keep each session on its assigned account while balancing new sessions.";return"Try the main account first. Use fallback accounts only when required."}async function m5(Y){let X=await Y.refreshAllQuota?.(),J=Y.quotaManager.getMain(),Q=["## OpenAI Quota",""];if(J?.quota){let W=J.quota;Q.push("### Main account");for(let z of["primary","secondary"]){let L=W[z];if(L){let H=Math.round(L.usedPercent),N="█".repeat(Math.max(0,Math.min(Math.round(H/10),10)))+"░".repeat(Math.max(0,10-Math.min(Math.round(H/10),10)));Q.push(`- ${z}: ${N} ${H}% used (${Math.round(L.remainingPercent)}% remaining)`)}}if(W.resetCreditsAvailable!==void 0)Q.push(`- resets: ${W.resetCreditsAvailable}`)}else Q.push("No main quota snapshot available. Send a request first.");let $=[...Y.quotaManager.getAllFallbacks().entries()].filter(([,W])=>W);if($.length>0){Q.push(""),Q.push("### Fallback accounts");for(let[W,z]of $){if(!z?.quota)continue;Q.push(`**${W}**`);for(let L of["primary","secondary"]){let H=z.quota[L];if(H){let N=Math.round(H.usedPercent);Q.push(` - ${L}: ${N}% used (${Math.round(H.remainingPercent)}% remaining)`)}}if(z.quota.resetCreditsAvailable!==void 0)Q.push(` - resets: ${z.quota.resetCreditsAvailable}`)}}if(X?.length){let W=X.filter((z)=>!z.ok);if(W.length>0){Q.push("");for(let z of W)Q.push(`- ${z.account}: fetch failed — Refresh to retry`)}}return{command:"openai-quota",text:Q.join(`
2
+ `),knobs:{}}}function x1(Y){return{id:Y.id,type:Y.type??"oauth",enabled:Y.enabled,label:Y.label}}async function c5(Y,X){let J=Y.trim().split(/\s+/).filter(Boolean),Q=await X.loadAccounts(X.accountStoragePath)??{version:1,accounts:[]},G=Q.accounts??[];if(J.length===0){let $=["## OpenAI Accounts",""];if(G.length===0)$.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";$.push(`Routing: \`${W}\` (set with \`/openai-routing\`). Modes: main-first, fallback-first, or sticky-balanced. \`/openai-routing reset\` clears this session's pin.`),$.push("");for(let z of G){let L=z.type??"oauth";$.push(`- \`${z.id}\` (${L})`)}}return $.push(""),$.push("Commands: `/openai-account add [label]` | `/openai-account remove <id>`"),{command:"openai-account",text:$.join(`
3
+ `),knobs:{accounts:G.map(x1)}}}if(J[0]==="remove"&&J[1]){let $=J[1],W=await cX(X.accountStoragePath),z=W?W.has($):!1,L=!1,H=await J0((O)=>{let Z=O.accounts.findIndex((V)=>V.id===$);if(Z===-1)return O;return O.accounts.splice(Z,1),L=!0,O},X.accountStoragePath,{allowDrop:[$]});if(!(L||z))return{command:"openai-account",text:`## Account Not Found
4
4
 
5
- No account with id \`${$}\` exists.`,knobs:{accounts:L.accounts.map(x1)}};return i.info("account removed",{id:$}),X.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Account Removed
5
+ No account with id \`${$}\` exists.`,knobs:{accounts:H.accounts.map(x1)}};return i.info("account removed",{id:$}),X.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Account Removed
6
6
 
7
- Removed account \`${$}\`.`,knobs:{accounts:L.accounts.map(x1)}}}if(J[0]==="order"&&J.length>=3){let $=!1,W=await J0((U)=>{let H=U.accounts.findIndex((O)=>O.id===J[1]),L=U.accounts.findIndex((O)=>O.id===J[2]);if(H===-1||L===-1)return U;$=!0;let N=U.accounts[H];return U.accounts[H]=U.accounts[L],U.accounts[L]=N,U},X.accountStoragePath);if(!$)return{command:"openai-account",text:`## Invalid Order
7
+ Removed account \`${$}\`.`,knobs:{accounts:H.accounts.map(x1)}}}if(J[0]==="order"&&J.length>=3){let $=!1,W=await J0((z)=>{let L=z.accounts.findIndex((O)=>O.id===J[1]),H=z.accounts.findIndex((O)=>O.id===J[2]);if(L===-1||H===-1)return z;$=!0;let N=z.accounts[L];return z.accounts[L]=z.accounts[H],z.accounts[H]=N,z},X.accountStoragePath);if(!$)return{command:"openai-account",text:`## Invalid Order
8
8
 
9
9
  Both account IDs must exist.`,knobs:{accounts:W.accounts.map(x1)}};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(x1)}}}if(J[0]==="add"){let $=J.includes("--headless"),W=J.filter((V)=>V!=="add"&&V!=="--headless"),U=W.length>0?W.join(" "):void 0,{url:H,instructions:L,completion:N}=await mX({label:U,headless:$}),O=X.notify,Z=X.sessionId;if(N.then(async(V)=>{let K=!1;if(await J0((j)=>{if(V.accountId&&j.mainAccountId&&V.accountId===j.mainAccountId)return K=!0,j;return fX(j.accounts,V),j},X.accountStoragePath),K){i.warn("account add rejected (main identity)",{id:V.id,sessionId:Z}),O?.({command:"openai-account",text:`## Add Failed
11
+ Swapped positions of \`${J[1]}\` and \`${J[2]}\`.`,knobs:{accounts:W.accounts.map(x1)}}}if(J[0]==="add"){let $=J.includes("--headless"),W=J.filter((V)=>V!=="add"&&V!=="--headless"),z=W.length>0?W.join(" "):void 0,{url:L,instructions:H,completion:N}=await mX({label:z,headless:$}),O=X.notify,Z=X.sessionId;if(N.then(async(V)=>{let K=!1;if(await J0((j)=>{if(V.accountId&&j.mainAccountId&&V.accountId===j.mainAccountId)return K=!0,j;return fX(j.accounts,V),j},X.accountStoragePath),K){i.warn("account add rejected (main identity)",{id:V.id,sessionId:Z}),O?.({command:"openai-account",text:`## Add Failed
12
12
 
13
13
  ${"That account is already your main account — not added as a fallback."}`,knobs:{}});return}i.info("account added",{id:V.id,label:V.label}),X.refreshSidebar?.().catch(()=>{}),O?.({command:"openai-account",text:`## Account Added
14
14
 
@@ -16,44 +16,44 @@ Added account \`${V.id}\`${V.label?` ("${V.label}")`:""}.
16
16
 
17
17
  Run \`/openai-account\` to confirm.`,knobs:{}})}).catch((V)=>{let K=V instanceof Error?V.message:String(V??"unknown error");i.warn("account add failed",{error:K,sessionId:Z}),O?.({command:"openai-account",text:`## Add Failed
18
18
 
19
- Account add failed: ${K}`,knobs:{}})}),$){let V=L.match(/Enter code: (.+)/)?.[1]??L;return{command:"openai-account",text:`## Device Code
19
+ Account add failed: ${K}`,knobs:{}})}),$){let V=H.match(/Enter code: (.+)/)?.[1]??H;return{command:"openai-account",text:`## Device Code
20
20
 
21
21
  1. Open this verification URL:
22
22
 
23
- ${H}
23
+ ${L}
24
24
 
25
25
  2. Enter the code: **${V}**
26
26
 
27
- ${L}
27
+ ${H}
28
28
 
29
- The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{verificationUrl:H,userCode:V,instructions:L}}}return{command:"openai-account",text:`## Add OpenAI Account
29
+ The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{verificationUrl:L,userCode:V,instructions:H}}}return{command:"openai-account",text:`## Add OpenAI Account
30
30
 
31
31
  Open this URL and complete sign-in:
32
32
 
33
- ${H}
34
-
35
33
  ${L}
36
34
 
37
- The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{url:H,instructions:L}}}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:G.map(x1)}}}async function f5(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),G=(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
35
+ ${H}
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:G.map(x1)}}}async function u5(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),G=(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:G}};if(!X.clearStickyRouting)return{command:"openai-routing",text:`## OpenAI Routing Reset
40
40
 
41
41
  This runtime cannot clear the current session pin.`,knobs:{mode:G}};return await X.clearStickyRouting(X.sessionId),i.info("routing session pin cleared"),{command:"openai-routing",text:`## OpenAI Routing Reset
42
42
 
43
- This session's pin was cleared. The next request may choose the same account if it remains the best selection.`,knobs:{mode:G}}}if(J.length===1&&(J[0]==="main-first"||J[0]==="fallback-first"||J[0]==="sticky-balanced")){let U=J[0];return await J0((H)=>{return H.routing={...H.routing??{},mode:U},H},X.accountStoragePath),i.info("routing mode changed",{mode:U}),{command:"openai-routing",text:`## OpenAI Routing Updated
43
+ This session's pin was cleared. The next request may choose the same account if it remains the best selection.`,knobs:{mode:G}}}if(J.length===1&&(J[0]==="main-first"||J[0]==="fallback-first"||J[0]==="sticky-balanced")){let z=J[0];return await J0((L)=>{return L.routing={...L.routing??{},mode:z},L},X.accountStoragePath),i.info("routing mode changed",{mode:z}),{command:"openai-routing",text:`## OpenAI Routing Updated
44
44
 
45
- Mode: \`${U}\`
46
- - ${hX(U)}
45
+ Mode: \`${z}\`
46
+ - ${hX(z)}
47
47
 
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=G==="sticky-balanced"?$?`
48
+ Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:z}}}let $=G==="sticky-balanced"&&X.sessionId?await X.getStickyRouting?.(X.sessionId):void 0,W=G==="sticky-balanced"?$?`
49
49
  - Session pin: \`${$}\`. 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: \`${G}\`
53
53
  - ${hX(G)}${W}
54
54
 
55
- Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:G}}}async function m5(Y,X){let J=await X.loadAccounts(X.accountStoragePath)??{version:1,accounts:[]},Q=J.killswitch??{},G=(J.accounts??[]).filter((W)=>W.enabled!==!1).map((W)=>W.id),$=Y.trim().toLowerCase().split(/\s+/).filter(Boolean);if($.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 H=Q.main??{},L=H.primary??H["5h"]??P1.primary,N=H.secondary??H["1w"]??P1.secondary;U.push(`| main | ≥ ${L}% | ≥ ${N}% |`);for(let O of G){let Z=Q.accounts?.[O]??Q.main??{},V=Z.primary??Z["5h"]??P1.primary,K=Z.secondary??Z["1w"]??P1.secondary;U.push(`| ${O} | ≥ ${V}% | ≥ ${K}% |`)}}return U.push(""),U.push("Commands: `/openai-killswitch on` | `/openai-killswitch off` | `/openai-killswitch set <acct>:<5h>,<1w> ...`"),{command:"openai-killswitch",text:U.join(`
56
- `),knobs:{config:Q,accountIds:G}}}if($[0]==="on"){let W={...Q,enabled:!0,main:Q.main??{primary:P1.primary,secondary:P1.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:G}}}if($[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:G}}}if($[0]==="set"&&$.length>1){let W={...Q,enabled:!0,accounts:{...Q.accounts??{}}};for(let U=1;U<$.length;U++){let H=$[U]?.match(/^([^:]+):(\d+),(\d+)$/);if(!H)continue;let[,L,N,O]=H,Z={primary:Number.parseInt(N,10),secondary:Number.parseInt(O,10)};if(L==="main")W.main=Z;else if(L==="all"){W.main=Z;for(let V of G)W.accounts[V]=Z}else W.accounts[L]=Z}return await J0((U)=>{return U.killswitch=W,U},X.accountStoragePath),i.info("killswitch thresholds updated",{count:$.length-1}),{command:"openai-killswitch",text:"## Killswitch Updated",knobs:{config:W,accountIds:G}}}return{command:"openai-killswitch",text:"Usage: `/openai-killswitch`, `/openai-killswitch on`, `/openai-killswitch off`, `/openai-killswitch set <acct>:<5h>,<1w> ...`",knobs:{config:Q,accountIds:G}}}async function c5(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),Q=A0(),G=Q.dump;if(J.length===0)return{command:"openai-dump",text:`## Request Dump
55
+ Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:G}}}async function p5(Y,X){let J=await X.loadAccounts(X.accountStoragePath)??{version:1,accounts:[]},Q=J.killswitch??{},G=(J.accounts??[]).filter((W)=>W.enabled!==!1).map((W)=>W.id),$=Y.trim().toLowerCase().split(/\s+/).filter(Boolean);if($.length===0){let W=Q.enabled===!0,z=["## Killswitch","",`Status: **${W?"ON":"OFF"}**`];if(W){z.push(""),z.push("| Account | primary threshold | secondary threshold |"),z.push("| ------- | ------------ | ------------ |");let L=Q.main??{},H=L.primary??L["5h"]??P1.primary,N=L.secondary??L["1w"]??P1.secondary;z.push(`| main | ≥ ${H}% | ≥ ${N}% |`);for(let O of G){let Z=Q.accounts?.[O]??Q.main??{},V=Z.primary??Z["5h"]??P1.primary,K=Z.secondary??Z["1w"]??P1.secondary;z.push(`| ${O} | ≥ ${V}% | ≥ ${K}% |`)}}return z.push(""),z.push("Commands: `/openai-killswitch on` | `/openai-killswitch off` | `/openai-killswitch set <acct>:<5h>,<1w> ...`"),{command:"openai-killswitch",text:z.join(`
56
+ `),knobs:{config:Q,accountIds:G}}}if($[0]==="on"){let W={...Q,enabled:!0,main:Q.main??{primary:P1.primary,secondary:P1.secondary}};return await J0((z)=>{return z.killswitch=W,z},X.accountStoragePath),i.info("killswitch enabled"),{command:"openai-killswitch",text:"## Killswitch Enabled",knobs:{config:W,accountIds:G}}}if($[0]==="off"){let W={...Q,enabled:!1};return await J0((z)=>{return z.killswitch=W,z},X.accountStoragePath),i.info("killswitch disabled"),{command:"openai-killswitch",text:"## Killswitch Disabled",knobs:{config:W,accountIds:G}}}if($[0]==="set"&&$.length>1){let W={...Q,enabled:!0,accounts:{...Q.accounts??{}}};for(let z=1;z<$.length;z++){let L=$[z]?.match(/^([^:]+):(\d+),(\d+)$/);if(!L)continue;let[,H,N,O]=L,Z={primary:Number.parseInt(N,10),secondary:Number.parseInt(O,10)};if(H==="main")W.main=Z;else if(H==="all"){W.main=Z;for(let V of G)W.accounts[V]=Z}else W.accounts[H]=Z}return await J0((z)=>{return z.killswitch=W,z},X.accountStoragePath),i.info("killswitch thresholds updated",{count:$.length-1}),{command:"openai-killswitch",text:"## Killswitch Updated",knobs:{config:W,accountIds:G}}}return{command:"openai-killswitch",text:"Usage: `/openai-killswitch`, `/openai-killswitch on`, `/openai-killswitch off`, `/openai-killswitch set <acct>:<5h>,<1w> ...`",knobs:{config:Q,accountIds:G}}}async function l5(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),Q=A0(),G=Q.dump;if(J.length===0)return{command:"openai-dump",text:`## Request Dump
57
57
 
58
58
  - Enabled: ${G?"ON":"OFF"}
59
59
  - Directory: ${Q.dumpDir}
@@ -62,40 +62,40 @@ Usage: \`/openai-dump on\` or \`/openai-dump off\``,knobs:{enabled:G}};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(($)=>{return $.dump={...$.dump??{},enabled:!1},$},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:G}}}async function u5(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
65
+ Warning: body dumps may contain prompt/session content. Turn this off after debugging.`,knobs:{enabled:!0}};if(J[0]==="off")return await J0(($)=>{return $.dump={...$.dump??{},enabled:!1},$},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:G}}}async function d5(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),Q=["error","warn","info","debug","trace"];if(J.length===0){let W=(await X.loadAccounts(X.accountStoragePath))?.logging?.level??"info";return{command:"openai-logging",text:`## Logging
66
66
 
67
67
  - Level: \`${W}\`
68
68
 
69
- Valid levels: ${Q.map((U)=>`\`${U}\``).join(", ")}
69
+ Valid levels: ${Q.map((z)=>`\`${z}\``).join(", ")}
70
70
 
71
71
  Usage: \`/openai-logging <level>\``,knobs:{level:W}}}let G=J[0];if(G&&Q.includes(G)){let $=G;return kY($),await J0((W)=>{return W.logging={...W.logging??{},level:$},W},X.accountStoragePath),i.info("log level changed",{level:$}),{command:"openai-logging",text:`## Logging Updated
72
72
 
73
73
  Level set to \`${$}\`.`,knobs:{level:$}}}return{command:"openai-logging",text:`## Invalid Level
74
74
 
75
- Valid levels: ${Q.map(($)=>`\`${$}\``).join(", ")}`,knobs:{level:"info"}}}function p5(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 l5(Y,X){let J=X.cacheKeepManager,Q=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),G=await X.loadAccounts(X.accountStoragePath),$=G?.cachekeep?.enabled===!0;if(Q.length===0||Q[0]==="status"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
75
+ Valid levels: ${Q.map(($)=>`\`${$}\``).join(", ")}`,knobs:{level:"info"}}}function i5(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 n5(Y,X){let J=X.cacheKeepManager,Q=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),G=await X.loadAccounts(X.accountStoragePath),$=G?.cachekeep?.enabled===!0;if(Q.length===0||Q[0]==="status"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
76
76
 
77
- Status: **not available** (manager not wired)`,knobs:{}};let U=J.status(),H=U.window,L=H?`${String(H.startHour).padStart(2,"0")}-${String(H.endHour).padStart(2,"0")}`:"always (no window)",N=["## Cachekeep","",`Status: **${$?"ON":"OFF"}**`,`Timer: **${U.running?"armed":"idle"}**`,`Subagent warming: **${G?.cachekeep?.subagents===!0?"ON":"OFF"}**`,`Idle policy: **sustain ${U.sustain?"ON":"OFF"} (main only)**`,`Window: **${L}**`];if(N.push(`Tracked sessions: **${U.tracked}**`),U.targets.length>0){N.push("");for(let Z of U.targets){let V=Z.sessionKey.length>12?`${Z.sessionKey.slice(0,12)}…`:Z.sessionKey,K=Math.ceil((Z.cacheExpiresAt-U.generatedAt)/1000);N.push(`- \`${V}\` (${Z.accountId??"main"}) — expires in ${K}s`+(Z.lastWarmedAt?`, last warm ${Math.ceil((U.generatedAt-Z.lastWarmedAt)/1000)}s ago`:"")+(Z.backoffUntil&&Z.backoffUntil>U.generatedAt?`, backoff ${Math.ceil((Z.backoffUntil-U.generatedAt)/1000)}s`:""))}}N.push(""),N.push(`TTL: ${Math.round(U.ttlMs/1000)}s | Lead: ${Math.round(U.leadMs/1000)}s | Max idle warm: ${Math.round(U.maxIdleWarmMs/60000)}min`),N.push(""),N.push("Commands: `/openai-cachekeep on` | `/openai-cachekeep off` | `/openai-cachekeep sustain on` | `/openai-cachekeep sustain off` | `/openai-cachekeep HH-HH` | `/openai-cachekeep window clear` | `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off` | `/openai-cachekeep`");let O=Math.max(0,...U.targets.map((Z)=>Z.lastWarmedAt??0));return{command:"openai-cachekeep",text:N.join(`
78
- `),knobs:{enabled:$,subagents:G?.cachekeep?.subagents===!0,sustain:U.sustain,window:H,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
77
+ Status: **not available** (manager not wired)`,knobs:{}};let z=J.status(),L=z.window,H=L?`${String(L.startHour).padStart(2,"0")}-${String(L.endHour).padStart(2,"0")}`:"always (no window)",N=["## Cachekeep","",`Status: **${$?"ON":"OFF"}**`,`Timer: **${z.running?"armed":"idle"}**`,`Subagent warming: **${G?.cachekeep?.subagents===!0?"ON":"OFF"}**`,`Idle policy: **sustain ${z.sustain?"ON":"OFF"} (main only)**`,`Window: **${H}**`];if(N.push(`Tracked sessions: **${z.tracked}**`),z.targets.length>0){N.push("");for(let Z of z.targets){let V=Z.sessionKey.length>12?`${Z.sessionKey.slice(0,12)}…`:Z.sessionKey,K=Math.ceil((Z.cacheExpiresAt-z.generatedAt)/1000);N.push(`- \`${V}\` (${Z.accountId??"main"}) — expires in ${K}s`+(Z.lastWarmedAt?`, last warm ${Math.ceil((z.generatedAt-Z.lastWarmedAt)/1000)}s ago`:"")+(Z.backoffUntil&&Z.backoffUntil>z.generatedAt?`, backoff ${Math.ceil((Z.backoffUntil-z.generatedAt)/1000)}s`:""))}}N.push(""),N.push(`TTL: ${Math.round(z.ttlMs/1000)}s | Lead: ${Math.round(z.leadMs/1000)}s | Max idle warm: ${Math.round(z.maxIdleWarmMs/60000)}min`),N.push(""),N.push("Commands: `/openai-cachekeep on` | `/openai-cachekeep off` | `/openai-cachekeep sustain on` | `/openai-cachekeep sustain off` | `/openai-cachekeep HH-HH` | `/openai-cachekeep window clear` | `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off` | `/openai-cachekeep`");let O=Math.max(0,...z.targets.map((Z)=>Z.lastWarmedAt??0));return{command:"openai-cachekeep",text:N.join(`
78
+ `),knobs:{enabled:$,subagents:G?.cachekeep?.subagents===!0,sustain:z.sustain,window:L,running:z.running,tracked:z.tracked,lastWarmAt:O||void 0,generatedAt:z.generatedAt,maxIdleWarmMs:z.maxIdleWarmMs,maxSubagentIdleMs:z.maxSubagentIdleMs}}}if(Q[0]==="on"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
79
79
 
80
- Cannot start: manager not wired.`,knobs:{}};await J0((L)=>{return L.cachekeep={...L.cachekeep??{},enabled:!0},L},X.accountStoragePath),i.info("cachekeep enabled"),X.setCacheKeepEnabled?.(!0),J.start();let U=J.status(),H=Math.max(0,...U.targets.map((L)=>L.lastWarmedAt??0));return{command:"openai-cachekeep",text:`## Cachekeep Enabled
80
+ Cannot start: manager not wired.`,knobs:{}};await J0((H)=>{return H.cachekeep={...H.cachekeep??{},enabled:!0},H},X.accountStoragePath),i.info("cachekeep enabled"),X.setCacheKeepEnabled?.(!0),J.start();let z=J.status(),L=Math.max(0,...z.targets.map((H)=>H.lastWarmedAt??0));return{command:"openai-cachekeep",text:`## Cachekeep Enabled
81
81
 
82
- TTL: ${Math.round(U.ttlMs/1000)}s | Max idle warm ${Math.round(U.maxIdleWarmMs/60000)}min`,knobs:{enabled:!0,subagents:G?.cachekeep?.subagents===!0,sustain:U.sustain,window:U.window,running:U.running,tracked:U.tracked,lastWarmAt:H||void 0,generatedAt:U.generatedAt,maxIdleWarmMs:U.maxIdleWarmMs,maxSubagentIdleMs:U.maxSubagentIdleMs}}}if(Q[0]==="off")return await J0((U)=>{return U.cachekeep={...U.cachekeep??{},enabled:!1},U},X.accountStoragePath),i.info("cachekeep disabled"),X.setCacheKeepEnabled?.(!1),J?.stop(),{command:"openai-cachekeep",text:"## Cachekeep Disabled",knobs:{enabled:!1,sustain:G?.cachekeep?.sustain===!0,running:!1,tracked:0}};if(Q[0]==="sustain"){let U=Q[1];if(Q.length!==2||U!=="on"&&U!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep sustain on` | `/openai-cachekeep sustain off`",knobs:{}};let H=U==="on";await J0((N)=>{return N.cachekeep={...N.cachekeep??{},sustain:H},N},X.accountStoragePath),i.info(`cachekeep sustain ${H?"enabled":"disabled"}`),X.setCacheKeepSustain?.(H);let L=J?.status();return{command:"openai-cachekeep",text:H?`## Cachekeep Sustain Enabled
82
+ TTL: ${Math.round(z.ttlMs/1000)}s | Max idle warm ${Math.round(z.maxIdleWarmMs/60000)}min`,knobs:{enabled:!0,subagents:G?.cachekeep?.subagents===!0,sustain:z.sustain,window:z.window,running:z.running,tracked:z.tracked,lastWarmAt:L||void 0,generatedAt:z.generatedAt,maxIdleWarmMs:z.maxIdleWarmMs,maxSubagentIdleMs:z.maxSubagentIdleMs}}}if(Q[0]==="off")return await J0((z)=>{return z.cachekeep={...z.cachekeep??{},enabled:!1},z},X.accountStoragePath),i.info("cachekeep disabled"),X.setCacheKeepEnabled?.(!1),J?.stop(),{command:"openai-cachekeep",text:"## Cachekeep Disabled",knobs:{enabled:!1,sustain:G?.cachekeep?.sustain===!0,running:!1,tracked:0}};if(Q[0]==="sustain"){let z=Q[1];if(Q.length!==2||z!=="on"&&z!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep sustain on` | `/openai-cachekeep sustain off`",knobs:{}};let L=z==="on";await J0((N)=>{return N.cachekeep={...N.cachekeep??{},sustain:L},N},X.accountStoragePath),i.info(`cachekeep sustain ${L?"enabled":"disabled"}`),X.setCacheKeepSustain?.(L);let H=J?.status();return{command:"openai-cachekeep",text:L?`## Cachekeep Sustain Enabled
83
83
 
84
84
  Sustain keeps main-agent sessions warming past the idle cap for this process. Clock windows still apply.
85
85
 
86
86
  Before enabling sustain with Magic Context, set a non-expiring \`cache_ttl\` for models used by main sessions; elapsed-time cold-cache assumptions are no longer valid.`:`## Cachekeep Sustain Disabled
87
87
 
88
- Main-agent sessions again stop warming at the configured idle cap.`,knobs:{enabled:$,subagents:G?.cachekeep?.subagents===!0,sustain:H,window:L?.window,running:L?.running??!1,tracked:L?.tracked??0,generatedAt:L?.generatedAt??Date.now(),maxIdleWarmMs:L?.maxIdleWarmMs??3600000,maxSubagentIdleMs:L?.maxSubagentIdleMs??1800000}}}if(Q[0]==="subagents"){let U=Q[1];if(!U||U!=="on"&&U!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off`",knobs:{}};let H=U==="on";await J0((N)=>{return N.cachekeep={...N.cachekeep??{},subagents:H},N},X.accountStoragePath),i.info(H?"cachekeep subagent warming enabled":"cachekeep subagent warming disabled"),X.setCacheKeepSubagents?.(H);let L=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Subagent Warming
88
+ Main-agent sessions again stop warming at the configured idle cap.`,knobs:{enabled:$,subagents:G?.cachekeep?.subagents===!0,sustain:L,window:H?.window,running:H?.running??!1,tracked:H?.tracked??0,generatedAt:H?.generatedAt??Date.now(),maxIdleWarmMs:H?.maxIdleWarmMs??3600000,maxSubagentIdleMs:H?.maxSubagentIdleMs??1800000}}}if(Q[0]==="subagents"){let z=Q[1];if(!z||z!=="on"&&z!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off`",knobs:{}};let L=z==="on";await J0((N)=>{return N.cachekeep={...N.cachekeep??{},subagents:L},N},X.accountStoragePath),i.info(L?"cachekeep subagent warming enabled":"cachekeep subagent warming disabled"),X.setCacheKeepSubagents?.(L);let H=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Subagent Warming
89
89
 
90
- Subagent warming: **${H?"ON":"OFF"}**`,knobs:{enabled:$,subagents:H,sustain:L?.sustain??G?.cachekeep?.sustain===!0,window:L?.window,running:L?.running??!1,tracked:L?.tracked??0,generatedAt:L?.generatedAt??Date.now(),maxIdleWarmMs:L?.maxIdleWarmMs??3600000,maxSubagentIdleMs:L?.maxSubagentIdleMs??1800000}}}if(Q[0]==="window"){let U=Q[1];if(U==="clear"||U==="off"){await J0((L)=>{if(L.cachekeep)delete L.cachekeep.startHour,delete L.cachekeep.endHour;return L},X.accountStoragePath),X.setCacheKeepWindow?.(void 0),i.info("cachekeep window cleared");let H=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Cleared
90
+ Subagent warming: **${L?"ON":"OFF"}**`,knobs:{enabled:$,subagents:L,sustain:H?.sustain??G?.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 z=Q[1];if(z==="clear"||z==="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:$,subagents:G?.cachekeep?.subagents===!0,sustain:H?.sustain??G?.cachekeep?.sustain===!0,window:void 0,running:H?.running??!1,tracked:H?.tracked??0,generatedAt:H?.generatedAt??Date.now(),maxIdleWarmMs:H?.maxIdleWarmMs??3600000,maxSubagentIdleMs:H?.maxSubagentIdleMs??1800000}}}return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep window clear`",knobs:{}}}let W=Q[0];if(W&&/^\d{1,2}-\d{1,2}$/.test(W)){let U=p5(W);if(!U.ok)return{command:"openai-cachekeep",text:`## Cachekeep Window Invalid
92
+ Cachekeep will now warm on every tick (within idle caps).`,knobs:{enabled:$,subagents:G?.cachekeep?.subagents===!0,sustain:L?.sustain??G?.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 z=i5(W);if(!z.ok)return{command:"openai-cachekeep",text:`## Cachekeep Window Invalid
93
93
 
94
- ${U.reason}`,knobs:{}};let{startHour:H,endHour:L}=U;await J0((Z)=>{return Z.cachekeep={...Z.cachekeep??{},startHour:H,endHour:L},Z},X.accountStoragePath),X.setCacheKeepWindow?.({startHour:H,endHour:L}),i.info("cachekeep window set",{startHour:H,endHour:L});let N=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Set
94
+ ${z.reason}`,knobs:{}};let{startHour:L,endHour:H}=z;await J0((Z)=>{return Z.cachekeep={...Z.cachekeep??{},startHour:L,endHour:H},Z},X.accountStoragePath),X.setCacheKeepWindow?.({startHour:L,endHour:H}),i.info("cachekeep window set",{startHour:L,endHour:H});let N=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Set
95
95
 
96
- Warming limited to **${`${String(H).padStart(2,"0")}-${String(L).padStart(2,"0")}`}** local hours.`,knobs:{enabled:$,subagents:G?.cachekeep?.subagents===!0,sustain:N?.sustain??G?.cachekeep?.sustain===!0,window:{startHour:H,endHour:L},running:N?.running??!1,tracked:N?.tracked??0,generatedAt:N?.generatedAt??Date.now(),maxIdleWarmMs:N?.maxIdleWarmMs??3600000,maxSubagentIdleMs:N?.maxSubagentIdleMs??1800000}}}return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep`, `/openai-cachekeep on`, `/openai-cachekeep off`, `/openai-cachekeep sustain on`, `/openai-cachekeep sustain off`, `/openai-cachekeep HH-HH`, `/openai-cachekeep window clear`, `/openai-cachekeep subagents on`, `/openai-cachekeep subagents off`",knobs:{}}}function pX(Y){let X=[Y.primary?.usedPercent,Y.secondary?.usedPercent].filter((J)=>J!==void 0);return X.length>0?Math.max(...X):void 0}function d5(Y,X){let J=[Y.primary,Y.secondary].filter((G)=>G!==void 0),Q=J.filter((G)=>s1(G,X));return(Q.length>0?Q:J).sort((G,$)=>$.usedPercent-G.usedPercent)[0]?.resetsAt}function i5(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)=>!s1(Q,X))}function w8(Y){if(!Y)return;try{return decodeURIComponent(Y)}catch{return}}async function gX(Y,X){try{let J=await X.resolveResetTarget(Y),Q=J.accountKey==="main"?void 0:J.chatgptAccountId,[G,$]=await Promise.all([$1({accessToken:J.accessToken,fetchImpl:X.fetchImpl,now:X.now,accountId:J.chatgptAccountId}),P8(X.fetchImpl,J.accessToken,Q)]),W=SY($.credits),U=$.availableCount??G.resetCreditsAvailable??0,H=G.resetCreditsApplicable??0,L=D8(G,X.quotaManager.isRateLimited(Y),H,X.now()),N;if(!J.chatgptAccountId)N="stable ChatGPT account identity unavailable";else if(!L.ok)N=L.reason;else if(!W)N="no eligible credit";return{accountKey:J.accountKey,label:J.label,chatgptAccountId:J.chatgptAccountId,usedPercent:pX(G),resetTime:d5(G,X.now()),availableCount:U,applicableAvailableCount:H,eligible:N===void 0,reason:N,selectedCreditId:W?.id,selectedCreditExpiresAt:W?.expiresAt}}catch(J){return i.warn("reset preview row failed",{accountKey:Y,error:J?.message??String(J)}),{accountKey:Y,label:Y==="main"?"Main account":Y,eligible:!1,reason:J?.message??String(J)}}}function n5(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`,G=J.availableCount===void 0?"credits unavailable":`${J.applicableAvailableCount??0}/${J.availableCount} applicable/available`,$=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(`
96
+ Warming limited to **${`${String(L).padStart(2,"0")}-${String(H).padStart(2,"0")}`}** local hours.`,knobs:{enabled:$,subagents:G?.cachekeep?.subagents===!0,sustain:N?.sustain??G?.cachekeep?.sustain===!0,window:{startHour:L,endHour:H},running:N?.running??!1,tracked:N?.tracked??0,generatedAt:N?.generatedAt??Date.now(),maxIdleWarmMs:N?.maxIdleWarmMs??3600000,maxSubagentIdleMs:N?.maxSubagentIdleMs??1800000}}}return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep`, `/openai-cachekeep on`, `/openai-cachekeep off`, `/openai-cachekeep sustain on`, `/openai-cachekeep sustain off`, `/openai-cachekeep HH-HH`, `/openai-cachekeep window clear`, `/openai-cachekeep subagents on`, `/openai-cachekeep subagents off`",knobs:{}}}function pX(Y){let X=[Y.primary?.usedPercent,Y.secondary?.usedPercent].filter((J)=>J!==void 0);return X.length>0?Math.max(...X):void 0}function o5(Y,X){let J=[Y.primary,Y.secondary].filter((G)=>G!==void 0),Q=J.filter((G)=>s1(G,X));return(Q.length>0?Q:J).sort((G,$)=>$.usedPercent-G.usedPercent)[0]?.resetsAt}function r5(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)=>!s1(Q,X))}function w8(Y){if(!Y)return;try{return decodeURIComponent(Y)}catch{return}}async function gX(Y,X){try{let J=await X.resolveResetTarget(Y),Q=J.accountKey==="main"?void 0:J.chatgptAccountId,[G,$]=await Promise.all([$1({accessToken:J.accessToken,fetchImpl:X.fetchImpl,now:X.now,accountId:J.chatgptAccountId}),P8(X.fetchImpl,J.accessToken,Q)]),W=SY($.credits),z=$.availableCount??G.resetCreditsAvailable??0,L=G.resetCreditsApplicable??0,H=D8(G,X.quotaManager.isRateLimited(Y),L,X.now()),N;if(!J.chatgptAccountId)N="stable ChatGPT account identity unavailable";else if(!H.ok)N=H.reason;else if(!W)N="no eligible credit";return{accountKey:J.accountKey,label:J.label,chatgptAccountId:J.chatgptAccountId,usedPercent:pX(G),resetTime:o5(G,X.now()),availableCount:z,applicableAvailableCount:L,eligible:N===void 0,reason:N,selectedCreditId:W?.id,selectedCreditExpiresAt:W?.expiresAt}}catch(J){return i.warn("reset preview row failed",{accountKey:Y,error:J?.message??String(J)}),{accountKey:Y,label:Y==="main"?"Main account":Y,eligible:!1,reason:J?.message??String(J)}}}function s5(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`,G=J.availableCount===void 0?"credits unavailable":`${J.applicableAvailableCount??0}/${J.availableCount} applicable/available`,$=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
97
  `)}function yX(Y){let X=["## Confirm reset credit","",`Account: **${Y.label}** (\`${Y.accountKey}\`)`,`Current quota: **${Y.usedPercent??"unknown"}% used**`,`Credit: **Spend 1 of ${Y.applicableAvailableCount??0}**`,`Credit expires: **${Y.selectedCreditExpiresAt??"unavailable"}**`,`Quota resets: **${Y.resetTime??"unavailable"}**`,""];if(Y.eligible&&Y.chatgptAccountId)X.push(`Confirm: \`/openai-reset confirm ${encodeURIComponent(Y.accountKey)} ${encodeURIComponent(Y.chatgptAccountId)}\``);else X.push(`Cannot reset: **${Y.reason??"not eligible"}**`);return X.join(`
98
- `)}function T0(Y,X,J,Q={}){return{command:M1,text:J,knobs:{stage:"result",accountKey:Y,code:X,...Q}}}function o5(Y,X,J){if(X instanceof k0){let G={identity_mismatch:"The account identity changed before redemption. Reopen the reset account list.",invalid_account_key:"The selected account key is reserved. Reopen the reset account list.",cooldown_active:"This account just reset — re-checking quota. Wait for the cooldown before another redemption.",expired_unreconciled:"The previous attempt outcome is unknown — retry replays the same identifiers, or wait until quota reflects the earlier attempt.",retry_without_inflight:"There is no active reset redemption to retry. Reopen the account list.",not_exhausted:"No credit was spent: the fresh account state is not exhausted.",no_applicable_credits:"No credit was spent: no applicable credits are available.",no_eligible_credit:"No credit was spent: no eligible credit was returned."};return T0(Y,X.kind,`## Reset credit
98
+ `)}function T0(Y,X,J,Q={}){return{command:M1,text:J,knobs:{stage:"result",accountKey:Y,code:X,...Q}}}function a5(Y,X,J){if(X instanceof k0){let G={identity_mismatch:"The account identity changed before redemption. Reopen the reset account list.",invalid_account_key:"The selected account key is reserved. Reopen the reset account list.",cooldown_active:"This account just reset — re-checking quota. Wait for the cooldown before another redemption.",expired_unreconciled:"The previous attempt outcome is unknown — retry replays the same identifiers, or wait until quota reflects the earlier attempt.",retry_without_inflight:"There is no active reset redemption to retry. Reopen the account list.",not_exhausted:"No credit was spent: the fresh account state is not exhausted.",no_applicable_credits:"No credit was spent: no applicable credits are available.",no_eligible_credit:"No credit was spent: no eligible credit was returned."};return T0(Y,X.kind,`## Reset credit
99
99
 
100
100
  ${G[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 r5(Y,X,J){let{accountKey:Q}=Y.target,G=Y.outcome.kind;if(Y.finalizeStateWriteFailed)return T0(Q,G,`## Reset credit result
112
+ The reset request failed before a known result: internal command failure — see plugin log.`)}async function t5(Y,X,J){let{accountKey:Q}=Y.target,G=Y.outcome.kind;if(Y.finalizeStateWriteFailed)return T0(Q,G,`## Reset credit result
113
113
 
114
114
  Account: **${Y.target.label}** (\`${Q}\`)
115
115
 
116
- The server outcome recorded as \`${G}\`, 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(G==="reset"||G==="already_redeemed"){let W={account:Q,ok:!1,error:"targeted quota refresh did not complete"};try{W=await X.refreshResetTargetQuota(Q)}catch(V){W.error=V?.message??String(V)}let U=!W.ok&&W.error!==void 0;if(U)i.warn("reset quota re-check failed",{accountKey:Q,error:W.error});let H=Q==="main"?X.quotaManager.getMain():X.quotaManager.getFallback(Q),L=W.ok&&i5(H?.quota,X.now()),N=H?.quota.resetCreditsApplicable,O=L?"Post-verification: **window fresh**.":`Post-verification: **window not yet refreshed** (server code \`${G}\`).`,Z=U?`
116
+ The server outcome recorded as \`${G}\`, 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(G==="reset"||G==="already_redeemed"){let W={account:Q,ok:!1,error:"targeted quota refresh did not complete"};try{W=await X.refreshResetTargetQuota(Q)}catch(V){W.error=V?.message??String(V)}let z=!W.ok&&W.error!==void 0;if(z)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&&r5(L?.quota,X.now()),N=L?.quota.resetCreditsApplicable,O=H?"Post-verification: **window fresh**.":`Post-verification: **window not yet refreshed** (server code \`${G}\`).`,Z=z?`
117
117
 
118
118
  quota re-check failed — see log.`:"";return T0(Q,G,`## Reset credit result
119
119
 
@@ -123,7 +123,7 @@ Code: \`${G}\`
123
123
 
124
124
  ${O}${Z}${N===void 0?"":`
125
125
 
126
- Remaining applicable credits: **${N}**`}`,{verifiedFresh:L,afterUsedPercent:pX(H?.quota??{}),remainingCredits:N})}if(G==="ambiguous_local")return T0(Q,G,`## Reset credit result
126
+ Remaining applicable credits: **${N}**`}`,{verifiedFresh:H,afterUsedPercent:pX(L?.quota??{}),remainingCredits:N})}if(G==="ambiguous_local")return T0(Q,G,`## 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: \`${G}\`
143
143
 
144
- ${$[G]??"The server returned a no-op result. No reset was confirmed."}`)}async function s5(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:M1,text:`## Reset credit
144
+ ${$[G]??"The server returned a no-op result. No reset was confirmed."}`)}async function e5(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:M1,text:`## Reset credit
145
145
 
146
- Unavailable: reset command runtime dependencies are not wired.`,knobs:{}};let Q=X,G=Y.trim().split(/\s+/).filter(Boolean),$=G[0];if(!$||$==="refresh"){let U=["main",...((await X.loadAccounts(X.accountStoragePath))?.accounts??[]).filter((L)=>L.enabled!==!1&&L.type==="oauth").map((L)=>L.id)];i.debug("reset accounts stage requested",{accountKeys:U});let H=await Promise.all(U.map((L)=>gX(L,Q)));return i.debug("reset accounts stage built",{rows:H.map((L)=>({accountKey:L.accountKey,eligible:L.eligible,reason:L.reason,usedPercent:L.usedPercent,availableCount:L.availableCount,applicableAvailableCount:L.applicableAvailableCount}))}),{command:M1,text:n5(H),knobs:{stage:"accounts",accounts:H}}}if($==="select"){let W=w8(G[1]);if(!W||!u0(W)||G.length!==2)return T0("","invalid_command","Usage: `/openai-reset select <encodedAccountKey>`");let U=await gX(W,Q);if(!U.eligible)return T0(W,"not_eligible",yX(U));return{command:M1,text:yX(U),knobs:{stage:"confirm",preview:U}}}if($==="confirm"||$==="retry"){let W=w8(G[1]),U=w8(G[2]);if(!W||!u0(W)||!U||G.length!==3)return T0(W??"","invalid_command",`Usage: \`/openai-reset ${$} <encodedAccountKey> <encodedChatgptAccountId>\``);i.info("reset redemption decision",{accountKey:W,action:$}),i.debug("reset redemption identity binding",{accountKey:W,expectedChatgptAccountId:U});try{let H=await vX({configPath:X.accountStoragePath,mutateAccountsFn:J0,loadAccountsFn:X.loadAccounts,now:Q.now,randomUUID:Q.randomUUID,fetchImpl:Q.fetchImpl,resolveTarget:Q.resolveResetTarget,fetchUsage:(L)=>$1({accessToken:L.accessToken,fetchImpl:Q.fetchImpl,now:Q.now,accountId:L.chatgptAccountId}),hasActiveRateLimitMark:(L)=>X.quotaManager.isRateLimited(L)},{accountKey:W,expectedChatgptAccountId:U,retry:$==="retry"});return i.info("reset redemption outcome",{accountKey:W,code:H.outcome.kind}),r5(H,Q,U)}catch(H){let L=o5(W,H,U);return i.info("reset redemption outcome",{accountKey:W,code:L.knobs.code}),L}}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 a5=new Set(["access","refresh","apikey","authheader","password","secret"]);function t5(Y){let X=Y.toLowerCase().replace(/[-_]/g,"");if(a5.has(X))return!0;return X.endsWith("token")}function E8(Y,X,J){if(Array.isArray(Y))return Y.map((G,$)=>E8(G,`${X}[${$}]`,J));if(!R(Y))return Y;let Q={};for(let[G,$]of Object.entries(Y)){if(t5(G)){J.push(`${X}.${G}`);continue}Q[G]=E8($,`${X}.${G}`,J)}return Q}async function k8(Y,X,J){let Q=await e5(Y,X,J),G=[],$=E8(Q.knobs,"knobs",G);if(G.length>0)return i.warn("credential-shaped knob stripped before RPC",{command:Y,fields:G}),{...Q,knobs:$};return Q}async function e5(Y,X,J){switch(Y){case"openai-quota":return g5(J);case"openai-account":return y5(X,J);case"openai-routing":return f5(X,J);case"openai-killswitch":return m5(X,J);case"openai-dump":return c5(X,J);case"openai-logging":return u5(X,J);case"openai-cachekeep":return l5(X,J);case"openai-reset":return s5(X,J);default:throw Error(`unhandled command: ${Y}`)}}var Y2=N0("quota");async function v1(Y,X={}){let J=Y.whamFn;if(!J)throw Error("whamFn is required for refreshAllQuota");let Q=[],G=Y.logger??Y2,$=(V)=>{Q.push(V);let K={pid:process.pid,accountId:V.account,status:V.ok?"ok":"error",...V.error?{error:V.error}:{}};if(V.ok)G.debug("quota refresh succeeded",K);else G.warn("quota refresh failed",K)},W=Y.skipFresherThanMs,U=!1,H;if(W!==void 0)try{H=await(Y.readSidebarState??w1)()}catch{}let L=new Map(H?.fallbacks.map((V)=>[V.id,V])??[]),N=(...V)=>W!==void 0&&V.some((K)=>typeof K==="number"&&Number.isFinite(K)&&K<=Y.now()&&Y.now()-K<W),O=await Y.loadAccounts(Y.configPath).catch(()=>{return}),Z=O?.mainAccountId??Y.storageMainAccountId;if(!X.accountKey||X.accountKey==="main")try{let V=await Y.getAuth();if(V.type==="oauth"){let K=H&&Z!==void 0&&H.main.mainAccountId===Z?H.main.quota:void 0;if(N(Y.quotaManager.peekMainForPolicy(Z)?.checkedAt,K?.primary?.checkedAt,K?.secondary?.checkedAt,K?.checkedAt))$({account:"main",ok:!0});else{if(!V.access||(V.expires??0)<Y.now()){let M=await Y.refreshMainWithLease();V={...V,access:M.access,expires:M.expires}}if(V.access)if(Y.respectBackoff&&Y.quotaManager.isBackedOff())$({account:"main",ok:!0});else{let M=await J({accessToken:V.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:Z,accountKey:"main"});Y.quotaManager.setMain(V.access,{quota:M,refreshAfter:Y.now()+300000,checkedAt:Y.now()},Z,!0),U=!0,$({account:"main",ok:!0})}else $({account:"main",ok:!1,error:"no access token"})}}else $({account:"main",ok:!1,error:"auth type is not oauth"})}catch(V){$({account:"main",ok:!1,error:W1(V)})}if(O)for(let V of O.accounts){if(X.accountKey&&(X.accountKey==="main"||V.id!==X.accountKey))continue;if(V.enabled===!1||!Y.isOAuthAccountFn(V)){if(X.accountKey)$({account:V.id,ok:!1,error:"account is not an enabled OAuth fallback"});continue}try{let K=L.get(V.id),j=V.accountId,M=K&&j!==void 0&&K.accountId===j?K.quota:void 0;if(N(Y.quotaManager.peekFallbackForPolicy(V.id,j)?.checkedAt,M?.primary?.checkedAt,M?.secondary?.checkedAt,M?.checkedAt)){$({account:V.id,ok:!0});continue}if(Y.respectBackoff&&Y.quotaManager.isFallbackBackedOff(V.id,V.access)){$({account:V.id,ok:!0});continue}let I;try{I=await Y.fallbackManager.refreshAccount(V,O)}catch{I=V}if(!I.access){$({account:V.id,ok:!1,error:"no access token"});continue}let E=await J({accessToken:I.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:I.accountId,accountKey:V.id});Y.quotaManager.setFallback(V.id,{quota:E,refreshAfter:Y.now()+300000,checkedAt:Y.now()},I.access,!0,I.accountId),U=!0,$({account:V.id,ok:!0})}catch(K){$({account:V.id,ok:!1,error:W1(K)})}}if(X.accountKey&&X.accountKey!=="main"&&!Q.some((V)=>V.account===X.accountKey))Q.push({account:X.accountKey,ok:!1,error:"account not found"});if(W===void 0||U){let V=await Y.loadAccounts(Y.configPath);await Y.writeSidebarState(Y.quotaManager,V)}return Q}var X2=300000,J2=30000,Q2=240000,G2="bg-quota-refresh",$2=120000;function W2(Y,X){return bY({name:G2,ttlMs:$2,path:Y,renew:!0,...X})}function lX(Y,X=v1,J=()=>W2(Y.configPath)){return z2(Y,X,J)}async function z2(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:Q2})}finally{await Q?.release().catch(()=>{})}}class b8{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)*J2);if(this.timer=this.setIntervalFn(()=>{let Q=this.run;if(this.stopped||!Q||this.tickPromise)return;let G=Q().catch(($)=>{try{this.onError?.($)}catch{}}).finally(()=>{if(this.tickPromise===G)this.tickPromise=void 0});this.tickPromise=G},X2+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 x8(Y){if(typeof Y!=="string")return!1;try{let X=JSON.parse(Y);return R(X)&&R(X.client_metadata)&&X.client_metadata.ws_request_header_x_openai_internal_codex_responses_lite==="true"}catch{return!1}}function v8(Y){if(typeof Y!=="string")return Y;try{let X=JSON.parse(Y);if(!R(X)||!R(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 xY(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"),x8(Y.body))X.set("x-openai-internal-codex-responses-lite","true");return{...Y,headers:X,body:v8(Y.body)}}function rX(Y){if(!Y.enabled||typeof Y.body!=="string")return;let X=Y.headers.has("x-parent-session-id");if(X&&!Y.includeSubagents)return;let J=Y.headers.get("session-id")??Y.headers.get("x-opencode-session")??Y.headers.get("x-session-affinity")??void 0;if(!J)return;let Q={};for(let G of["session-id","x-session-affinity","x-parent-session-id","user-agent","version","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-client-request-id","thread-id","x-openai-internal-codex-responses-lite"]){let $=Y.headers.get(G);if($)Q[G]=$}return{sessionKey:J,bodyText:Y.body,replayHeaders:Q,isSubagent:X}}function sX(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 dX(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 U2=300000,aX=1800000,iX=2*aX+900000,H2=3600000,nX=1800000,oX=60000,L2=32,V2=8388608,h8=600000;function tX(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 N2(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 B2(Y,X){return tX(Y)?aX:X}function g8(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function eX(Y){if(!Y||typeof Y!=="object")return g8();let X=Y,J=Number(X.input_tokens)||Number(X.prompt_tokens)||0,Q=Number(X.output_tokens)||Number(X.completion_tokens)||0,G=X.input_tokens_details??X.prompt_tokens_details,$=Number(G?.cached_tokens)||Number(X.cached_tokens)||0,W=J>0?$/J:null;return{input_tokens:J,output_tokens:Q,cached_tokens:$,hit_rate:W}}function Z2(Y){try{let X=JSON.parse(Y);return eX(X.usage)}catch{return g8()}}function K2(Y){let X,J=[],Q,G=()=>{if(!J.length)return;let $=J.join(`
147
- `).trim();J=[];let W=X;if(X=void 0,!$||$==="[DONE]")return;try{let U=JSON.parse($),H=U.type??W;if(H!=="response.completed"&&H!=="response.done")return;let L=U.response;Q=eX(L?.usage??U.usage)}catch{}};for(let $ of Y.split(/\r?\n/)){if($===""){G();continue}if($.startsWith("event:")){X=$.slice(6).trim();continue}if($.startsWith("data:"))J.push($.slice(5).trim())}return G(),Q??g8()}class y8{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??U2,this.tickIntervalMs=Y.tickIntervalMs??oX,this.leadMs=Y.leadMs??this.tickIntervalMs+15000;let X=Y.maxIdleWarmMs??Y.maxDurationMs;this.maxIdleWarmMs=typeof X==="number"&&Number.isFinite(X)&&X>0?X:H2;let J=Y.maxSubagentIdleMs??nX;this.maxSubagentIdleMs=typeof J==="number"&&Number.isFinite(J)&&J>0?J:nX,this.tickIntervalMs=Y.tickIntervalMs??oX,this.maxTargets=Y.maxTargets??L2,this.maxBytes=Y.maxBytes??V2,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&&!dX(U,new Date(this.now()))){this.log.debug("cachekeep track skipped (outside window)",this.logPayload({sessionKey:Y,startHour:U.startHour,endHour:U.endHour}));return}if(this.targets.has(Y)){let N=this.targets.get(Y);if(N)this.totalBytes-=N.bodyText.length;this.targets.delete(Y)}else this.log.debug("cachekeep captured target",this.logPayload({sessionKey:Y,accountId:J}));while(this.targets.size>=this.maxTargets||this.totalBytes+W>this.maxBytes&&this.targets.size>0){let N,O=Number.POSITIVE_INFINITY;for(let[V,K]of this.targets){let j=Math.max(K.lastRealRequestAt,K.lastWarmedAt??0);if(j<O)N=V,O=j}if(N===void 0)break;let Z=this.targets.get(N);if(Z)this.totalBytes-=Z.bodyText.length;this.targets.delete(N)}let H=B2(X,this.ttlMs),L={bodyText:X,accountId:J||void 0,chatgptAccountId:Q,route:"main",ttlMs:H,cacheExpiresAt:this.now()+H,warmCount:0,lastRealRequestAt:this.now(),replayHeaders:G,isSubagent:$,is56:tX(X)};this.targets.set(Y,L),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-iX;for(let[G,$]of this.targets){let W,U;if(this.isGpt56Subagent($))W=Q,U=iX;else W=$.isSubagent?J:X,U=$.isSubagent?this.maxSubagentIdleMs:this.maxIdleWarmMs;if(!($.isSubagent!==!0&&this.getSustain?.()===!0)&&$.lastRealRequestAt<W)this.log.debug("cachekeep pruned idle target",this.logPayload({sessionKey:G,accountId:$.accountId??"main",lastRealRequestAt:$.lastRealRequestAt,maxIdleWarmMs:U})),this.totalBytes-=$.bodyText.length,this.targets.delete(G)}}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&&!dX(Y,new Date(this.now())))return;let X=this.now(),J=X+this.leadMs;for(let[Q,G]of this.targets)if(G.backoffUntil&&X>=G.backoffUntil&&G.cacheExpiresAt<=J)await this.prewarm(Q,G);for(let[Q,G]of this.targets){if(G.backoffUntil&&X<G.backoffUntil)continue;if(G.cacheExpiresAt<=J)await this.prewarm(Q,G)}}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(G){if(!this.disposed&&this.targets.get(Y)===X)X.backoffUntil=this.now()+h8;this.log.debug("cachekeep skip (no token)",this.logPayload({sessionKey:Y,accountId:X.accountId??"main",error:G instanceof Error?G.message:String(G)}));return}if(this.disposed||this.targets.get(Y)!==X)return;let 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 G=N2(X.bodyText),$;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({...$,headerKeys:Object.keys(Q),hasChatGptAccountId:"ChatGPT-Account-Id"in Q}));let W=xY({method:"POST",headers:Q,body:G,signal:AbortSignal.any([AbortSignal.timeout(30000),this.abortController.signal])}),U=await this.fetchImpl(this.codexResponsesUrl,W),H="";try{H=await U.text()}catch{}if(this.disposed||this.targets.get(Y)!==X)return;if(!U.ok){X.backoffUntil=this.now()+h8,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",status:U.status,error:`HTTP ${U.status}`,responseBody:H.slice(0,600)}));return}let L=U.headers.get("content-type")??"",N=L.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(H.slice(0,200));this.log.debug("cachekeep warm response",this.logPayload({status:U.status,contentType:L,bodyLen:H.length,isSse:N}));let O=N?K2(H):Z2(H),Z=h1(U.headers),V=Z.primary?.usedPercent??null,K=Z.secondary?.usedPercent??null;if(this.log.debug("cachekeep fired",this.logPayload({session:Y,accountId:X.accountId??"main",input_tokens:O.input_tokens,cached_tokens:O.cached_tokens,hit_rate:O.hit_rate,output_tokens:O.output_tokens,quota_primary_pct:V,quota_secondary_pct:K})),X.cacheExpiresAt=this.now()+X.ttlMs,X.lastWarmedAt=this.now(),X.backoffUntil=void 0,X.warmCount+=1,this.isGpt56Subagent(X)&&X.warmCount>=2){if(this.targets.get(Y)===X)this.totalBytes-=X.bodyText.length,this.targets.delete(Y);return}}catch(G){if(this.disposed||this.targets.get(Y)!==X)return;X.backoffUntil=this.now()+h8,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",error:G instanceof Error?G.message:String(G)}))}}}var JJ=900000,O2=0.016666666666666666,YJ=0.000001;function m8(Y,X){for(let J of[Y?.primary?.checkedAt,Y?.checkedAt,X])if(typeof J==="number"&&Number.isFinite(J))return J;return}function c8(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let X=m8(Y.quota,Y.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||Y.now-X>JJ)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let J=f8(Y.quota).sort((Q,G)=>{let $=Q.windowMs,W=G.windowMs,U=typeof $==="number"&&Number.isFinite($),H=typeof W==="number"&&Number.isFinite(W);if(U!==H)return U?-1:1;if(U&&H)return W-$;return 0});for(let{key:Q,window:G}of J)if(Number.isFinite(G.remainingPercent)&&G.remainingPercent<=0)return{action:"migrate",reason:"exhausted",windowKey:Q,...typeof G.resetsAt==="string"?{resetsAt:G.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 q2(Y,X,J){let Q=Math.max(0,Y.remainingPercent-X);if(Q<=0)return 0;if(!Y.resetsAt)return Q;let G=Date.parse(Y.resetsAt);if(!Number.isFinite(G)||G<=J)return Q;let $=Math.max((G-J)/3600000,O2);return Q/$}function XJ(Y,X){if(Y<X)return-1;if(Y>X)return 1;return 0}function F2(Y,X){if(!Y.quota)return;let J=m8(Y.quota,Y.quotaCheckedAt);if(J===void 0||X-J>JJ)return;let Q=f8(Y.quota).map(({key:$,window:W})=>{return q2(W,Y.reservePercent[$]??0,X)}),G=Q.length>0?Math.min(...Q):0;return G>0?{candidate:Y,quotaCheckedAt:J,weight:G}:void 0}function QJ(Y){let X=Y.candidates.filter((G)=>G.killswitchPasses!==!1);if(Y.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if(X.length===0)return;let J=X.map((G)=>F2(G,Y.now)).filter((G)=>G!==void 0);if(J.length>0){J.sort(($,W)=>{let U=((Y.pendingBytes.get($.candidate.accountId)??0)+Y.requestBytes)/Math.max($.weight,YJ),H=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,YJ);return U-H||$.candidate.configuredOrder-W.candidate.configuredOrder||XJ($.candidate.accountId,W.candidate.accountId)});let G=J[0];if(G)return{accountId:G.candidate.accountId,quotaCheckedAt:G.quotaCheckedAt,source:"weighted"}}Y.onEmptyWeightedSet?.();let Q=[...X].sort((G,$)=>{let W=(G.resetCreditsApplicable??0)>0?1:0;return(($.resetCreditsApplicable??0)>0?1:0)-W||G.configuredOrder-$.configuredOrder||XJ(G.accountId,$.accountId)})[0];if(!Q)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Q.accountId,quotaCheckedAt:m8(Q.quota,Q.quotaCheckedAt),source:"mode-fallback"}}import{createHash as j2}from"node:crypto";import{chmod as D2,mkdir as P2,writeFile as u8}from"node:fs/promises";import{join as M2}from"node:path";var d8=N0("dump"),z1="x-cortexkit-openai-auth-dump-session",GJ=0,g1=new Map,w2=100;function p8(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function E2(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 WJ(Y){return j2("sha256").update(Y).digest("hex")}function l8(Y){return WJ(JSON.stringify(Y))}function zJ(Y){try{let X=JSON.parse(Y);return X!=null&&typeof X==="object"&&!Array.isArray(X)?X:void 0}catch{return}}function A2(Y,X){if(Y===void 0)return null;if(Y===X)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:Y.length,currentBytes:X.length};let J=0;while(J<Y.length&&J<X.length&&Y[J]===X[J])J++;let Q=Y.length-1,G=X.length-1;while(Q>=J&&G>=J&&Y[Q]===X[G])Q--,G--;return{changed:!0,firstByte:J,lastPreviousByte:Q,lastCurrentByte:G,changedPreviousBytes:Q-J+1,changedCurrentBytes:G-J+1,previousBytes:Y.length,currentBytes:X.length}}function T2(Y,X){if(!g1.has(Y))while(g1.size>=w2){let J=g1.keys().next().value;if(J===void 0)break;g1.delete(J)}g1.set(Y,X)}function R2(Y){if(Y===void 0)return;return Object.fromEntries(new Headers(Y).entries())}function i8(Y){if(Array.isArray(Y))return Y.map(i8);if(Y==null||typeof Y!=="object")return Y;let X={};for(let[J,Q]of Object.entries(Y)){let G=J.toLowerCase();if(G==="authorization"||G==="chatgpt-account-id"||G==="cookie"||G==="set-cookie"){X[J]="[redacted]";continue}X[J]=i8(Q)}return X}function C2(Y){let X=zJ(Y);if(X===void 0)return Y;let J=$J(X),Q=JSON.stringify(J);if(Q===void 0)return Y;return JSON.stringify(X)===Q?Y:Q}function _2(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function I2(Y){let X=zJ(Y);if(!X)return{parseable:!1};let J=Array.isArray(X.input)?X.input:[],Q=Array.isArray(X.tools)?X.tools:[],G=Q.map(_2),$=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:l8(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:l8(J[0]),toolsCount:Q.length,toolTypes:G,toolsHash:l8(Q),hasWebSearch:G.includes("web_search"),clientMetadataKeys:$?Object.keys($).sort():[]}}async function y1(Y){let X=A0();if(!X.dump)return;GJ++;let J=Y.sessionID?.trim()||"session-unknown",Q=`${new Date().toISOString().replace(/[:.]/g,"-")}-${String(GJ).padStart(5,"0")}-${E2(J)}-${Y.transport}-${Y.phase}`,G=M2(X.dumpDir,Q),$={body:`${G}.body.json`,metadata:`${G}.meta.json`,request:`${G}.request.json`},W=`${Y.transport}:${J}`,U=g1.get(W);try{await P2(X.dumpDir,{recursive:!0,mode:448}),await D2(X.dumpDir,448).catch(()=>{});let H=C2(Y.bodyText),L={id:Q,createdAt:new Date().toISOString(),session:p8(J),transport:Y.transport,phase:Y.phase,accountId:Y.accountId,status:Y.status,error:Y.error,bodyBytes:Y.bodyText.length,bodyHash:WJ(Y.bodyText),diff:A2(U,Y.bodyText),body:I2(Y.bodyText),files:$};await Promise.all([u8($.body,H,{encoding:"utf8",mode:384}),u8($.metadata,`${JSON.stringify(L,null,2)}
148
- `,{encoding:"utf8",mode:384}),u8($.request,`${JSON.stringify(i8({url:Y.url,method:Y.method,accountId:Y.accountId,headers:R2(Y.headers)}),null,2)}
149
- `,{encoding:"utf8",mode:384})]),d8.debug("dumped request",{id:Q,session:p8(J),body:$.body,meta:$.metadata}),T2(W,Y.bodyText)}catch(H){d8.warn("request dump failed",{session:p8(J),error:H instanceof Error?H.message:String(H)})}}async function t0(Y){if(!A0().dump)return;d8.debug("diagnostic",Y)}import{tool as a1}from"@opencode-ai/plugin";var vY="ws_",LJ=new Map,VJ=a1({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:a1.schema.string().optional(),query:a1.schema.string().optional(),queries:a1.schema.array(a1.schema.string()).optional()},async execute(Y){return{title:"OpenAI Web Search",output:JSON.stringify({action:Y}),metadata:{action:Y}}}});function o8(Y){if(S2(Y))return;if(!b2(Y))return Y;let X=Y.item;return LJ.set(X.id,X),{...Y,item:{type:"function_call",id:X.id,call_id:X.id,name:"web_search",arguments:JSON.stringify(R(X.action)?X.action:{})}}}function NJ(Y){if(!Y.body)return Y;if(!(Y.headers.get("content-type")??"").includes("text/event-stream"))return Y;return new Response(k2(Y.body),{status:Y.status,statusText:Y.statusText,headers:Y.headers})}function BJ(Y){if(!Array.isArray(Y.input))return!1;let X=!1,J=new Map,Q=[],G=new Map,$=new Map;for(let W of Y.input)if(R(W)&&typeof W.call_id==="string"&&W.call_id.startsWith(vY)){if(W.type==="function_call")G.set(W.call_id,W);else if(W.type==="function_call_output"&&typeof W.output==="string")$.set(W.call_id,W.output)}for(let W of Y.input){if(x2(W)){J.set(W.call_id,W),X=!0;continue}if(v2(W,J)){Q.push(n8(W.call_id,W.output,J.get(W.call_id))),X=!0;continue}if(h2(W)){let U=LJ.get(W.id);if(U)Q.push(n8(W.id,U));else{let H=G.get(W.id),L=$.get(W.id);if(H||L)Q.push(n8(W.id,L,H));else Q.push(W)}X=!0;continue}Q.push(W)}if(X)Y.input=Q;return X}function S2(Y){if(typeof Y.type==="string"&&Y.type.startsWith("response.web_search_call."))return!0;return Y.type==="response.output_item.added"&&R(Y.item)&&Y.item.type==="web_search_call"}function k2(Y){let X=new TextDecoder,J=new TextEncoder,Q="";return Y.pipeThrough(new TransformStream({transform(G,$){Q+=X.decode(G,{stream:!0});let W=UJ(Q);while(W){let U=Q.slice(0,W.index);Q=Q.slice(W.index+W.length);let H=HJ(U);if(H)$.enqueue(J.encode(H));W=UJ(Q)}},flush(G){if(Q+=X.decode(),!Q)return;let $=HJ(Q);if($)G.enqueue(J.encode($))}}))}function UJ(Y){let X=Y.indexOf(`
146
+ Unavailable: reset command runtime dependencies are not wired.`,knobs:{}};let Q=X,G=Y.trim().split(/\s+/).filter(Boolean),$=G[0];if(!$||$==="refresh"){let z=["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:z});let L=await Promise.all(z.map((H)=>gX(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:M1,text:s5(L),knobs:{stage:"accounts",accounts:L}}}if($==="select"){let W=w8(G[1]);if(!W||!u0(W)||G.length!==2)return T0("","invalid_command","Usage: `/openai-reset select <encodedAccountKey>`");let z=await gX(W,Q);if(!z.eligible)return T0(W,"not_eligible",yX(z));return{command:M1,text:yX(z),knobs:{stage:"confirm",preview:z}}}if($==="confirm"||$==="retry"){let W=w8(G[1]),z=w8(G[2]);if(!W||!u0(W)||!z||G.length!==3)return T0(W??"","invalid_command",`Usage: \`/openai-reset ${$} <encodedAccountKey> <encodedChatgptAccountId>\``);i.info("reset redemption decision",{accountKey:W,action:$}),i.debug("reset redemption identity binding",{accountKey:W,expectedChatgptAccountId:z});try{let L=await vX({configPath:X.accountStoragePath,mutateAccountsFn:J0,loadAccountsFn:X.loadAccounts,now:Q.now,randomUUID:Q.randomUUID,fetchImpl:Q.fetchImpl,resolveTarget:Q.resolveResetTarget,fetchUsage:(H)=>$1({accessToken:H.accessToken,fetchImpl:Q.fetchImpl,now:Q.now,accountId:H.chatgptAccountId}),hasActiveRateLimitMark:(H)=>X.quotaManager.isRateLimited(H)},{accountKey:W,expectedChatgptAccountId:z,retry:$==="retry"});return i.info("reset redemption outcome",{accountKey:W,code:L.outcome.kind}),t5(L,Q,z)}catch(L){let H=a5(W,L,z);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 Y2=new Set(["access","refresh","apikey","authheader","password","secret"]);function X2(Y){let X=Y.toLowerCase().replace(/[-_]/g,"");if(Y2.has(X))return!0;return X.endsWith("token")}function E8(Y,X,J){if(Array.isArray(Y))return Y.map((G,$)=>E8(G,`${X}[${$}]`,J));if(!R(Y))return Y;let Q={};for(let[G,$]of Object.entries(Y)){if(X2(G)){J.push(`${X}.${G}`);continue}Q[G]=E8($,`${X}.${G}`,J)}return Q}async function k8(Y,X,J){let Q=await J2(Y,X,J),G=[],$=E8(Q.knobs,"knobs",G);if(G.length>0)return i.warn("credential-shaped knob stripped before RPC",{command:Y,fields:G}),{...Q,knobs:$};return Q}async function J2(Y,X,J){switch(Y){case"openai-quota":return m5(J);case"openai-account":return c5(X,J);case"openai-routing":return u5(X,J);case"openai-killswitch":return p5(X,J);case"openai-dump":return l5(X,J);case"openai-logging":return d5(X,J);case"openai-cachekeep":return n5(X,J);case"openai-reset":return e5(X,J);default:throw Error(`unhandled command: ${Y}`)}}var Q2=N0("quota");async function v1(Y,X={}){let J=Y.whamFn;if(!J)throw Error("whamFn is required for refreshAllQuota");let Q=[],G=Y.logger??Q2,$=(V)=>{Q.push(V);let K={pid:process.pid,accountId:V.account,status:V.ok?"ok":"error",...V.error?{error:V.error}:{}};if(V.ok)G.debug("quota refresh succeeded",K);else G.warn("quota refresh failed",K)},W=Y.skipFresherThanMs,z=!1,L;if(W!==void 0)try{L=await(Y.readSidebarState??w1)()}catch{}let H=new Map(L?.fallbacks.map((V)=>[V.id,V])??[]),N=(...V)=>W!==void 0&&V.some((K)=>typeof K==="number"&&Number.isFinite(K)&&K<=Y.now()&&Y.now()-K<W),O=await Y.loadAccounts(Y.configPath).catch(()=>{return}),Z=O?.mainAccountId??Y.storageMainAccountId;if(!X.accountKey||X.accountKey==="main")try{let V=await Y.getAuth();if(V.type==="oauth"){let K=L&&Z!==void 0&&L.main.mainAccountId===Z?L.main.quota:void 0;if(N(Y.quotaManager.peekMainForPolicy(Z)?.checkedAt,K?.primary?.checkedAt,K?.secondary?.checkedAt,K?.checkedAt))$({account:"main",ok:!0});else{if(!V.access||(V.expires??0)<Y.now()){let M=await Y.refreshMainWithLease();V={...V,access:M.access,expires:M.expires}}if(V.access)if(Y.respectBackoff&&Y.quotaManager.isBackedOff())$({account:"main",ok:!0});else{let M=await J({accessToken:V.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:Z,accountKey:"main"});Y.quotaManager.setMain(V.access,{quota:M,refreshAfter:Y.now()+300000,checkedAt:Y.now()},Z,!0),z=!0,$({account:"main",ok:!0})}else $({account:"main",ok:!1,error:"no access token"})}}else $({account:"main",ok:!1,error:"auth type is not oauth"})}catch(V){$({account:"main",ok:!1,error:W1(V)})}if(O)for(let V of O.accounts){if(X.accountKey&&(X.accountKey==="main"||V.id!==X.accountKey))continue;if(V.enabled===!1||!Y.isOAuthAccountFn(V)){if(X.accountKey)$({account:V.id,ok:!1,error:"account is not an enabled OAuth fallback"});continue}try{let K=H.get(V.id),j=V.accountId,M=K&&j!==void 0&&K.accountId===j?K.quota:void 0;if(N(Y.quotaManager.peekFallbackForPolicy(V.id,j)?.checkedAt,M?.primary?.checkedAt,M?.secondary?.checkedAt,M?.checkedAt)){$({account:V.id,ok:!0});continue}if(Y.respectBackoff&&Y.quotaManager.isFallbackBackedOff(V.id,V.access)){$({account:V.id,ok:!0});continue}let I;try{I=await Y.fallbackManager.refreshAccount(V,O)}catch{I=V}if(!I.access){$({account:V.id,ok:!1,error:"no access token"});continue}let E=await J({accessToken:I.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:I.accountId,accountKey:V.id});Y.quotaManager.setFallback(V.id,{quota:E,refreshAfter:Y.now()+300000,checkedAt:Y.now()},I.access,!0,I.accountId),z=!0,$({account:V.id,ok:!0})}catch(K){$({account:V.id,ok:!1,error:W1(K)})}}if(X.accountKey&&X.accountKey!=="main"&&!Q.some((V)=>V.account===X.accountKey))Q.push({account:X.accountKey,ok:!1,error:"account not found"});if(W===void 0||z){let V=await Y.loadAccounts(Y.configPath);await Y.writeSidebarState(Y.quotaManager,V)}return Q}var G2=300000,$2=30000,W2=240000,z2="bg-quota-refresh",U2=120000;function H2(Y,X){return bY({name:z2,ttlMs:U2,path:Y,renew:!0,...X})}function lX(Y,X=v1,J=()=>H2(Y.configPath)){return L2(Y,X,J)}async function L2(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:W2})}finally{await Q?.release().catch(()=>{})}}class b8{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)*$2);if(this.timer=this.setIntervalFn(()=>{let Q=this.run;if(this.stopped||!Q||this.tickPromise)return;let G=Q().catch(($)=>{try{this.onError?.($)}catch{}}).finally(()=>{if(this.tickPromise===G)this.tickPromise=void 0});this.tickPromise=G},G2+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 x8(Y){if(typeof Y!=="string")return!1;try{let X=JSON.parse(Y);return R(X)&&R(X.client_metadata)&&X.client_metadata.ws_request_header_x_openai_internal_codex_responses_lite==="true"}catch{return!1}}function v8(Y){if(typeof Y!=="string")return Y;try{let X=JSON.parse(Y);if(!R(X)||!R(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 xY(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"),x8(Y.body))X.set("x-openai-internal-codex-responses-lite","true");return{...Y,headers:X,body:v8(Y.body)}}function rX(Y){if(!Y.enabled||typeof Y.body!=="string")return;let X=Y.headers.has("x-parent-session-id");if(X&&!Y.includeSubagents)return;let J=Y.headers.get("session-id")??Y.headers.get("x-opencode-session")??Y.headers.get("x-session-affinity")??void 0;if(!J)return;let Q={};for(let G of["session-id","x-session-affinity","x-parent-session-id","user-agent","version","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-client-request-id","thread-id","x-openai-internal-codex-responses-lite"]){let $=Y.headers.get(G);if($)Q[G]=$}return{sessionKey:J,bodyText:Y.body,replayHeaders:Q,isSubagent:X}}function sX(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 dX(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 V2=300000,aX=1800000,iX=2*aX+900000,N2=3600000,nX=1800000,oX=60000,B2=32,Z2=8388608,h8=600000;function tX(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 K2(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 O2(Y,X){return tX(Y)?aX:X}function g8(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function eX(Y){if(!Y||typeof Y!=="object")return g8();let X=Y,J=Number(X.input_tokens)||Number(X.prompt_tokens)||0,Q=Number(X.output_tokens)||Number(X.completion_tokens)||0,G=X.input_tokens_details??X.prompt_tokens_details,$=Number(G?.cached_tokens)||Number(X.cached_tokens)||0,W=J>0?$/J:null;return{input_tokens:J,output_tokens:Q,cached_tokens:$,hit_rate:W}}function q2(Y){try{let X=JSON.parse(Y);return eX(X.usage)}catch{return g8()}}function F2(Y){let X,J=[],Q,G=()=>{if(!J.length)return;let $=J.join(`
147
+ `).trim();J=[];let W=X;if(X=void 0,!$||$==="[DONE]")return;try{let z=JSON.parse($),L=z.type??W;if(L!=="response.completed"&&L!=="response.done")return;let H=z.response;Q=eX(H?.usage??z.usage)}catch{}};for(let $ of Y.split(/\r?\n/)){if($===""){G();continue}if($.startsWith("event:")){X=$.slice(6).trim();continue}if($.startsWith("data:"))J.push($.slice(5).trim())}return G(),Q??g8()}class y8{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??V2,this.tickIntervalMs=Y.tickIntervalMs??oX,this.leadMs=Y.leadMs??this.tickIntervalMs+15000;let X=Y.maxIdleWarmMs??Y.maxDurationMs;this.maxIdleWarmMs=typeof X==="number"&&Number.isFinite(X)&&X>0?X:N2;let J=Y.maxSubagentIdleMs??nX;this.maxSubagentIdleMs=typeof J==="number"&&Number.isFinite(J)&&J>0?J:nX,this.tickIntervalMs=Y.tickIntervalMs??oX,this.maxTargets=Y.maxTargets??B2,this.maxBytes=Y.maxBytes??Z2,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 z=this.getWindow?.();if(z&&!dX(z,new Date(this.now()))){this.log.debug("cachekeep track skipped (outside window)",this.logPayload({sessionKey:Y,startHour:z.startHour,endHour:z.endHour}));return}if(this.targets.has(Y)){let N=this.targets.get(Y);if(N)this.totalBytes-=N.bodyText.length;this.targets.delete(Y)}else this.log.debug("cachekeep captured target",this.logPayload({sessionKey:Y,accountId:J}));while(this.targets.size>=this.maxTargets||this.totalBytes+W>this.maxBytes&&this.targets.size>0){let N,O=Number.POSITIVE_INFINITY;for(let[V,K]of this.targets){let j=Math.max(K.lastRealRequestAt,K.lastWarmedAt??0);if(j<O)N=V,O=j}if(N===void 0)break;let Z=this.targets.get(N);if(Z)this.totalBytes-=Z.bodyText.length;this.targets.delete(N)}let L=O2(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:G,isSubagent:$,is56:tX(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-iX;for(let[G,$]of this.targets){let W,z;if(this.isGpt56Subagent($))W=Q,z=iX;else W=$.isSubagent?J:X,z=$.isSubagent?this.maxSubagentIdleMs:this.maxIdleWarmMs;if(!($.isSubagent!==!0&&this.getSustain?.()===!0)&&$.lastRealRequestAt<W)this.log.debug("cachekeep pruned idle target",this.logPayload({sessionKey:G,accountId:$.accountId??"main",lastRealRequestAt:$.lastRealRequestAt,maxIdleWarmMs:z})),this.totalBytes-=$.bodyText.length,this.targets.delete(G)}}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&&!dX(Y,new Date(this.now())))return;let X=this.now(),J=X+this.leadMs;for(let[Q,G]of this.targets)if(G.backoffUntil&&X>=G.backoffUntil&&G.cacheExpiresAt<=J)await this.prewarm(Q,G);for(let[Q,G]of this.targets){if(G.backoffUntil&&X<G.backoffUntil)continue;if(G.cacheExpiresAt<=J)await this.prewarm(Q,G)}}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(G){if(!this.disposed&&this.targets.get(Y)===X)X.backoffUntil=this.now()+h8;this.log.debug("cachekeep skip (no token)",this.logPayload({sessionKey:Y,accountId:X.accountId??"main",error:G instanceof Error?G.message:String(G)}));return}if(this.disposed||this.targets.get(Y)!==X)return;let 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 G=K2(X.bodyText),$;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({...$,headerKeys:Object.keys(Q),hasChatGptAccountId:"ChatGPT-Account-Id"in Q}));let W=xY({method:"POST",headers:Q,body:G,signal:AbortSignal.any([AbortSignal.timeout(30000),this.abortController.signal])}),z=await this.fetchImpl(this.codexResponsesUrl,W),L="";try{L=await z.text()}catch{}if(this.disposed||this.targets.get(Y)!==X)return;if(!z.ok){X.backoffUntil=this.now()+h8,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",status:z.status,error:`HTTP ${z.status}`,responseBody:L.slice(0,600)}));return}let H=z.headers.get("content-type")??"",N=H.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(L.slice(0,200));this.log.debug("cachekeep warm response",this.logPayload({status:z.status,contentType:H,bodyLen:L.length,isSse:N}));let O=N?F2(L):q2(L),Z=h1(z.headers),V=Z.primary?.usedPercent??null,K=Z.secondary?.usedPercent??null;if(this.log.debug("cachekeep fired",this.logPayload({session:Y,accountId:X.accountId??"main",input_tokens:O.input_tokens,cached_tokens:O.cached_tokens,hit_rate:O.hit_rate,output_tokens:O.output_tokens,quota_primary_pct:V,quota_secondary_pct:K})),X.cacheExpiresAt=this.now()+X.ttlMs,X.lastWarmedAt=this.now(),X.backoffUntil=void 0,X.warmCount+=1,this.isGpt56Subagent(X)&&X.warmCount>=2){if(this.targets.get(Y)===X)this.totalBytes-=X.bodyText.length,this.targets.delete(Y);return}}catch(G){if(this.disposed||this.targets.get(Y)!==X)return;X.backoffUntil=this.now()+h8,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",error:G instanceof Error?G.message:String(G)}))}}}var JJ=900000,j2=0.016666666666666666,YJ=0.000001;function m8(Y,X){for(let J of[Y?.primary?.checkedAt,Y?.checkedAt,X])if(typeof J==="number"&&Number.isFinite(J))return J;return}function c8(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let X=m8(Y.quota,Y.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||Y.now-X>JJ)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let J=f8(Y.quota).sort((Q,G)=>{let $=Q.windowMs,W=G.windowMs,z=typeof $==="number"&&Number.isFinite($),L=typeof W==="number"&&Number.isFinite(W);if(z!==L)return z?-1:1;if(z&&L)return W-$;return 0});for(let{key:Q,window:G}of J)if(Number.isFinite(G.remainingPercent)&&G.remainingPercent<=0)return{action:"migrate",reason:"exhausted",windowKey:Q,...typeof G.resetsAt==="string"?{resetsAt:G.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 D2(Y,X,J){let Q=Math.max(0,Y.remainingPercent-X);if(Q<=0)return 0;if(!Y.resetsAt)return Q;let G=Date.parse(Y.resetsAt);if(!Number.isFinite(G)||G<=J)return Q;let $=Math.max((G-J)/3600000,j2);return Q/$}function XJ(Y,X){if(Y<X)return-1;if(Y>X)return 1;return 0}function P2(Y,X){if(!Y.quota)return;let J=m8(Y.quota,Y.quotaCheckedAt);if(J===void 0||X-J>JJ)return;let Q=f8(Y.quota).map(({key:$,window:W})=>{return D2(W,Y.reservePercent[$]??0,X)}),G=Q.length>0?Math.min(...Q):0;return G>0?{candidate:Y,quotaCheckedAt:J,weight:G}:void 0}function QJ(Y){let X=Y.candidates.filter((G)=>G.killswitchPasses!==!1);if(Y.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if(X.length===0)return;let J=X.map((G)=>P2(G,Y.now)).filter((G)=>G!==void 0);if(J.length>0){J.sort(($,W)=>{let z=((Y.pendingBytes.get($.candidate.accountId)??0)+Y.requestBytes)/Math.max($.weight,YJ),L=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,YJ);return z-L||$.candidate.configuredOrder-W.candidate.configuredOrder||XJ($.candidate.accountId,W.candidate.accountId)});let G=J[0];if(G)return{accountId:G.candidate.accountId,quotaCheckedAt:G.quotaCheckedAt,source:"weighted"}}Y.onEmptyWeightedSet?.();let Q=[...X].sort((G,$)=>{let W=(G.resetCreditsApplicable??0)>0?1:0;return(($.resetCreditsApplicable??0)>0?1:0)-W||G.configuredOrder-$.configuredOrder||XJ(G.accountId,$.accountId)})[0];if(!Q)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Q.accountId,quotaCheckedAt:m8(Q.quota,Q.quotaCheckedAt),source:"mode-fallback"}}import{createHash as M2}from"node:crypto";import{chmod as w2,mkdir as E2,readdir as A2,readFile as T2,writeFile as u8}from"node:fs/promises";import{join as zJ}from"node:path";var d8=N0("dump"),z1="x-cortexkit-openai-auth-dump-session",R2=["http","prewarm","main"],GJ=0,g1=new Map,C2=100;function p8(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function UJ(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 HJ(Y){return M2("sha256").update(Y).digest("hex")}function l8(Y){return HJ(JSON.stringify(Y))}function LJ(Y){try{let X=JSON.parse(Y);return X!=null&&typeof X==="object"&&!Array.isArray(X)?X:void 0}catch{return}}function _2(Y,X){if(Y===void 0)return null;if(Y===X)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:Y.length,currentBytes:X.length};let J=0;while(J<Y.length&&J<X.length&&Y[J]===X[J])J++;let Q=Y.length-1,G=X.length-1;while(Q>=J&&G>=J&&Y[Q]===X[G])Q--,G--;return{changed:!0,firstByte:J,lastPreviousByte:Q,lastCurrentByte:G,changedPreviousBytes:Q-J+1,changedCurrentBytes:G-J+1,previousBytes:Y.length,currentBytes:X.length}}function I2(Y,X){if(!g1.has(Y))while(g1.size>=C2){let J=g1.keys().next().value;if(J===void 0)break;g1.delete(J)}g1.set(Y,X)}var $J=new Set;async function S2(Y,X,J){let Q=UJ(X),G=R2.map(($)=>`-${Q}-${J}-${$}.body.json`);try{let W=(await A2(Y)).filter((z)=>G.some((L)=>z.endsWith(L))).sort().pop();if(!W)return;return await T2(zJ(Y,W),"utf8")}catch{return}}function k2(Y){if(Y===void 0)return;return Object.fromEntries(new Headers(Y).entries())}function i8(Y){if(Array.isArray(Y))return Y.map(i8);if(Y==null||typeof Y!=="object")return Y;let X={};for(let[J,Q]of Object.entries(Y)){let G=J.toLowerCase();if(G==="authorization"||G==="chatgpt-account-id"||G==="cookie"||G==="set-cookie"){X[J]="[redacted]";continue}X[J]=i8(Q)}return X}function b2(Y){let X=LJ(Y);if(X===void 0)return Y;let J=WJ(X),Q=JSON.stringify(J);if(Q===void 0)return Y;return JSON.stringify(X)===Q?Y:Q}function x2(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function v2(Y){let X=LJ(Y);if(!X)return{parseable:!1};let J=Array.isArray(X.input)?X.input:[],Q=Array.isArray(X.tools)?X.tools:[],G=Q.map(x2),$=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:l8(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:l8(J[0]),toolsCount:Q.length,toolTypes:G,toolsHash:l8(Q),hasWebSearch:G.includes("web_search"),clientMetadataKeys:$?Object.keys($).sort():[]}}async function y1(Y){let X=A0();if(!X.dump)return;GJ++;let J=Y.sessionID?.trim()||"session-unknown",Q=`${new Date().toISOString().replace(/[:.]/g,"-")}-${process.pid}-${String(GJ).padStart(5,"0")}-${UJ(J)}-${Y.transport}-${Y.phase}`,G=zJ(X.dumpDir,Q),$={body:`${G}.body.json`,metadata:`${G}.meta.json`,request:`${G}.request.json`},W=`${Y.transport}:${J}`,z=g1.get(W),L=z?"memory":void 0;if(z===void 0&&!$J.has(W)){if($J.add(W),z=await S2(X.dumpDir,J,Y.transport),z!==void 0)L="disk"}try{await E2(X.dumpDir,{recursive:!0,mode:448}),await w2(X.dumpDir,448).catch(()=>{});let H=b2(Y.bodyText),N={id:Q,createdAt:new Date().toISOString(),session:p8(J),transport:Y.transport,phase:Y.phase,accountId:Y.accountId,status:Y.status,error:Y.error,bodyBytes:Y.bodyText.length,bodyHash:HJ(Y.bodyText),diff:_2(z,H),baselineSource:L,body:v2(Y.bodyText),files:$};await Promise.all([u8($.body,H,{encoding:"utf8",mode:384}),u8($.metadata,`${JSON.stringify(N,null,2)}
148
+ `,{encoding:"utf8",mode:384}),u8($.request,`${JSON.stringify(i8({url:Y.url,method:Y.method,accountId:Y.accountId,headers:k2(Y.headers)}),null,2)}
149
+ `,{encoding:"utf8",mode:384})]),d8.debug("dumped request",{id:Q,session:p8(J),body:$.body,meta:$.metadata}),I2(W,H)}catch(H){d8.warn("request dump failed",{session:p8(J),error:H instanceof Error?H.message:String(H)})}}async function t0(Y){if(!A0().dump)return;d8.debug("diagnostic",Y)}import{tool as a1}from"@opencode-ai/plugin";var vY="ws_",BJ=new Map,ZJ=a1({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:a1.schema.string().optional(),query:a1.schema.string().optional(),queries:a1.schema.array(a1.schema.string()).optional()},async execute(Y){return{title:"OpenAI Web Search",output:JSON.stringify({action:Y}),metadata:{action:Y}}}});function o8(Y){if(h2(Y))return;if(!y2(Y))return Y;let X=Y.item;return BJ.set(X.id,X),{...Y,item:{type:"function_call",id:X.id,call_id:X.id,name:"web_search",arguments:JSON.stringify(R(X.action)?X.action:{})}}}function KJ(Y){if(!Y.body)return Y;if(!(Y.headers.get("content-type")??"").includes("text/event-stream"))return Y;return new Response(g2(Y.body),{status:Y.status,statusText:Y.statusText,headers:Y.headers})}function OJ(Y){if(!Array.isArray(Y.input))return!1;let X=!1,J=new Map,Q=[],G=new Map,$=new Map;for(let W of Y.input)if(R(W)&&typeof W.call_id==="string"&&W.call_id.startsWith(vY)){if(W.type==="function_call")G.set(W.call_id,W);else if(W.type==="function_call_output"&&typeof W.output==="string")$.set(W.call_id,W.output)}for(let W of Y.input){if(f2(W)){J.set(W.call_id,W),X=!0;continue}if(m2(W,J)){Q.push(n8(W.call_id,W.output,J.get(W.call_id))),X=!0;continue}if(c2(W)){let z=BJ.get(W.id);if(z)Q.push(n8(W.id,z));else{let L=G.get(W.id),H=$.get(W.id);if(L||H)Q.push(n8(W.id,H,L));else Q.push(W)}X=!0;continue}Q.push(W)}if(X)Y.input=Q;return X}function h2(Y){if(typeof Y.type==="string"&&Y.type.startsWith("response.web_search_call."))return!0;return Y.type==="response.output_item.added"&&R(Y.item)&&Y.item.type==="web_search_call"}function g2(Y){let X=new TextDecoder,J=new TextEncoder,Q="";return Y.pipeThrough(new TransformStream({transform(G,$){Q+=X.decode(G,{stream:!0});let W=VJ(Q);while(W){let z=Q.slice(0,W.index);Q=Q.slice(W.index+W.length);let L=NJ(z);if(L)$.enqueue(J.encode(L));W=VJ(Q)}},flush(G){if(Q+=X.decode(),!Q)return;let $=NJ(Q);if($)G.enqueue(J.encode($))}}))}function VJ(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 HJ(Y){let X=Y.split(/\r?\n/).filter((J)=>J.startsWith("data:")).map((J)=>J.slice(5).trimStart()).join(`
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 NJ(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 b2(Y){return Y.type==="response.output_item.done"&&R(Y.item)&&Y.item.type==="web_search_call"&&typeof Y.item.id==="string"}function x2(Y){return R(Y)&&Y.type==="function_call"&&Y.name==="web_search"&&typeof Y.call_id==="string"&&Y.call_id.startsWith(vY)}function v2(Y,X){return R(Y)&&Y.type==="function_call_output"&&typeof Y.call_id==="string"&&typeof Y.output==="string"&&Y.call_id.startsWith(vY)&&X.has(Y.call_id)}function h2(Y){return R(Y)&&Y.type==="item_reference"&&typeof Y.id==="string"&&Y.id.startsWith(vY)}function n8(Y,X,J){let Q=g2(X),G=R(Q?.action)?Q.action:y2(J?.arguments);return{type:"web_search_call",status:"completed",...G?{action:G}:{}}}function g2(Y){if(R(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return R(X)?X:void 0}catch{return}}function y2(Y){if(R(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return R(X)?X:void 0}catch{return}}import{readFile as f2}from"node:fs/promises";import{homedir as m2}from"node:os";import{join as ZJ}from"node:path";var c2="https://models.dev/api.json",u2="OPENCODE_OPENAI_AUTH_MODELS_CACHE",p2="OPENCODE_MODELS_PATH",l2="OPENCODE_DISABLE_MODELS_FETCH",d2=1e4,i2=300000;function U1(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function KJ(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function r8(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=KJ(Y.cache_read),G=KJ(Y.cache_write);if(Q===null||G===null)return null;return{input:X,output:J,cache:{read:Q,write:G}}}function n2(Y){let X=U1(Y);if(!X)return null;let J=r8(X);if(!J)return null;let Q=J;if(Array.isArray(X.tiers)){let W=[];for(let U of X.tiers){let H=U1(U);if(!H)continue;let L=U1(H.tier),N=L?.size;if(L?.type!=="context")continue;if(typeof N!=="number"||!Number.isFinite(N)||N<=0)continue;let O=r8(H);if(!O)continue;W.push({...O,tier:{type:"context",size:N}})}if(W.length>0)Q.tiers=W}let G=U1(X.context_over_200k),$=G?r8(G):null;if($)Q.experimentalOver200K=$;return Q}function OJ(Y){let X=U1(Y),J=U1(X?.openai),Q=U1(J?.models);if(!Q)return null;let G={};for(let[$,W]of Object.entries(Q)){let U=U1(W),H=n2(U?.cost);if(H)G[$]=H}return Object.keys(G).length>0?G:null}function o2(){let Y=process.env[u2]?.trim();if(Y)return Y;let X=process.env[p2]?.trim();if(X)return X;let J=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||ZJ(m2(),".cache");return ZJ(J,"opencode","models.json")}function r2(){let Y=process.env[l2]?.toLowerCase();return Y==="true"||Y==="1"}async function s2(){try{let Y=OJ(JSON.parse(await f2(o2(),"utf8")));if(Y)return Y}catch{}if(r2())return null;try{let Y=await fetch(c2,{signal:AbortSignal.timeout(d2)});if(!Y.ok)return null;return OJ(await Y.json())}catch{return null}}var f1;function qJ(){let Y=Date.now();if(f1&&f1.expiresAt>Y)return f1.promise;let X={expiresAt:Y+i2,promise:s2()};return f1=X,X.promise.then((J)=>{if(J===null&&f1===X)f1=void 0}),X.promise}function m1(Y){return typeof Y==="object"&&Y!==null}function a2(Y){if(Array.isArray(Y))return Y;if(m1(Y)&&Array.isArray(Y.data))return Y.data;return[]}function t2(Y){if(!m1(Y)||!m1(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function FJ(Y){if(!m1(Y)||!m1(Y.info))return null;let X=Y.info,J=m1(X.model)?X.model:void 0,Q=typeof X.agent==="string"?X.agent:void 0,G=typeof J?.providerID==="string"?J.providerID:typeof X.providerID==="string"?X.providerID:void 0,$=typeof J?.modelID==="string"?J.modelID:typeof X.modelID==="string"?X.modelID:void 0,W=typeof J?.variant==="string"?J.variant:typeof X.variant==="string"?X.variant:void 0;if(!Q&&(!G||!$)&&!W)return null;let U={};if(Q)U.agent=Q;if(G&&$)U.model={providerID:G,modelID:$};if(W)U.variant=W;return U}function jJ(Y,X){return{agent:Y.agent??X.agent,model:Y.model??X.model,variant:Y.variant??X.variant}}function DJ(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function PJ(Y,X){if(!Y||!X)return null;let J=Y;if(typeof J.session?.messages!=="function")return null;let Q=[];try{Q=a2(await Promise.resolve(J.session.messages({path:{id:X},query:{limit:100}})))}catch{return null}if(Q.length===0)return null;let G={};for(let $=Q.length-1;$>=0;$--){if(t2(Q[$])!=="assistant")continue;let W=FJ(Q[$]);if(!W)continue;if(G=jJ(G,W),DJ(G))return G}for(let $=Q.length-1;$>=0;$--){let W=FJ(Q[$]);if(!W)continue;if(G=jJ(G,W),DJ(G))return G}if(!G.agent&&!G.model&&!G.variant)return null;return G}var H1=[],e2=1,s8=0,MJ=new Map;function a8(Y,X){if(H1.push({id:e2++,type:"open-dialog",payload:Y,sessionId:X}),H1.length>100)H1=H1.slice(H1.length-100)}function wJ(Y=0,X){let J=Date.now();if(s8=J,X!==void 0)MJ.set(X,J);let Q=(G)=>X===void 0||G.sessionId===void 0||G.sessionId===X;if(Y>0)H1=H1.filter((G)=>{if(G.id>Y)return!0;if(X===void 0)return!1;return G.sessionId!==X});return H1.filter((G)=>G.id>Y&&Q(G))}function EJ(Y){let X=Date.now();if(Y!==void 0){let J=MJ.get(Y)??0;return J>0&&X-J<3000}return s8>0&&X-s8<3000}import{randomBytes as Yz,timingSafeEqual as Xz}from"node:crypto";import{unlink as Jz}from"node:fs/promises";import{createServer as Qz}from"node:http";import{join as Gz}from"node:path";var AJ=N0("rpc");function $z(Y){return new Promise((X,J)=>{let Q=[],G=0;Y.on("data",($)=>{if(G+=$.length,G>1e6){Y.destroy(),J(Error("body too large"));return}Q.push($)}),Y.on("end",()=>X(Buffer.concat(Q).toString("utf8"))),Y.on("error",J)})}function Wz(Y,X){if(!Y?.startsWith("Bearer "))return!1;let J=Buffer.from(Y.slice(7)),Q=Buffer.from(X);return J.length===Q.length&&Xz(J,Q)}async function CJ(Y){let X=Yz(32).toString("hex"),J=Y.timeoutMs??90000,Q=Y.receiptTimeoutMs??2000,G=Qz((U,H)=>{U.setTimeout(J,()=>{U.socket.destroy()}),$(U,H)});G.requestTimeout=Q,G.headersTimeout=Q;async function $(U,H){let L=(N,O)=>{if(H.headersSent||H.writableEnded||H.destroyed)return;H.writeHead(N,{"content-type":"application/json"}),H.end(JSON.stringify(O))};try{let N=U.url??"";if(U.method==="GET"&&N==="/health")return L(200,{ok:!0});if(U.method!=="POST"||!N.startsWith("/rpc/"))return L(404,{error:"not found"});if(!Wz(U.headers.authorization,X))return L(401,{error:"unauthorized"});let O=N.slice(5),Z=await $z(U),V=JSON.parse(Z||"{}");if(O==="pending-notifications"){let K=Y.drain(Number(V.lastReceivedId??0),typeof V.sessionId==="string"?V.sessionId:void 0);return L(200,{messages:K})}if(O==="apply"){let K=await Y.apply(V);return L(200,K)}return L(404,{error:"unknown method"})}catch(N){L(500,{error:N instanceof Error?N.message:String(N)})}}let W=await new Promise((U,H)=>{G.on("error",H),G.listen(0,"127.0.0.1",()=>{let L=G.address();if(L&&typeof L==="object")U(L.port);else H(Error("no port"))})});if(G.unref(),Y.sweepRoot)try{await RJ(Y.sweepRoot,Y.dir)}catch(U){AJ.warn("rpc state sweep failed",{pid:process.pid,error:U instanceof Error?U.message:String(U)})}try{await TJ(Y.dir,{port:W,token:X,pid:process.pid},{secureDir:Y.secureDir}),AJ.debug("rpc server pid",{pid:process.pid,rpcPort:W})}catch(U){throw await new Promise((H)=>G.close(()=>H())),U}return{port:W,token:X,async stop(){await new Promise((U)=>G.close(()=>U())),await Jz(Gz(Y.dir,`port-${process.pid}.json`)).catch(()=>{})}}}function e0(Y){return JSON.stringify(t8(Y))??"undefined"}function t8(Y){if(Array.isArray(Y))return Y.map(t8);if(!R(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((X)=>[X,t8(Y[X])]))}function E1(){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 O1={};X9(O1,{withoutInternalHeaders:()=>jW,sanitizeHttpFallbackBody:()=>v8,orderCodexBody:()=>qY,hasWebSocketResponsesLiteMetadata:()=>x8,createWebSocketFetch:()=>BB,applyTurnId:()=>KW,advanceTurn:()=>a9,TITLE_HEADER:()=>s9,QUOTA_ACCOUNT_HEADER:()=>H8,OpenAIWebSocketPool:()=>O1,CODEX_BODY_KEY_ORDER:()=>BW});import{createHash as UB}from"node:crypto";var $6="vercel.ai.error",zz=Symbol.for($6),_J,IJ,m=class Y extends(IJ=Error,_J=zz,IJ){constructor({name:X,message:J,cause:Q}){super(J);this[_J]=!0,this.name=X,this.cause=Q}static isInstance(X){return Y.hasMarker(X,$6)}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}},W6="AI_APICallError",z6=`vercel.ai.error.${W6}`,Uz=Symbol.for(z6),SJ,kJ,t1=class extends(kJ=m,SJ=Uz,kJ){constructor({message:Y,url:X,requestBodyValues:J,statusCode:Q,responseHeaders:G,responseBody:$,cause:W,isRetryable:U=Q!=null&&(Q===408||Q===409||Q===429||Q>=500),data:H}){super({name:W6,message:Y,cause:W});this[SJ]=!0,this.url=X,this.requestBodyValues=J,this.statusCode=Q,this.responseHeaders=G,this.responseBody=$,this.isRetryable=U,this.data=H}static isInstance(Y){return m.hasMarker(Y,z6)}},U6="AI_EmptyResponseBodyError",H6=`vercel.ai.error.${U6}`,Hz=Symbol.for(H6),bJ,xJ,Lz=class extends(xJ=m,bJ=Hz,xJ){constructor({message:Y="Empty response body"}={}){super({name:U6,message:Y});this[bJ]=!0}static isInstance(Y){return m.hasMarker(Y,H6)}};function e8(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 L6="AI_InvalidArgumentError",V6=`vercel.ai.error.${L6}`,Vz=Symbol.for(V6),vJ,hJ,N6=class extends(hJ=m,vJ=Vz,hJ){constructor({message:Y,cause:X,argument:J}){super({name:L6,message:Y,cause:X});this[vJ]=!0,this.argument=J}static isInstance(Y){return m.hasMarker(Y,V6)}},B6="AI_InvalidPromptError",Z6=`vercel.ai.error.${B6}`,Nz=Symbol.for(Z6),gJ,yJ,Bz=class extends(yJ=m,gJ=Nz,yJ){constructor({prompt:Y,message:X,cause:J}){super({name:B6,message:`Invalid prompt: ${X}`,cause:J});this[gJ]=!0,this.prompt=Y}static isInstance(Y){return m.hasMarker(Y,Z6)}},K6="AI_InvalidResponseDataError",O6=`vercel.ai.error.${K6}`,Zz=Symbol.for(O6),fJ,mJ,Kz=class extends(mJ=m,fJ=Zz,mJ){constructor({data:Y,message:X=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:K6,message:X});this[fJ]=!0,this.data=Y}static isInstance(Y){return m.hasMarker(Y,O6)}},q6="AI_JSONParseError",F6=`vercel.ai.error.${q6}`,Oz=Symbol.for(F6),cJ,uJ,hY=class extends(uJ=m,cJ=Oz,uJ){constructor({text:Y,cause:X}){super({name:q6,message:`JSON parsing failed: Text: ${Y}.
165
- Error message: ${e8(X)}`,cause:X});this[cJ]=!0,this.text=Y}static isInstance(Y){return m.hasMarker(Y,F6)}},j6="AI_LoadAPIKeyError",D6=`vercel.ai.error.${j6}`,qz=Symbol.for(D6),pJ,lJ,Fz=class extends(lJ=m,pJ=qz,lJ){constructor({message:Y}){super({name:j6,message:Y});this[pJ]=!0}static isInstance(Y){return m.hasMarker(Y,D6)}},P6="AI_LoadSettingError",M6=`vercel.ai.error.${P6}`,jz=Symbol.for(M6),dJ,iJ,Dz=class extends(iJ=m,dJ=jz,iJ){constructor({message:Y}){super({name:P6,message:Y});this[dJ]=!0}static isInstance(Y){return m.hasMarker(Y,M6)}},w6="AI_NoContentGeneratedError",E6=`vercel.ai.error.${w6}`,Pz=Symbol.for(E6),nJ,oJ,Mz=class extends(oJ=m,nJ=Pz,oJ){constructor({message:Y="No content generated."}={}){super({name:w6,message:Y});this[nJ]=!0}static isInstance(Y){return m.hasMarker(Y,E6)}},A6="AI_NoSuchModelError",T6=`vercel.ai.error.${A6}`,wz=Symbol.for(T6),rJ,sJ,Ez=class extends(sJ=m,rJ=wz,sJ){constructor({errorName:Y=A6,modelId:X,modelType:J,message:Q=`No such ${J}: ${X}`}){super({name:Y,message:Q});this[rJ]=!0,this.modelId=X,this.modelType=J}static isInstance(Y){return m.hasMarker(Y,T6)}},R6="AI_NoSuchProviderReferenceError",C6=`vercel.ai.error.${R6}`,Az=Symbol.for(C6),aJ,tJ,Tz=class extends(tJ=m,aJ=Az,tJ){constructor({provider:Y,reference:X,message:J=`No provider reference found for provider '${Y}'. Available providers: ${Object.keys(X).join(", ")}`}){super({name:R6,message:J});this[aJ]=!0,this.provider=Y,this.reference=X}static isInstance(Y){return m.hasMarker(Y,C6)}},_6="AI_TooManyEmbeddingValuesForCallError",I6=`vercel.ai.error.${_6}`,Rz=Symbol.for(I6),eJ,Y6,Cz=class extends(Y6=m,eJ=Rz,Y6){constructor(Y){super({name:_6,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[eJ]=!0,this.provider=Y.provider,this.modelId=Y.modelId,this.maxEmbeddingsPerCall=Y.maxEmbeddingsPerCall,this.values=Y.values}static isInstance(Y){return m.hasMarker(Y,I6)}},S6="AI_TypeValidationError",k6=`vercel.ai.error.${S6}`,_z=Symbol.for(k6),X6,J6,p0=class Y extends(J6=m,X6=_z,J6){constructor({value:X,cause:J,context:Q}){let G="Type validation failed";if(Q==null?void 0:Q.field)G+=` for ${Q.field}`;if((Q==null?void 0:Q.entityName)||(Q==null?void 0:Q.entityId)){G+=" (";let $=[];if(Q.entityName)$.push(Q.entityName);if(Q.entityId)$.push(`id: "${Q.entityId}"`);G+=$.join(", "),G+=")"}super({name:S6,message:`${G}: Value: ${JSON.stringify(X)}.
166
- Error message: ${e8(J)}`,cause:J});this[X6]=!0,this.value=X,this.context=Q}static isInstance(X){return m.hasMarker(X,k6)}static wrap({value:X,cause:J,context:Q}){var G,$,W;if(Y.isInstance(J)&&J.value===X&&((G=J.context)==null?void 0:G.field)===(Q==null?void 0:Q.field)&&(($=J.context)==null?void 0:$.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})}},b6="AI_UnsupportedFunctionalityError",x6=`vercel.ai.error.${b6}`,Iz=Symbol.for(x6),Q6,G6,Sz=class extends(G6=m,Q6=Iz,G6){constructor({functionality:Y,message:X=`'${Y}' functionality not supported.`}){super({name:b6,message:X});this[Q6]=!0,this.functionality=Y}static isInstance(Y){return m.hasMarker(Y,x6)}};var _K=Object.freeze({status:"aborted"});function F(Y,X,J){function Q(U,H){var L;Object.defineProperty(U,"_zod",{value:U._zod??{},enumerable:!1}),(L=U._zod).traits??(L.traits=new Set),U._zod.traits.add(Y),X(U,H);for(let N in W.prototype)if(!(N in U))Object.defineProperty(U,N,{value:W.prototype[N].bind(U)});U._zod.constr=W,U._zod.def=H}let G=J?.Parent??Object;class $ extends G{}Object.defineProperty($,"name",{value:Y});function W(U){var H;let L=J?.Parent?new $:this;Q(L,U),(H=L._zod).deferred??(H.deferred=[]);for(let N of L._zod.deferred)N();return L}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 IK=Symbol("zod_brand");class Y1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class e1 extends Error{constructor(Y){super(`Encountered unidirectional transform during encode: ${Y}`);this.name="ZodEncodeError"}}var gY={};function l0(Y){if(Y)Object.assign(gY,Y);return gY}var c={};X9(c,{unwrapMessage:()=>YY,uint8ArrayToHex:()=>QU,uint8ArrayToBase64url:()=>XU,uint8ArrayToBase64:()=>u6,stringifyPrimitive:()=>y6,shallowClone:()=>h6,safeExtend:()=>rz,required:()=>tz,randomString:()=>uz,propertyKeyTypes:()=>G9,promiseAllObject:()=>cz,primitiveTypes:()=>g6,prefixIssues:()=>J1,pick:()=>iz,partial:()=>az,optionalKeys:()=>$9,omit:()=>nz,objectClone:()=>yz,numKeys:()=>pz,nullish:()=>JY,normalizeParams:()=>v,mergeDefs:()=>V1,merge:()=>sz,jsonStringifyReplacer:()=>c1,joinValues:()=>gz,issue:()=>p1,isPlainObject:()=>N1,isObject:()=>A1,hexToUint8Array:()=>JU,getSizableOrigin:()=>m6,getParsedType:()=>lz,getLengthableOrigin:()=>GY,getEnumValues:()=>XY,getElementAtPath:()=>mz,floatSafeRemainder:()=>J9,finalizeIssue:()=>x0,extend:()=>oz,escapeRegex:()=>X1,esc:()=>yY,defineLazy:()=>p,createTransparentProxy:()=>dz,cloneDef:()=>fz,clone:()=>b0,cleanRegex:()=>QY,cleanEnum:()=>ez,captureStackTrace:()=>fY,cached:()=>u1,base64urlToUint8Array:()=>YU,base64ToUint8Array:()=>c6,assignProp:()=>L1,assertNotEqual:()=>bz,assertNever:()=>vz,assertIs:()=>xz,assertEqual:()=>kz,assert:()=>hz,allowsEval:()=>Q9,aborted:()=>B1,NUMBER_FORMAT_RANGES:()=>W9,Class:()=>p6,BIGINT_FORMAT_RANGES:()=>f6});function kz(Y){return Y}function bz(Y){return Y}function xz(Y){}function vz(Y){throw Error()}function hz(Y){}function XY(Y){let X=Object.values(Y).filter((Q)=>typeof Q==="number");return Object.entries(Y).filter(([Q,G])=>X.indexOf(+Q)===-1).map(([Q,G])=>G)}function gz(Y,X="|"){return Y.map((J)=>y6(J)).join(X)}function c1(Y,X){if(typeof X==="bigint")return X.toString();return X}function u1(Y){return{get value(){{let J=Y();return Object.defineProperty(this,"value",{value:J}),J}throw Error("cached value already set")}}}function JY(Y){return Y===null||Y===void 0}function QY(Y){let X=Y.startsWith("^")?1:0,J=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(X,J)}function J9(Y,X){let J=(Y.toString().split(".")[1]||"").length,Q=X.toString(),G=(Q.split(".")[1]||"").length;if(G===0&&/\d?e-\d?/.test(Q)){let H=Q.match(/\d?e-(\d?)/);if(H?.[1])G=Number.parseInt(H[1])}let $=J>G?J:G,W=Number.parseInt(Y.toFixed($).replace(".","")),U=Number.parseInt(X.toFixed($).replace(".",""));return W%U/10**$}var v6=Symbol("evaluating");function p(Y,X,J){let Q=void 0;Object.defineProperty(Y,X,{get(){if(Q===v6)return;if(Q===void 0)Q=v6,Q=J();return Q},set(G){Object.defineProperty(Y,X,{value:G})},configurable:!0})}function yz(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function L1(Y,X,J){Object.defineProperty(Y,X,{value:J,writable:!0,enumerable:!0,configurable:!0})}function V1(...Y){let X={};for(let J of Y){let Q=Object.getOwnPropertyDescriptors(J);Object.assign(X,Q)}return Object.defineProperties({},X)}function fz(Y){return V1(Y._zod.def)}function mz(Y,X){if(!X)return Y;return X.reduce((J,Q)=>J?.[Q],Y)}function cz(Y){let X=Object.keys(Y),J=X.map((Q)=>Y[Q]);return Promise.all(J).then((Q)=>{let G={};for(let $=0;$<X.length;$++)G[X[$]]=Q[$];return G})}function uz(Y=10){let J="";for(let Q=0;Q<Y;Q++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function yY(Y){return JSON.stringify(Y)}var fY="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function A1(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var Q9=u1(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function N1(Y){if(A1(Y)===!1)return!1;let X=Y.constructor;if(X===void 0)return!0;let J=X.prototype;if(A1(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function h6(Y){if(N1(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function pz(Y){let X=0;for(let J in Y)if(Object.prototype.hasOwnProperty.call(Y,J))X++;return X}var lz=(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}`)}},G9=new Set(["string","number","symbol"]),g6=new Set(["string","number","bigint","boolean","symbol","undefined"]);function X1(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 v(Y){let X=Y;if(!X)return{};if(typeof X==="string")return{error:()=>X};if(X?.message!==void 0){if(X?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");X.error=X.message}if(delete X.message,typeof X.error==="string")return{...X,error:()=>X.error};return X}function dz(Y){let X;return new Proxy({},{get(J,Q,G){return X??(X=Y()),Reflect.get(X,Q,G)},set(J,Q,G,$){return X??(X=Y()),Reflect.set(X,Q,G,$)},has(J,Q){return X??(X=Y()),Reflect.has(X,Q)},deleteProperty(J,Q){return X??(X=Y()),Reflect.deleteProperty(X,Q)},ownKeys(J){return X??(X=Y()),Reflect.ownKeys(X)},getOwnPropertyDescriptor(J,Q){return X??(X=Y()),Reflect.getOwnPropertyDescriptor(X,Q)},defineProperty(J,Q,G){return X??(X=Y()),Reflect.defineProperty(X,Q,G)}})}function y6(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function $9(Y){return Object.keys(Y).filter((X)=>{return Y[X]._zod.optin==="optional"&&Y[X]._zod.optout==="optional"})}var W9={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]},f6={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function iz(Y,X){let J=Y._zod.def,Q=V1(Y._zod.def,{get shape(){let G={};for(let $ in X){if(!($ in J.shape))throw Error(`Unrecognized key: "${$}"`);if(!X[$])continue;G[$]=J.shape[$]}return L1(this,"shape",G),G},checks:[]});return b0(Y,Q)}function nz(Y,X){let J=Y._zod.def,Q=V1(Y._zod.def,{get shape(){let G={...Y._zod.def.shape};for(let $ in X){if(!($ in J.shape))throw Error(`Unrecognized key: "${$}"`);if(!X[$])continue;delete G[$]}return L1(this,"shape",G),G},checks:[]});return b0(Y,Q)}function oz(Y,X){if(!N1(X))throw Error("Invalid input to extend: expected a plain object");let J=Y._zod.def.checks;if(J&&J.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let G=V1(Y._zod.def,{get shape(){let $={...Y._zod.def.shape,...X};return L1(this,"shape",$),$},checks:[]});return b0(Y,G)}function rz(Y,X){if(!N1(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 L1(this,"shape",Q),Q},checks:Y._zod.def.checks};return b0(Y,J)}function sz(Y,X){let J=V1(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape,...X._zod.def.shape};return L1(this,"shape",Q),Q},get catchall(){return X._zod.def.catchall},checks:[]});return b0(Y,J)}function az(Y,X,J){let Q=V1(X._zod.def,{get shape(){let G=X._zod.def.shape,$={...G};if(J)for(let W in J){if(!(W in G))throw Error(`Unrecognized key: "${W}"`);if(!J[W])continue;$[W]=Y?new Y({type:"optional",innerType:G[W]}):G[W]}else for(let W in G)$[W]=Y?new Y({type:"optional",innerType:G[W]}):G[W];return L1(this,"shape",$),$},checks:[]});return b0(X,Q)}function tz(Y,X,J){let Q=V1(X._zod.def,{get shape(){let G=X._zod.def.shape,$={...G};if(J)for(let W in J){if(!(W in $))throw Error(`Unrecognized key: "${W}"`);if(!J[W])continue;$[W]=new Y({type:"nonoptional",innerType:G[W]})}else for(let W in G)$[W]=new Y({type:"nonoptional",innerType:G[W]});return L1(this,"shape",$),$},checks:[]});return b0(X,Q)}function B1(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 J1(Y,X){return X.map((J)=>{var Q;return(Q=J).path??(Q.path=[]),J.path.unshift(Y),J})}function YY(Y){return typeof Y==="string"?Y:Y?.message}function x0(Y,X,J){let Q={...Y,path:Y.path??[]};if(!Y.message){let G=YY(Y.inst?._zod.def?.error?.(Y))??YY(X?.error?.(Y))??YY(J.customError?.(Y))??YY(J.localeError?.(Y))??"Invalid input";Q.message=G}if(delete Q.inst,delete Q.continue,!X?.reportInput)delete Q.input;return Q}function m6(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function GY(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function p1(...Y){let[X,J,Q]=Y;if(typeof X==="string")return{message:X,code:"custom",input:J,inst:Q};return{...X}}function ez(Y){return Object.entries(Y).filter(([X,J])=>{return Number.isNaN(Number.parseInt(X,10))}).map((X)=>X[1])}function c6(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 u6(Y){let X="";for(let J=0;J<Y.length;J++)X+=String.fromCharCode(Y[J]);return btoa(X)}function YU(Y){let X=Y.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-X.length%4)%4);return c6(X+J)}function XU(Y){return u6(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function JU(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 QU(Y){return Array.from(Y).map((X)=>X.toString(16).padStart(2,"0")).join("")}class p6{constructor(...Y){}}var l6=(Y,X)=>{Y.name="$ZodError",Object.defineProperty(Y,"_zod",{value:Y._zod,enumerable:!1}),Object.defineProperty(Y,"issues",{value:X,enumerable:!1}),Y.message=JSON.stringify(X,c1,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},mY=F("$ZodError",l6),z9=F("$ZodError",l6,{Parent:Error});function d6(Y,X=(J)=>J.message){let J={},Q=[];for(let G of Y.issues)if(G.path.length>0)J[G.path[0]]=J[G.path[0]]||[],J[G.path[0]].push(X(G));else Q.push(X(G));return{formErrors:Q,fieldErrors:J}}function i6(Y,X){let J=X||function($){return $.message},Q={_errors:[]},G=($)=>{for(let W of $.issues)if(W.code==="invalid_union"&&W.errors.length)W.errors.map((U)=>G({issues:U}));else if(W.code==="invalid_key")G({issues:W.issues});else if(W.code==="invalid_element")G({issues:W.issues});else if(W.path.length===0)Q._errors.push(J(W));else{let U=Q,H=0;while(H<W.path.length){let L=W.path[H];if(H!==W.path.length-1)U[L]=U[L]||{_errors:[]};else U[L]=U[L]||{_errors:[]},U[L]._errors.push(J(W));U=U[L],H++}}};return G(Y),Q}var cY=(Y)=>(X,J,Q,G)=>{let $=Q?Object.assign(Q,{async:!1}):{async:!1},W=X._zod.run({value:J,issues:[]},$);if(W instanceof Promise)throw new Y1;if(W.issues.length){let U=new(G?.Err??Y)(W.issues.map((H)=>x0(H,$,l0())));throw fY(U,G?.callee),U}return W.value};var uY=(Y)=>async(X,J,Q,G)=>{let $=Q?Object.assign(Q,{async:!0}):{async:!0},W=X._zod.run({value:J,issues:[]},$);if(W instanceof Promise)W=await W;if(W.issues.length){let U=new(G?.Err??Y)(W.issues.map((H)=>x0(H,$,l0())));throw fY(U,G?.callee),U}return W.value};var $Y=(Y)=>(X,J,Q)=>{let G=Q?{...Q,async:!1}:{async:!1},$=X._zod.run({value:J,issues:[]},G);if($ instanceof Promise)throw new Y1;return $.issues.length?{success:!1,error:new(Y??mY)($.issues.map((W)=>x0(W,G,l0())))}:{success:!0,data:$.value}},n6=$Y(z9),WY=(Y)=>async(X,J,Q)=>{let G=Q?Object.assign(Q,{async:!0}):{async:!0},$=X._zod.run({value:J,issues:[]},G);if($ instanceof Promise)$=await $;return $.issues.length?{success:!1,error:new Y($.issues.map((W)=>x0(W,G,l0())))}:{success:!0,data:$.value}},o6=WY(z9),r6=(Y)=>(X,J,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return cY(Y)(X,J,G)};var s6=(Y)=>(X,J,Q)=>{return cY(Y)(X,J,Q)};var a6=(Y)=>async(X,J,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return uY(Y)(X,J,G)};var t6=(Y)=>async(X,J,Q)=>{return uY(Y)(X,J,Q)};var e6=(Y)=>(X,J,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return $Y(Y)(X,J,G)};var YQ=(Y)=>(X,J,Q)=>{return $Y(Y)(X,J,Q)};var XQ=(Y)=>async(X,J,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return WY(Y)(X,J,G)};var JQ=(Y)=>async(X,J,Q)=>{return WY(Y)(X,J,Q)};var QQ=/^[cC][^\s-]{8,}$/,GQ=/^[0-9a-z]+$/,$Q=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,WQ=/^[0-9a-vA-V]{20}$/,zQ=/^[A-Za-z0-9]{27}$/,UQ=/^[a-zA-Z0-9_-]{21}$/,HQ=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var LQ=/^([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})$/,U9=(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 VQ=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function NQ(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var BQ=/^(?:(?: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])$/,ZQ=/^(([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}|:))$/,KQ=/^((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])$/,OQ=/^(([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])$/,qQ=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,H9=/^[A-Za-z0-9_-]*$/,FQ=/^(?=.{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 jQ=/^\+(?:[0-9]){6,14}[0-9]$/,DQ="(?:(?:\\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])))",PQ=new RegExp(`^${DQ}$`);function MQ(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 wQ(Y){return new RegExp(`^${MQ(Y)}$`)}function EQ(Y){let X=MQ({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(`^${DQ}T(?:${Q})$`)}var AQ=(Y)=>{let X=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${X}$`)};var TQ=/^-?\d+$/,RQ=/^-?\d+(?:\.\d+)?/,CQ=/^(?:true|false)$/i,_Q=/^null$/i;var IQ=/^[^A-Z]*$/,SQ=/^[^a-z]*$/;var B0=F("$ZodCheck",(Y,X)=>{var J;Y._zod??(Y._zod={}),Y._zod.def=X,(J=Y._zod).onattach??(J.onattach=[])}),kQ={number:"number",bigint:"bigint",object:"date"},L9=F("$ZodCheckLessThan",(Y,X)=>{B0.init(Y,X);let J=kQ[typeof X.value];Y._zod.onattach.push((Q)=>{let G=Q._zod.bag,$=(X.inclusive?G.maximum:G.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(X.value<$)if(X.inclusive)G.maximum=X.value;else G.exclusiveMaximum=X.value}),Y._zod.check=(Q)=>{if(X.inclusive?Q.value<=X.value:Q.value<X.value)return;Q.issues.push({origin:J,code:"too_big",maximum:X.value,input:Q.value,inclusive:X.inclusive,inst:Y,continue:!X.abort})}}),V9=F("$ZodCheckGreaterThan",(Y,X)=>{B0.init(Y,X);let J=kQ[typeof X.value];Y._zod.onattach.push((Q)=>{let G=Q._zod.bag,$=(X.inclusive?G.minimum:G.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(X.value>$)if(X.inclusive)G.minimum=X.value;else G.exclusiveMinimum=X.value}),Y._zod.check=(Q)=>{if(X.inclusive?Q.value>=X.value:Q.value>X.value)return;Q.issues.push({origin:J,code:"too_small",minimum:X.value,input:Q.value,inclusive:X.inclusive,inst:Y,continue:!X.abort})}}),bQ=F("$ZodCheckMultipleOf",(Y,X)=>{B0.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):J9(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})}}),xQ=F("$ZodCheckNumberFormat",(Y,X)=>{B0.init(Y,X),X.format=X.format||"float64";let J=X.format?.includes("int"),Q=J?"int":"number",[G,$]=W9[X.format];Y._zod.onattach.push((W)=>{let U=W._zod.bag;if(U.format=X.format,U.minimum=G,U.maximum=$,J)U.pattern=TQ}),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<G)W.issues.push({origin:"number",input:U,code:"too_small",minimum:G,inclusive:!0,inst:Y,continue:!X.abort});if(U>$)W.issues.push({origin:"number",input:U,code:"too_big",maximum:$,inst:Y})}});var vQ=F("$ZodCheckMaxLength",(Y,X)=>{var J;B0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let G=Q.value;return!JY(G)&&G.length!==void 0}),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(X.maximum<G)Q._zod.bag.maximum=X.maximum}),Y._zod.check=(Q)=>{let G=Q.value;if(G.length<=X.maximum)return;let W=GY(G);Q.issues.push({origin:W,code:"too_big",maximum:X.maximum,inclusive:!0,input:G,inst:Y,continue:!X.abort})}}),hQ=F("$ZodCheckMinLength",(Y,X)=>{var J;B0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let G=Q.value;return!JY(G)&&G.length!==void 0}),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(X.minimum>G)Q._zod.bag.minimum=X.minimum}),Y._zod.check=(Q)=>{let G=Q.value;if(G.length>=X.minimum)return;let W=GY(G);Q.issues.push({origin:W,code:"too_small",minimum:X.minimum,inclusive:!0,input:G,inst:Y,continue:!X.abort})}}),gQ=F("$ZodCheckLengthEquals",(Y,X)=>{var J;B0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let G=Q.value;return!JY(G)&&G.length!==void 0}),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.minimum=X.length,G.maximum=X.length,G.length=X.length}),Y._zod.check=(Q)=>{let G=Q.value,$=G.length;if($===X.length)return;let W=GY(G),U=$>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})}}),zY=F("$ZodCheckStringFormat",(Y,X)=>{var J,Q;if(B0.init(Y,X),Y._zod.onattach.push((G)=>{let $=G._zod.bag;if($.format=X.format,X.pattern)$.patterns??($.patterns=new Set),$.patterns.add(X.pattern)}),X.pattern)(J=Y._zod).check??(J.check=(G)=>{if(X.pattern.lastIndex=0,X.pattern.test(G.value))return;G.issues.push({origin:"string",code:"invalid_format",format:X.format,input:G.value,...X.pattern?{pattern:X.pattern.toString()}:{},inst:Y,continue:!X.abort})});else(Q=Y._zod).check??(Q.check=()=>{})}),yQ=F("$ZodCheckRegex",(Y,X)=>{zY.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})}}),fQ=F("$ZodCheckLowerCase",(Y,X)=>{X.pattern??(X.pattern=IQ),zY.init(Y,X)}),mQ=F("$ZodCheckUpperCase",(Y,X)=>{X.pattern??(X.pattern=SQ),zY.init(Y,X)}),cQ=F("$ZodCheckIncludes",(Y,X)=>{B0.init(Y,X);let J=X1(X.includes),Q=new RegExp(typeof X.position==="number"?`^.{${X.position}}${J}`:J);X.pattern=Q,Y._zod.onattach.push((G)=>{let $=G._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(Q)}),Y._zod.check=(G)=>{if(G.value.includes(X.includes,X.position))return;G.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:X.includes,input:G.value,inst:Y,continue:!X.abort})}}),uQ=F("$ZodCheckStartsWith",(Y,X)=>{B0.init(Y,X);let J=new RegExp(`^${X1(X.prefix)}.*`);X.pattern??(X.pattern=J),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(J)}),Y._zod.check=(Q)=>{if(Q.value.startsWith(X.prefix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:X.prefix,input:Q.value,inst:Y,continue:!X.abort})}}),pQ=F("$ZodCheckEndsWith",(Y,X)=>{B0.init(Y,X);let J=new RegExp(`.*${X1(X.suffix)}$`);X.pattern??(X.pattern=J),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(J)}),Y._zod.check=(Q)=>{if(Q.value.endsWith(X.suffix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:X.suffix,input:Q.value,inst:Y,continue:!X.abort})}});var lQ=F("$ZodCheckOverwrite",(Y,X)=>{B0.init(Y,X),Y._zod.check=(J)=>{J.value=X.tx(J.value)}});class N9{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 y2(Y){return Y.type==="response.output_item.done"&&R(Y.item)&&Y.item.type==="web_search_call"&&typeof Y.item.id==="string"}function f2(Y){return R(Y)&&Y.type==="function_call"&&Y.name==="web_search"&&typeof Y.call_id==="string"&&Y.call_id.startsWith(vY)}function m2(Y,X){return R(Y)&&Y.type==="function_call_output"&&typeof Y.call_id==="string"&&typeof Y.output==="string"&&Y.call_id.startsWith(vY)&&X.has(Y.call_id)}function c2(Y){return R(Y)&&Y.type==="item_reference"&&typeof Y.id==="string"&&Y.id.startsWith(vY)}function n8(Y,X,J){let Q=u2(X),G=R(Q?.action)?Q.action:p2(J?.arguments);return{type:"web_search_call",status:"completed",...G?{action:G}:{}}}function u2(Y){if(R(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return R(X)?X:void 0}catch{return}}function p2(Y){if(R(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return R(X)?X:void 0}catch{return}}import{readFile as l2}from"node:fs/promises";import{homedir as d2}from"node:os";import{join as qJ}from"node:path";var i2="https://models.dev/api.json",n2="OPENCODE_OPENAI_AUTH_MODELS_CACHE",o2="OPENCODE_MODELS_PATH",r2="OPENCODE_DISABLE_MODELS_FETCH",s2=1e4,a2=300000;function U1(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function FJ(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function r8(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=FJ(Y.cache_read),G=FJ(Y.cache_write);if(Q===null||G===null)return null;return{input:X,output:J,cache:{read:Q,write:G}}}function t2(Y){let X=U1(Y);if(!X)return null;let J=r8(X);if(!J)return null;let Q=J;if(Array.isArray(X.tiers)){let W=[];for(let z of X.tiers){let L=U1(z);if(!L)continue;let H=U1(L.tier),N=H?.size;if(H?.type!=="context")continue;if(typeof N!=="number"||!Number.isFinite(N)||N<=0)continue;let O=r8(L);if(!O)continue;W.push({...O,tier:{type:"context",size:N}})}if(W.length>0)Q.tiers=W}let G=U1(X.context_over_200k),$=G?r8(G):null;if($)Q.experimentalOver200K=$;return Q}function jJ(Y){let X=U1(Y),J=U1(X?.openai),Q=U1(J?.models);if(!Q)return null;let G={};for(let[$,W]of Object.entries(Q)){let z=U1(W),L=t2(z?.cost);if(L)G[$]=L}return Object.keys(G).length>0?G:null}function e2(){let Y=process.env[n2]?.trim();if(Y)return Y;let X=process.env[o2]?.trim();if(X)return X;let J=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||qJ(d2(),".cache");return qJ(J,"opencode","models.json")}function Yz(){let Y=process.env[r2]?.toLowerCase();return Y==="true"||Y==="1"}async function Xz(){try{let Y=jJ(JSON.parse(await l2(e2(),"utf8")));if(Y)return Y}catch{}if(Yz())return null;try{let Y=await fetch(i2,{signal:AbortSignal.timeout(s2)});if(!Y.ok)return null;return jJ(await Y.json())}catch{return null}}var f1;function DJ(){let Y=Date.now();if(f1&&f1.expiresAt>Y)return f1.promise;let X={expiresAt:Y+a2,promise:Xz()};return f1=X,X.promise.then((J)=>{if(J===null&&f1===X)f1=void 0}),X.promise}function m1(Y){return typeof Y==="object"&&Y!==null}function Jz(Y){if(Array.isArray(Y))return Y;if(m1(Y)&&Array.isArray(Y.data))return Y.data;return[]}function Qz(Y){if(!m1(Y)||!m1(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function PJ(Y){if(!m1(Y)||!m1(Y.info))return null;let X=Y.info,J=m1(X.model)?X.model:void 0,Q=typeof X.agent==="string"?X.agent:void 0,G=typeof J?.providerID==="string"?J.providerID:typeof X.providerID==="string"?X.providerID:void 0,$=typeof J?.modelID==="string"?J.modelID:typeof X.modelID==="string"?X.modelID:void 0,W=typeof J?.variant==="string"?J.variant:typeof X.variant==="string"?X.variant:void 0;if(!Q&&(!G||!$)&&!W)return null;let z={};if(Q)z.agent=Q;if(G&&$)z.model={providerID:G,modelID:$};if(W)z.variant=W;return z}function MJ(Y,X){return{agent:Y.agent??X.agent,model:Y.model??X.model,variant:Y.variant??X.variant}}function wJ(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function EJ(Y,X){if(!Y||!X)return null;let J=Y;if(typeof J.session?.messages!=="function")return null;let Q=[];try{Q=Jz(await Promise.resolve(J.session.messages({path:{id:X},query:{limit:100}})))}catch{return null}if(Q.length===0)return null;let G={};for(let $=Q.length-1;$>=0;$--){if(Qz(Q[$])!=="assistant")continue;let W=PJ(Q[$]);if(!W)continue;if(G=MJ(G,W),wJ(G))return G}for(let $=Q.length-1;$>=0;$--){let W=PJ(Q[$]);if(!W)continue;if(G=MJ(G,W),wJ(G))return G}if(!G.agent&&!G.model&&!G.variant)return null;return G}var H1=[],Gz=1,s8=0,AJ=new Map;function a8(Y,X){if(H1.push({id:Gz++,type:"open-dialog",payload:Y,sessionId:X}),H1.length>100)H1=H1.slice(H1.length-100)}function TJ(Y=0,X){let J=Date.now();if(s8=J,X!==void 0)AJ.set(X,J);let Q=(G)=>X===void 0||G.sessionId===void 0||G.sessionId===X;if(Y>0)H1=H1.filter((G)=>{if(G.id>Y)return!0;if(X===void 0)return!1;return G.sessionId!==X});return H1.filter((G)=>G.id>Y&&Q(G))}function RJ(Y){let X=Date.now();if(Y!==void 0){let J=AJ.get(Y)??0;return J>0&&X-J<3000}return s8>0&&X-s8<3000}import{randomBytes as $z,timingSafeEqual as Wz}from"node:crypto";import{unlink as zz}from"node:fs/promises";import{createServer as Uz}from"node:http";import{join as Hz}from"node:path";var CJ=N0("rpc");function Lz(Y){return new Promise((X,J)=>{let Q=[],G=0;Y.on("data",($)=>{if(G+=$.length,G>1e6){Y.destroy(),J(Error("body too large"));return}Q.push($)}),Y.on("end",()=>X(Buffer.concat(Q).toString("utf8"))),Y.on("error",J)})}function Vz(Y,X){if(!Y?.startsWith("Bearer "))return!1;let J=Buffer.from(Y.slice(7)),Q=Buffer.from(X);return J.length===Q.length&&Wz(J,Q)}async function SJ(Y){let X=$z(32).toString("hex"),J=Y.timeoutMs??90000,Q=Y.receiptTimeoutMs??2000,G=Uz((z,L)=>{z.setTimeout(J,()=>{z.socket.destroy()}),$(z,L)});G.requestTimeout=Q,G.headersTimeout=Q;async function $(z,L){let H=(N,O)=>{if(L.headersSent||L.writableEnded||L.destroyed)return;L.writeHead(N,{"content-type":"application/json"}),L.end(JSON.stringify(O))};try{let N=z.url??"";if(z.method==="GET"&&N==="/health")return H(200,{ok:!0});if(z.method!=="POST"||!N.startsWith("/rpc/"))return H(404,{error:"not found"});if(!Vz(z.headers.authorization,X))return H(401,{error:"unauthorized"});let O=N.slice(5),Z=await Lz(z),V=JSON.parse(Z||"{}");if(O==="pending-notifications"){let K=Y.drain(Number(V.lastReceivedId??0),typeof V.sessionId==="string"?V.sessionId:void 0);return H(200,{messages:K})}if(O==="apply"){let K=await Y.apply(V);return H(200,K)}return H(404,{error:"unknown method"})}catch(N){H(500,{error:N instanceof Error?N.message:String(N)})}}let W=await new Promise((z,L)=>{G.on("error",L),G.listen(0,"127.0.0.1",()=>{let H=G.address();if(H&&typeof H==="object")z(H.port);else L(Error("no port"))})});if(G.unref(),Y.sweepRoot)try{await IJ(Y.sweepRoot,Y.dir)}catch(z){CJ.warn("rpc state sweep failed",{pid:process.pid,error:z instanceof Error?z.message:String(z)})}try{await _J(Y.dir,{port:W,token:X,pid:process.pid},{secureDir:Y.secureDir}),CJ.debug("rpc server pid",{pid:process.pid,rpcPort:W})}catch(z){throw await new Promise((L)=>G.close(()=>L())),z}return{port:W,token:X,async stop(){await new Promise((z)=>G.close(()=>z())),await zz(Hz(Y.dir,`port-${process.pid}.json`)).catch(()=>{})}}}function e0(Y){return JSON.stringify(t8(Y))??"undefined"}function t8(Y){if(Array.isArray(Y))return Y.map(t8);if(!R(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((X)=>[X,t8(Y[X])]))}function E1(){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 O1={};X9(O1,{withoutInternalHeaders:()=>MW,sanitizeHttpFallbackBody:()=>v8,orderCodexBody:()=>qY,hasWebSocketResponsesLiteMetadata:()=>x8,createWebSocketFetch:()=>FB,applyTurnId:()=>FW,advanceTurn:()=>a9,TITLE_HEADER:()=>s9,QUOTA_ACCOUNT_HEADER:()=>H8,OpenAIWebSocketPool:()=>O1,CODEX_BODY_KEY_ORDER:()=>OW});import{createHash as BB}from"node:crypto";var U6="vercel.ai.error",Nz=Symbol.for(U6),kJ,bJ,m=class Y extends(bJ=Error,kJ=Nz,bJ){constructor({name:X,message:J,cause:Q}){super(J);this[kJ]=!0,this.name=X,this.cause=Q}static isInstance(X){return Y.hasMarker(X,U6)}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}},H6="AI_APICallError",L6=`vercel.ai.error.${H6}`,Bz=Symbol.for(L6),xJ,vJ,t1=class extends(vJ=m,xJ=Bz,vJ){constructor({message:Y,url:X,requestBodyValues:J,statusCode:Q,responseHeaders:G,responseBody:$,cause:W,isRetryable:z=Q!=null&&(Q===408||Q===409||Q===429||Q>=500),data:L}){super({name:H6,message:Y,cause:W});this[xJ]=!0,this.url=X,this.requestBodyValues=J,this.statusCode=Q,this.responseHeaders=G,this.responseBody=$,this.isRetryable=z,this.data=L}static isInstance(Y){return m.hasMarker(Y,L6)}},V6="AI_EmptyResponseBodyError",N6=`vercel.ai.error.${V6}`,Zz=Symbol.for(N6),hJ,gJ,Kz=class extends(gJ=m,hJ=Zz,gJ){constructor({message:Y="Empty response body"}={}){super({name:V6,message:Y});this[hJ]=!0}static isInstance(Y){return m.hasMarker(Y,N6)}};function e8(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 B6="AI_InvalidArgumentError",Z6=`vercel.ai.error.${B6}`,Oz=Symbol.for(Z6),yJ,fJ,K6=class extends(fJ=m,yJ=Oz,fJ){constructor({message:Y,cause:X,argument:J}){super({name:B6,message:Y,cause:X});this[yJ]=!0,this.argument=J}static isInstance(Y){return m.hasMarker(Y,Z6)}},O6="AI_InvalidPromptError",q6=`vercel.ai.error.${O6}`,qz=Symbol.for(q6),mJ,cJ,Fz=class extends(cJ=m,mJ=qz,cJ){constructor({prompt:Y,message:X,cause:J}){super({name:O6,message:`Invalid prompt: ${X}`,cause:J});this[mJ]=!0,this.prompt=Y}static isInstance(Y){return m.hasMarker(Y,q6)}},F6="AI_InvalidResponseDataError",j6=`vercel.ai.error.${F6}`,jz=Symbol.for(j6),uJ,pJ,Dz=class extends(pJ=m,uJ=jz,pJ){constructor({data:Y,message:X=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:F6,message:X});this[uJ]=!0,this.data=Y}static isInstance(Y){return m.hasMarker(Y,j6)}},D6="AI_JSONParseError",P6=`vercel.ai.error.${D6}`,Pz=Symbol.for(P6),lJ,dJ,hY=class extends(dJ=m,lJ=Pz,dJ){constructor({text:Y,cause:X}){super({name:D6,message:`JSON parsing failed: Text: ${Y}.
165
+ Error message: ${e8(X)}`,cause:X});this[lJ]=!0,this.text=Y}static isInstance(Y){return m.hasMarker(Y,P6)}},M6="AI_LoadAPIKeyError",w6=`vercel.ai.error.${M6}`,Mz=Symbol.for(w6),iJ,nJ,wz=class extends(nJ=m,iJ=Mz,nJ){constructor({message:Y}){super({name:M6,message:Y});this[iJ]=!0}static isInstance(Y){return m.hasMarker(Y,w6)}},E6="AI_LoadSettingError",A6=`vercel.ai.error.${E6}`,Ez=Symbol.for(A6),oJ,rJ,Az=class extends(rJ=m,oJ=Ez,rJ){constructor({message:Y}){super({name:E6,message:Y});this[oJ]=!0}static isInstance(Y){return m.hasMarker(Y,A6)}},T6="AI_NoContentGeneratedError",R6=`vercel.ai.error.${T6}`,Tz=Symbol.for(R6),sJ,aJ,Rz=class extends(aJ=m,sJ=Tz,aJ){constructor({message:Y="No content generated."}={}){super({name:T6,message:Y});this[sJ]=!0}static isInstance(Y){return m.hasMarker(Y,R6)}},C6="AI_NoSuchModelError",_6=`vercel.ai.error.${C6}`,Cz=Symbol.for(_6),tJ,eJ,_z=class extends(eJ=m,tJ=Cz,eJ){constructor({errorName:Y=C6,modelId:X,modelType:J,message:Q=`No such ${J}: ${X}`}){super({name:Y,message:Q});this[tJ]=!0,this.modelId=X,this.modelType=J}static isInstance(Y){return m.hasMarker(Y,_6)}},I6="AI_NoSuchProviderReferenceError",S6=`vercel.ai.error.${I6}`,Iz=Symbol.for(S6),Y6,X6,Sz=class extends(X6=m,Y6=Iz,X6){constructor({provider:Y,reference:X,message:J=`No provider reference found for provider '${Y}'. Available providers: ${Object.keys(X).join(", ")}`}){super({name:I6,message:J});this[Y6]=!0,this.provider=Y,this.reference=X}static isInstance(Y){return m.hasMarker(Y,S6)}},k6="AI_TooManyEmbeddingValuesForCallError",b6=`vercel.ai.error.${k6}`,kz=Symbol.for(b6),J6,Q6,bz=class extends(Q6=m,J6=kz,Q6){constructor(Y){super({name:k6,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[J6]=!0,this.provider=Y.provider,this.modelId=Y.modelId,this.maxEmbeddingsPerCall=Y.maxEmbeddingsPerCall,this.values=Y.values}static isInstance(Y){return m.hasMarker(Y,b6)}},x6="AI_TypeValidationError",v6=`vercel.ai.error.${x6}`,xz=Symbol.for(v6),G6,$6,p0=class Y extends($6=m,G6=xz,$6){constructor({value:X,cause:J,context:Q}){let G="Type validation failed";if(Q==null?void 0:Q.field)G+=` for ${Q.field}`;if((Q==null?void 0:Q.entityName)||(Q==null?void 0:Q.entityId)){G+=" (";let $=[];if(Q.entityName)$.push(Q.entityName);if(Q.entityId)$.push(`id: "${Q.entityId}"`);G+=$.join(", "),G+=")"}super({name:x6,message:`${G}: Value: ${JSON.stringify(X)}.
166
+ Error message: ${e8(J)}`,cause:J});this[G6]=!0,this.value=X,this.context=Q}static isInstance(X){return m.hasMarker(X,v6)}static wrap({value:X,cause:J,context:Q}){var G,$,W;if(Y.isInstance(J)&&J.value===X&&((G=J.context)==null?void 0:G.field)===(Q==null?void 0:Q.field)&&(($=J.context)==null?void 0:$.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})}},h6="AI_UnsupportedFunctionalityError",g6=`vercel.ai.error.${h6}`,vz=Symbol.for(g6),W6,z6,hz=class extends(z6=m,W6=vz,z6){constructor({functionality:Y,message:X=`'${Y}' functionality not supported.`}){super({name:h6,message:X});this[W6]=!0,this.functionality=Y}static isInstance(Y){return m.hasMarker(Y,g6)}};var xK=Object.freeze({status:"aborted"});function F(Y,X,J){function Q(z,L){var H;Object.defineProperty(z,"_zod",{value:z._zod??{},enumerable:!1}),(H=z._zod).traits??(H.traits=new Set),z._zod.traits.add(Y),X(z,L);for(let N in W.prototype)if(!(N in z))Object.defineProperty(z,N,{value:W.prototype[N].bind(z)});z._zod.constr=W,z._zod.def=L}let G=J?.Parent??Object;class $ extends G{}Object.defineProperty($,"name",{value:Y});function W(z){var L;let H=J?.Parent?new $:this;Q(H,z),(L=H._zod).deferred??(L.deferred=[]);for(let N of H._zod.deferred)N();return H}return Object.defineProperty(W,"init",{value:Q}),Object.defineProperty(W,Symbol.hasInstance,{value:(z)=>{if(J?.Parent&&z instanceof J.Parent)return!0;return z?._zod?.traits?.has(Y)}}),Object.defineProperty(W,"name",{value:Y}),W}var vK=Symbol("zod_brand");class Y1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class e1 extends Error{constructor(Y){super(`Encountered unidirectional transform during encode: ${Y}`);this.name="ZodEncodeError"}}var gY={};function l0(Y){if(Y)Object.assign(gY,Y);return gY}var c={};X9(c,{unwrapMessage:()=>YY,uint8ArrayToHex:()=>UU,uint8ArrayToBase64url:()=>WU,uint8ArrayToBase64:()=>d6,stringifyPrimitive:()=>c6,shallowClone:()=>f6,safeExtend:()=>YU,required:()=>QU,randomString:()=>nz,propertyKeyTypes:()=>G9,promiseAllObject:()=>iz,primitiveTypes:()=>m6,prefixIssues:()=>J1,pick:()=>az,partial:()=>JU,optionalKeys:()=>$9,omit:()=>tz,objectClone:()=>pz,numKeys:()=>oz,nullish:()=>JY,normalizeParams:()=>v,mergeDefs:()=>V1,merge:()=>XU,jsonStringifyReplacer:()=>c1,joinValues:()=>uz,issue:()=>p1,isPlainObject:()=>N1,isObject:()=>A1,hexToUint8Array:()=>zU,getSizableOrigin:()=>p6,getParsedType:()=>rz,getLengthableOrigin:()=>GY,getEnumValues:()=>XY,getElementAtPath:()=>dz,floatSafeRemainder:()=>J9,finalizeIssue:()=>x0,extend:()=>ez,escapeRegex:()=>X1,esc:()=>yY,defineLazy:()=>p,createTransparentProxy:()=>sz,cloneDef:()=>lz,clone:()=>b0,cleanRegex:()=>QY,cleanEnum:()=>GU,captureStackTrace:()=>fY,cached:()=>u1,base64urlToUint8Array:()=>$U,base64ToUint8Array:()=>l6,assignProp:()=>L1,assertNotEqual:()=>yz,assertNever:()=>mz,assertIs:()=>fz,assertEqual:()=>gz,assert:()=>cz,allowsEval:()=>Q9,aborted:()=>B1,NUMBER_FORMAT_RANGES:()=>W9,Class:()=>i6,BIGINT_FORMAT_RANGES:()=>u6});function gz(Y){return Y}function yz(Y){return Y}function fz(Y){}function mz(Y){throw Error()}function cz(Y){}function XY(Y){let X=Object.values(Y).filter((Q)=>typeof Q==="number");return Object.entries(Y).filter(([Q,G])=>X.indexOf(+Q)===-1).map(([Q,G])=>G)}function uz(Y,X="|"){return Y.map((J)=>c6(J)).join(X)}function c1(Y,X){if(typeof X==="bigint")return X.toString();return X}function u1(Y){return{get value(){{let J=Y();return Object.defineProperty(this,"value",{value:J}),J}throw Error("cached value already set")}}}function JY(Y){return Y===null||Y===void 0}function QY(Y){let X=Y.startsWith("^")?1:0,J=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(X,J)}function J9(Y,X){let J=(Y.toString().split(".")[1]||"").length,Q=X.toString(),G=(Q.split(".")[1]||"").length;if(G===0&&/\d?e-\d?/.test(Q)){let L=Q.match(/\d?e-(\d?)/);if(L?.[1])G=Number.parseInt(L[1])}let $=J>G?J:G,W=Number.parseInt(Y.toFixed($).replace(".","")),z=Number.parseInt(X.toFixed($).replace(".",""));return W%z/10**$}var y6=Symbol("evaluating");function p(Y,X,J){let Q=void 0;Object.defineProperty(Y,X,{get(){if(Q===y6)return;if(Q===void 0)Q=y6,Q=J();return Q},set(G){Object.defineProperty(Y,X,{value:G})},configurable:!0})}function pz(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function L1(Y,X,J){Object.defineProperty(Y,X,{value:J,writable:!0,enumerable:!0,configurable:!0})}function V1(...Y){let X={};for(let J of Y){let Q=Object.getOwnPropertyDescriptors(J);Object.assign(X,Q)}return Object.defineProperties({},X)}function lz(Y){return V1(Y._zod.def)}function dz(Y,X){if(!X)return Y;return X.reduce((J,Q)=>J?.[Q],Y)}function iz(Y){let X=Object.keys(Y),J=X.map((Q)=>Y[Q]);return Promise.all(J).then((Q)=>{let G={};for(let $=0;$<X.length;$++)G[X[$]]=Q[$];return G})}function nz(Y=10){let J="";for(let Q=0;Q<Y;Q++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function yY(Y){return JSON.stringify(Y)}var fY="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function A1(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var Q9=u1(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function N1(Y){if(A1(Y)===!1)return!1;let X=Y.constructor;if(X===void 0)return!0;let J=X.prototype;if(A1(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function f6(Y){if(N1(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function oz(Y){let X=0;for(let J in Y)if(Object.prototype.hasOwnProperty.call(Y,J))X++;return X}var rz=(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}`)}},G9=new Set(["string","number","symbol"]),m6=new Set(["string","number","bigint","boolean","symbol","undefined"]);function X1(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 v(Y){let X=Y;if(!X)return{};if(typeof X==="string")return{error:()=>X};if(X?.message!==void 0){if(X?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");X.error=X.message}if(delete X.message,typeof X.error==="string")return{...X,error:()=>X.error};return X}function sz(Y){let X;return new Proxy({},{get(J,Q,G){return X??(X=Y()),Reflect.get(X,Q,G)},set(J,Q,G,$){return X??(X=Y()),Reflect.set(X,Q,G,$)},has(J,Q){return X??(X=Y()),Reflect.has(X,Q)},deleteProperty(J,Q){return X??(X=Y()),Reflect.deleteProperty(X,Q)},ownKeys(J){return X??(X=Y()),Reflect.ownKeys(X)},getOwnPropertyDescriptor(J,Q){return X??(X=Y()),Reflect.getOwnPropertyDescriptor(X,Q)},defineProperty(J,Q,G){return X??(X=Y()),Reflect.defineProperty(X,Q,G)}})}function c6(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function $9(Y){return Object.keys(Y).filter((X)=>{return Y[X]._zod.optin==="optional"&&Y[X]._zod.optout==="optional"})}var W9={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]},u6={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function az(Y,X){let J=Y._zod.def,Q=V1(Y._zod.def,{get shape(){let G={};for(let $ in X){if(!($ in J.shape))throw Error(`Unrecognized key: "${$}"`);if(!X[$])continue;G[$]=J.shape[$]}return L1(this,"shape",G),G},checks:[]});return b0(Y,Q)}function tz(Y,X){let J=Y._zod.def,Q=V1(Y._zod.def,{get shape(){let G={...Y._zod.def.shape};for(let $ in X){if(!($ in J.shape))throw Error(`Unrecognized key: "${$}"`);if(!X[$])continue;delete G[$]}return L1(this,"shape",G),G},checks:[]});return b0(Y,Q)}function ez(Y,X){if(!N1(X))throw Error("Invalid input to extend: expected a plain object");let J=Y._zod.def.checks;if(J&&J.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let G=V1(Y._zod.def,{get shape(){let $={...Y._zod.def.shape,...X};return L1(this,"shape",$),$},checks:[]});return b0(Y,G)}function YU(Y,X){if(!N1(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 L1(this,"shape",Q),Q},checks:Y._zod.def.checks};return b0(Y,J)}function XU(Y,X){let J=V1(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape,...X._zod.def.shape};return L1(this,"shape",Q),Q},get catchall(){return X._zod.def.catchall},checks:[]});return b0(Y,J)}function JU(Y,X,J){let Q=V1(X._zod.def,{get shape(){let G=X._zod.def.shape,$={...G};if(J)for(let W in J){if(!(W in G))throw Error(`Unrecognized key: "${W}"`);if(!J[W])continue;$[W]=Y?new Y({type:"optional",innerType:G[W]}):G[W]}else for(let W in G)$[W]=Y?new Y({type:"optional",innerType:G[W]}):G[W];return L1(this,"shape",$),$},checks:[]});return b0(X,Q)}function QU(Y,X,J){let Q=V1(X._zod.def,{get shape(){let G=X._zod.def.shape,$={...G};if(J)for(let W in J){if(!(W in $))throw Error(`Unrecognized key: "${W}"`);if(!J[W])continue;$[W]=new Y({type:"nonoptional",innerType:G[W]})}else for(let W in G)$[W]=new Y({type:"nonoptional",innerType:G[W]});return L1(this,"shape",$),$},checks:[]});return b0(X,Q)}function B1(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 J1(Y,X){return X.map((J)=>{var Q;return(Q=J).path??(Q.path=[]),J.path.unshift(Y),J})}function YY(Y){return typeof Y==="string"?Y:Y?.message}function x0(Y,X,J){let Q={...Y,path:Y.path??[]};if(!Y.message){let G=YY(Y.inst?._zod.def?.error?.(Y))??YY(X?.error?.(Y))??YY(J.customError?.(Y))??YY(J.localeError?.(Y))??"Invalid input";Q.message=G}if(delete Q.inst,delete Q.continue,!X?.reportInput)delete Q.input;return Q}function p6(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function GY(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function p1(...Y){let[X,J,Q]=Y;if(typeof X==="string")return{message:X,code:"custom",input:J,inst:Q};return{...X}}function GU(Y){return Object.entries(Y).filter(([X,J])=>{return Number.isNaN(Number.parseInt(X,10))}).map((X)=>X[1])}function l6(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 d6(Y){let X="";for(let J=0;J<Y.length;J++)X+=String.fromCharCode(Y[J]);return btoa(X)}function $U(Y){let X=Y.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-X.length%4)%4);return l6(X+J)}function WU(Y){return d6(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function zU(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 UU(Y){return Array.from(Y).map((X)=>X.toString(16).padStart(2,"0")).join("")}class i6{constructor(...Y){}}var n6=(Y,X)=>{Y.name="$ZodError",Object.defineProperty(Y,"_zod",{value:Y._zod,enumerable:!1}),Object.defineProperty(Y,"issues",{value:X,enumerable:!1}),Y.message=JSON.stringify(X,c1,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},mY=F("$ZodError",n6),z9=F("$ZodError",n6,{Parent:Error});function o6(Y,X=(J)=>J.message){let J={},Q=[];for(let G of Y.issues)if(G.path.length>0)J[G.path[0]]=J[G.path[0]]||[],J[G.path[0]].push(X(G));else Q.push(X(G));return{formErrors:Q,fieldErrors:J}}function r6(Y,X){let J=X||function($){return $.message},Q={_errors:[]},G=($)=>{for(let W of $.issues)if(W.code==="invalid_union"&&W.errors.length)W.errors.map((z)=>G({issues:z}));else if(W.code==="invalid_key")G({issues:W.issues});else if(W.code==="invalid_element")G({issues:W.issues});else if(W.path.length===0)Q._errors.push(J(W));else{let z=Q,L=0;while(L<W.path.length){let H=W.path[L];if(L!==W.path.length-1)z[H]=z[H]||{_errors:[]};else z[H]=z[H]||{_errors:[]},z[H]._errors.push(J(W));z=z[H],L++}}};return G(Y),Q}var cY=(Y)=>(X,J,Q,G)=>{let $=Q?Object.assign(Q,{async:!1}):{async:!1},W=X._zod.run({value:J,issues:[]},$);if(W instanceof Promise)throw new Y1;if(W.issues.length){let z=new(G?.Err??Y)(W.issues.map((L)=>x0(L,$,l0())));throw fY(z,G?.callee),z}return W.value};var uY=(Y)=>async(X,J,Q,G)=>{let $=Q?Object.assign(Q,{async:!0}):{async:!0},W=X._zod.run({value:J,issues:[]},$);if(W instanceof Promise)W=await W;if(W.issues.length){let z=new(G?.Err??Y)(W.issues.map((L)=>x0(L,$,l0())));throw fY(z,G?.callee),z}return W.value};var $Y=(Y)=>(X,J,Q)=>{let G=Q?{...Q,async:!1}:{async:!1},$=X._zod.run({value:J,issues:[]},G);if($ instanceof Promise)throw new Y1;return $.issues.length?{success:!1,error:new(Y??mY)($.issues.map((W)=>x0(W,G,l0())))}:{success:!0,data:$.value}},s6=$Y(z9),WY=(Y)=>async(X,J,Q)=>{let G=Q?Object.assign(Q,{async:!0}):{async:!0},$=X._zod.run({value:J,issues:[]},G);if($ instanceof Promise)$=await $;return $.issues.length?{success:!1,error:new Y($.issues.map((W)=>x0(W,G,l0())))}:{success:!0,data:$.value}},a6=WY(z9),t6=(Y)=>(X,J,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return cY(Y)(X,J,G)};var e6=(Y)=>(X,J,Q)=>{return cY(Y)(X,J,Q)};var YQ=(Y)=>async(X,J,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return uY(Y)(X,J,G)};var XQ=(Y)=>async(X,J,Q)=>{return uY(Y)(X,J,Q)};var JQ=(Y)=>(X,J,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return $Y(Y)(X,J,G)};var QQ=(Y)=>(X,J,Q)=>{return $Y(Y)(X,J,Q)};var GQ=(Y)=>async(X,J,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return WY(Y)(X,J,G)};var $Q=(Y)=>async(X,J,Q)=>{return WY(Y)(X,J,Q)};var WQ=/^[cC][^\s-]{8,}$/,zQ=/^[0-9a-z]+$/,UQ=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,HQ=/^[0-9a-vA-V]{20}$/,LQ=/^[A-Za-z0-9]{27}$/,VQ=/^[a-zA-Z0-9_-]{21}$/,NQ=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var BQ=/^([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})$/,U9=(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 ZQ=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function KQ(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var OQ=/^(?:(?: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])$/,qQ=/^(([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}|:))$/,FQ=/^((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])$/,jQ=/^(([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])$/,DQ=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,H9=/^[A-Za-z0-9_-]*$/,PQ=/^(?=.{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 MQ=/^\+(?:[0-9]){6,14}[0-9]$/,wQ="(?:(?:\\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])))",EQ=new RegExp(`^${wQ}$`);function AQ(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 TQ(Y){return new RegExp(`^${AQ(Y)}$`)}function RQ(Y){let X=AQ({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(`^${wQ}T(?:${Q})$`)}var CQ=(Y)=>{let X=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${X}$`)};var _Q=/^-?\d+$/,IQ=/^-?\d+(?:\.\d+)?/,SQ=/^(?:true|false)$/i,kQ=/^null$/i;var bQ=/^[^A-Z]*$/,xQ=/^[^a-z]*$/;var B0=F("$ZodCheck",(Y,X)=>{var J;Y._zod??(Y._zod={}),Y._zod.def=X,(J=Y._zod).onattach??(J.onattach=[])}),vQ={number:"number",bigint:"bigint",object:"date"},L9=F("$ZodCheckLessThan",(Y,X)=>{B0.init(Y,X);let J=vQ[typeof X.value];Y._zod.onattach.push((Q)=>{let G=Q._zod.bag,$=(X.inclusive?G.maximum:G.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(X.value<$)if(X.inclusive)G.maximum=X.value;else G.exclusiveMaximum=X.value}),Y._zod.check=(Q)=>{if(X.inclusive?Q.value<=X.value:Q.value<X.value)return;Q.issues.push({origin:J,code:"too_big",maximum:X.value,input:Q.value,inclusive:X.inclusive,inst:Y,continue:!X.abort})}}),V9=F("$ZodCheckGreaterThan",(Y,X)=>{B0.init(Y,X);let J=vQ[typeof X.value];Y._zod.onattach.push((Q)=>{let G=Q._zod.bag,$=(X.inclusive?G.minimum:G.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(X.value>$)if(X.inclusive)G.minimum=X.value;else G.exclusiveMinimum=X.value}),Y._zod.check=(Q)=>{if(X.inclusive?Q.value>=X.value:Q.value>X.value)return;Q.issues.push({origin:J,code:"too_small",minimum:X.value,input:Q.value,inclusive:X.inclusive,inst:Y,continue:!X.abort})}}),hQ=F("$ZodCheckMultipleOf",(Y,X)=>{B0.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):J9(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})}}),gQ=F("$ZodCheckNumberFormat",(Y,X)=>{B0.init(Y,X),X.format=X.format||"float64";let J=X.format?.includes("int"),Q=J?"int":"number",[G,$]=W9[X.format];Y._zod.onattach.push((W)=>{let z=W._zod.bag;if(z.format=X.format,z.minimum=G,z.maximum=$,J)z.pattern=_Q}),Y._zod.check=(W)=>{let z=W.value;if(J){if(!Number.isInteger(z)){W.issues.push({expected:Q,format:X.format,code:"invalid_type",continue:!1,input:z,inst:Y});return}if(!Number.isSafeInteger(z)){if(z>0)W.issues.push({input:z,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:z,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(z<G)W.issues.push({origin:"number",input:z,code:"too_small",minimum:G,inclusive:!0,inst:Y,continue:!X.abort});if(z>$)W.issues.push({origin:"number",input:z,code:"too_big",maximum:$,inst:Y})}});var yQ=F("$ZodCheckMaxLength",(Y,X)=>{var J;B0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let G=Q.value;return!JY(G)&&G.length!==void 0}),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(X.maximum<G)Q._zod.bag.maximum=X.maximum}),Y._zod.check=(Q)=>{let G=Q.value;if(G.length<=X.maximum)return;let W=GY(G);Q.issues.push({origin:W,code:"too_big",maximum:X.maximum,inclusive:!0,input:G,inst:Y,continue:!X.abort})}}),fQ=F("$ZodCheckMinLength",(Y,X)=>{var J;B0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let G=Q.value;return!JY(G)&&G.length!==void 0}),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(X.minimum>G)Q._zod.bag.minimum=X.minimum}),Y._zod.check=(Q)=>{let G=Q.value;if(G.length>=X.minimum)return;let W=GY(G);Q.issues.push({origin:W,code:"too_small",minimum:X.minimum,inclusive:!0,input:G,inst:Y,continue:!X.abort})}}),mQ=F("$ZodCheckLengthEquals",(Y,X)=>{var J;B0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let G=Q.value;return!JY(G)&&G.length!==void 0}),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.minimum=X.length,G.maximum=X.length,G.length=X.length}),Y._zod.check=(Q)=>{let G=Q.value,$=G.length;if($===X.length)return;let W=GY(G),z=$>X.length;Q.issues.push({origin:W,...z?{code:"too_big",maximum:X.length}:{code:"too_small",minimum:X.length},inclusive:!0,exact:!0,input:Q.value,inst:Y,continue:!X.abort})}}),zY=F("$ZodCheckStringFormat",(Y,X)=>{var J,Q;if(B0.init(Y,X),Y._zod.onattach.push((G)=>{let $=G._zod.bag;if($.format=X.format,X.pattern)$.patterns??($.patterns=new Set),$.patterns.add(X.pattern)}),X.pattern)(J=Y._zod).check??(J.check=(G)=>{if(X.pattern.lastIndex=0,X.pattern.test(G.value))return;G.issues.push({origin:"string",code:"invalid_format",format:X.format,input:G.value,...X.pattern?{pattern:X.pattern.toString()}:{},inst:Y,continue:!X.abort})});else(Q=Y._zod).check??(Q.check=()=>{})}),cQ=F("$ZodCheckRegex",(Y,X)=>{zY.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})}}),uQ=F("$ZodCheckLowerCase",(Y,X)=>{X.pattern??(X.pattern=bQ),zY.init(Y,X)}),pQ=F("$ZodCheckUpperCase",(Y,X)=>{X.pattern??(X.pattern=xQ),zY.init(Y,X)}),lQ=F("$ZodCheckIncludes",(Y,X)=>{B0.init(Y,X);let J=X1(X.includes),Q=new RegExp(typeof X.position==="number"?`^.{${X.position}}${J}`:J);X.pattern=Q,Y._zod.onattach.push((G)=>{let $=G._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(Q)}),Y._zod.check=(G)=>{if(G.value.includes(X.includes,X.position))return;G.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:X.includes,input:G.value,inst:Y,continue:!X.abort})}}),dQ=F("$ZodCheckStartsWith",(Y,X)=>{B0.init(Y,X);let J=new RegExp(`^${X1(X.prefix)}.*`);X.pattern??(X.pattern=J),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(J)}),Y._zod.check=(Q)=>{if(Q.value.startsWith(X.prefix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:X.prefix,input:Q.value,inst:Y,continue:!X.abort})}}),iQ=F("$ZodCheckEndsWith",(Y,X)=>{B0.init(Y,X);let J=new RegExp(`.*${X1(X.suffix)}$`);X.pattern??(X.pattern=J),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(J)}),Y._zod.check=(Q)=>{if(Q.value.endsWith(X.suffix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:X.suffix,input:Q.value,inst:Y,continue:!X.abort})}});var nQ=F("$ZodCheckOverwrite",(Y,X)=>{B0.init(Y,X),Y._zod.check=(J)=>{J.value=X.tx(J.value)}});class N9{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(($)=>$),Q=Math.min(...J.map(($)=>$.length-$.trimStart().length)),G=J.map(($)=>$.slice(Q)).map(($)=>" ".repeat(this.indent*2)+$);for(let $ of G)this.content.push($)}compile(){let Y=Function,X=this?.args,Q=[...(this?.content??[""]).map((G)=>` ${G}`)];return new Y(...X,Q.join(`
168
- `))}}var iQ={major:4,minor:1,patch:8};var o=F("$ZodType",(Y,X)=>{var J;Y??(Y={}),Y._zod.def=X,Y._zod.bag=Y._zod.bag||{},Y._zod.version=iQ;let Q=[...Y._zod.def.checks??[]];if(Y._zod.traits.has("$ZodCheck"))Q.unshift(Y);for(let G of Q)for(let $ of G._zod.onattach)$(Y);if(Q.length===0)(J=Y._zod).deferred??(J.deferred=[]),Y._zod.deferred?.push(()=>{Y._zod.run=Y._zod.parse});else{let G=(W,U,H)=>{let L=B1(W),N;for(let O of U){if(O._zod.def.when){if(!O._zod.def.when(W))continue}else if(L)continue;let Z=W.issues.length,V=O._zod.check(W);if(V instanceof Promise&&H?.async===!1)throw new Y1;if(N||V instanceof Promise)N=(N??Promise.resolve()).then(async()=>{if(await V,W.issues.length===Z)return;if(!L)L=B1(W,Z)});else{if(W.issues.length===Z)continue;if(!L)L=B1(W,Z)}}if(N)return N.then(()=>{return W});return W},$=(W,U,H)=>{if(B1(W))return W.aborted=!0,W;let L=G(U,Q,H);if(L instanceof Promise){if(H.async===!1)throw new Y1;return L.then((N)=>Y._zod.parse(N,H))}return Y._zod.parse(L,H)};Y._zod.run=(W,U)=>{if(U.skipChecks)return Y._zod.parse(W,U);if(U.direction==="backward"){let L=Y._zod.parse({value:W.value,issues:[]},{...U,skipChecks:!0});if(L instanceof Promise)return L.then((N)=>{return $(N,W,U)});return $(L,W,U)}let H=Y._zod.parse(W,U);if(H instanceof Promise){if(U.async===!1)throw new Y1;return H.then((L)=>G(L,Q,U))}return G(H,Q,U)}}Y["~standard"]={validate:(G)=>{try{let $=n6(Y,G);return $.success?{value:$.data}:{issues:$.error?.issues}}catch($){return o6(Y,G).then((W)=>W.success?{value:W.data}:{issues:W.error?.issues})}},vendor:"zod",version:1}}),iY=F("$ZodString",(Y,X)=>{o.init(Y,X),Y._zod.pattern=[...Y?._zod.bag?.patterns??[]].pop()??AQ(Y._zod.bag),Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=String(J.value)}catch(G){}if(typeof J.value==="string")return J;return J.issues.push({expected:"string",code:"invalid_type",input:J.value,inst:Y}),J}}),s=F("$ZodStringFormat",(Y,X)=>{zY.init(Y,X),iY.init(Y,X)}),X7=F("$ZodGUID",(Y,X)=>{X.pattern??(X.pattern=LQ),s.init(Y,X)}),J7=F("$ZodUUID",(Y,X)=>{if(X.version){let Q={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[X.version];if(Q===void 0)throw Error(`Invalid UUID version: "${X.version}"`);X.pattern??(X.pattern=U9(Q))}else X.pattern??(X.pattern=U9());s.init(Y,X)}),Q7=F("$ZodEmail",(Y,X)=>{X.pattern??(X.pattern=VQ),s.init(Y,X)}),G7=F("$ZodURL",(Y,X)=>{s.init(Y,X),Y._zod.check=(J)=>{try{let Q=J.value.trim(),G=new URL(Q);if(X.hostname){if(X.hostname.lastIndex=0,!X.hostname.test(G.hostname))J.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:FQ.source,input:J.value,inst:Y,continue:!X.abort})}if(X.protocol){if(X.protocol.lastIndex=0,!X.protocol.test(G.protocol.endsWith(":")?G.protocol.slice(0,-1):G.protocol))J.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:X.protocol.source,input:J.value,inst:Y,continue:!X.abort})}if(X.normalize)J.value=G.href;else J.value=Q;return}catch(Q){J.issues.push({code:"invalid_format",format:"url",input:J.value,inst:Y,continue:!X.abort})}}}),$7=F("$ZodEmoji",(Y,X)=>{X.pattern??(X.pattern=NQ()),s.init(Y,X)}),W7=F("$ZodNanoID",(Y,X)=>{X.pattern??(X.pattern=UQ),s.init(Y,X)}),z7=F("$ZodCUID",(Y,X)=>{X.pattern??(X.pattern=QQ),s.init(Y,X)}),U7=F("$ZodCUID2",(Y,X)=>{X.pattern??(X.pattern=GQ),s.init(Y,X)}),H7=F("$ZodULID",(Y,X)=>{X.pattern??(X.pattern=$Q),s.init(Y,X)}),L7=F("$ZodXID",(Y,X)=>{X.pattern??(X.pattern=WQ),s.init(Y,X)}),V7=F("$ZodKSUID",(Y,X)=>{X.pattern??(X.pattern=zQ),s.init(Y,X)}),N7=F("$ZodISODateTime",(Y,X)=>{X.pattern??(X.pattern=EQ(X)),s.init(Y,X)}),B7=F("$ZodISODate",(Y,X)=>{X.pattern??(X.pattern=PQ),s.init(Y,X)}),Z7=F("$ZodISOTime",(Y,X)=>{X.pattern??(X.pattern=wQ(X)),s.init(Y,X)}),K7=F("$ZodISODuration",(Y,X)=>{X.pattern??(X.pattern=HQ),s.init(Y,X)}),O7=F("$ZodIPv4",(Y,X)=>{X.pattern??(X.pattern=BQ),s.init(Y,X),Y._zod.onattach.push((J)=>{let Q=J._zod.bag;Q.format="ipv4"})}),q7=F("$ZodIPv6",(Y,X)=>{X.pattern??(X.pattern=ZQ),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})}}}),F7=F("$ZodCIDRv4",(Y,X)=>{X.pattern??(X.pattern=KQ),s.init(Y,X)}),j7=F("$ZodCIDRv6",(Y,X)=>{X.pattern??(X.pattern=OQ),s.init(Y,X),Y._zod.check=(J)=>{let Q=J.value.split("/");try{if(Q.length!==2)throw Error();let[G,$]=Q;if(!$)throw Error();let W=Number($);if(`${W}`!==$)throw Error();if(W<0||W>128)throw Error();new URL(`http://[${G}]`)}catch{J.issues.push({code:"invalid_format",format:"cidrv6",input:J.value,inst:Y,continue:!X.abort})}}});function D7(Y){if(Y==="")return!0;if(Y.length%4!==0)return!1;try{return atob(Y),!0}catch{return!1}}var P7=F("$ZodBase64",(Y,X)=>{X.pattern??(X.pattern=qQ),s.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64"}),Y._zod.check=(J)=>{if(D7(J.value))return;J.issues.push({code:"invalid_format",format:"base64",input:J.value,inst:Y,continue:!X.abort})}});function $U(Y){if(!H9.test(Y))return!1;let X=Y.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),J=X.padEnd(Math.ceil(X.length/4)*4,"=");return D7(J)}var M7=F("$ZodBase64URL",(Y,X)=>{X.pattern??(X.pattern=H9),s.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64url"}),Y._zod.check=(J)=>{if($U(J.value))return;J.issues.push({code:"invalid_format",format:"base64url",input:J.value,inst:Y,continue:!X.abort})}}),w7=F("$ZodE164",(Y,X)=>{X.pattern??(X.pattern=jQ),s.init(Y,X)});function WU(Y,X=null){try{let J=Y.split(".");if(J.length!==3)return!1;let[Q]=J;if(!Q)return!1;let G=JSON.parse(atob(Q));if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(X&&(!("alg"in G)||G.alg!==X))return!1;return!0}catch{return!1}}var E7=F("$ZodJWT",(Y,X)=>{s.init(Y,X),Y._zod.check=(J)=>{if(WU(J.value,X.alg))return;J.issues.push({code:"invalid_format",format:"jwt",input:J.value,inst:Y,continue:!X.abort})}});var Z9=F("$ZodNumber",(Y,X)=>{o.init(Y,X),Y._zod.pattern=Y._zod.bag.pattern??RQ,Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=Number(J.value)}catch(W){}let G=J.value;if(typeof G==="number"&&!Number.isNaN(G)&&Number.isFinite(G))return J;let $=typeof G==="number"?Number.isNaN(G)?"NaN":!Number.isFinite(G)?"Infinity":void 0:void 0;return J.issues.push({expected:"number",code:"invalid_type",input:G,inst:Y,...$?{received:$}:{}}),J}}),A7=F("$ZodNumber",(Y,X)=>{xQ.init(Y,X),Z9.init(Y,X)}),T7=F("$ZodBoolean",(Y,X)=>{o.init(Y,X),Y._zod.pattern=CQ,Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=Boolean(J.value)}catch($){}let G=J.value;if(typeof G==="boolean")return J;return J.issues.push({expected:"boolean",code:"invalid_type",input:G,inst:Y}),J}});var R7=F("$ZodNull",(Y,X)=>{o.init(Y,X),Y._zod.pattern=_Q,Y._zod.values=new Set([null]),Y._zod.parse=(J,Q)=>{let G=J.value;if(G===null)return J;return J.issues.push({expected:"null",code:"invalid_type",input:G,inst:Y}),J}});var C7=F("$ZodUnknown",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J)=>J}),_7=F("$ZodNever",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{return J.issues.push({expected:"never",code:"invalid_type",input:J.value,inst:Y}),J}});function nQ(Y,X,J){if(Y.issues.length)X.issues.push(...J1(J,Y.issues));X.value[J]=Y.value}var I7=F("$ZodArray",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{let G=J.value;if(!Array.isArray(G))return J.issues.push({expected:"array",code:"invalid_type",input:G,inst:Y}),J;J.value=Array(G.length);let $=[];for(let W=0;W<G.length;W++){let U=G[W],H=X.element._zod.run({value:U,issues:[]},Q);if(H instanceof Promise)$.push(H.then((L)=>nQ(L,J,W)));else nQ(H,J,W)}if($.length)return Promise.all($).then(()=>J);return J}});function dY(Y,X,J,Q){if(Y.issues.length)X.issues.push(...J1(J,Y.issues));if(Y.value===void 0){if(J in Q)X.value[J]=void 0}else X.value[J]=Y.value}function S7(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=$9(Y.shape);return{...Y,keys:X,keySet:new Set(X),numKeys:X.length,optionalKeys:new Set(J)}}function k7(Y,X,J,Q,G,$){let W=[],U=G.keySet,H=G.catchall._zod,L=H.def.type;for(let N of Object.keys(X)){if(U.has(N))continue;if(L==="never"){W.push(N);continue}let O=H.run({value:X[N],issues:[]},Q);if(O instanceof Promise)Y.push(O.then((Z)=>dY(Z,J,N,X)));else dY(O,J,N,X)}if(W.length)J.issues.push({code:"unrecognized_keys",keys:W,input:X,inst:$});if(!Y.length)return J;return Promise.all(Y).then(()=>{return J})}var zU=F("$ZodObject",(Y,X)=>{o.init(Y,X);let J=u1(()=>S7(X));p(Y._zod,"propValues",()=>{let W=X.shape,U={};for(let H in W){let L=W[H]._zod;if(L.values){U[H]??(U[H]=new Set);for(let N of L.values)U[H].add(N)}}return U});let Q=A1,G=X.catchall,$;Y._zod.parse=(W,U)=>{$??($=J.value);let H=W.value;if(!Q(H))return W.issues.push({expected:"object",code:"invalid_type",input:H,inst:Y}),W;W.value={};let L=[],N=$.shape;for(let O of $.keys){let V=N[O]._zod.run({value:H[O],issues:[]},U);if(V instanceof Promise)L.push(V.then((K)=>dY(K,W,O,H)));else dY(V,W,O,H)}if(!G)return L.length?Promise.all(L).then(()=>W):W;return k7(L,H,W,U,J.value,Y)}}),b7=F("$ZodObjectJIT",(Y,X)=>{zU.init(Y,X);let J=Y._zod.parse,Q=u1(()=>S7(X)),G=(Z)=>{let V=new N9(["shape","payload","ctx"]),K=Q.value,j=(b)=>{let f=yY(b);return`shape[${f}]._zod.run({ value: input[${f}], issues: [] }, ctx)`};V.write("const input = payload.value;");let M=Object.create(null),I=0;for(let b of K.keys)M[b]=`key_${I++}`;V.write("const newResult = {};");for(let b of K.keys){let f=M[b],l=yY(b);V.write(`const ${f} = ${j(b)};`),V.write(`
168
+ `))}}var rQ={major:4,minor:1,patch:8};var o=F("$ZodType",(Y,X)=>{var J;Y??(Y={}),Y._zod.def=X,Y._zod.bag=Y._zod.bag||{},Y._zod.version=rQ;let Q=[...Y._zod.def.checks??[]];if(Y._zod.traits.has("$ZodCheck"))Q.unshift(Y);for(let G of Q)for(let $ of G._zod.onattach)$(Y);if(Q.length===0)(J=Y._zod).deferred??(J.deferred=[]),Y._zod.deferred?.push(()=>{Y._zod.run=Y._zod.parse});else{let G=(W,z,L)=>{let H=B1(W),N;for(let O of z){if(O._zod.def.when){if(!O._zod.def.when(W))continue}else if(H)continue;let Z=W.issues.length,V=O._zod.check(W);if(V instanceof Promise&&L?.async===!1)throw new Y1;if(N||V instanceof Promise)N=(N??Promise.resolve()).then(async()=>{if(await V,W.issues.length===Z)return;if(!H)H=B1(W,Z)});else{if(W.issues.length===Z)continue;if(!H)H=B1(W,Z)}}if(N)return N.then(()=>{return W});return W},$=(W,z,L)=>{if(B1(W))return W.aborted=!0,W;let H=G(z,Q,L);if(H instanceof Promise){if(L.async===!1)throw new Y1;return H.then((N)=>Y._zod.parse(N,L))}return Y._zod.parse(H,L)};Y._zod.run=(W,z)=>{if(z.skipChecks)return Y._zod.parse(W,z);if(z.direction==="backward"){let H=Y._zod.parse({value:W.value,issues:[]},{...z,skipChecks:!0});if(H instanceof Promise)return H.then((N)=>{return $(N,W,z)});return $(H,W,z)}let L=Y._zod.parse(W,z);if(L instanceof Promise){if(z.async===!1)throw new Y1;return L.then((H)=>G(H,Q,z))}return G(L,Q,z)}}Y["~standard"]={validate:(G)=>{try{let $=s6(Y,G);return $.success?{value:$.data}:{issues:$.error?.issues}}catch($){return a6(Y,G).then((W)=>W.success?{value:W.data}:{issues:W.error?.issues})}},vendor:"zod",version:1}}),iY=F("$ZodString",(Y,X)=>{o.init(Y,X),Y._zod.pattern=[...Y?._zod.bag?.patterns??[]].pop()??CQ(Y._zod.bag),Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=String(J.value)}catch(G){}if(typeof J.value==="string")return J;return J.issues.push({expected:"string",code:"invalid_type",input:J.value,inst:Y}),J}}),s=F("$ZodStringFormat",(Y,X)=>{zY.init(Y,X),iY.init(Y,X)}),G7=F("$ZodGUID",(Y,X)=>{X.pattern??(X.pattern=BQ),s.init(Y,X)}),$7=F("$ZodUUID",(Y,X)=>{if(X.version){let Q={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[X.version];if(Q===void 0)throw Error(`Invalid UUID version: "${X.version}"`);X.pattern??(X.pattern=U9(Q))}else X.pattern??(X.pattern=U9());s.init(Y,X)}),W7=F("$ZodEmail",(Y,X)=>{X.pattern??(X.pattern=ZQ),s.init(Y,X)}),z7=F("$ZodURL",(Y,X)=>{s.init(Y,X),Y._zod.check=(J)=>{try{let Q=J.value.trim(),G=new URL(Q);if(X.hostname){if(X.hostname.lastIndex=0,!X.hostname.test(G.hostname))J.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:PQ.source,input:J.value,inst:Y,continue:!X.abort})}if(X.protocol){if(X.protocol.lastIndex=0,!X.protocol.test(G.protocol.endsWith(":")?G.protocol.slice(0,-1):G.protocol))J.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:X.protocol.source,input:J.value,inst:Y,continue:!X.abort})}if(X.normalize)J.value=G.href;else J.value=Q;return}catch(Q){J.issues.push({code:"invalid_format",format:"url",input:J.value,inst:Y,continue:!X.abort})}}}),U7=F("$ZodEmoji",(Y,X)=>{X.pattern??(X.pattern=KQ()),s.init(Y,X)}),H7=F("$ZodNanoID",(Y,X)=>{X.pattern??(X.pattern=VQ),s.init(Y,X)}),L7=F("$ZodCUID",(Y,X)=>{X.pattern??(X.pattern=WQ),s.init(Y,X)}),V7=F("$ZodCUID2",(Y,X)=>{X.pattern??(X.pattern=zQ),s.init(Y,X)}),N7=F("$ZodULID",(Y,X)=>{X.pattern??(X.pattern=UQ),s.init(Y,X)}),B7=F("$ZodXID",(Y,X)=>{X.pattern??(X.pattern=HQ),s.init(Y,X)}),Z7=F("$ZodKSUID",(Y,X)=>{X.pattern??(X.pattern=LQ),s.init(Y,X)}),K7=F("$ZodISODateTime",(Y,X)=>{X.pattern??(X.pattern=RQ(X)),s.init(Y,X)}),O7=F("$ZodISODate",(Y,X)=>{X.pattern??(X.pattern=EQ),s.init(Y,X)}),q7=F("$ZodISOTime",(Y,X)=>{X.pattern??(X.pattern=TQ(X)),s.init(Y,X)}),F7=F("$ZodISODuration",(Y,X)=>{X.pattern??(X.pattern=NQ),s.init(Y,X)}),j7=F("$ZodIPv4",(Y,X)=>{X.pattern??(X.pattern=OQ),s.init(Y,X),Y._zod.onattach.push((J)=>{let Q=J._zod.bag;Q.format="ipv4"})}),D7=F("$ZodIPv6",(Y,X)=>{X.pattern??(X.pattern=qQ),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})}}}),P7=F("$ZodCIDRv4",(Y,X)=>{X.pattern??(X.pattern=FQ),s.init(Y,X)}),M7=F("$ZodCIDRv6",(Y,X)=>{X.pattern??(X.pattern=jQ),s.init(Y,X),Y._zod.check=(J)=>{let Q=J.value.split("/");try{if(Q.length!==2)throw Error();let[G,$]=Q;if(!$)throw Error();let W=Number($);if(`${W}`!==$)throw Error();if(W<0||W>128)throw Error();new URL(`http://[${G}]`)}catch{J.issues.push({code:"invalid_format",format:"cidrv6",input:J.value,inst:Y,continue:!X.abort})}}});function w7(Y){if(Y==="")return!0;if(Y.length%4!==0)return!1;try{return atob(Y),!0}catch{return!1}}var E7=F("$ZodBase64",(Y,X)=>{X.pattern??(X.pattern=DQ),s.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64"}),Y._zod.check=(J)=>{if(w7(J.value))return;J.issues.push({code:"invalid_format",format:"base64",input:J.value,inst:Y,continue:!X.abort})}});function LU(Y){if(!H9.test(Y))return!1;let X=Y.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),J=X.padEnd(Math.ceil(X.length/4)*4,"=");return w7(J)}var A7=F("$ZodBase64URL",(Y,X)=>{X.pattern??(X.pattern=H9),s.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64url"}),Y._zod.check=(J)=>{if(LU(J.value))return;J.issues.push({code:"invalid_format",format:"base64url",input:J.value,inst:Y,continue:!X.abort})}}),T7=F("$ZodE164",(Y,X)=>{X.pattern??(X.pattern=MQ),s.init(Y,X)});function VU(Y,X=null){try{let J=Y.split(".");if(J.length!==3)return!1;let[Q]=J;if(!Q)return!1;let G=JSON.parse(atob(Q));if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(X&&(!("alg"in G)||G.alg!==X))return!1;return!0}catch{return!1}}var R7=F("$ZodJWT",(Y,X)=>{s.init(Y,X),Y._zod.check=(J)=>{if(VU(J.value,X.alg))return;J.issues.push({code:"invalid_format",format:"jwt",input:J.value,inst:Y,continue:!X.abort})}});var Z9=F("$ZodNumber",(Y,X)=>{o.init(Y,X),Y._zod.pattern=Y._zod.bag.pattern??IQ,Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=Number(J.value)}catch(W){}let G=J.value;if(typeof G==="number"&&!Number.isNaN(G)&&Number.isFinite(G))return J;let $=typeof G==="number"?Number.isNaN(G)?"NaN":!Number.isFinite(G)?"Infinity":void 0:void 0;return J.issues.push({expected:"number",code:"invalid_type",input:G,inst:Y,...$?{received:$}:{}}),J}}),C7=F("$ZodNumber",(Y,X)=>{gQ.init(Y,X),Z9.init(Y,X)}),_7=F("$ZodBoolean",(Y,X)=>{o.init(Y,X),Y._zod.pattern=SQ,Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=Boolean(J.value)}catch($){}let G=J.value;if(typeof G==="boolean")return J;return J.issues.push({expected:"boolean",code:"invalid_type",input:G,inst:Y}),J}});var I7=F("$ZodNull",(Y,X)=>{o.init(Y,X),Y._zod.pattern=kQ,Y._zod.values=new Set([null]),Y._zod.parse=(J,Q)=>{let G=J.value;if(G===null)return J;return J.issues.push({expected:"null",code:"invalid_type",input:G,inst:Y}),J}});var S7=F("$ZodUnknown",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J)=>J}),k7=F("$ZodNever",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{return J.issues.push({expected:"never",code:"invalid_type",input:J.value,inst:Y}),J}});function sQ(Y,X,J){if(Y.issues.length)X.issues.push(...J1(J,Y.issues));X.value[J]=Y.value}var b7=F("$ZodArray",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{let G=J.value;if(!Array.isArray(G))return J.issues.push({expected:"array",code:"invalid_type",input:G,inst:Y}),J;J.value=Array(G.length);let $=[];for(let W=0;W<G.length;W++){let z=G[W],L=X.element._zod.run({value:z,issues:[]},Q);if(L instanceof Promise)$.push(L.then((H)=>sQ(H,J,W)));else sQ(L,J,W)}if($.length)return Promise.all($).then(()=>J);return J}});function dY(Y,X,J,Q){if(Y.issues.length)X.issues.push(...J1(J,Y.issues));if(Y.value===void 0){if(J in Q)X.value[J]=void 0}else X.value[J]=Y.value}function x7(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=$9(Y.shape);return{...Y,keys:X,keySet:new Set(X),numKeys:X.length,optionalKeys:new Set(J)}}function v7(Y,X,J,Q,G,$){let W=[],z=G.keySet,L=G.catchall._zod,H=L.def.type;for(let N of Object.keys(X)){if(z.has(N))continue;if(H==="never"){W.push(N);continue}let O=L.run({value:X[N],issues:[]},Q);if(O instanceof Promise)Y.push(O.then((Z)=>dY(Z,J,N,X)));else dY(O,J,N,X)}if(W.length)J.issues.push({code:"unrecognized_keys",keys:W,input:X,inst:$});if(!Y.length)return J;return Promise.all(Y).then(()=>{return J})}var NU=F("$ZodObject",(Y,X)=>{o.init(Y,X);let J=u1(()=>x7(X));p(Y._zod,"propValues",()=>{let W=X.shape,z={};for(let L in W){let H=W[L]._zod;if(H.values){z[L]??(z[L]=new Set);for(let N of H.values)z[L].add(N)}}return z});let Q=A1,G=X.catchall,$;Y._zod.parse=(W,z)=>{$??($=J.value);let L=W.value;if(!Q(L))return W.issues.push({expected:"object",code:"invalid_type",input:L,inst:Y}),W;W.value={};let H=[],N=$.shape;for(let O of $.keys){let V=N[O]._zod.run({value:L[O],issues:[]},z);if(V instanceof Promise)H.push(V.then((K)=>dY(K,W,O,L)));else dY(V,W,O,L)}if(!G)return H.length?Promise.all(H).then(()=>W):W;return v7(H,L,W,z,J.value,Y)}}),h7=F("$ZodObjectJIT",(Y,X)=>{NU.init(Y,X);let J=Y._zod.parse,Q=u1(()=>x7(X)),G=(Z)=>{let V=new N9(["shape","payload","ctx"]),K=Q.value,j=(b)=>{let f=yY(b);return`shape[${f}]._zod.run({ value: input[${f}], issues: [] }, ctx)`};V.write("const input = payload.value;");let M=Object.create(null),I=0;for(let b of K.keys)M[b]=`key_${I++}`;V.write("const newResult = {};");for(let b of K.keys){let f=M[b],l=yY(b);V.write(`const ${f} = ${j(b)};`),V.write(`
169
169
  if (${f}.issues.length) {
170
170
  payload.issues = payload.issues.concat(${f}.issues.map(iss => ({
171
171
  ...iss,
@@ -182,37 +182,37 @@ Error message: ${e8(J)}`,cause:J});this[X6]=!0,this.value=X,this.context=Q}stati
182
182
  newResult[${l}] = ${f}.value;
183
183
  }
184
184
 
185
- `)}V.write("payload.value = newResult;"),V.write("return payload;");let E=V.compile();return(b,f)=>E(Z,b,f)},$,W=A1,U=!gY.jitless,L=U&&Q9.value,N=X.catchall,O;Y._zod.parse=(Z,V)=>{O??(O=Q.value);let K=Z.value;if(!W(K))return Z.issues.push({expected:"object",code:"invalid_type",input:K,inst:Y}),Z;if(U&&L&&V?.async===!1&&V.jitless!==!0){if(!$)$=G(X.shape);if(Z=$(Z,V),!N)return Z;return k7([],K,Z,V,O,Y)}return J(Z,V)}});function oQ(Y,X,J,Q){for(let $ of Y)if($.issues.length===0)return X.value=$.value,X;let G=Y.filter(($)=>!B1($));if(G.length===1)return X.value=G[0].value,G[0];return X.issues.push({code:"invalid_union",input:X.value,inst:J,errors:Y.map(($)=>$.issues.map((W)=>x0(W,Q,l0())))}),X}var K9=F("$ZodUnion",(Y,X)=>{o.init(Y,X),p(Y._zod,"optin",()=>X.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),p(Y._zod,"optout",()=>X.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),p(Y._zod,"values",()=>{if(X.options.every((G)=>G._zod.values))return new Set(X.options.flatMap((G)=>Array.from(G._zod.values)));return}),p(Y._zod,"pattern",()=>{if(X.options.every((G)=>G._zod.pattern)){let G=X.options.map(($)=>$._zod.pattern);return new RegExp(`^(${G.map(($)=>QY($.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 H of X.options){let L=H._zod.run({value:G.value,issues:[]},$);if(L instanceof Promise)U.push(L),W=!0;else{if(L.issues.length===0)return L;U.push(L)}}if(!W)return oQ(U,G,Y,$);return Promise.all(U).then((H)=>{return oQ(H,G,Y,$)})}}),x7=F("$ZodDiscriminatedUnion",(Y,X)=>{K9.init(Y,X);let J=Y._zod.parse;p(Y._zod,"propValues",()=>{let G={};for(let $ of X.options){let W=$._zod.propValues;if(!W||Object.keys(W).length===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf($)}"`);for(let[U,H]of Object.entries(W)){if(!G[U])G[U]=new Set;for(let L of H)G[U].add(L)}}return G});let Q=u1(()=>{let G=X.options,$=new Map;for(let W of G){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 H of U){if($.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);$.set(H,W)}}return $});Y._zod.parse=(G,$)=>{let W=G.value;if(!A1(W))return G.issues.push({code:"invalid_type",expected:"object",input:W,inst:Y}),G;let U=Q.value.get(W?.[X.discriminator]);if(U)return U._zod.run(G,$);if(X.unionFallback)return J(G,$);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:X.discriminator,input:W,path:[X.discriminator],inst:Y}),G}}),v7=F("$ZodIntersection",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{let G=J.value,$=X.left._zod.run({value:G,issues:[]},Q),W=X.right._zod.run({value:G,issues:[]},Q);if($ instanceof Promise||W instanceof Promise)return Promise.all([$,W]).then(([H,L])=>{return rQ(J,H,L)});return rQ(J,$,W)}});function B9(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(N1(Y)&&N1(X)){let J=Object.keys(X),Q=Object.keys(Y).filter(($)=>J.indexOf($)!==-1),G={...Y,...X};for(let $ of Q){let W=B9(Y[$],X[$]);if(!W.valid)return{valid:!1,mergeErrorPath:[$,...W.mergeErrorPath]};G[$]=W.data}return{valid:!0,data:G}}if(Array.isArray(Y)&&Array.isArray(X)){if(Y.length!==X.length)return{valid:!1,mergeErrorPath:[]};let J=[];for(let Q=0;Q<Y.length;Q++){let G=Y[Q],$=X[Q],W=B9(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 rQ(Y,X,J){if(X.issues.length)Y.issues.push(...X.issues);if(J.issues.length)Y.issues.push(...J.issues);if(B1(Y))return Y;let Q=B9(X.value,J.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return Y.value=Q.data,Y}var h7=F("$ZodRecord",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{let G=J.value;if(!N1(G))return J.issues.push({expected:"record",code:"invalid_type",input:G,inst:Y}),J;let $=[];if(X.keyType._zod.values){let W=X.keyType._zod.values;J.value={};for(let H of W)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let L=X.valueType._zod.run({value:G[H],issues:[]},Q);if(L instanceof Promise)$.push(L.then((N)=>{if(N.issues.length)J.issues.push(...J1(H,N.issues));J.value[H]=N.value}));else{if(L.issues.length)J.issues.push(...J1(H,L.issues));J.value[H]=L.value}}let U;for(let H in G)if(!W.has(H))U=U??[],U.push(H);if(U&&U.length>0)J.issues.push({code:"unrecognized_keys",input:G,inst:Y,keys:U})}else{J.value={};for(let W of Reflect.ownKeys(G)){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((L)=>x0(L,Q,l0())),input:W,path:[W],inst:Y}),J.value[U.value]=U.value;continue}let H=X.valueType._zod.run({value:G[W],issues:[]},Q);if(H instanceof Promise)$.push(H.then((L)=>{if(L.issues.length)J.issues.push(...J1(W,L.issues));J.value[U.value]=L.value}));else{if(H.issues.length)J.issues.push(...J1(W,H.issues));J.value[U.value]=H.value}}}if($.length)return Promise.all($).then(()=>J);return J}});var g7=F("$ZodEnum",(Y,X)=>{o.init(Y,X);let J=XY(X.entries),Q=new Set(J);Y._zod.values=Q,Y._zod.pattern=new RegExp(`^(${J.filter((G)=>G9.has(typeof G)).map((G)=>typeof G==="string"?X1(G):G.toString()).join("|")})$`),Y._zod.parse=(G,$)=>{let W=G.value;if(Q.has(W))return G;return G.issues.push({code:"invalid_value",values:J,input:W,inst:Y}),G}}),y7=F("$ZodLiteral",(Y,X)=>{if(o.init(Y,X),X.values.length===0)throw Error("Cannot create literal schema with no valid values");Y._zod.values=new Set(X.values),Y._zod.pattern=new RegExp(`^(${X.values.map((J)=>typeof J==="string"?X1(J):J?X1(J.toString()):String(J)).join("|")})$`),Y._zod.parse=(J,Q)=>{let G=J.value;if(Y._zod.values.has(G))return J;return J.issues.push({code:"invalid_value",values:X.values,input:G,inst:Y}),J}});var f7=F("$ZodTransform",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new e1(Y.constructor.name);let G=X.transform(J.value,J);if(Q.async)return(G instanceof Promise?G:Promise.resolve(G)).then((W)=>{return J.value=W,J});if(G instanceof Promise)throw new Y1;return J.value=G,J}});function sQ(Y,X){if(Y.issues.length&&X===void 0)return{issues:[],value:void 0};return Y}var m7=F("$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(`^(${QY(J.source)})?$`):void 0}),Y._zod.parse=(J,Q)=>{if(X.innerType._zod.optin==="optional"){let G=X.innerType._zod.run(J,Q);if(G instanceof Promise)return G.then(($)=>sQ($,J.value));return sQ(G,J.value)}if(J.value===void 0)return J;return X.innerType._zod.run(J,Q)}}),c7=F("$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(`^(${QY(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)}}),u7=F("$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 G=X.innerType._zod.run(J,Q);if(G instanceof Promise)return G.then(($)=>aQ($,X));return aQ(G,X)}});function aQ(Y,X){if(Y.value===void 0)Y.value=X.defaultValue;return Y}var p7=F("$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)}}),l7=F("$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 G=X.innerType._zod.run(J,Q);if(G instanceof Promise)return G.then(($)=>tQ($,Y));return tQ(G,Y)}});function tQ(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 d7=F("$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 G=X.innerType._zod.run(J,Q);if(G instanceof Promise)return G.then(($)=>{if(J.value=$.value,$.issues.length)J.value=X.catchValue({...J,error:{issues:$.issues.map((W)=>x0(W,Q,l0()))},input:J.value}),J.issues=[];return J});if(J.value=G.value,G.issues.length)J.value=X.catchValue({...J,error:{issues:G.issues.map(($)=>x0($,Q,l0()))},input:J.value}),J.issues=[];return J}});var i7=F("$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 $=X.out._zod.run(J,Q);if($ instanceof Promise)return $.then((W)=>lY(W,X.in,Q));return lY($,X.in,Q)}let G=X.in._zod.run(J,Q);if(G instanceof Promise)return G.then(($)=>lY($,X.out,Q));return lY(G,X.out,Q)}});function lY(Y,X,J){if(Y.issues.length)return Y.aborted=!0,Y;return X._zod.run({value:Y.value,issues:Y.issues},J)}var n7=F("$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 G=X.innerType._zod.run(J,Q);if(G instanceof Promise)return G.then(eQ);return eQ(G)}});function eQ(Y){return Y.value=Object.freeze(Y.value),Y}var o7=F("$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)}}),r7=F("$ZodCustom",(Y,X)=>{B0.init(Y,X),o.init(Y,X),Y._zod.parse=(J,Q)=>{return J},Y._zod.check=(J)=>{let Q=J.value,G=X.fn(Q);if(G instanceof Promise)return G.then(($)=>Y7($,J,Q,Y));Y7(G,J,Q,Y);return}});function Y7(Y,X,J,Q){if(!Y){let G={code:"custom",input:J,inst:Q,path:[...Q._zod.def.path??[]],continue:!Q._zod.def.abort};if(Q._zod.def.params)G.params=Q._zod.def.params;X.issues.push(p1(G))}}var dK=Symbol("ZodOutput"),iK=Symbol("ZodInput");class nY{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 UU(){return new nY}var T1=UU();function s7(Y,X){return new Y({type:"string",...v(X)})}function a7(Y,X){return new Y({type:"string",format:"email",check:"string_format",abort:!1,...v(X)})}function O9(Y,X){return new Y({type:"string",format:"guid",check:"string_format",abort:!1,...v(X)})}function t7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...v(X)})}function e7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...v(X)})}function YG(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...v(X)})}function XG(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...v(X)})}function JG(Y,X){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...v(X)})}function QG(Y,X){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...v(X)})}function GG(Y,X){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...v(X)})}function $G(Y,X){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...v(X)})}function WG(Y,X){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...v(X)})}function zG(Y,X){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...v(X)})}function UG(Y,X){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...v(X)})}function HG(Y,X){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...v(X)})}function LG(Y,X){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...v(X)})}function VG(Y,X){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...v(X)})}function NG(Y,X){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...v(X)})}function BG(Y,X){return new Y({type:"string",format:"cidrv6",check:"string_format",abort:!1,...v(X)})}function ZG(Y,X){return new Y({type:"string",format:"base64",check:"string_format",abort:!1,...v(X)})}function KG(Y,X){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...v(X)})}function OG(Y,X){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...v(X)})}function qG(Y,X){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...v(X)})}function FG(Y,X){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...v(X)})}function jG(Y,X){return new Y({type:"string",format:"date",check:"string_format",...v(X)})}function DG(Y,X){return new Y({type:"string",format:"time",check:"string_format",precision:null,...v(X)})}function PG(Y,X){return new Y({type:"string",format:"duration",check:"string_format",...v(X)})}function MG(Y,X){return new Y({type:"number",checks:[],...v(X)})}function wG(Y,X){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...v(X)})}function EG(Y,X){return new Y({type:"boolean",...v(X)})}function AG(Y,X){return new Y({type:"null",...v(X)})}function TG(Y){return new Y({type:"unknown"})}function RG(Y,X){return new Y({type:"never",...v(X)})}function oY(Y,X){return new L9({check:"less_than",...v(X),value:Y,inclusive:!1})}function UY(Y,X){return new L9({check:"less_than",...v(X),value:Y,inclusive:!0})}function rY(Y,X){return new V9({check:"greater_than",...v(X),value:Y,inclusive:!1})}function HY(Y,X){return new V9({check:"greater_than",...v(X),value:Y,inclusive:!0})}function sY(Y,X){return new bQ({check:"multiple_of",...v(X),value:Y})}function aY(Y,X){return new vQ({check:"max_length",...v(X),maximum:Y})}function l1(Y,X){return new hQ({check:"min_length",...v(X),minimum:Y})}function tY(Y,X){return new gQ({check:"length_equals",...v(X),length:Y})}function q9(Y,X){return new yQ({check:"string_format",format:"regex",...v(X),pattern:Y})}function F9(Y){return new fQ({check:"string_format",format:"lowercase",...v(Y)})}function j9(Y){return new mQ({check:"string_format",format:"uppercase",...v(Y)})}function D9(Y,X){return new cQ({check:"string_format",format:"includes",...v(X),includes:Y})}function P9(Y,X){return new uQ({check:"string_format",format:"starts_with",...v(X),prefix:Y})}function M9(Y,X){return new pQ({check:"string_format",format:"ends_with",...v(X),suffix:Y})}function R1(Y){return new lQ({check:"overwrite",tx:Y})}function w9(Y){return R1((X)=>X.normalize(Y))}function E9(){return R1((Y)=>Y.trim())}function A9(){return R1((Y)=>Y.toLowerCase())}function T9(){return R1((Y)=>Y.toUpperCase())}function CG(Y,X,J){return new Y({type:"array",element:X,...v(J)})}function _G(Y,X,J){let Q=v(J);return Q.abort??(Q.abort=!0),new Y({type:"custom",check:"custom",fn:X,...Q})}function IG(Y,X,J){return new Y({type:"custom",check:"custom",fn:X,...v(J)})}function SG(Y){let X=HU((J)=>{return J.addIssue=(Q)=>{if(typeof Q==="string")J.issues.push(p1(Q,J.value,X._zod.def));else{let G=Q;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=J.value),G.inst??(G.inst=X),G.continue??(G.continue=!X._zod.def.abort),J.issues.push(p1(G))}},Y(J.value,J)});return X}function HU(Y,X){let J=new B0({check:"custom",...v(X)});return J._zod.check=Y,J}class R9{constructor(Y){this.counter=0,this.metadataRegistry=Y?.metadata??T1,this.target=Y?.target??"draft-2020-12",this.unrepresentable=Y?.unrepresentable??"throw",this.override=Y?.override??(()=>{}),this.io=Y?.io??"output",this.seen=new Map}process(Y,X={path:[],schemaPath:[]}){var J;let Q=Y._zod.def,G={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},$=this.seen.get(Y);if($){if($.count++,X.schemaPath.includes(Y))$.cycle=X.path;return $.schema}let W={schema:{},count:1,cycle:void 0,path:X.path};this.seen.set(Y,W);let U=Y._zod.toJSONSchema?.();if(U)W.schema=U;else{let N={...X,schemaPath:[...X.schemaPath,Y],path:X.path},O=Y._zod.parent;if(O)W.ref=O,this.process(O,N),this.seen.get(O).isParent=!0;else{let Z=W.schema;switch(Q.type){case"string":{let V=Z;V.type="string";let{minimum:K,maximum:j,format:M,patterns:I,contentEncoding:E}=Y._zod.bag;if(typeof K==="number")V.minLength=K;if(typeof j==="number")V.maxLength=j;if(M){if(V.format=G[M]??M,V.format==="")delete V.format}if(E)V.contentEncoding=E;if(I&&I.size>0){let b=[...I];if(b.length===1)V.pattern=b[0].source;else if(b.length>1)W.schema.allOf=[...b.map((f)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))]}break}case"number":{let V=Z,{minimum:K,maximum:j,format:M,multipleOf:I,exclusiveMaximum:E,exclusiveMinimum:b}=Y._zod.bag;if(typeof M==="string"&&M.includes("int"))V.type="integer";else V.type="number";if(typeof b==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")V.minimum=b,V.exclusiveMinimum=!0;else V.exclusiveMinimum=b;if(typeof K==="number"){if(V.minimum=K,typeof b==="number"&&this.target!=="draft-4")if(b>=K)delete V.minimum;else delete V.exclusiveMinimum}if(typeof E==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")V.maximum=E,V.exclusiveMaximum=!0;else V.exclusiveMaximum=E;if(typeof j==="number"){if(V.maximum=j,typeof E==="number"&&this.target!=="draft-4")if(E<=j)delete V.maximum;else delete V.exclusiveMaximum}if(typeof I==="number")V.multipleOf=I;break}case"boolean":{let V=Z;V.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema");break}case"null":{if(this.target==="openapi-3.0")Z.type="string",Z.nullable=!0,Z.enum=[null];else Z.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema");break}case"never":{Z.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let V=Z,{minimum:K,maximum:j}=Y._zod.bag;if(typeof K==="number")V.minItems=K;if(typeof j==="number")V.maxItems=j;V.type="array",V.items=this.process(Q.element,{...N,path:[...N.path,"items"]});break}case"object":{let V=Z;V.type="object",V.properties={};let K=Q.shape;for(let I in K)V.properties[I]=this.process(K[I],{...N,path:[...N.path,"properties",I]});let j=new Set(Object.keys(K)),M=new Set([...j].filter((I)=>{let E=Q.shape[I]._zod;if(this.io==="input")return E.optin===void 0;else return E.optout===void 0}));if(M.size>0)V.required=Array.from(M);if(Q.catchall?._zod.def.type==="never")V.additionalProperties=!1;else if(!Q.catchall){if(this.io==="output")V.additionalProperties=!1}else if(Q.catchall)V.additionalProperties=this.process(Q.catchall,{...N,path:[...N.path,"additionalProperties"]});break}case"union":{let V=Z,K=Q.options.map((j,M)=>this.process(j,{...N,path:[...N.path,"anyOf",M]}));V.anyOf=K;break}case"intersection":{let V=Z,K=this.process(Q.left,{...N,path:[...N.path,"allOf",0]}),j=this.process(Q.right,{...N,path:[...N.path,"allOf",1]}),M=(E)=>("allOf"in E)&&Object.keys(E).length===1,I=[...M(K)?K.allOf:[K],...M(j)?j.allOf:[j]];V.allOf=I;break}case"tuple":{let V=Z;V.type="array";let K=this.target==="draft-2020-12"?"prefixItems":"items",j=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",M=Q.items.map((f,l)=>this.process(f,{...N,path:[...N.path,K,l]})),I=Q.rest?this.process(Q.rest,{...N,path:[...N.path,j,...this.target==="openapi-3.0"?[Q.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(V.prefixItems=M,I)V.items=I}else if(this.target==="openapi-3.0"){if(V.items={anyOf:M},I)V.items.anyOf.push(I);if(V.minItems=M.length,!I)V.maxItems=M.length}else if(V.items=M,I)V.additionalItems=I;let{minimum:E,maximum:b}=Y._zod.bag;if(typeof E==="number")V.minItems=E;if(typeof b==="number")V.maxItems=b;break}case"record":{let V=Z;if(V.type="object",this.target==="draft-7"||this.target==="draft-2020-12")V.propertyNames=this.process(Q.keyType,{...N,path:[...N.path,"propertyNames"]});V.additionalProperties=this.process(Q.valueType,{...N,path:[...N.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let V=Z,K=XY(Q.entries);if(K.every((j)=>typeof j==="number"))V.type="number";if(K.every((j)=>typeof j==="string"))V.type="string";V.enum=K;break}case"literal":{let V=Z,K=[];for(let j of Q.values)if(j===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof j==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else K.push(Number(j));else K.push(j);if(K.length===0);else if(K.length===1){let j=K[0];if(V.type=j===null?"null":typeof j,this.target==="draft-4"||this.target==="openapi-3.0")V.enum=[j];else V.const=j}else{if(K.every((j)=>typeof j==="number"))V.type="number";if(K.every((j)=>typeof j==="string"))V.type="string";if(K.every((j)=>typeof j==="boolean"))V.type="string";if(K.every((j)=>j===null))V.type="null";V.enum=K}break}case"file":{let V=Z,K={type:"string",format:"binary",contentEncoding:"binary"},{minimum:j,maximum:M,mime:I}=Y._zod.bag;if(j!==void 0)K.minLength=j;if(M!==void 0)K.maxLength=M;if(I)if(I.length===1)K.contentMediaType=I[0],Object.assign(V,K);else V.anyOf=I.map((E)=>{return{...K,contentMediaType:E}});else Object.assign(V,K);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let V=this.process(Q.innerType,N);if(this.target==="openapi-3.0")W.ref=Q.innerType,Z.nullable=!0;else Z.anyOf=[V,{type:"null"}];break}case"nonoptional":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"success":{let V=Z;V.type="boolean";break}case"default":{this.process(Q.innerType,N),W.ref=Q.innerType,Z.default=JSON.parse(JSON.stringify(Q.defaultValue));break}case"prefault":{if(this.process(Q.innerType,N),W.ref=Q.innerType,this.io==="input")Z._prefault=JSON.parse(JSON.stringify(Q.defaultValue));break}case"catch":{this.process(Q.innerType,N),W.ref=Q.innerType;let V;try{V=Q.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}Z.default=V;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let V=Z,K=Y._zod.pattern;if(!K)throw Error("Pattern not found in template literal");V.type="string",V.pattern=K.source;break}case"pipe":{let V=this.io==="input"?Q.in._zod.def.type==="transform"?Q.out:Q.in:Q.out;this.process(V,N),W.ref=V;break}case"readonly":{this.process(Q.innerType,N),W.ref=Q.innerType,Z.readOnly=!0;break}case"promise":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"optional":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"lazy":{let V=Y._zod.innerType;this.process(V,N),W.ref=V;break}case"custom":{if(this.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema");break}case"function":{if(this.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema");break}default:}}}let H=this.metadataRegistry.get(Y);if(H)Object.assign(W.schema,H);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 G=(L)=>{let N=this.target==="draft-2020-12"?"$defs":"definitions";if(J.external){let K=J.external.registry.get(L[0])?.id,j=J.external.uri??((I)=>I);if(K)return{ref:j(K)};let M=L[1].defId??L[1].schema.id??`schema${this.counter++}`;return L[1].defId=M,{defId:M,ref:`${j("__shared")}#/${N}/${M}`}}if(L[1]===Q)return{ref:"#"};let Z=`${"#"}/${N}/`,V=L[1].schema.id??`__schema${this.counter++}`;return{defId:V,ref:Z+V}},$=(L)=>{if(L[1].schema.$ref)return;let N=L[1],{ref:O,defId:Z}=G(L);if(N.def={...N.schema},Z)N.defId=Z;let V=N.schema;for(let K in V)delete V[K];V.$ref=O};if(J.cycles==="throw")for(let L of this.seen.entries()){let N=L[1];if(N.cycle)throw Error(`Cycle detected: #/${N.cycle?.join("/")}/<root>
185
+ `)}V.write("payload.value = newResult;"),V.write("return payload;");let E=V.compile();return(b,f)=>E(Z,b,f)},$,W=A1,z=!gY.jitless,H=z&&Q9.value,N=X.catchall,O;Y._zod.parse=(Z,V)=>{O??(O=Q.value);let K=Z.value;if(!W(K))return Z.issues.push({expected:"object",code:"invalid_type",input:K,inst:Y}),Z;if(z&&H&&V?.async===!1&&V.jitless!==!0){if(!$)$=G(X.shape);if(Z=$(Z,V),!N)return Z;return v7([],K,Z,V,O,Y)}return J(Z,V)}});function aQ(Y,X,J,Q){for(let $ of Y)if($.issues.length===0)return X.value=$.value,X;let G=Y.filter(($)=>!B1($));if(G.length===1)return X.value=G[0].value,G[0];return X.issues.push({code:"invalid_union",input:X.value,inst:J,errors:Y.map(($)=>$.issues.map((W)=>x0(W,Q,l0())))}),X}var K9=F("$ZodUnion",(Y,X)=>{o.init(Y,X),p(Y._zod,"optin",()=>X.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),p(Y._zod,"optout",()=>X.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),p(Y._zod,"values",()=>{if(X.options.every((G)=>G._zod.values))return new Set(X.options.flatMap((G)=>Array.from(G._zod.values)));return}),p(Y._zod,"pattern",()=>{if(X.options.every((G)=>G._zod.pattern)){let G=X.options.map(($)=>$._zod.pattern);return new RegExp(`^(${G.map(($)=>QY($.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,z=[];for(let L of X.options){let H=L._zod.run({value:G.value,issues:[]},$);if(H instanceof Promise)z.push(H),W=!0;else{if(H.issues.length===0)return H;z.push(H)}}if(!W)return aQ(z,G,Y,$);return Promise.all(z).then((L)=>{return aQ(L,G,Y,$)})}}),g7=F("$ZodDiscriminatedUnion",(Y,X)=>{K9.init(Y,X);let J=Y._zod.parse;p(Y._zod,"propValues",()=>{let G={};for(let $ of X.options){let W=$._zod.propValues;if(!W||Object.keys(W).length===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf($)}"`);for(let[z,L]of Object.entries(W)){if(!G[z])G[z]=new Set;for(let H of L)G[z].add(H)}}return G});let Q=u1(()=>{let G=X.options,$=new Map;for(let W of G){let z=W._zod.propValues?.[X.discriminator];if(!z||z.size===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf(W)}"`);for(let L of z){if($.has(L))throw Error(`Duplicate discriminator value "${String(L)}"`);$.set(L,W)}}return $});Y._zod.parse=(G,$)=>{let W=G.value;if(!A1(W))return G.issues.push({code:"invalid_type",expected:"object",input:W,inst:Y}),G;let z=Q.value.get(W?.[X.discriminator]);if(z)return z._zod.run(G,$);if(X.unionFallback)return J(G,$);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:X.discriminator,input:W,path:[X.discriminator],inst:Y}),G}}),y7=F("$ZodIntersection",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{let G=J.value,$=X.left._zod.run({value:G,issues:[]},Q),W=X.right._zod.run({value:G,issues:[]},Q);if($ instanceof Promise||W instanceof Promise)return Promise.all([$,W]).then(([L,H])=>{return tQ(J,L,H)});return tQ(J,$,W)}});function B9(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(N1(Y)&&N1(X)){let J=Object.keys(X),Q=Object.keys(Y).filter(($)=>J.indexOf($)!==-1),G={...Y,...X};for(let $ of Q){let W=B9(Y[$],X[$]);if(!W.valid)return{valid:!1,mergeErrorPath:[$,...W.mergeErrorPath]};G[$]=W.data}return{valid:!0,data:G}}if(Array.isArray(Y)&&Array.isArray(X)){if(Y.length!==X.length)return{valid:!1,mergeErrorPath:[]};let J=[];for(let Q=0;Q<Y.length;Q++){let G=Y[Q],$=X[Q],W=B9(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 tQ(Y,X,J){if(X.issues.length)Y.issues.push(...X.issues);if(J.issues.length)Y.issues.push(...J.issues);if(B1(Y))return Y;let Q=B9(X.value,J.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return Y.value=Q.data,Y}var f7=F("$ZodRecord",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{let G=J.value;if(!N1(G))return J.issues.push({expected:"record",code:"invalid_type",input:G,inst:Y}),J;let $=[];if(X.keyType._zod.values){let W=X.keyType._zod.values;J.value={};for(let L of W)if(typeof L==="string"||typeof L==="number"||typeof L==="symbol"){let H=X.valueType._zod.run({value:G[L],issues:[]},Q);if(H instanceof Promise)$.push(H.then((N)=>{if(N.issues.length)J.issues.push(...J1(L,N.issues));J.value[L]=N.value}));else{if(H.issues.length)J.issues.push(...J1(L,H.issues));J.value[L]=H.value}}let z;for(let L in G)if(!W.has(L))z=z??[],z.push(L);if(z&&z.length>0)J.issues.push({code:"unrecognized_keys",input:G,inst:Y,keys:z})}else{J.value={};for(let W of Reflect.ownKeys(G)){if(W==="__proto__")continue;let z=X.keyType._zod.run({value:W,issues:[]},Q);if(z instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(z.issues.length){J.issues.push({code:"invalid_key",origin:"record",issues:z.issues.map((H)=>x0(H,Q,l0())),input:W,path:[W],inst:Y}),J.value[z.value]=z.value;continue}let L=X.valueType._zod.run({value:G[W],issues:[]},Q);if(L instanceof Promise)$.push(L.then((H)=>{if(H.issues.length)J.issues.push(...J1(W,H.issues));J.value[z.value]=H.value}));else{if(L.issues.length)J.issues.push(...J1(W,L.issues));J.value[z.value]=L.value}}}if($.length)return Promise.all($).then(()=>J);return J}});var m7=F("$ZodEnum",(Y,X)=>{o.init(Y,X);let J=XY(X.entries),Q=new Set(J);Y._zod.values=Q,Y._zod.pattern=new RegExp(`^(${J.filter((G)=>G9.has(typeof G)).map((G)=>typeof G==="string"?X1(G):G.toString()).join("|")})$`),Y._zod.parse=(G,$)=>{let W=G.value;if(Q.has(W))return G;return G.issues.push({code:"invalid_value",values:J,input:W,inst:Y}),G}}),c7=F("$ZodLiteral",(Y,X)=>{if(o.init(Y,X),X.values.length===0)throw Error("Cannot create literal schema with no valid values");Y._zod.values=new Set(X.values),Y._zod.pattern=new RegExp(`^(${X.values.map((J)=>typeof J==="string"?X1(J):J?X1(J.toString()):String(J)).join("|")})$`),Y._zod.parse=(J,Q)=>{let G=J.value;if(Y._zod.values.has(G))return J;return J.issues.push({code:"invalid_value",values:X.values,input:G,inst:Y}),J}});var u7=F("$ZodTransform",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new e1(Y.constructor.name);let G=X.transform(J.value,J);if(Q.async)return(G instanceof Promise?G:Promise.resolve(G)).then((W)=>{return J.value=W,J});if(G instanceof Promise)throw new Y1;return J.value=G,J}});function eQ(Y,X){if(Y.issues.length&&X===void 0)return{issues:[],value:void 0};return Y}var p7=F("$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(`^(${QY(J.source)})?$`):void 0}),Y._zod.parse=(J,Q)=>{if(X.innerType._zod.optin==="optional"){let G=X.innerType._zod.run(J,Q);if(G instanceof Promise)return G.then(($)=>eQ($,J.value));return eQ(G,J.value)}if(J.value===void 0)return J;return X.innerType._zod.run(J,Q)}}),l7=F("$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(`^(${QY(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)}}),d7=F("$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 G=X.innerType._zod.run(J,Q);if(G instanceof Promise)return G.then(($)=>Y7($,X));return Y7(G,X)}});function Y7(Y,X){if(Y.value===void 0)Y.value=X.defaultValue;return Y}var i7=F("$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)}}),n7=F("$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 G=X.innerType._zod.run(J,Q);if(G instanceof Promise)return G.then(($)=>X7($,Y));return X7(G,Y)}});function X7(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 o7=F("$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 G=X.innerType._zod.run(J,Q);if(G instanceof Promise)return G.then(($)=>{if(J.value=$.value,$.issues.length)J.value=X.catchValue({...J,error:{issues:$.issues.map((W)=>x0(W,Q,l0()))},input:J.value}),J.issues=[];return J});if(J.value=G.value,G.issues.length)J.value=X.catchValue({...J,error:{issues:G.issues.map(($)=>x0($,Q,l0()))},input:J.value}),J.issues=[];return J}});var r7=F("$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 $=X.out._zod.run(J,Q);if($ instanceof Promise)return $.then((W)=>lY(W,X.in,Q));return lY($,X.in,Q)}let G=X.in._zod.run(J,Q);if(G instanceof Promise)return G.then(($)=>lY($,X.out,Q));return lY(G,X.out,Q)}});function lY(Y,X,J){if(Y.issues.length)return Y.aborted=!0,Y;return X._zod.run({value:Y.value,issues:Y.issues},J)}var s7=F("$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 G=X.innerType._zod.run(J,Q);if(G instanceof Promise)return G.then(J7);return J7(G)}});function J7(Y){return Y.value=Object.freeze(Y.value),Y}var a7=F("$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)}}),t7=F("$ZodCustom",(Y,X)=>{B0.init(Y,X),o.init(Y,X),Y._zod.parse=(J,Q)=>{return J},Y._zod.check=(J)=>{let Q=J.value,G=X.fn(Q);if(G instanceof Promise)return G.then(($)=>Q7($,J,Q,Y));Q7(G,J,Q,Y);return}});function Q7(Y,X,J,Q){if(!Y){let G={code:"custom",input:J,inst:Q,path:[...Q._zod.def.path??[]],continue:!Q._zod.def.abort};if(Q._zod.def.params)G.params=Q._zod.def.params;X.issues.push(p1(G))}}var sK=Symbol("ZodOutput"),aK=Symbol("ZodInput");class nY{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 BU(){return new nY}var T1=BU();function e7(Y,X){return new Y({type:"string",...v(X)})}function YG(Y,X){return new Y({type:"string",format:"email",check:"string_format",abort:!1,...v(X)})}function O9(Y,X){return new Y({type:"string",format:"guid",check:"string_format",abort:!1,...v(X)})}function XG(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...v(X)})}function JG(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...v(X)})}function QG(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...v(X)})}function GG(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...v(X)})}function $G(Y,X){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...v(X)})}function WG(Y,X){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...v(X)})}function zG(Y,X){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...v(X)})}function UG(Y,X){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...v(X)})}function HG(Y,X){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...v(X)})}function LG(Y,X){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...v(X)})}function VG(Y,X){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...v(X)})}function NG(Y,X){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...v(X)})}function BG(Y,X){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...v(X)})}function ZG(Y,X){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...v(X)})}function KG(Y,X){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...v(X)})}function OG(Y,X){return new Y({type:"string",format:"cidrv6",check:"string_format",abort:!1,...v(X)})}function qG(Y,X){return new Y({type:"string",format:"base64",check:"string_format",abort:!1,...v(X)})}function FG(Y,X){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...v(X)})}function jG(Y,X){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...v(X)})}function DG(Y,X){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...v(X)})}function PG(Y,X){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...v(X)})}function MG(Y,X){return new Y({type:"string",format:"date",check:"string_format",...v(X)})}function wG(Y,X){return new Y({type:"string",format:"time",check:"string_format",precision:null,...v(X)})}function EG(Y,X){return new Y({type:"string",format:"duration",check:"string_format",...v(X)})}function AG(Y,X){return new Y({type:"number",checks:[],...v(X)})}function TG(Y,X){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...v(X)})}function RG(Y,X){return new Y({type:"boolean",...v(X)})}function CG(Y,X){return new Y({type:"null",...v(X)})}function _G(Y){return new Y({type:"unknown"})}function IG(Y,X){return new Y({type:"never",...v(X)})}function oY(Y,X){return new L9({check:"less_than",...v(X),value:Y,inclusive:!1})}function UY(Y,X){return new L9({check:"less_than",...v(X),value:Y,inclusive:!0})}function rY(Y,X){return new V9({check:"greater_than",...v(X),value:Y,inclusive:!1})}function HY(Y,X){return new V9({check:"greater_than",...v(X),value:Y,inclusive:!0})}function sY(Y,X){return new hQ({check:"multiple_of",...v(X),value:Y})}function aY(Y,X){return new yQ({check:"max_length",...v(X),maximum:Y})}function l1(Y,X){return new fQ({check:"min_length",...v(X),minimum:Y})}function tY(Y,X){return new mQ({check:"length_equals",...v(X),length:Y})}function q9(Y,X){return new cQ({check:"string_format",format:"regex",...v(X),pattern:Y})}function F9(Y){return new uQ({check:"string_format",format:"lowercase",...v(Y)})}function j9(Y){return new pQ({check:"string_format",format:"uppercase",...v(Y)})}function D9(Y,X){return new lQ({check:"string_format",format:"includes",...v(X),includes:Y})}function P9(Y,X){return new dQ({check:"string_format",format:"starts_with",...v(X),prefix:Y})}function M9(Y,X){return new iQ({check:"string_format",format:"ends_with",...v(X),suffix:Y})}function R1(Y){return new nQ({check:"overwrite",tx:Y})}function w9(Y){return R1((X)=>X.normalize(Y))}function E9(){return R1((Y)=>Y.trim())}function A9(){return R1((Y)=>Y.toLowerCase())}function T9(){return R1((Y)=>Y.toUpperCase())}function SG(Y,X,J){return new Y({type:"array",element:X,...v(J)})}function kG(Y,X,J){let Q=v(J);return Q.abort??(Q.abort=!0),new Y({type:"custom",check:"custom",fn:X,...Q})}function bG(Y,X,J){return new Y({type:"custom",check:"custom",fn:X,...v(J)})}function xG(Y){let X=ZU((J)=>{return J.addIssue=(Q)=>{if(typeof Q==="string")J.issues.push(p1(Q,J.value,X._zod.def));else{let G=Q;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=J.value),G.inst??(G.inst=X),G.continue??(G.continue=!X._zod.def.abort),J.issues.push(p1(G))}},Y(J.value,J)});return X}function ZU(Y,X){let J=new B0({check:"custom",...v(X)});return J._zod.check=Y,J}class R9{constructor(Y){this.counter=0,this.metadataRegistry=Y?.metadata??T1,this.target=Y?.target??"draft-2020-12",this.unrepresentable=Y?.unrepresentable??"throw",this.override=Y?.override??(()=>{}),this.io=Y?.io??"output",this.seen=new Map}process(Y,X={path:[],schemaPath:[]}){var J;let Q=Y._zod.def,G={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},$=this.seen.get(Y);if($){if($.count++,X.schemaPath.includes(Y))$.cycle=X.path;return $.schema}let W={schema:{},count:1,cycle:void 0,path:X.path};this.seen.set(Y,W);let z=Y._zod.toJSONSchema?.();if(z)W.schema=z;else{let N={...X,schemaPath:[...X.schemaPath,Y],path:X.path},O=Y._zod.parent;if(O)W.ref=O,this.process(O,N),this.seen.get(O).isParent=!0;else{let Z=W.schema;switch(Q.type){case"string":{let V=Z;V.type="string";let{minimum:K,maximum:j,format:M,patterns:I,contentEncoding:E}=Y._zod.bag;if(typeof K==="number")V.minLength=K;if(typeof j==="number")V.maxLength=j;if(M){if(V.format=G[M]??M,V.format==="")delete V.format}if(E)V.contentEncoding=E;if(I&&I.size>0){let b=[...I];if(b.length===1)V.pattern=b[0].source;else if(b.length>1)W.schema.allOf=[...b.map((f)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))]}break}case"number":{let V=Z,{minimum:K,maximum:j,format:M,multipleOf:I,exclusiveMaximum:E,exclusiveMinimum:b}=Y._zod.bag;if(typeof M==="string"&&M.includes("int"))V.type="integer";else V.type="number";if(typeof b==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")V.minimum=b,V.exclusiveMinimum=!0;else V.exclusiveMinimum=b;if(typeof K==="number"){if(V.minimum=K,typeof b==="number"&&this.target!=="draft-4")if(b>=K)delete V.minimum;else delete V.exclusiveMinimum}if(typeof E==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")V.maximum=E,V.exclusiveMaximum=!0;else V.exclusiveMaximum=E;if(typeof j==="number"){if(V.maximum=j,typeof E==="number"&&this.target!=="draft-4")if(E<=j)delete V.maximum;else delete V.exclusiveMaximum}if(typeof I==="number")V.multipleOf=I;break}case"boolean":{let V=Z;V.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema");break}case"null":{if(this.target==="openapi-3.0")Z.type="string",Z.nullable=!0,Z.enum=[null];else Z.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema");break}case"never":{Z.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let V=Z,{minimum:K,maximum:j}=Y._zod.bag;if(typeof K==="number")V.minItems=K;if(typeof j==="number")V.maxItems=j;V.type="array",V.items=this.process(Q.element,{...N,path:[...N.path,"items"]});break}case"object":{let V=Z;V.type="object",V.properties={};let K=Q.shape;for(let I in K)V.properties[I]=this.process(K[I],{...N,path:[...N.path,"properties",I]});let j=new Set(Object.keys(K)),M=new Set([...j].filter((I)=>{let E=Q.shape[I]._zod;if(this.io==="input")return E.optin===void 0;else return E.optout===void 0}));if(M.size>0)V.required=Array.from(M);if(Q.catchall?._zod.def.type==="never")V.additionalProperties=!1;else if(!Q.catchall){if(this.io==="output")V.additionalProperties=!1}else if(Q.catchall)V.additionalProperties=this.process(Q.catchall,{...N,path:[...N.path,"additionalProperties"]});break}case"union":{let V=Z,K=Q.options.map((j,M)=>this.process(j,{...N,path:[...N.path,"anyOf",M]}));V.anyOf=K;break}case"intersection":{let V=Z,K=this.process(Q.left,{...N,path:[...N.path,"allOf",0]}),j=this.process(Q.right,{...N,path:[...N.path,"allOf",1]}),M=(E)=>("allOf"in E)&&Object.keys(E).length===1,I=[...M(K)?K.allOf:[K],...M(j)?j.allOf:[j]];V.allOf=I;break}case"tuple":{let V=Z;V.type="array";let K=this.target==="draft-2020-12"?"prefixItems":"items",j=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",M=Q.items.map((f,l)=>this.process(f,{...N,path:[...N.path,K,l]})),I=Q.rest?this.process(Q.rest,{...N,path:[...N.path,j,...this.target==="openapi-3.0"?[Q.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(V.prefixItems=M,I)V.items=I}else if(this.target==="openapi-3.0"){if(V.items={anyOf:M},I)V.items.anyOf.push(I);if(V.minItems=M.length,!I)V.maxItems=M.length}else if(V.items=M,I)V.additionalItems=I;let{minimum:E,maximum:b}=Y._zod.bag;if(typeof E==="number")V.minItems=E;if(typeof b==="number")V.maxItems=b;break}case"record":{let V=Z;if(V.type="object",this.target==="draft-7"||this.target==="draft-2020-12")V.propertyNames=this.process(Q.keyType,{...N,path:[...N.path,"propertyNames"]});V.additionalProperties=this.process(Q.valueType,{...N,path:[...N.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let V=Z,K=XY(Q.entries);if(K.every((j)=>typeof j==="number"))V.type="number";if(K.every((j)=>typeof j==="string"))V.type="string";V.enum=K;break}case"literal":{let V=Z,K=[];for(let j of Q.values)if(j===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof j==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else K.push(Number(j));else K.push(j);if(K.length===0);else if(K.length===1){let j=K[0];if(V.type=j===null?"null":typeof j,this.target==="draft-4"||this.target==="openapi-3.0")V.enum=[j];else V.const=j}else{if(K.every((j)=>typeof j==="number"))V.type="number";if(K.every((j)=>typeof j==="string"))V.type="string";if(K.every((j)=>typeof j==="boolean"))V.type="string";if(K.every((j)=>j===null))V.type="null";V.enum=K}break}case"file":{let V=Z,K={type:"string",format:"binary",contentEncoding:"binary"},{minimum:j,maximum:M,mime:I}=Y._zod.bag;if(j!==void 0)K.minLength=j;if(M!==void 0)K.maxLength=M;if(I)if(I.length===1)K.contentMediaType=I[0],Object.assign(V,K);else V.anyOf=I.map((E)=>{return{...K,contentMediaType:E}});else Object.assign(V,K);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let V=this.process(Q.innerType,N);if(this.target==="openapi-3.0")W.ref=Q.innerType,Z.nullable=!0;else Z.anyOf=[V,{type:"null"}];break}case"nonoptional":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"success":{let V=Z;V.type="boolean";break}case"default":{this.process(Q.innerType,N),W.ref=Q.innerType,Z.default=JSON.parse(JSON.stringify(Q.defaultValue));break}case"prefault":{if(this.process(Q.innerType,N),W.ref=Q.innerType,this.io==="input")Z._prefault=JSON.parse(JSON.stringify(Q.defaultValue));break}case"catch":{this.process(Q.innerType,N),W.ref=Q.innerType;let V;try{V=Q.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}Z.default=V;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let V=Z,K=Y._zod.pattern;if(!K)throw Error("Pattern not found in template literal");V.type="string",V.pattern=K.source;break}case"pipe":{let V=this.io==="input"?Q.in._zod.def.type==="transform"?Q.out:Q.in:Q.out;this.process(V,N),W.ref=V;break}case"readonly":{this.process(Q.innerType,N),W.ref=Q.innerType,Z.readOnly=!0;break}case"promise":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"optional":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"lazy":{let V=Y._zod.innerType;this.process(V,N),W.ref=V;break}case"custom":{if(this.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema");break}case"function":{if(this.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema");break}default:}}}let L=this.metadataRegistry.get(Y);if(L)Object.assign(W.schema,L);if(this.io==="input"&&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 G=(H)=>{let N=this.target==="draft-2020-12"?"$defs":"definitions";if(J.external){let K=J.external.registry.get(H[0])?.id,j=J.external.uri??((I)=>I);if(K)return{ref:j(K)};let M=H[1].defId??H[1].schema.id??`schema${this.counter++}`;return H[1].defId=M,{defId:M,ref:`${j("__shared")}#/${N}/${M}`}}if(H[1]===Q)return{ref:"#"};let Z=`${"#"}/${N}/`,V=H[1].schema.id??`__schema${this.counter++}`;return{defId:V,ref:Z+V}},$=(H)=>{if(H[1].schema.$ref)return;let N=H[1],{ref:O,defId:Z}=G(H);if(N.def={...N.schema},Z)N.defId=Z;let V=N.schema;for(let K in V)delete V[K];V.$ref=O};if(J.cycles==="throw")for(let H of this.seen.entries()){let N=H[1];if(N.cycle)throw Error(`Cycle detected: #/${N.cycle?.join("/")}/<root>
186
186
 
187
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let L of this.seen.entries()){let N=L[1];if(Y===L[0]){$(L);continue}if(J.external){let Z=J.external.registry.get(L[0])?.id;if(Y!==L[0]&&Z){$(L);continue}}if(this.metadataRegistry.get(L[0])?.id){$(L);continue}if(N.cycle){$(L);continue}if(N.count>1){if(J.reused==="ref"){$(L);continue}}}let W=(L,N)=>{let O=this.seen.get(L),Z=O.def??O.schema,V={...Z};if(O.ref===null)return;let K=O.ref;if(O.ref=null,K){W(K,N);let j=this.seen.get(K).schema;if(j.$ref&&(N.target==="draft-7"||N.target==="draft-4"||N.target==="openapi-3.0"))Z.allOf=Z.allOf??[],Z.allOf.push(j);else Object.assign(Z,j),Object.assign(Z,V)}if(!O.isParent)this.override({zodSchema:L,jsonSchema:Z,path:O.path??[]})};for(let L of[...this.seen.entries()].reverse())W(L[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 L=J.external.registry.get(Y)?.id;if(!L)throw Error("Schema is missing an `id` property");U.$id=J.external.uri(L)}Object.assign(U,Q.def);let H=J.external?.defs??{};for(let L of this.seen.entries()){let N=L[1];if(N.def&&N.defId)H[N.defId]=N.def}if(J.external);else if(Object.keys(H).length>0)if(this.target==="draft-2020-12")U.$defs=H;else U.definitions=H;try{return JSON.parse(JSON.stringify(U))}catch(L){throw Error("Error converting schema to JSON.")}}}function kG(Y,X){if(Y instanceof nY){let Q=new R9(X),G={};for(let U of Y._idmap.entries()){let[H,L]=U;Q.process(L)}let $={},W={registry:Y,uri:X?.uri,defs:G};for(let U of Y._idmap.entries()){let[H,L]=U;$[H]=Q.emit(L,{...X,external:W})}if(Object.keys(G).length>0){let U=Q.target==="draft-2020-12"?"$defs":"definitions";$.__shared={[U]:G}}return{schemas:$}}let J=new R9(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 G=Y._zod.def;switch(G.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return U0(G.element,J);case"object":{for(let $ in G.shape)if(U0(G.shape[$],J))return!0;return!1}case"union":{for(let $ of G.options)if(U0($,J))return!0;return!1}case"intersection":return U0(G.left,J)||U0(G.right,J);case"tuple":{for(let $ of G.items)if(U0($,J))return!0;if(G.rest&&U0(G.rest,J))return!0;return!1}case"record":return U0(G.keyType,J)||U0(G.valueType,J);case"map":return U0(G.keyType,J)||U0(G.valueType,J);case"set":return U0(G.valueType,J);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return U0(G.innerType,J);case"lazy":return U0(G.getter(),J);case"default":return U0(G.innerType,J);case"prefault":return U0(G.innerType,J);case"custom":return!1;case"transform":return!0;case"pipe":return U0(G.in,J)||U0(G.out,J);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${G.type}`)}var KU=F("ZodISODateTime",(Y,X)=>{N7.init(Y,X),a.init(Y,X)});function bG(Y){return FG(KU,Y)}var OU=F("ZodISODate",(Y,X)=>{B7.init(Y,X),a.init(Y,X)});function xG(Y){return jG(OU,Y)}var qU=F("ZodISOTime",(Y,X)=>{Z7.init(Y,X),a.init(Y,X)});function vG(Y){return DG(qU,Y)}var FU=F("ZodISODuration",(Y,X)=>{K7.init(Y,X),a.init(Y,X)});function hG(Y){return PG(FU,Y)}var gG=(Y,X)=>{mY.init(Y,X),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(J)=>i6(Y,J)},flatten:{value:(J)=>d6(Y,J)},addIssue:{value:(J)=>{Y.issues.push(J),Y.message=JSON.stringify(Y.issues,c1,2)}},addIssues:{value:(J)=>{Y.issues.push(...J),Y.message=JSON.stringify(Y.issues,c1,2)}},isEmpty:{get(){return Y.issues.length===0}}})},M4=F("ZodError",gG),R0=F("ZodError",gG,{Parent:Error});var yG=cY(R0),fG=uY(R0),mG=$Y(R0),Y8=WY(R0),cG=r6(R0),uG=s6(R0),pG=a6(R0),lG=t6(R0),dG=e6(R0),iG=YQ(R0),nG=XQ(R0),oG=JQ(R0);var t=F("ZodType",(Y,X)=>{return o.init(Y,X),Y.def=X,Y.type=X.type,Object.defineProperty(Y,"_def",{value:X}),Y.check=(...J)=>{return Y.clone({...X,checks:[...X.checks??[],...J.map((Q)=>typeof Q==="function"?{_zod:{check:Q,def:{check:"custom"},onattach:[]}}:Q)]})},Y.clone=(J,Q)=>b0(Y,J,Q),Y.brand=()=>Y,Y.register=(J,Q)=>{return J.add(Y,Q),Y},Y.parse=(J,Q)=>yG(Y,J,Q,{callee:Y.parse}),Y.safeParse=(J,Q)=>mG(Y,J,Q),Y.parseAsync=async(J,Q)=>fG(Y,J,Q,{callee:Y.parseAsync}),Y.safeParseAsync=async(J,Q)=>Y8(Y,J,Q),Y.spa=Y.safeParseAsync,Y.encode=(J,Q)=>cG(Y,J,Q),Y.decode=(J,Q)=>uG(Y,J,Q),Y.encodeAsync=async(J,Q)=>pG(Y,J,Q),Y.decodeAsync=async(J,Q)=>lG(Y,J,Q),Y.safeEncode=(J,Q)=>dG(Y,J,Q),Y.safeDecode=(J,Q)=>iG(Y,J,Q),Y.safeEncodeAsync=async(J,Q)=>nG(Y,J,Q),Y.safeDecodeAsync=async(J,Q)=>oG(Y,J,Q),Y.refine=(J,Q)=>Y.check(VH(J,Q)),Y.superRefine=(J)=>Y.check(NH(J)),Y.overwrite=(J)=>Y.check(R1(J)),Y.optional=()=>aG(Y),Y.nullable=()=>tG(Y),Y.nullish=()=>aG(tG(Y)),Y.nonoptional=(J)=>GH(Y,J),Y.array=()=>I9(Y),Y.or=(J)=>S9([Y,J]),Y.and=(J)=>oU(Y,J),Y.transform=(J)=>eG(Y,tU(J)),Y.default=(J)=>XH(Y,J),Y.prefault=(J)=>QH(Y,J),Y.catch=(J)=>WH(Y,J),Y.pipe=(J)=>eG(Y,J),Y.readonly=()=>HH(Y),Y.describe=(J)=>{let Q=Y.clone();return T1.add(Q,{description:J}),Q},Object.defineProperty(Y,"description",{get(){return T1.get(Y)?.description},configurable:!0}),Y.meta=(...J)=>{if(J.length===0)return T1.get(Y);let Q=Y.clone();return T1.add(Q,J[0]),Q},Y.isOptional=()=>Y.safeParse(void 0).success,Y.isNullable=()=>Y.safeParse(null).success,Y}),Y$=F("_ZodString",(Y,X)=>{iY.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(q9(...Q)),Y.includes=(...Q)=>Y.check(D9(...Q)),Y.startsWith=(...Q)=>Y.check(P9(...Q)),Y.endsWith=(...Q)=>Y.check(M9(...Q)),Y.min=(...Q)=>Y.check(l1(...Q)),Y.max=(...Q)=>Y.check(aY(...Q)),Y.length=(...Q)=>Y.check(tY(...Q)),Y.nonempty=(...Q)=>Y.check(l1(1,...Q)),Y.lowercase=(Q)=>Y.check(F9(Q)),Y.uppercase=(Q)=>Y.check(j9(Q)),Y.trim=()=>Y.check(E9()),Y.normalize=(...Q)=>Y.check(w9(...Q)),Y.toLowerCase=()=>Y.check(A9()),Y.toUpperCase=()=>Y.check(T9())}),MU=F("ZodString",(Y,X)=>{iY.init(Y,X),Y$.init(Y,X),Y.email=(J)=>Y.check(a7(wU,J)),Y.url=(J)=>Y.check(JG(EU,J)),Y.jwt=(J)=>Y.check(qG(fU,J)),Y.emoji=(J)=>Y.check(QG(AU,J)),Y.guid=(J)=>Y.check(O9(rG,J)),Y.uuid=(J)=>Y.check(t7(X8,J)),Y.uuidv4=(J)=>Y.check(e7(X8,J)),Y.uuidv6=(J)=>Y.check(YG(X8,J)),Y.uuidv7=(J)=>Y.check(XG(X8,J)),Y.nanoid=(J)=>Y.check(GG(TU,J)),Y.guid=(J)=>Y.check(O9(rG,J)),Y.cuid=(J)=>Y.check($G(RU,J)),Y.cuid2=(J)=>Y.check(WG(CU,J)),Y.ulid=(J)=>Y.check(zG(_U,J)),Y.base64=(J)=>Y.check(ZG(hU,J)),Y.base64url=(J)=>Y.check(KG(gU,J)),Y.xid=(J)=>Y.check(UG(IU,J)),Y.ksuid=(J)=>Y.check(HG(SU,J)),Y.ipv4=(J)=>Y.check(LG(kU,J)),Y.ipv6=(J)=>Y.check(VG(bU,J)),Y.cidrv4=(J)=>Y.check(NG(xU,J)),Y.cidrv6=(J)=>Y.check(BG(vU,J)),Y.e164=(J)=>Y.check(OG(yU,J)),Y.datetime=(J)=>Y.check(bG(J)),Y.date=(J)=>Y.check(xG(J)),Y.time=(J)=>Y.check(vG(J)),Y.duration=(J)=>Y.check(hG(J))});function X$(Y){return s7(MU,Y)}var a=F("ZodStringFormat",(Y,X)=>{s.init(Y,X),Y$.init(Y,X)}),wU=F("ZodEmail",(Y,X)=>{Q7.init(Y,X),a.init(Y,X)});var rG=F("ZodGUID",(Y,X)=>{X7.init(Y,X),a.init(Y,X)});var X8=F("ZodUUID",(Y,X)=>{J7.init(Y,X),a.init(Y,X)});var EU=F("ZodURL",(Y,X)=>{G7.init(Y,X),a.init(Y,X)});var AU=F("ZodEmoji",(Y,X)=>{$7.init(Y,X),a.init(Y,X)});var TU=F("ZodNanoID",(Y,X)=>{W7.init(Y,X),a.init(Y,X)});var RU=F("ZodCUID",(Y,X)=>{z7.init(Y,X),a.init(Y,X)});var CU=F("ZodCUID2",(Y,X)=>{U7.init(Y,X),a.init(Y,X)});var _U=F("ZodULID",(Y,X)=>{H7.init(Y,X),a.init(Y,X)});var IU=F("ZodXID",(Y,X)=>{L7.init(Y,X),a.init(Y,X)});var SU=F("ZodKSUID",(Y,X)=>{V7.init(Y,X),a.init(Y,X)});var kU=F("ZodIPv4",(Y,X)=>{O7.init(Y,X),a.init(Y,X)});var bU=F("ZodIPv6",(Y,X)=>{q7.init(Y,X),a.init(Y,X)});var xU=F("ZodCIDRv4",(Y,X)=>{F7.init(Y,X),a.init(Y,X)});var vU=F("ZodCIDRv6",(Y,X)=>{j7.init(Y,X),a.init(Y,X)});var hU=F("ZodBase64",(Y,X)=>{P7.init(Y,X),a.init(Y,X)});var gU=F("ZodBase64URL",(Y,X)=>{M7.init(Y,X),a.init(Y,X)});var yU=F("ZodE164",(Y,X)=>{w7.init(Y,X),a.init(Y,X)});var fU=F("ZodJWT",(Y,X)=>{E7.init(Y,X),a.init(Y,X)});var J$=F("ZodNumber",(Y,X)=>{Z9.init(Y,X),t.init(Y,X),Y.gt=(Q,G)=>Y.check(rY(Q,G)),Y.gte=(Q,G)=>Y.check(HY(Q,G)),Y.min=(Q,G)=>Y.check(HY(Q,G)),Y.lt=(Q,G)=>Y.check(oY(Q,G)),Y.lte=(Q,G)=>Y.check(UY(Q,G)),Y.max=(Q,G)=>Y.check(UY(Q,G)),Y.int=(Q)=>Y.check(sG(Q)),Y.safe=(Q)=>Y.check(sG(Q)),Y.positive=(Q)=>Y.check(rY(0,Q)),Y.nonnegative=(Q)=>Y.check(HY(0,Q)),Y.negative=(Q)=>Y.check(oY(0,Q)),Y.nonpositive=(Q)=>Y.check(UY(0,Q)),Y.multipleOf=(Q,G)=>Y.check(sY(Q,G)),Y.step=(Q,G)=>Y.check(sY(Q,G)),Y.finite=()=>Y;let J=Y._zod.bag;Y.minValue=Math.max(J.minimum??Number.NEGATIVE_INFINITY,J.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Y.maxValue=Math.min(J.maximum??Number.POSITIVE_INFINITY,J.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Y.isInt=(J.format??"").includes("int")||Number.isSafeInteger(J.multipleOf??0.5),Y.isFinite=!0,Y.format=J.format??null});function Q$(Y){return MG(J$,Y)}var mU=F("ZodNumberFormat",(Y,X)=>{A7.init(Y,X),J$.init(Y,X)});function sG(Y){return wG(mU,Y)}var cU=F("ZodBoolean",(Y,X)=>{T7.init(Y,X),t.init(Y,X)});function G$(Y){return EG(cU,Y)}var uU=F("ZodNull",(Y,X)=>{R7.init(Y,X),t.init(Y,X)});function $$(Y){return AG(uU,Y)}var pU=F("ZodUnknown",(Y,X)=>{C7.init(Y,X),t.init(Y,X)});function LY(){return TG(pU)}var lU=F("ZodNever",(Y,X)=>{_7.init(Y,X),t.init(Y,X)});function _9(Y){return RG(lU,Y)}var dU=F("ZodArray",(Y,X)=>{I7.init(Y,X),t.init(Y,X),Y.element=X.element,Y.min=(J,Q)=>Y.check(l1(J,Q)),Y.nonempty=(J)=>Y.check(l1(1,J)),Y.max=(J,Q)=>Y.check(aY(J,Q)),Y.length=(J,Q)=>Y.check(tY(J,Q)),Y.unwrap=()=>Y.element});function I9(Y,X){return CG(dU,Y,X)}var W$=F("ZodObject",(Y,X)=>{b7.init(Y,X),t.init(Y,X),c.defineLazy(Y,"shape",()=>X.shape),Y.keyof=()=>k9(Object.keys(Y._zod.def.shape)),Y.catchall=(J)=>Y.clone({...Y._zod.def,catchall:J}),Y.passthrough=()=>Y.clone({...Y._zod.def,catchall:LY()}),Y.loose=()=>Y.clone({...Y._zod.def,catchall:LY()}),Y.strict=()=>Y.clone({...Y._zod.def,catchall:_9()}),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(B$,Y,J[0]),Y.required=(...J)=>c.required(Z$,Y,J[0])});function z$(Y,X){let J={type:"object",get shape(){return c.assignProp(this,"shape",Y?c.objectClone(Y):{}),this.shape},...c.normalizeParams(X)};return new W$(J)}function U$(Y,X){return new W$({type:"object",get shape(){return c.assignProp(this,"shape",c.objectClone(Y)),this.shape},catchall:LY(),...c.normalizeParams(X)})}var H$=F("ZodUnion",(Y,X)=>{K9.init(Y,X),t.init(Y,X),Y.options=X.options});function S9(Y,X){return new H$({type:"union",options:Y,...c.normalizeParams(X)})}var iU=F("ZodDiscriminatedUnion",(Y,X)=>{H$.init(Y,X),x7.init(Y,X)});function L$(Y,X,J){return new iU({type:"union",options:X,discriminator:Y,...c.normalizeParams(J)})}var nU=F("ZodIntersection",(Y,X)=>{v7.init(Y,X),t.init(Y,X)});function oU(Y,X){return new nU({type:"intersection",left:Y,right:X})}var rU=F("ZodRecord",(Y,X)=>{h7.init(Y,X),t.init(Y,X),Y.keyType=X.keyType,Y.valueType=X.valueType});function V$(Y,X,J){return new rU({type:"record",keyType:Y,valueType:X,...c.normalizeParams(J)})}var C9=F("ZodEnum",(Y,X)=>{g7.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,G)=>{let $={};for(let W of Q)if(J.has(W))$[W]=X.entries[W];else throw Error(`Key ${W} not found in enum`);return new C9({...X,checks:[],...c.normalizeParams(G),entries:$})},Y.exclude=(Q,G)=>{let $={...X.entries};for(let W of Q)if(J.has(W))delete $[W];else throw Error(`Key ${W} not found in enum`);return new C9({...X,checks:[],...c.normalizeParams(G),entries:$})}});function k9(Y,X){let J=Array.isArray(Y)?Object.fromEntries(Y.map((Q)=>[Q,Q])):Y;return new C9({type:"enum",entries:J,...c.normalizeParams(X)})}var sU=F("ZodLiteral",(Y,X)=>{y7.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 N$(Y,X){return new sU({type:"literal",values:Array.isArray(Y)?Y:[Y],...c.normalizeParams(X)})}var aU=F("ZodTransform",(Y,X)=>{f7.init(Y,X),t.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new e1(Y.constructor.name);J.addIssue=($)=>{if(typeof $==="string")J.issues.push(c.issue($,J.value,X));else{let W=$;if(W.fatal)W.continue=!1;W.code??(W.code="custom"),W.input??(W.input=J.value),W.inst??(W.inst=Y),J.issues.push(c.issue(W))}};let G=X.transform(J.value,J);if(G instanceof Promise)return G.then(($)=>{return J.value=$,J});return J.value=G,J}});function tU(Y){return new aU({type:"transform",transform:Y})}var B$=F("ZodOptional",(Y,X)=>{m7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function aG(Y){return new B$({type:"optional",innerType:Y})}var eU=F("ZodNullable",(Y,X)=>{c7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function tG(Y){return new eU({type:"nullable",innerType:Y})}var YH=F("ZodDefault",(Y,X)=>{u7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function XH(Y,X){return new YH({type:"default",innerType:Y,get defaultValue(){return typeof X==="function"?X():c.shallowClone(X)}})}var JH=F("ZodPrefault",(Y,X)=>{p7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function QH(Y,X){return new JH({type:"prefault",innerType:Y,get defaultValue(){return typeof X==="function"?X():c.shallowClone(X)}})}var Z$=F("ZodNonOptional",(Y,X)=>{l7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function GH(Y,X){return new Z$({type:"nonoptional",innerType:Y,...c.normalizeParams(X)})}var $H=F("ZodCatch",(Y,X)=>{d7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function WH(Y,X){return new $H({type:"catch",innerType:Y,catchValue:typeof X==="function"?X:()=>X})}var zH=F("ZodPipe",(Y,X)=>{i7.init(Y,X),t.init(Y,X),Y.in=X.in,Y.out=X.out});function eG(Y,X){return new zH({type:"pipe",in:Y,out:X})}var UH=F("ZodReadonly",(Y,X)=>{n7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function HH(Y){return new UH({type:"readonly",innerType:Y})}var LH=F("ZodLazy",(Y,X)=>{o7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.getter()});function K$(Y){return new LH({type:"lazy",getter:Y})}var b9=F("ZodCustom",(Y,X)=>{r7.init(Y,X),t.init(Y,X)});function O$(Y,X){return _G(b9,Y??(()=>!0),X)}function VH(Y,X={}){return IG(b9,Y,X)}function NH(Y){return SG(Y)}function q$(Y,X={error:`Input not instance of ${Y.name}`}){let J=new b9({type:"custom",check:"custom",fn:(Q)=>Q instanceof Y,abort:!0,...c.normalizeParams(X)});return J._zod.bag.Class=Y,J}var BH=[{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]}],HO=[...BH,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];var ZH=12,KH=131072,LO=KH+ZH;async function J8(Y){var X;try{await((X=Y.body)==null?void 0:X.cancel())}catch(J){}}var R$="AI_DownloadError",C$=`vercel.ai.error.${R$}`,OH=Symbol.for(C$),F$,j$,j0=class extends(j$=m,F$=OH,j$){constructor({url:Y,statusCode:X,statusText:J,cause:Q,message:G=Q==null?`Failed to download ${Y}: ${X} ${J}`:`Failed to download ${Y}: ${Q}`}){super({name:R$,message:G,cause:Q});this[F$]=!0,this.url=Y,this.statusCode=X,this.statusText=J}static isInstance(Y){return m.hasMarker(Y,C$)}};function qH(Y=globalThis){return Y.window!=null}function D$(Y,X){try{return new URL(Y).origin===new URL(X).origin}catch(J){return!1}}function FH(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(_$(Q))throw new j0({url:Y,message:`URL with IPv6 address ${J} is not allowed`});return}if(f9(J)){if(m9(J))throw new j0({url:Y,message:`URL with IP address ${J} is not allowed`});return}}function jH({address:Y,family:X,hostname:J}){if(X===4?!f9(Y)||m9(Y):X===6?_$(Y):!0)throw new j0({url:J,message:`Hostname ${J} resolved to disallowed IP address ${Y}`})}function f9(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 m9(Y){let X=Y.split(".").map(Number),[J,Q,G]=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&&G===0)return!0;if(J===192&&Q===0&&G===2)return!0;if(J===192&&Q===168)return!0;if(J===198&&(Q===18||Q===19))return!0;if(J===198&&Q===51&&G===100)return!0;if(J===203&&Q===0&&G===113)return!0;if(J>=224)return!0;return!1}function DH(Y){let X=Y.toLowerCase(),J=X.indexOf("%");if(J!==-1)X=X.slice(0,J);let Q=X.split("::");if(Q.length>2)return null;let G=(W)=>{if(W==="")return[];let U=[],H=W.split(":");for(let L=0;L<H.length;L++){let N=H[L];if(N.includes(".")){if(L!==H.length-1||!f9(N))return null;let[O,Z,V,K]=N.split(".").map(Number);U.push(O<<8|Z,V<<8|K);continue}if(!/^[0-9a-f]{1,4}$/.test(N))return null;U.push(parseInt(N,16))}return U},$=G(Q[0]);if($===null)return null;if(Q.length===2){let W=G(Q[1]);if(W===null)return null;let U=8-$.length-W.length;if(U<0)return null;return[...$,...Array(U).fill(0),...W]}return $.length===8?$:null}function _$(Y){let X=DH(Y);if(X===null)return!0;let J=(G)=>X.slice(0,G).every(($)=>$===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 G=X[6]>>8&255,$=X[6]&255,W=X[7]>>8&255,U=X[7]&255;return m9(`${G}.${$}.${W}.${U}`)}return!1}function PH(Y){return(X,J,Q)=>{Y(X,{...J,all:!0},(G,$)=>{if(G){Q(G);return}try{let[W]=$;if(W==null)throw Error(`Hostname ${X} did not resolve to an address`);for(let{address:U,family:H}of $)jH({address:U,family:H,hostname:X});if(J.all===!0)Q(null,$);else Q(null,W.address,W.family)}catch(W){Q(W instanceof Error?W:Error(String(W)))}})}}var x9,I$=globalThis.fetch,MH=AH(I$);function wH(){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 EH(){if(!wH()||!MH||globalThis.fetch!==I$)return globalThis.fetch;return x9!=null?x9:x9=Promise.resolve().then(TH)}function AH(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 TH(){let{createRequire:Y}=P$("node:module"),{lookup:X}=P$("node:dns"),{Agent:J,fetch:Q}=Y(S$())("undici"),G=new J({connect:{lookup:PH(X)}});return($,W)=>Q($,{...W,dispatcher:G})}function P$(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 S$(){let Y=Error.prepareStackTrace;try{Error.prepareStackTrace=(G,$)=>$;let X=Error("Capture current module path");Error.captureStackTrace(X,S$);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 RH=["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 CH(Y){let X=new Headers(Y);for(let J of RH)X.delete(J);return X}var _H=10,IH=new Set([301,302,303,307,308]);async function k$({url:Y,headers:X,abortSignal:J,maxRedirects:Q=_H,fetch:G,trustedOrigin:$}){let W=X===void 0?void 0:CH(X),U=(L)=>{let N={signal:J,redirect:L};if(W!==void 0)N.headers=new Headers(W);return N},H=Y;for(let L=0;L<=Q;L++){let N=$!==void 0&&D$(H,$);if(!N)FH(H);let O=G!=null?G:N?globalThis.fetch:await EH(),Z=await O(H,U("manual"));if(Z.type==="opaqueredirect"){if(!qH())throw new j0({url:Y,message:`Redirect from ${H} could not be validated and was blocked`});return await O(H,U("follow"))}let V=Z.headers.get("location");if(IH.has(Z.status)&&V){await J8(Z);let K=new URL(V,H).toString();if(W!==void 0&&!D$(K,H)){let j=W.get("user-agent");W=new Headers(j==null?void 0:{"user-agent":j})}H=K;continue}return Z}throw new j0({url:Y,message:`Too many redirects (max ${Q})`})}var c9=2147483648;async function b$({response:Y,url:X,maxBytes:J=c9}){let Q=Y.headers.get("content-length");if(Q!=null){let N=parseInt(Q,10);if(!isNaN(N)&&N>J)throw await J8(Y),new j0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes (Content-Length: ${N}).`})}let G=Y.body;if(G==null)return new Uint8Array(0);let $=G.getReader(),W=[],U=0;try{while(!0){let{done:N,value:O}=await $.read();if(N)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 $.cancel()}catch(N){}finally{$.releaseLock()}}let H=new Uint8Array(U),L=0;for(let N of W)H.set(N,L),L+=N.length;return H}var W0=({prefix:Y,size:X=16,alphabet:J="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:Q="-"}={})=>{let G=()=>{let $=J.length,W=Array(X);for(let U=0;U<X;U++)W[U]=J[Math.random()*$|0];return W.join("")};if(Y==null)return G;if(J.includes(Q))throw new N6({argument:"separator",message:`The separator "${Q}" must not be part of the alphabet "${J}".`});return()=>`${Y}${Q}${G()}`},BO=W0();function x$(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 SH(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 d1(Y,...X){let J=new Headers(SH(Y)),Q=J.get("user-agent")||"";return J.set("user-agent",[Q,...X].filter(Boolean).join(" ")),Object.fromEntries(J.entries())}function v$(Y){var X,J;return(J=(X=globalThis.Buffer)==null?void 0:X.isBuffer(Y))!=null?J:!1}var kH=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,bH=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function M$(Y){let X=JSON.parse(Y);if(X===null||typeof X!=="object")return X;if(kH.test(Y)===!1&&bH.test(Y)===!1)return X;return xH(X)}function xH(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 G in Q){let $=Q[G];if($&&typeof $==="object")X.push($)}}}return Y}function vH(Y){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(J){return M$(Y)}try{return M$(Y)}finally{Error.stackTraceLimit=X}}function u9(Y){if(Y.type==="object"||Array.isArray(Y.type)&&Y.type.includes("object")){Y.additionalProperties=!1;let{properties:J}=Y;if(J!=null)for(let Q of Object.keys(J))J[Q]=C1(J[Q])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(C1):C1(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(C1);if(Y.allOf!=null)Y.allOf=Y.allOf.map(C1);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(C1);let{definitions:X}=Y;if(X!=null)for(let J of Object.keys(X))X[J]=C1(X[J]);return Y}function C1(Y){if(typeof Y==="boolean")return Y;return u9(Y)}var hH=Symbol("Let zodToJsonSchema decide on which parser to use"),w$={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"},gH=(Y)=>typeof Y==="string"?{...w$,name:Y}:{...w$,...Y};function C0(){return{}}function yH(Y,X){var J,Q,G;let $={type:"array"};if(((J=Y.type)==null?void 0:J._def)&&((G=(Q=Y.type)==null?void 0:Q._def)==null?void 0:G.typeName)!=="ZodAny")$.items=n(Y.type._def,{...X,currentPath:[...X.currentPath,"items"]});if(Y.minLength)$.minItems=Y.minLength.value;if(Y.maxLength)$.maxItems=Y.maxLength.value;if(Y.exactLength)$.minItems=Y.exactLength.value,$.maxItems=Y.exactLength.value;return $}function fH(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 mH(){return{type:"boolean"}}function h$(Y,X){return n(Y.type._def,X)}var cH=(Y,X)=>{return n(Y.innerType._def,X)};function g$(Y,X,J){let Q=J!=null?J:X.dateStrategy;if(Array.isArray(Q))return{anyOf:Q.map((G)=>g$(Y,X,G))};switch(Q){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return uH(Y)}}var uH=(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 pH(Y,X){return{...n(Y.innerType._def,X),default:Y.defaultValue()}}function lH(Y,X){return X.effectStrategy==="input"?n(Y.schema._def,X):C0()}function dH(Y){return{type:"string",enum:Array.from(Y.values)}}var iH=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function nH(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((G)=>!!G),Q=[];return J.forEach((G)=>{if(iH(G))Q.push(...G.allOf);else{let $=G;if("additionalProperties"in G&&G.additionalProperties===!1){let{additionalProperties:W,...U}=G;$=U}Q.push($)}}),Q.length?{allOf:Q}:void 0}function oH(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 v9=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(v9===void 0)v9=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return v9},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 y$(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":F0(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":F0(J,Q.regex,Q.message,X);break;case"cuid":F0(J,v0.cuid,Q.message,X);break;case"cuid2":F0(J,v0.cuid2,Q.message,X);break;case"startsWith":F0(J,RegExp(`^${h9(Q.value,X)}`),Q.message,X);break;case"endsWith":F0(J,RegExp(`${h9(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":{F0(J,RegExp(h9(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":F0(J,v0.base64url,Q.message,X);break;case"jwt":F0(J,v0.jwt,Q.message,X);break;case"cidr":{if(Q.version!=="v6")F0(J,v0.ipv4Cidr,Q.message,X);if(Q.version!=="v4")F0(J,v0.ipv6Cidr,Q.message,X);break}case"emoji":F0(J,v0.emoji(),Q.message,X);break;case"ulid":{F0(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":{F0(J,v0.base64,Q.message,X);break}}break}case"nanoid":F0(J,v0.nanoid,Q.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return J}function h9(Y,X){return X.patternStrategy==="escape"?sH(Y):Y}var rH=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function sH(Y){let X="";for(let J=0;J<Y.length;J++){if(!rH.has(Y[J]))X+="\\";X+=Y[J]}return X}function h0(Y,X,J,Q){var G;if(Y.format||((G=Y.anyOf)==null?void 0:G.some(($)=>$.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 F0(Y,X,J,Q){var G;if(Y.pattern||((G=Y.allOf)==null?void 0:G.some(($)=>$.pattern))){if(!Y.allOf)Y.allOf=[];if(Y.pattern)Y.allOf.push({pattern:Y.pattern}),delete Y.pattern;Y.allOf.push({pattern:E$(X,Q),...J&&Q.errorMessages&&{errorMessage:{pattern:J}}})}else Y.pattern=E$(X,Q)}function E$(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")},G=Q.i?Y.source.toLowerCase():Y.source,$="",W=!1,U=!1,H=!1;for(let L=0;L<G.length;L++){if(W){$+=G[L],W=!1;continue}if(Q.i){if(U){if(G[L].match(/[a-z]/)){if(H)$+=G[L],$+=`${G[L-2]}-${G[L]}`.toUpperCase(),H=!1;else if(G[L+1]==="-"&&((J=G[L+2])==null?void 0:J.match(/[a-z]/)))$+=G[L],H=!0;else $+=`${G[L]}${G[L].toUpperCase()}`;continue}}else if(G[L].match(/[a-z]/)){$+=`[${G[L]}${G[L].toUpperCase()}]`;continue}}if(Q.m){if(G[L]==="^"){$+=`(^|(?<=[\r
188
- ]))`;continue}else if(G[L]==="$"){$+=`($|(?=[\r
189
- ]))`;continue}}if(Q.s&&G[L]==="."){$+=U?`${G[L]}\r
190
- `:`[${G[L]}\r
191
- ]`;continue}if($+=G[L],G[L]==="\\")W=!0;else if(U&&G[L]==="]")U=!1;else if(!U&&G[L]==="[")U=!0}try{new RegExp($)}catch(L){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 $}function f$(Y,X){var J,Q,G,$,W,U;let H={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"&&((G=Y.keyType._def.checks)==null?void 0:G.length)){let{type:L,...N}=y$(Y.keyType._def,X);return{...H,propertyNames:N}}else if((($=Y.keyType)==null?void 0:$._def.typeName)==="ZodEnum")return{...H,propertyNames:{enum:Y.keyType._def.values}};else if(((W=Y.keyType)==null?void 0:W._def.typeName)==="ZodBranded"&&Y.keyType._def.type._def.typeName==="ZodString"&&((U=Y.keyType._def.type._def.checks)==null?void 0:U.length)){let{type:L,...N}=h$(Y.keyType._def,X);return{...H,propertyNames:N}}return H}function aH(Y,X){if(X.mapStrategy==="record")return f$(Y,X);let J=n(Y.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||C0(),Q=n(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||C0();return{type:"array",maxItems:125,items:{type:"array",items:[J,Q],minItems:2,maxItems:2}}}function tH(Y){let X=Y.values,Q=Object.keys(Y.values).filter(($)=>{return typeof X[X[$]]!=="number"}).map(($)=>X[$]),G=Array.from(new Set(Q.map(($)=>typeof $)));return{type:G.length===1?G[0]==="string"?"string":"number":["string","number"],enum:Q}}function eH(){return{not:C0()}}function YL(){return{type:"null"}}var g9={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function XL(Y,X){let J=Y.options instanceof Map?Array.from(Y.options.values()):Y.options;if(J.every((Q)=>(Q._def.typeName in g9)&&(!Q._def.checks||!Q._def.checks.length))){let Q=J.reduce((G,$)=>{let W=g9[$._def.typeName];return W&&!G.includes(W)?[...G,W]:G},[]);return{type:Q.length>1?Q:Q[0]}}else if(J.every((Q)=>Q._def.typeName==="ZodLiteral"&&!Q.description)){let Q=J.reduce((G,$)=>{let W=typeof $._def.value;switch(W){case"string":case"number":case"boolean":return[...G,W];case"bigint":return[...G,"integer"];case"object":if($._def.value===null)return[...G,"null"];case"symbol":case"undefined":case"function":default:return G}},[]);if(Q.length===J.length){let G=Q.filter(($,W,U)=>U.indexOf($)===W);return{type:G.length>1?G:G[0],enum:J.reduce(($,W)=>{return $.includes(W._def.value)?$:[...$,W._def.value]},[])}}}else if(J.every((Q)=>Q._def.typeName==="ZodEnum"))return{type:"string",enum:J.reduce((Q,G)=>[...Q,...G._def.values.filter(($)=>!Q.includes($))],[])};return JL(Y,X)}var JL=(Y,X)=>{let J=(Y.options instanceof Map?Array.from(Y.options.values()):Y.options).map((Q,G)=>n(Q._def,{...X,currentPath:[...X.currentPath,"anyOf",`${G}`]})).filter((Q)=>!!Q&&(!X.strictUnions||typeof Q==="object"&&Object.keys(Q).length>0));return J.length?{anyOf:J}:void 0};function QL(Y,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Y.innerType._def.typeName)&&(!Y.innerType._def.checks||!Y.innerType._def.checks.length))return{type:[g9[Y.innerType._def.typeName],"null"]};let J=n(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return J&&{anyOf:[J,{type:"null"}]}}function GL(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 $L(Y,X){let J={type:"object",properties:{}},Q=[],G=Y.shape();for(let W in G){let U=G[W];if(U===void 0||U._def===void 0)continue;let H=zL(U),L=n(U._def,{...X,currentPath:[...X.currentPath,"properties",W],propertyPath:[...X.currentPath,"properties",W]});if(L===void 0)continue;if(J.properties[W]=L,!H)Q.push(W)}if(Q.length)J.required=Q;let $=WL(Y,X);if($!==void 0)J.additionalProperties=$;return J}function WL(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 zL(Y){try{return Y.isOptional()}catch(X){return!0}}var UL=(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:C0()},Q]}:C0()},HL=(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((G)=>G!==void 0)}};function LL(Y,X){return n(Y.type._def,X)}function VL(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 NL(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 BL(){return{not:C0()}}function ZL(){return C0()}var KL=(Y,X)=>{return n(Y.innerType._def,X)},OL=(Y,X,J)=>{switch(X){case"ZodString":return y$(Y,J);case"ZodNumber":return GL(Y);case"ZodObject":return $L(Y,J);case"ZodBigInt":return fH(Y);case"ZodBoolean":return mH();case"ZodDate":return g$(Y,J);case"ZodUndefined":return BL();case"ZodNull":return YL();case"ZodArray":return yH(Y,J);case"ZodUnion":case"ZodDiscriminatedUnion":return XL(Y,J);case"ZodIntersection":return nH(Y,J);case"ZodTuple":return NL(Y,J);case"ZodRecord":return f$(Y,J);case"ZodLiteral":return oH(Y);case"ZodEnum":return dH(Y);case"ZodNativeEnum":return tH(Y);case"ZodNullable":return QL(Y,J);case"ZodOptional":return UL(Y,J);case"ZodMap":return aH(Y,J);case"ZodSet":return VL(Y,J);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return LL(Y,J);case"ZodNaN":case"ZodNever":return eH();case"ZodEffects":return lH(Y,J);case"ZodAny":return C0();case"ZodUnknown":return ZL();case"ZodDefault":return pH(Y,J);case"ZodBranded":return h$(Y,J);case"ZodReadonly":return KL(Y,J);case"ZodCatch":return cH(Y,J);case"ZodPipeline":return HL(Y,J);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Q)=>{return})(X)}},qL=(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 G=X.seen.get(Y);if(X.override){let H=(Q=X.override)==null?void 0:Q.call(X,Y,X,G,J);if(H!==hH)return H}if(G&&!J){let H=FL(G,X);if(H!==void 0)return H}let $={def:Y,path:X.currentPath,jsonSchema:void 0};X.seen.set(Y,$);let W=OL(Y,Y.typeName,X),U=typeof W==="function"?n(W(),X):W;if(U)jL(Y,X,U);if(X.postProcess){let H=X.postProcess(U,Y,X);return $.jsonSchema=U,H}return $.jsonSchema=U,U}var FL=(Y,X)=>{switch(X.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:qL(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`),C0();return X.$refStrategy==="seen"?C0():void 0}}},jL=(Y,X,J)=>{if(Y.description)J.description=Y.description;return J},DL=(Y)=>{let X=gH(Y),J=X.name!==void 0?[...X.basePath,X.definitionPath,X.name]:X.basePath;return{...X,currentPath:J,propertyPath:void 0,seen:new Map(Object.entries(X.definitions).map(([Q,G])=>[G._def,{def:G._def,path:[...X.basePath,X.definitionPath,Q],jsonSchema:void 0}]))}},PL=(Y,X)=>{var J;let Q=DL(X),G=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((L,[N,O])=>{var Z;return{...L,[N]:(Z=n(O._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,N]},!0))!=null?Z:C0()}},{}):void 0,$=typeof X==="string"?X:(X==null?void 0:X.nameStrategy)==="title"?void 0:X==null?void 0:X.name,W=(J=n(Y._def,$===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,$]},!1))!=null?J:C0(),U=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if(U!==void 0)W.title=U;let H=$===void 0?G?{...W,[Q.definitionPath]:G}:W:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,$].join("/"),[Q.definitionPath]:{...G,[$]:W}};return H.$schema="http://json-schema.org/draft-07/schema#",H},y9=Symbol.for("vercel.ai.schema");function Q8(Y){let X;return()=>{if(X==null)X=Y();return X}}function G8(Y,{validate:X}={}){return{[y9]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:X}}function ML(Y){return typeof Y==="object"&&Y!==null&&y9 in Y&&Y[y9]===!0&&"jsonSchema"in Y&&"validate"in Y}function $8(Y){return Y==null?G8({type:"object",properties:{},additionalProperties:!1}):ML(Y)?Y:("~standard"in Y)?Y["~standard"].vendor==="zod"?VY(Y):wL(Y):Y()}function wL(Y){return G8(()=>{if(!EL(Y))throw Error(`Standard schema vendor '${Y["~standard"].vendor}' does not support JSON Schema conversion.`);return u9(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 EL(Y){return Y["~standard"].jsonSchema!=null}function AL(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return G8(()=>PL(Y,{$refStrategy:Q?"root":"none"}),{validate:async(G)=>{let $=await Y.safeParseAsync(G);return $.success?{success:!0,value:$.data}:{success:!1,error:$.error}}})}function TL(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return G8(()=>u9(kG(Y,{target:"draft-7",io:"input",reused:Q?"ref":"inline"})),{validate:async(G)=>{let $=await Y8(Y,G);return $.success?{success:!0,value:$.data}:{success:!1,error:$.error}}})}function RL(Y){return"_zod"in Y}function VY(Y,X){if(RL(Y))return TL(Y,X);else return AL(Y,X)}async function NY({value:Y,schema:X,context:J}){let Q=$8(X);try{if(Q.validate==null)return{success:!0,value:Y,rawValue:Y};let G=await Q.validate(Y);if(G.success)return{success:!0,value:G.value,rawValue:Y};return{success:!1,error:p0.wrap({value:Y,cause:G.error,context:J}),rawValue:Y}}catch(G){return{success:!1,error:p0.wrap({value:Y,cause:G,context:J}),rawValue:Y}}}async function Z1({text:Y,schema:X}){try{let J=vH(Y);if(X==null)return{success:!0,value:J,rawValue:J};return await NY({value:J,schema:X})}catch(J){return{success:!1,error:hY.isInstance(J)?J:new hY({text:Y,cause:J}),rawValue:void 0}}}async function p9(Y){if(typeof Y==="function")Y=Y();return Promise.resolve(Y)}var m$="AI_SerializationError",c$=`vercel.ai.error.${m$}`,CL=Symbol.for(c$),A$,T$,DO=class extends(T$=m,A$=CL,T$){constructor({message:Y="Failed to serialize value.",cause:X}={}){super({name:m$,message:Y,cause:X});this[A$]=!0}static isInstance(Y){return m.hasMarker(Y,c$)}};var SL=Object.defineProperty,kL=(Y,X)=>{for(var J in X)SL(Y,J,{get:X[J],enumerable:!0})},bL="AI_InvalidArgumentError",xL=`vercel.ai.error.${bL}`,vL=Symbol.for(xL),hL;hL=vL;var gL="AI_InvalidStreamPartError",yL=`vercel.ai.error.${gL}`,fL=Symbol.for(yL),mL;mL=fL;var cL="AI_InvalidToolApprovalError",uL=`vercel.ai.error.${cL}`,pL=Symbol.for(uL),lL;lL=pL;var dL="AI_InvalidToolApprovalSignatureError",iL=`vercel.ai.error.${dL}`,nL=Symbol.for(iL),oL;oL=nL;var rL="AI_InvalidToolInputError",sL=`vercel.ai.error.${rL}`,aL=Symbol.for(sL),tL;tL=aL;var eL="AI_ToolCallNotFoundForApprovalError",YV=`vercel.ai.error.${eL}`,XV=Symbol.for(YV),JV;JV=XV;var QV="AI_MissingToolResultsError",GV=`vercel.ai.error.${QV}`,$V=Symbol.for(GV),WV;WV=$V;var zV="AI_NoImageGeneratedError",UV=`vercel.ai.error.${zV}`,HV=Symbol.for(UV),LV;LV=HV;var u$="AI_NoObjectGeneratedError",p$=`vercel.ai.error.${u$}`,VV=Symbol.for(p$),l$,K1=class extends m{constructor({message:Y="No object generated.",cause:X,text:J,response:Q,usage:G,finishReason:$}){super({name:u$,message:Y,cause:X});this[l$]=!0,this.text=J,this.response=Q,this.usage=G,this.finishReason=$}static isInstance(Y){return m.hasMarker(Y,p$)}};l$=VV;var NV="AI_NoOutputGeneratedError",BV=`vercel.ai.error.${NV}`,ZV=Symbol.for(BV),KV;KV=ZV;var OV="AI_NoSpeechGeneratedError",qV=`vercel.ai.error.${OV}`,FV=Symbol.for(qV),jV;jV=FV;var DV="AI_NoTranscriptGeneratedError",PV=`vercel.ai.error.${DV}`,MV=Symbol.for(PV),wV;wV=MV;var EV="AI_NoTranslationGeneratedError",AV=`vercel.ai.error.${EV}`,TV=Symbol.for(AV),RV;RV=TV;var CV="AI_NoVideoGeneratedError",_V=`vercel.ai.error.${CV}`,IV=Symbol.for(_V),SV;SV=IV;var kV="AI_NoSuchToolError",bV=`vercel.ai.error.${kV}`,xV=Symbol.for(bV),vV;vV=xV;var hV="AI_ToolCallRepairError",gV=`vercel.ai.error.${hV}`,yV=Symbol.for(gV),fV;fV=yV;var mV="AI_UIMessageStreamError",cV=`vercel.ai.error.${mV}`,uV=Symbol.for(cV),pV;pV=uV;var lV="AI_InvalidDataContentError",dV=`vercel.ai.error.${lV}`,iV=Symbol.for(dV),nV;nV=iV;var oV="AI_InvalidMessageRoleError",rV=`vercel.ai.error.${oV}`,sV=Symbol.for(rV),aV;aV=sV;var tV="AI_MessageConversionError",eV=`vercel.ai.error.${tV}`,YN=Symbol.for(eV),XN;XN=YN;var JN="AI_RetryError",QN=`vercel.ai.error.${JN}`,GN=Symbol.for(QN),$N;$N=GN;var WN="7.0.69",zN=async({url:Y,maxBytes:X,abortSignal:J})=>{var Q;let G=Y.toString();try{let $=d1({},`ai-sdk/${WN}`,x$()),W=await k$({url:G,headers:$,abortSignal:J});if(!W.ok)throw await J8(W),new j0({url:G,statusCode:W.status,statusText:W.statusText});return{data:await b$({response:W,url:G,maxBytes:X!=null?X:c9}),mediaType:(Q=W.headers.get("content-type"))!=null?Q:void 0}}catch($){if(j0.isInstance($))throw $;throw new j0({url:G,cause:$})}};var z={array:I9,boolean:G$,custom:O$,discriminatedUnion:L$,enum:k9,instanceof:q$,lazy:K$,literal:N$,looseObject:U$,never:_9,null:$$,number:Q$,object:z$,record:V$,string:X$,union:S9,unknown:LY},_1=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),_1.optional()),z.array(_1)])),A=z.record(z.string(),z.record(z.string(),_1.optional())),ZY=z.union([z.string(),z.instanceof(Uint8Array),z.instanceof(ArrayBuffer),z.custom(v$,{message:"Must be a Buffer"})]),l9=z.record(z.string(),z.string()),d$=z.object({type:z.literal("text"),text:z.string(),providerOptions:A.optional()}),UN=z.object({type:z.literal("image"),image:z.union([ZY,z.instanceof(URL),l9]),mediaType:z.string().optional(),providerOptions:A.optional()}),i$=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:ZY}),z.object({type:z.literal("url"),url:z.instanceof(URL)}),z.object({type:z.literal("reference"),reference:l9}),z.object({type:z.literal("text"),text:z.string()})]),HN=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:ZY}),z.object({type:z.literal("url"),url:z.instanceof(URL)})]),n$=z.object({type:z.literal("file"),data:z.union([i$,ZY,z.instanceof(URL),l9]),filename:z.string().optional(),mediaType:z.string(),providerOptions:A.optional()}),LN=z.object({type:z.literal("reasoning"),text:z.string(),providerOptions:A.optional()}),VN=z.object({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerOptions:A.optional()}),NN=z.object({type:z.literal("reasoning-file"),data:z.union([HN,ZY,z.instanceof(URL)]),mediaType:z.string(),providerOptions:A.optional()}),BN=z.object({type:z.literal("tool-call"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerOptions:A.optional(),providerExecuted:z.boolean().optional()}),ZN=z.discriminatedUnion("type",[z.object({type:z.literal("text"),value:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("json"),value:_1,providerOptions:A.optional()}),z.object({type:z.literal("execution-denied"),reason:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("error-text"),value:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("error-json"),value:_1,providerOptions:A.optional()}),z.object({type:z.literal("content"),value:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("file"),data:i$,mediaType:z.string(),filename:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("file-data"),data:z.string(),mediaType:z.string(),filename:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("file-url"),url:z.string(),mediaType:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:A.optional()}),z.object({type:z.literal("file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:A.optional()}),z.object({type:z.literal("image-data"),data:z.string(),mediaType:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("image-url"),url:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("image-file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:A.optional()}),z.object({type:z.literal("image-file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:A.optional()}),z.object({type:z.literal("custom"),providerOptions:A.optional()})]))})]),o$=z.object({type:z.literal("tool-result"),toolCallId:z.string(),toolName:z.string(),output:ZN,providerOptions:A.optional()}),KN=z.object({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string()}),ON=z.object({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional()}),qN=z.object({role:z.literal("system"),content:z.string(),providerOptions:A.optional()}),FN=z.object({role:z.literal("user"),content:z.union([z.string(),z.array(z.union([d$,UN,n$]))]),providerOptions:A.optional()}),jN=z.object({role:z.literal("assistant"),content:z.union([z.string(),z.array(z.union([d$,VN,n$,LN,NN,BN,o$,KN]))]),providerOptions:A.optional()}),DN=z.object({role:z.literal("tool"),content:z.array(z.union([o$,ON])),providerOptions:A.optional()}),xO=z.union([qN,FN,jN,DN]);var PN={};kL(PN,{array:()=>AN,choice:()=>TN,json:()=>RN,object:()=>EN,text:()=>wN});function MN(Y){let X=["ROOT"],J=-1,Q=null,G=0;function $(N){return N>="0"&&N<="9"||N>="A"&&N<="F"||N>="a"&&N<="f"}function W(N,O,Z){switch(N){case'"':{J=O,X.pop(),X.push(Z),X.push("INSIDE_STRING");break}case"f":case"t":case"n":{J=O,Q=O,X.pop(),X.push(Z),X.push("INSIDE_LITERAL");break}case"-":{X.pop(),X.push(Z),X.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=O,X.pop(),X.push(Z),X.push("INSIDE_NUMBER");break}case"{":{J=O,X.pop(),X.push(Z),X.push("INSIDE_OBJECT_START");break}case"[":{J=O,X.pop(),X.push(Z),X.push("INSIDE_ARRAY_START");break}}}function U(N,O){switch(N){case",":{X.pop(),X.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{J=O,X.pop();break}}}function H(N,O){switch(N){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=O,X.pop();break}}}for(let N=0;N<Y.length;N++){let O=Y[N];switch(X[X.length-1]){case"ROOT":W(O,N,"FINISH");break;case"INSIDE_OBJECT_START":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}case"}":{J=N,X.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(O){case":":{X.pop(),X.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{W(O,N,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{U(O,N);break}case"INSIDE_STRING":{switch(O){case'"':{X.pop(),J=N;break}case"\\":{X.push("INSIDE_STRING_ESCAPE");break}default:J=N}break}case"INSIDE_ARRAY_START":{switch(O){case"]":{J=N,X.pop();break}default:{J=N,W(O,N,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(O){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=N,X.pop();break}default:{J=N;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{W(O,N,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{if(X.pop(),O==="u")G=0,X.push("INSIDE_STRING_UNICODE_ESCAPE");else J=N;break}case"INSIDE_STRING_UNICODE_ESCAPE":{if($(O)){if(G++,G===4)X.pop(),J=N}break}case"INSIDE_NUMBER":{switch(O){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=N;break}case"e":case"E":case"-":case".":break;case",":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")H(O,N);if(X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")U(O,N);break}case"}":{if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")U(O,N);break}case"]":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")H(O,N);break}default:{X.pop();break}}break}case"INSIDE_LITERAL":{let V=Y.substring(Q,N+1);if(!"false".startsWith(V)&&!"true".startsWith(V)&&!"null".startsWith(V)){if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")U(O,N);else if(X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")H(O,N)}else J=N;break}}}let L=Y.slice(0,J+1);for(let N=X.length-1;N>=0;N--)switch(X[N]){case"INSIDE_STRING":{L+='"';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":{L+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{L+="]";break}case"INSIDE_LITERAL":{let Z=Y.substring(Q,Y.length);if("true".startsWith(Z))L+="true".slice(Z.length);else if("false".startsWith(Z))L+="false".slice(Z.length);else if("null".startsWith(Z))L+="null".slice(Z.length)}}return L}async function W8(Y){if(Y===void 0)return{value:void 0,state:"undefined-input"};let X=await Z1({text:Y});if(X.success)return{value:X.value,state:"successful-parse"};if(X=await Z1({text:MN(Y)}),X.success)return{value:X.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var wN=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:Y}){return Y},async parsePartialOutput({text:Y}){return{partial:Y}},createElementStreamTransform(){return}}),EN=({schema:Y,name:X,description:J})=>{let Q=$8(Y);return{name:"object",responseFormat:p9(Q.jsonSchema).then((G)=>({type:"json",schema:G,...X!=null&&{name:X},...J!=null&&{description:J}})),async parseCompleteOutput({text:G},$){let W=await Z1({text:G});if(!W.success)throw new K1({message:"No object generated: could not parse the response.",cause:W.error,text:G,response:$.response,usage:$.usage,finishReason:$.finishReason});let U=await NY({value:W.value,schema:Q});if(!U.success)throw new K1({message:"No object generated: response did not match schema.",cause:U.error,text:G,response:$.response,usage:$.usage,finishReason:$.finishReason});return U.value},async parsePartialOutput({text:G}){let $=await W8(G);switch($.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:$.value}}},createElementStreamTransform(){return}}},AN=({element:Y,name:X,description:J})=>{let Q=$8(Y);return{name:"array",responseFormat:p9(Q.jsonSchema).then((G)=>{let{$schema:$,definitions:W,$defs:U,...H}=G;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:H}},required:["elements"],additionalProperties:!1},...X!=null&&{name:X},...J!=null&&{description:J}}}),async parseCompleteOutput({text:G},$){let W=await Z1({text:G});if(!W.success)throw new K1({message:"No object generated: could not parse the response.",cause:W.error,text:G,response:$.response,usage:$.usage,finishReason:$.finishReason});let U=W.value;if(U==null||typeof U!=="object"||!("elements"in U)||!Array.isArray(U.elements))throw new K1({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:G,response:$.response,usage:$.usage,finishReason:$.finishReason});let H=[];for(let L of U.elements){let N=await NY({value:L,schema:Q});if(!N.success)throw new K1({message:"No object generated: response did not match schema.",cause:N.error,text:G,response:$.response,usage:$.usage,finishReason:$.finishReason});H.push(N.value)}return H},async parsePartialOutput({text:G}){let $=await W8(G);switch($.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let W=$.value;if(W==null||typeof W!=="object"||!("elements"in W)||!Array.isArray(W.elements))return;let U=$.state==="repaired-parse"&&W.elements.length>0?W.elements.slice(0,-1):W.elements,H=[];for(let L of U){let N=await NY({value:L,schema:Q});if(N.success)H.push(N.value)}return{partial:H}}}},createElementStreamTransform(){let G=0;return new TransformStream({transform({partialOutput:$},W){if($!=null)for(;G<$.length;G++)W.enqueue($[G])}})}}},TN=({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},G){let $=await Z1({text:Q});if(!$.success)throw new K1({message:"No object generated: could not parse the response.",cause:$.error,text:Q,response:G.response,usage:G.usage,finishReason:G.finishReason});let W=$.value;if(W==null||typeof W!=="object"||!("result"in W)||typeof W.result!=="string"||!Y.includes(W.result))throw new K1({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:G.response,usage:G.usage,finishReason:G.finishReason});return W.result},async parsePartialOutput({text:Q}){let G=await W8(Q);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let $=G.value;if($==null||typeof $!=="object"||!("result"in $)||typeof $.result!=="string")return;let W=Y.filter((U)=>U.startsWith($.result));if(G.state==="successful-parse")return W.includes($.result)?{partial:$.result}:void 0;else return W.length===1?{partial:W[0]}:void 0}}},createElementStreamTransform(){return}}},RN=({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 G=await Z1({text:J});if(!G.success)throw new K1({message:"No object generated: could not parse the response.",cause:G.error,text:J,response:Q.response,usage:Q.usage,finishReason:Q.finishReason});return G.value},async parsePartialOutput({text:J}){let Q=await W8(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 yO=W0({prefix:"aitxt",size:24}),fO=W0({prefix:"call",size:24});var cO=class extends TransformStream{constructor(){super({transform(Y,X){X.enqueue(`data: ${JSON.stringify(Y)}
187
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let H of this.seen.entries()){let N=H[1];if(Y===H[0]){$(H);continue}if(J.external){let Z=J.external.registry.get(H[0])?.id;if(Y!==H[0]&&Z){$(H);continue}}if(this.metadataRegistry.get(H[0])?.id){$(H);continue}if(N.cycle){$(H);continue}if(N.count>1){if(J.reused==="ref"){$(H);continue}}}let W=(H,N)=>{let O=this.seen.get(H),Z=O.def??O.schema,V={...Z};if(O.ref===null)return;let K=O.ref;if(O.ref=null,K){W(K,N);let j=this.seen.get(K).schema;if(j.$ref&&(N.target==="draft-7"||N.target==="draft-4"||N.target==="openapi-3.0"))Z.allOf=Z.allOf??[],Z.allOf.push(j);else Object.assign(Z,j),Object.assign(Z,V)}if(!O.isParent)this.override({zodSchema:H,jsonSchema:Z,path:O.path??[]})};for(let H of[...this.seen.entries()].reverse())W(H[0],{target:this.target});let z={};if(this.target==="draft-2020-12")z.$schema="https://json-schema.org/draft/2020-12/schema";else if(this.target==="draft-7")z.$schema="http://json-schema.org/draft-07/schema#";else if(this.target==="draft-4")z.$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");z.$id=J.external.uri(H)}Object.assign(z,Q.def);let L=J.external?.defs??{};for(let H of this.seen.entries()){let N=H[1];if(N.def&&N.defId)L[N.defId]=N.def}if(J.external);else if(Object.keys(L).length>0)if(this.target==="draft-2020-12")z.$defs=L;else z.definitions=L;try{return JSON.parse(JSON.stringify(z))}catch(H){throw Error("Error converting schema to JSON.")}}}function vG(Y,X){if(Y instanceof nY){let Q=new R9(X),G={};for(let z of Y._idmap.entries()){let[L,H]=z;Q.process(H)}let $={},W={registry:Y,uri:X?.uri,defs:G};for(let z of Y._idmap.entries()){let[L,H]=z;$[L]=Q.emit(H,{...X,external:W})}if(Object.keys(G).length>0){let z=Q.target==="draft-2020-12"?"$defs":"definitions";$.__shared={[z]:G}}return{schemas:$}}let J=new R9(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 G=Y._zod.def;switch(G.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return U0(G.element,J);case"object":{for(let $ in G.shape)if(U0(G.shape[$],J))return!0;return!1}case"union":{for(let $ of G.options)if(U0($,J))return!0;return!1}case"intersection":return U0(G.left,J)||U0(G.right,J);case"tuple":{for(let $ of G.items)if(U0($,J))return!0;if(G.rest&&U0(G.rest,J))return!0;return!1}case"record":return U0(G.keyType,J)||U0(G.valueType,J);case"map":return U0(G.keyType,J)||U0(G.valueType,J);case"set":return U0(G.valueType,J);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return U0(G.innerType,J);case"lazy":return U0(G.getter(),J);case"default":return U0(G.innerType,J);case"prefault":return U0(G.innerType,J);case"custom":return!1;case"transform":return!0;case"pipe":return U0(G.in,J)||U0(G.out,J);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${G.type}`)}var DU=F("ZodISODateTime",(Y,X)=>{K7.init(Y,X),a.init(Y,X)});function hG(Y){return PG(DU,Y)}var PU=F("ZodISODate",(Y,X)=>{O7.init(Y,X),a.init(Y,X)});function gG(Y){return MG(PU,Y)}var MU=F("ZodISOTime",(Y,X)=>{q7.init(Y,X),a.init(Y,X)});function yG(Y){return wG(MU,Y)}var wU=F("ZodISODuration",(Y,X)=>{F7.init(Y,X),a.init(Y,X)});function fG(Y){return EG(wU,Y)}var mG=(Y,X)=>{mY.init(Y,X),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(J)=>r6(Y,J)},flatten:{value:(J)=>o6(Y,J)},addIssue:{value:(J)=>{Y.issues.push(J),Y.message=JSON.stringify(Y.issues,c1,2)}},addIssues:{value:(J)=>{Y.issues.push(...J),Y.message=JSON.stringify(Y.issues,c1,2)}},isEmpty:{get(){return Y.issues.length===0}}})},R4=F("ZodError",mG),R0=F("ZodError",mG,{Parent:Error});var cG=cY(R0),uG=uY(R0),pG=$Y(R0),Y8=WY(R0),lG=t6(R0),dG=e6(R0),iG=YQ(R0),nG=XQ(R0),oG=JQ(R0),rG=QQ(R0),sG=GQ(R0),aG=$Q(R0);var t=F("ZodType",(Y,X)=>{return o.init(Y,X),Y.def=X,Y.type=X.type,Object.defineProperty(Y,"_def",{value:X}),Y.check=(...J)=>{return Y.clone({...X,checks:[...X.checks??[],...J.map((Q)=>typeof Q==="function"?{_zod:{check:Q,def:{check:"custom"},onattach:[]}}:Q)]})},Y.clone=(J,Q)=>b0(Y,J,Q),Y.brand=()=>Y,Y.register=(J,Q)=>{return J.add(Y,Q),Y},Y.parse=(J,Q)=>cG(Y,J,Q,{callee:Y.parse}),Y.safeParse=(J,Q)=>pG(Y,J,Q),Y.parseAsync=async(J,Q)=>uG(Y,J,Q,{callee:Y.parseAsync}),Y.safeParseAsync=async(J,Q)=>Y8(Y,J,Q),Y.spa=Y.safeParseAsync,Y.encode=(J,Q)=>lG(Y,J,Q),Y.decode=(J,Q)=>dG(Y,J,Q),Y.encodeAsync=async(J,Q)=>iG(Y,J,Q),Y.decodeAsync=async(J,Q)=>nG(Y,J,Q),Y.safeEncode=(J,Q)=>oG(Y,J,Q),Y.safeDecode=(J,Q)=>rG(Y,J,Q),Y.safeEncodeAsync=async(J,Q)=>sG(Y,J,Q),Y.safeDecodeAsync=async(J,Q)=>aG(Y,J,Q),Y.refine=(J,Q)=>Y.check(OH(J,Q)),Y.superRefine=(J)=>Y.check(qH(J)),Y.overwrite=(J)=>Y.check(R1(J)),Y.optional=()=>Y$(Y),Y.nullable=()=>X$(Y),Y.nullish=()=>Y$(X$(Y)),Y.nonoptional=(J)=>HH(Y,J),Y.array=()=>I9(Y),Y.or=(J)=>S9([Y,J]),Y.and=(J)=>eU(Y,J),Y.transform=(J)=>J$(Y,QH(J)),Y.default=(J)=>WH(Y,J),Y.prefault=(J)=>UH(Y,J),Y.catch=(J)=>VH(Y,J),Y.pipe=(J)=>J$(Y,J),Y.readonly=()=>ZH(Y),Y.describe=(J)=>{let Q=Y.clone();return T1.add(Q,{description:J}),Q},Object.defineProperty(Y,"description",{get(){return T1.get(Y)?.description},configurable:!0}),Y.meta=(...J)=>{if(J.length===0)return T1.get(Y);let Q=Y.clone();return T1.add(Q,J[0]),Q},Y.isOptional=()=>Y.safeParse(void 0).success,Y.isNullable=()=>Y.safeParse(null).success,Y}),Q$=F("_ZodString",(Y,X)=>{iY.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(q9(...Q)),Y.includes=(...Q)=>Y.check(D9(...Q)),Y.startsWith=(...Q)=>Y.check(P9(...Q)),Y.endsWith=(...Q)=>Y.check(M9(...Q)),Y.min=(...Q)=>Y.check(l1(...Q)),Y.max=(...Q)=>Y.check(aY(...Q)),Y.length=(...Q)=>Y.check(tY(...Q)),Y.nonempty=(...Q)=>Y.check(l1(1,...Q)),Y.lowercase=(Q)=>Y.check(F9(Q)),Y.uppercase=(Q)=>Y.check(j9(Q)),Y.trim=()=>Y.check(E9()),Y.normalize=(...Q)=>Y.check(w9(...Q)),Y.toLowerCase=()=>Y.check(A9()),Y.toUpperCase=()=>Y.check(T9())}),RU=F("ZodString",(Y,X)=>{iY.init(Y,X),Q$.init(Y,X),Y.email=(J)=>Y.check(YG(CU,J)),Y.url=(J)=>Y.check($G(_U,J)),Y.jwt=(J)=>Y.check(DG(lU,J)),Y.emoji=(J)=>Y.check(WG(IU,J)),Y.guid=(J)=>Y.check(O9(tG,J)),Y.uuid=(J)=>Y.check(XG(X8,J)),Y.uuidv4=(J)=>Y.check(JG(X8,J)),Y.uuidv6=(J)=>Y.check(QG(X8,J)),Y.uuidv7=(J)=>Y.check(GG(X8,J)),Y.nanoid=(J)=>Y.check(zG(SU,J)),Y.guid=(J)=>Y.check(O9(tG,J)),Y.cuid=(J)=>Y.check(UG(kU,J)),Y.cuid2=(J)=>Y.check(HG(bU,J)),Y.ulid=(J)=>Y.check(LG(xU,J)),Y.base64=(J)=>Y.check(qG(cU,J)),Y.base64url=(J)=>Y.check(FG(uU,J)),Y.xid=(J)=>Y.check(VG(vU,J)),Y.ksuid=(J)=>Y.check(NG(hU,J)),Y.ipv4=(J)=>Y.check(BG(gU,J)),Y.ipv6=(J)=>Y.check(ZG(yU,J)),Y.cidrv4=(J)=>Y.check(KG(fU,J)),Y.cidrv6=(J)=>Y.check(OG(mU,J)),Y.e164=(J)=>Y.check(jG(pU,J)),Y.datetime=(J)=>Y.check(hG(J)),Y.date=(J)=>Y.check(gG(J)),Y.time=(J)=>Y.check(yG(J)),Y.duration=(J)=>Y.check(fG(J))});function G$(Y){return e7(RU,Y)}var a=F("ZodStringFormat",(Y,X)=>{s.init(Y,X),Q$.init(Y,X)}),CU=F("ZodEmail",(Y,X)=>{W7.init(Y,X),a.init(Y,X)});var tG=F("ZodGUID",(Y,X)=>{G7.init(Y,X),a.init(Y,X)});var X8=F("ZodUUID",(Y,X)=>{$7.init(Y,X),a.init(Y,X)});var _U=F("ZodURL",(Y,X)=>{z7.init(Y,X),a.init(Y,X)});var IU=F("ZodEmoji",(Y,X)=>{U7.init(Y,X),a.init(Y,X)});var SU=F("ZodNanoID",(Y,X)=>{H7.init(Y,X),a.init(Y,X)});var kU=F("ZodCUID",(Y,X)=>{L7.init(Y,X),a.init(Y,X)});var bU=F("ZodCUID2",(Y,X)=>{V7.init(Y,X),a.init(Y,X)});var xU=F("ZodULID",(Y,X)=>{N7.init(Y,X),a.init(Y,X)});var vU=F("ZodXID",(Y,X)=>{B7.init(Y,X),a.init(Y,X)});var hU=F("ZodKSUID",(Y,X)=>{Z7.init(Y,X),a.init(Y,X)});var gU=F("ZodIPv4",(Y,X)=>{j7.init(Y,X),a.init(Y,X)});var yU=F("ZodIPv6",(Y,X)=>{D7.init(Y,X),a.init(Y,X)});var fU=F("ZodCIDRv4",(Y,X)=>{P7.init(Y,X),a.init(Y,X)});var mU=F("ZodCIDRv6",(Y,X)=>{M7.init(Y,X),a.init(Y,X)});var cU=F("ZodBase64",(Y,X)=>{E7.init(Y,X),a.init(Y,X)});var uU=F("ZodBase64URL",(Y,X)=>{A7.init(Y,X),a.init(Y,X)});var pU=F("ZodE164",(Y,X)=>{T7.init(Y,X),a.init(Y,X)});var lU=F("ZodJWT",(Y,X)=>{R7.init(Y,X),a.init(Y,X)});var $$=F("ZodNumber",(Y,X)=>{Z9.init(Y,X),t.init(Y,X),Y.gt=(Q,G)=>Y.check(rY(Q,G)),Y.gte=(Q,G)=>Y.check(HY(Q,G)),Y.min=(Q,G)=>Y.check(HY(Q,G)),Y.lt=(Q,G)=>Y.check(oY(Q,G)),Y.lte=(Q,G)=>Y.check(UY(Q,G)),Y.max=(Q,G)=>Y.check(UY(Q,G)),Y.int=(Q)=>Y.check(eG(Q)),Y.safe=(Q)=>Y.check(eG(Q)),Y.positive=(Q)=>Y.check(rY(0,Q)),Y.nonnegative=(Q)=>Y.check(HY(0,Q)),Y.negative=(Q)=>Y.check(oY(0,Q)),Y.nonpositive=(Q)=>Y.check(UY(0,Q)),Y.multipleOf=(Q,G)=>Y.check(sY(Q,G)),Y.step=(Q,G)=>Y.check(sY(Q,G)),Y.finite=()=>Y;let J=Y._zod.bag;Y.minValue=Math.max(J.minimum??Number.NEGATIVE_INFINITY,J.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Y.maxValue=Math.min(J.maximum??Number.POSITIVE_INFINITY,J.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Y.isInt=(J.format??"").includes("int")||Number.isSafeInteger(J.multipleOf??0.5),Y.isFinite=!0,Y.format=J.format??null});function W$(Y){return AG($$,Y)}var dU=F("ZodNumberFormat",(Y,X)=>{C7.init(Y,X),$$.init(Y,X)});function eG(Y){return TG(dU,Y)}var iU=F("ZodBoolean",(Y,X)=>{_7.init(Y,X),t.init(Y,X)});function z$(Y){return RG(iU,Y)}var nU=F("ZodNull",(Y,X)=>{I7.init(Y,X),t.init(Y,X)});function U$(Y){return CG(nU,Y)}var oU=F("ZodUnknown",(Y,X)=>{S7.init(Y,X),t.init(Y,X)});function LY(){return _G(oU)}var rU=F("ZodNever",(Y,X)=>{k7.init(Y,X),t.init(Y,X)});function _9(Y){return IG(rU,Y)}var sU=F("ZodArray",(Y,X)=>{b7.init(Y,X),t.init(Y,X),Y.element=X.element,Y.min=(J,Q)=>Y.check(l1(J,Q)),Y.nonempty=(J)=>Y.check(l1(1,J)),Y.max=(J,Q)=>Y.check(aY(J,Q)),Y.length=(J,Q)=>Y.check(tY(J,Q)),Y.unwrap=()=>Y.element});function I9(Y,X){return SG(sU,Y,X)}var H$=F("ZodObject",(Y,X)=>{h7.init(Y,X),t.init(Y,X),c.defineLazy(Y,"shape",()=>X.shape),Y.keyof=()=>k9(Object.keys(Y._zod.def.shape)),Y.catchall=(J)=>Y.clone({...Y._zod.def,catchall:J}),Y.passthrough=()=>Y.clone({...Y._zod.def,catchall:LY()}),Y.loose=()=>Y.clone({...Y._zod.def,catchall:LY()}),Y.strict=()=>Y.clone({...Y._zod.def,catchall:_9()}),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(O$,Y,J[0]),Y.required=(...J)=>c.required(q$,Y,J[0])});function L$(Y,X){let J={type:"object",get shape(){return c.assignProp(this,"shape",Y?c.objectClone(Y):{}),this.shape},...c.normalizeParams(X)};return new H$(J)}function V$(Y,X){return new H$({type:"object",get shape(){return c.assignProp(this,"shape",c.objectClone(Y)),this.shape},catchall:LY(),...c.normalizeParams(X)})}var N$=F("ZodUnion",(Y,X)=>{K9.init(Y,X),t.init(Y,X),Y.options=X.options});function S9(Y,X){return new N$({type:"union",options:Y,...c.normalizeParams(X)})}var aU=F("ZodDiscriminatedUnion",(Y,X)=>{N$.init(Y,X),g7.init(Y,X)});function B$(Y,X,J){return new aU({type:"union",options:X,discriminator:Y,...c.normalizeParams(J)})}var tU=F("ZodIntersection",(Y,X)=>{y7.init(Y,X),t.init(Y,X)});function eU(Y,X){return new tU({type:"intersection",left:Y,right:X})}var YH=F("ZodRecord",(Y,X)=>{f7.init(Y,X),t.init(Y,X),Y.keyType=X.keyType,Y.valueType=X.valueType});function Z$(Y,X,J){return new YH({type:"record",keyType:Y,valueType:X,...c.normalizeParams(J)})}var C9=F("ZodEnum",(Y,X)=>{m7.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,G)=>{let $={};for(let W of Q)if(J.has(W))$[W]=X.entries[W];else throw Error(`Key ${W} not found in enum`);return new C9({...X,checks:[],...c.normalizeParams(G),entries:$})},Y.exclude=(Q,G)=>{let $={...X.entries};for(let W of Q)if(J.has(W))delete $[W];else throw Error(`Key ${W} not found in enum`);return new C9({...X,checks:[],...c.normalizeParams(G),entries:$})}});function k9(Y,X){let J=Array.isArray(Y)?Object.fromEntries(Y.map((Q)=>[Q,Q])):Y;return new C9({type:"enum",entries:J,...c.normalizeParams(X)})}var XH=F("ZodLiteral",(Y,X)=>{c7.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 K$(Y,X){return new XH({type:"literal",values:Array.isArray(Y)?Y:[Y],...c.normalizeParams(X)})}var JH=F("ZodTransform",(Y,X)=>{u7.init(Y,X),t.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new e1(Y.constructor.name);J.addIssue=($)=>{if(typeof $==="string")J.issues.push(c.issue($,J.value,X));else{let W=$;if(W.fatal)W.continue=!1;W.code??(W.code="custom"),W.input??(W.input=J.value),W.inst??(W.inst=Y),J.issues.push(c.issue(W))}};let G=X.transform(J.value,J);if(G instanceof Promise)return G.then(($)=>{return J.value=$,J});return J.value=G,J}});function QH(Y){return new JH({type:"transform",transform:Y})}var O$=F("ZodOptional",(Y,X)=>{p7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function Y$(Y){return new O$({type:"optional",innerType:Y})}var GH=F("ZodNullable",(Y,X)=>{l7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function X$(Y){return new GH({type:"nullable",innerType:Y})}var $H=F("ZodDefault",(Y,X)=>{d7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function WH(Y,X){return new $H({type:"default",innerType:Y,get defaultValue(){return typeof X==="function"?X():c.shallowClone(X)}})}var zH=F("ZodPrefault",(Y,X)=>{i7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function UH(Y,X){return new zH({type:"prefault",innerType:Y,get defaultValue(){return typeof X==="function"?X():c.shallowClone(X)}})}var q$=F("ZodNonOptional",(Y,X)=>{n7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function HH(Y,X){return new q$({type:"nonoptional",innerType:Y,...c.normalizeParams(X)})}var LH=F("ZodCatch",(Y,X)=>{o7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function VH(Y,X){return new LH({type:"catch",innerType:Y,catchValue:typeof X==="function"?X:()=>X})}var NH=F("ZodPipe",(Y,X)=>{r7.init(Y,X),t.init(Y,X),Y.in=X.in,Y.out=X.out});function J$(Y,X){return new NH({type:"pipe",in:Y,out:X})}var BH=F("ZodReadonly",(Y,X)=>{s7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function ZH(Y){return new BH({type:"readonly",innerType:Y})}var KH=F("ZodLazy",(Y,X)=>{a7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.getter()});function F$(Y){return new KH({type:"lazy",getter:Y})}var b9=F("ZodCustom",(Y,X)=>{t7.init(Y,X),t.init(Y,X)});function j$(Y,X){return kG(b9,Y??(()=>!0),X)}function OH(Y,X={}){return bG(b9,Y,X)}function qH(Y){return xG(Y)}function D$(Y,X={error:`Input not instance of ${Y.name}`}){let J=new b9({type:"custom",check:"custom",fn:(Q)=>Q instanceof Y,abort:!0,...c.normalizeParams(X)});return J._zod.bag.Class=Y,J}var FH=[{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]}],ZO=[...FH,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];var jH=12,DH=131072,KO=DH+jH;async function J8(Y){var X;try{await((X=Y.body)==null?void 0:X.cancel())}catch(J){}}var I$="AI_DownloadError",S$=`vercel.ai.error.${I$}`,PH=Symbol.for(S$),P$,M$,j0=class extends(M$=m,P$=PH,M$){constructor({url:Y,statusCode:X,statusText:J,cause:Q,message:G=Q==null?`Failed to download ${Y}: ${X} ${J}`:`Failed to download ${Y}: ${Q}`}){super({name:I$,message:G,cause:Q});this[P$]=!0,this.url=Y,this.statusCode=X,this.statusText=J}static isInstance(Y){return m.hasMarker(Y,S$)}};function MH(Y=globalThis){return Y.window!=null}function w$(Y,X){try{return new URL(Y).origin===new URL(X).origin}catch(J){return!1}}function wH(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(k$(Q))throw new j0({url:Y,message:`URL with IPv6 address ${J} is not allowed`});return}if(f9(J)){if(m9(J))throw new j0({url:Y,message:`URL with IP address ${J} is not allowed`});return}}function EH({address:Y,family:X,hostname:J}){if(X===4?!f9(Y)||m9(Y):X===6?k$(Y):!0)throw new j0({url:J,message:`Hostname ${J} resolved to disallowed IP address ${Y}`})}function f9(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 m9(Y){let X=Y.split(".").map(Number),[J,Q,G]=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&&G===0)return!0;if(J===192&&Q===0&&G===2)return!0;if(J===192&&Q===168)return!0;if(J===198&&(Q===18||Q===19))return!0;if(J===198&&Q===51&&G===100)return!0;if(J===203&&Q===0&&G===113)return!0;if(J>=224)return!0;return!1}function AH(Y){let X=Y.toLowerCase(),J=X.indexOf("%");if(J!==-1)X=X.slice(0,J);let Q=X.split("::");if(Q.length>2)return null;let G=(W)=>{if(W==="")return[];let z=[],L=W.split(":");for(let H=0;H<L.length;H++){let N=L[H];if(N.includes(".")){if(H!==L.length-1||!f9(N))return null;let[O,Z,V,K]=N.split(".").map(Number);z.push(O<<8|Z,V<<8|K);continue}if(!/^[0-9a-f]{1,4}$/.test(N))return null;z.push(parseInt(N,16))}return z},$=G(Q[0]);if($===null)return null;if(Q.length===2){let W=G(Q[1]);if(W===null)return null;let z=8-$.length-W.length;if(z<0)return null;return[...$,...Array(z).fill(0),...W]}return $.length===8?$:null}function k$(Y){let X=AH(Y);if(X===null)return!0;let J=(G)=>X.slice(0,G).every(($)=>$===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 G=X[6]>>8&255,$=X[6]&255,W=X[7]>>8&255,z=X[7]&255;return m9(`${G}.${$}.${W}.${z}`)}return!1}function TH(Y){return(X,J,Q)=>{Y(X,{...J,all:!0},(G,$)=>{if(G){Q(G);return}try{let[W]=$;if(W==null)throw Error(`Hostname ${X} did not resolve to an address`);for(let{address:z,family:L}of $)EH({address:z,family:L,hostname:X});if(J.all===!0)Q(null,$);else Q(null,W.address,W.family)}catch(W){Q(W instanceof Error?W:Error(String(W)))}})}}var x9,b$=globalThis.fetch,RH=IH(b$);function CH(){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 _H(){if(!CH()||!RH||globalThis.fetch!==b$)return globalThis.fetch;return x9!=null?x9:x9=Promise.resolve().then(SH)}function IH(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 SH(){let{createRequire:Y}=E$("node:module"),{lookup:X}=E$("node:dns"),{Agent:J,fetch:Q}=Y(x$())("undici"),G=new J({connect:{lookup:TH(X)}});return($,W)=>Q($,{...W,dispatcher:G})}function E$(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 x$(){let Y=Error.prepareStackTrace;try{Error.prepareStackTrace=(G,$)=>$;let X=Error("Capture current module path");Error.captureStackTrace(X,x$);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 kH=["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 bH(Y){let X=new Headers(Y);for(let J of kH)X.delete(J);return X}var xH=10,vH=new Set([301,302,303,307,308]);async function v$({url:Y,headers:X,abortSignal:J,maxRedirects:Q=xH,fetch:G,trustedOrigin:$}){let W=X===void 0?void 0:bH(X),z=(H)=>{let N={signal:J,redirect:H};if(W!==void 0)N.headers=new Headers(W);return N},L=Y;for(let H=0;H<=Q;H++){let N=$!==void 0&&w$(L,$);if(!N)wH(L);let O=G!=null?G:N?globalThis.fetch:await _H(),Z=await O(L,z("manual"));if(Z.type==="opaqueredirect"){if(!MH())throw new j0({url:Y,message:`Redirect from ${L} could not be validated and was blocked`});return await O(L,z("follow"))}let V=Z.headers.get("location");if(vH.has(Z.status)&&V){await J8(Z);let K=new URL(V,L).toString();if(W!==void 0&&!w$(K,L)){let j=W.get("user-agent");W=new Headers(j==null?void 0:{"user-agent":j})}L=K;continue}return Z}throw new j0({url:Y,message:`Too many redirects (max ${Q})`})}var c9=2147483648;async function h$({response:Y,url:X,maxBytes:J=c9}){let Q=Y.headers.get("content-length");if(Q!=null){let N=parseInt(Q,10);if(!isNaN(N)&&N>J)throw await J8(Y),new j0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes (Content-Length: ${N}).`})}let G=Y.body;if(G==null)return new Uint8Array(0);let $=G.getReader(),W=[],z=0;try{while(!0){let{done:N,value:O}=await $.read();if(N)break;if(z+=O.length,z>J)throw new j0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes.`});W.push(O)}}finally{try{await $.cancel()}catch(N){}finally{$.releaseLock()}}let L=new Uint8Array(z),H=0;for(let N of W)L.set(N,H),H+=N.length;return L}var W0=({prefix:Y,size:X=16,alphabet:J="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:Q="-"}={})=>{let G=()=>{let $=J.length,W=Array(X);for(let z=0;z<X;z++)W[z]=J[Math.random()*$|0];return W.join("")};if(Y==null)return G;if(J.includes(Q))throw new K6({argument:"separator",message:`The separator "${Q}" must not be part of the alphabet "${J}".`});return()=>`${Y}${Q}${G()}`},FO=W0();function g$(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 hH(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 d1(Y,...X){let J=new Headers(hH(Y)),Q=J.get("user-agent")||"";return J.set("user-agent",[Q,...X].filter(Boolean).join(" ")),Object.fromEntries(J.entries())}function y$(Y){var X,J;return(J=(X=globalThis.Buffer)==null?void 0:X.isBuffer(Y))!=null?J:!1}var gH=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,yH=/"(?: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 A$(Y){let X=JSON.parse(Y);if(X===null||typeof X!=="object")return X;if(gH.test(Y)===!1&&yH.test(Y)===!1)return X;return fH(X)}function fH(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 G in Q){let $=Q[G];if($&&typeof $==="object")X.push($)}}}return Y}function mH(Y){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(J){return A$(Y)}try{return A$(Y)}finally{Error.stackTraceLimit=X}}function u9(Y){if(Y.type==="object"||Array.isArray(Y.type)&&Y.type.includes("object")){Y.additionalProperties=!1;let{properties:J}=Y;if(J!=null)for(let Q of Object.keys(J))J[Q]=C1(J[Q])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(C1):C1(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(C1);if(Y.allOf!=null)Y.allOf=Y.allOf.map(C1);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(C1);let{definitions:X}=Y;if(X!=null)for(let J of Object.keys(X))X[J]=C1(X[J]);return Y}function C1(Y){if(typeof Y==="boolean")return Y;return u9(Y)}var cH=Symbol("Let zodToJsonSchema decide on which parser to use"),T$={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"},uH=(Y)=>typeof Y==="string"?{...T$,name:Y}:{...T$,...Y};function C0(){return{}}function pH(Y,X){var J,Q,G;let $={type:"array"};if(((J=Y.type)==null?void 0:J._def)&&((G=(Q=Y.type)==null?void 0:Q._def)==null?void 0:G.typeName)!=="ZodAny")$.items=n(Y.type._def,{...X,currentPath:[...X.currentPath,"items"]});if(Y.minLength)$.minItems=Y.minLength.value;if(Y.maxLength)$.maxItems=Y.maxLength.value;if(Y.exactLength)$.minItems=Y.exactLength.value,$.maxItems=Y.exactLength.value;return $}function lH(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 dH(){return{type:"boolean"}}function f$(Y,X){return n(Y.type._def,X)}var iH=(Y,X)=>{return n(Y.innerType._def,X)};function m$(Y,X,J){let Q=J!=null?J:X.dateStrategy;if(Array.isArray(Q))return{anyOf:Q.map((G)=>m$(Y,X,G))};switch(Q){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return nH(Y)}}var nH=(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 oH(Y,X){return{...n(Y.innerType._def,X),default:Y.defaultValue()}}function rH(Y,X){return X.effectStrategy==="input"?n(Y.schema._def,X):C0()}function sH(Y){return{type:"string",enum:Array.from(Y.values)}}var aH=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function tH(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((G)=>!!G),Q=[];return J.forEach((G)=>{if(aH(G))Q.push(...G.allOf);else{let $=G;if("additionalProperties"in G&&G.additionalProperties===!1){let{additionalProperties:W,...z}=G;$=z}Q.push($)}}),Q.length?{allOf:Q}:void 0}function eH(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 v9=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(v9===void 0)v9=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return v9},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 c$(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":F0(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":F0(J,Q.regex,Q.message,X);break;case"cuid":F0(J,v0.cuid,Q.message,X);break;case"cuid2":F0(J,v0.cuid2,Q.message,X);break;case"startsWith":F0(J,RegExp(`^${h9(Q.value,X)}`),Q.message,X);break;case"endsWith":F0(J,RegExp(`${h9(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":{F0(J,RegExp(h9(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":F0(J,v0.base64url,Q.message,X);break;case"jwt":F0(J,v0.jwt,Q.message,X);break;case"cidr":{if(Q.version!=="v6")F0(J,v0.ipv4Cidr,Q.message,X);if(Q.version!=="v4")F0(J,v0.ipv6Cidr,Q.message,X);break}case"emoji":F0(J,v0.emoji(),Q.message,X);break;case"ulid":{F0(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":{F0(J,v0.base64,Q.message,X);break}}break}case"nanoid":F0(J,v0.nanoid,Q.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return J}function h9(Y,X){return X.patternStrategy==="escape"?XL(Y):Y}var YL=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function XL(Y){let X="";for(let J=0;J<Y.length;J++){if(!YL.has(Y[J]))X+="\\";X+=Y[J]}return X}function h0(Y,X,J,Q){var G;if(Y.format||((G=Y.anyOf)==null?void 0:G.some(($)=>$.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 F0(Y,X,J,Q){var G;if(Y.pattern||((G=Y.allOf)==null?void 0:G.some(($)=>$.pattern))){if(!Y.allOf)Y.allOf=[];if(Y.pattern)Y.allOf.push({pattern:Y.pattern}),delete Y.pattern;Y.allOf.push({pattern:R$(X,Q),...J&&Q.errorMessages&&{errorMessage:{pattern:J}}})}else Y.pattern=R$(X,Q)}function R$(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")},G=Q.i?Y.source.toLowerCase():Y.source,$="",W=!1,z=!1,L=!1;for(let H=0;H<G.length;H++){if(W){$+=G[H],W=!1;continue}if(Q.i){if(z){if(G[H].match(/[a-z]/)){if(L)$+=G[H],$+=`${G[H-2]}-${G[H]}`.toUpperCase(),L=!1;else if(G[H+1]==="-"&&((J=G[H+2])==null?void 0:J.match(/[a-z]/)))$+=G[H],L=!0;else $+=`${G[H]}${G[H].toUpperCase()}`;continue}}else if(G[H].match(/[a-z]/)){$+=`[${G[H]}${G[H].toUpperCase()}]`;continue}}if(Q.m){if(G[H]==="^"){$+=`(^|(?<=[\r
188
+ ]))`;continue}else if(G[H]==="$"){$+=`($|(?=[\r
189
+ ]))`;continue}}if(Q.s&&G[H]==="."){$+=z?`${G[H]}\r
190
+ `:`[${G[H]}\r
191
+ ]`;continue}if($+=G[H],G[H]==="\\")W=!0;else if(z&&G[H]==="]")z=!1;else if(!z&&G[H]==="[")z=!0}try{new RegExp($)}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 $}function u$(Y,X){var J,Q,G,$,W,z;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"&&((G=Y.keyType._def.checks)==null?void 0:G.length)){let{type:H,...N}=c$(Y.keyType._def,X);return{...L,propertyNames:N}}else if((($=Y.keyType)==null?void 0:$._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"&&((z=Y.keyType._def.type._def.checks)==null?void 0:z.length)){let{type:H,...N}=f$(Y.keyType._def,X);return{...L,propertyNames:N}}return L}function JL(Y,X){if(X.mapStrategy==="record")return u$(Y,X);let J=n(Y.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||C0(),Q=n(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||C0();return{type:"array",maxItems:125,items:{type:"array",items:[J,Q],minItems:2,maxItems:2}}}function QL(Y){let X=Y.values,Q=Object.keys(Y.values).filter(($)=>{return typeof X[X[$]]!=="number"}).map(($)=>X[$]),G=Array.from(new Set(Q.map(($)=>typeof $)));return{type:G.length===1?G[0]==="string"?"string":"number":["string","number"],enum:Q}}function GL(){return{not:C0()}}function $L(){return{type:"null"}}var g9={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function WL(Y,X){let J=Y.options instanceof Map?Array.from(Y.options.values()):Y.options;if(J.every((Q)=>(Q._def.typeName in g9)&&(!Q._def.checks||!Q._def.checks.length))){let Q=J.reduce((G,$)=>{let W=g9[$._def.typeName];return W&&!G.includes(W)?[...G,W]:G},[]);return{type:Q.length>1?Q:Q[0]}}else if(J.every((Q)=>Q._def.typeName==="ZodLiteral"&&!Q.description)){let Q=J.reduce((G,$)=>{let W=typeof $._def.value;switch(W){case"string":case"number":case"boolean":return[...G,W];case"bigint":return[...G,"integer"];case"object":if($._def.value===null)return[...G,"null"];case"symbol":case"undefined":case"function":default:return G}},[]);if(Q.length===J.length){let G=Q.filter(($,W,z)=>z.indexOf($)===W);return{type:G.length>1?G:G[0],enum:J.reduce(($,W)=>{return $.includes(W._def.value)?$:[...$,W._def.value]},[])}}}else if(J.every((Q)=>Q._def.typeName==="ZodEnum"))return{type:"string",enum:J.reduce((Q,G)=>[...Q,...G._def.values.filter(($)=>!Q.includes($))],[])};return zL(Y,X)}var zL=(Y,X)=>{let J=(Y.options instanceof Map?Array.from(Y.options.values()):Y.options).map((Q,G)=>n(Q._def,{...X,currentPath:[...X.currentPath,"anyOf",`${G}`]})).filter((Q)=>!!Q&&(!X.strictUnions||typeof Q==="object"&&Object.keys(Q).length>0));return J.length?{anyOf:J}:void 0};function UL(Y,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Y.innerType._def.typeName)&&(!Y.innerType._def.checks||!Y.innerType._def.checks.length))return{type:[g9[Y.innerType._def.typeName],"null"]};let J=n(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return J&&{anyOf:[J,{type:"null"}]}}function HL(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 LL(Y,X){let J={type:"object",properties:{}},Q=[],G=Y.shape();for(let W in G){let z=G[W];if(z===void 0||z._def===void 0)continue;let L=NL(z),H=n(z._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 $=VL(Y,X);if($!==void 0)J.additionalProperties=$;return J}function VL(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 NL(Y){try{return Y.isOptional()}catch(X){return!0}}var BL=(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:C0()},Q]}:C0()},ZL=(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((G)=>G!==void 0)}};function KL(Y,X){return n(Y.type._def,X)}function OL(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 qL(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 FL(){return{not:C0()}}function jL(){return C0()}var DL=(Y,X)=>{return n(Y.innerType._def,X)},PL=(Y,X,J)=>{switch(X){case"ZodString":return c$(Y,J);case"ZodNumber":return HL(Y);case"ZodObject":return LL(Y,J);case"ZodBigInt":return lH(Y);case"ZodBoolean":return dH();case"ZodDate":return m$(Y,J);case"ZodUndefined":return FL();case"ZodNull":return $L();case"ZodArray":return pH(Y,J);case"ZodUnion":case"ZodDiscriminatedUnion":return WL(Y,J);case"ZodIntersection":return tH(Y,J);case"ZodTuple":return qL(Y,J);case"ZodRecord":return u$(Y,J);case"ZodLiteral":return eH(Y);case"ZodEnum":return sH(Y);case"ZodNativeEnum":return QL(Y);case"ZodNullable":return UL(Y,J);case"ZodOptional":return BL(Y,J);case"ZodMap":return JL(Y,J);case"ZodSet":return OL(Y,J);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return KL(Y,J);case"ZodNaN":case"ZodNever":return GL();case"ZodEffects":return rH(Y,J);case"ZodAny":return C0();case"ZodUnknown":return jL();case"ZodDefault":return oH(Y,J);case"ZodBranded":return f$(Y,J);case"ZodReadonly":return DL(Y,J);case"ZodCatch":return iH(Y,J);case"ZodPipeline":return ZL(Y,J);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Q)=>{return})(X)}},ML=(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 G=X.seen.get(Y);if(X.override){let L=(Q=X.override)==null?void 0:Q.call(X,Y,X,G,J);if(L!==cH)return L}if(G&&!J){let L=wL(G,X);if(L!==void 0)return L}let $={def:Y,path:X.currentPath,jsonSchema:void 0};X.seen.set(Y,$);let W=PL(Y,Y.typeName,X),z=typeof W==="function"?n(W(),X):W;if(z)EL(Y,X,z);if(X.postProcess){let L=X.postProcess(z,Y,X);return $.jsonSchema=z,L}return $.jsonSchema=z,z}var wL=(Y,X)=>{switch(X.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:ML(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`),C0();return X.$refStrategy==="seen"?C0():void 0}}},EL=(Y,X,J)=>{if(Y.description)J.description=Y.description;return J},AL=(Y)=>{let X=uH(Y),J=X.name!==void 0?[...X.basePath,X.definitionPath,X.name]:X.basePath;return{...X,currentPath:J,propertyPath:void 0,seen:new Map(Object.entries(X.definitions).map(([Q,G])=>[G._def,{def:G._def,path:[...X.basePath,X.definitionPath,Q],jsonSchema:void 0}]))}},TL=(Y,X)=>{var J;let Q=AL(X),G=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((H,[N,O])=>{var Z;return{...H,[N]:(Z=n(O._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,N]},!0))!=null?Z:C0()}},{}):void 0,$=typeof X==="string"?X:(X==null?void 0:X.nameStrategy)==="title"?void 0:X==null?void 0:X.name,W=(J=n(Y._def,$===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,$]},!1))!=null?J:C0(),z=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if(z!==void 0)W.title=z;let L=$===void 0?G?{...W,[Q.definitionPath]:G}:W:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,$].join("/"),[Q.definitionPath]:{...G,[$]:W}};return L.$schema="http://json-schema.org/draft-07/schema#",L},y9=Symbol.for("vercel.ai.schema");function Q8(Y){let X;return()=>{if(X==null)X=Y();return X}}function G8(Y,{validate:X}={}){return{[y9]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:X}}function RL(Y){return typeof Y==="object"&&Y!==null&&y9 in Y&&Y[y9]===!0&&"jsonSchema"in Y&&"validate"in Y}function $8(Y){return Y==null?G8({type:"object",properties:{},additionalProperties:!1}):RL(Y)?Y:("~standard"in Y)?Y["~standard"].vendor==="zod"?VY(Y):CL(Y):Y()}function CL(Y){return G8(()=>{if(!_L(Y))throw Error(`Standard schema vendor '${Y["~standard"].vendor}' does not support JSON Schema conversion.`);return u9(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 _L(Y){return Y["~standard"].jsonSchema!=null}function IL(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return G8(()=>TL(Y,{$refStrategy:Q?"root":"none"}),{validate:async(G)=>{let $=await Y.safeParseAsync(G);return $.success?{success:!0,value:$.data}:{success:!1,error:$.error}}})}function SL(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return G8(()=>u9(vG(Y,{target:"draft-7",io:"input",reused:Q?"ref":"inline"})),{validate:async(G)=>{let $=await Y8(Y,G);return $.success?{success:!0,value:$.data}:{success:!1,error:$.error}}})}function kL(Y){return"_zod"in Y}function VY(Y,X){if(kL(Y))return SL(Y,X);else return IL(Y,X)}async function NY({value:Y,schema:X,context:J}){let Q=$8(X);try{if(Q.validate==null)return{success:!0,value:Y,rawValue:Y};let G=await Q.validate(Y);if(G.success)return{success:!0,value:G.value,rawValue:Y};return{success:!1,error:p0.wrap({value:Y,cause:G.error,context:J}),rawValue:Y}}catch(G){return{success:!1,error:p0.wrap({value:Y,cause:G,context:J}),rawValue:Y}}}async function Z1({text:Y,schema:X}){try{let J=mH(Y);if(X==null)return{success:!0,value:J,rawValue:J};return await NY({value:J,schema:X})}catch(J){return{success:!1,error:hY.isInstance(J)?J:new hY({text:Y,cause:J}),rawValue:void 0}}}async function p9(Y){if(typeof Y==="function")Y=Y();return Promise.resolve(Y)}var p$="AI_SerializationError",l$=`vercel.ai.error.${p$}`,bL=Symbol.for(l$),C$,_$,AO=class extends(_$=m,C$=bL,_$){constructor({message:Y="Failed to serialize value.",cause:X}={}){super({name:p$,message:Y,cause:X});this[C$]=!0}static isInstance(Y){return m.hasMarker(Y,l$)}};var hL=Object.defineProperty,gL=(Y,X)=>{for(var J in X)hL(Y,J,{get:X[J],enumerable:!0})},yL="AI_InvalidArgumentError",fL=`vercel.ai.error.${yL}`,mL=Symbol.for(fL),cL;cL=mL;var uL="AI_InvalidStreamPartError",pL=`vercel.ai.error.${uL}`,lL=Symbol.for(pL),dL;dL=lL;var iL="AI_InvalidToolApprovalError",nL=`vercel.ai.error.${iL}`,oL=Symbol.for(nL),rL;rL=oL;var sL="AI_InvalidToolApprovalSignatureError",aL=`vercel.ai.error.${sL}`,tL=Symbol.for(aL),eL;eL=tL;var YV="AI_InvalidToolInputError",XV=`vercel.ai.error.${YV}`,JV=Symbol.for(XV),QV;QV=JV;var GV="AI_ToolCallNotFoundForApprovalError",$V=`vercel.ai.error.${GV}`,WV=Symbol.for($V),zV;zV=WV;var UV="AI_MissingToolResultsError",HV=`vercel.ai.error.${UV}`,LV=Symbol.for(HV),VV;VV=LV;var NV="AI_NoImageGeneratedError",BV=`vercel.ai.error.${NV}`,ZV=Symbol.for(BV),KV;KV=ZV;var d$="AI_NoObjectGeneratedError",i$=`vercel.ai.error.${d$}`,OV=Symbol.for(i$),n$,K1=class extends m{constructor({message:Y="No object generated.",cause:X,text:J,response:Q,usage:G,finishReason:$}){super({name:d$,message:Y,cause:X});this[n$]=!0,this.text=J,this.response=Q,this.usage=G,this.finishReason=$}static isInstance(Y){return m.hasMarker(Y,i$)}};n$=OV;var qV="AI_NoOutputGeneratedError",FV=`vercel.ai.error.${qV}`,jV=Symbol.for(FV),DV;DV=jV;var PV="AI_NoSpeechGeneratedError",MV=`vercel.ai.error.${PV}`,wV=Symbol.for(MV),EV;EV=wV;var AV="AI_NoTranscriptGeneratedError",TV=`vercel.ai.error.${AV}`,RV=Symbol.for(TV),CV;CV=RV;var _V="AI_NoTranslationGeneratedError",IV=`vercel.ai.error.${_V}`,SV=Symbol.for(IV),kV;kV=SV;var bV="AI_NoVideoGeneratedError",xV=`vercel.ai.error.${bV}`,vV=Symbol.for(xV),hV;hV=vV;var gV="AI_NoSuchToolError",yV=`vercel.ai.error.${gV}`,fV=Symbol.for(yV),mV;mV=fV;var cV="AI_ToolCallRepairError",uV=`vercel.ai.error.${cV}`,pV=Symbol.for(uV),lV;lV=pV;var dV="AI_UIMessageStreamError",iV=`vercel.ai.error.${dV}`,nV=Symbol.for(iV),oV;oV=nV;var rV="AI_InvalidDataContentError",sV=`vercel.ai.error.${rV}`,aV=Symbol.for(sV),tV;tV=aV;var eV="AI_InvalidMessageRoleError",YN=`vercel.ai.error.${eV}`,XN=Symbol.for(YN),JN;JN=XN;var QN="AI_MessageConversionError",GN=`vercel.ai.error.${QN}`,$N=Symbol.for(GN),WN;WN=$N;var zN="AI_RetryError",UN=`vercel.ai.error.${zN}`,HN=Symbol.for(UN),LN;LN=HN;var VN="7.0.69",NN=async({url:Y,maxBytes:X,abortSignal:J})=>{var Q;let G=Y.toString();try{let $=d1({},`ai-sdk/${VN}`,g$()),W=await v$({url:G,headers:$,abortSignal:J});if(!W.ok)throw await J8(W),new j0({url:G,statusCode:W.status,statusText:W.statusText});return{data:await h$({response:W,url:G,maxBytes:X!=null?X:c9}),mediaType:(Q=W.headers.get("content-type"))!=null?Q:void 0}}catch($){if(j0.isInstance($))throw $;throw new j0({url:G,cause:$})}};var U={array:I9,boolean:z$,custom:j$,discriminatedUnion:B$,enum:k9,instanceof:D$,lazy:F$,literal:K$,looseObject:V$,never:_9,null:U$,number:W$,object:L$,record:Z$,string:G$,union:S9,unknown:LY},_1=U.lazy(()=>U.union([U.null(),U.string(),U.number(),U.boolean(),U.record(U.string(),_1.optional()),U.array(_1)])),A=U.record(U.string(),U.record(U.string(),_1.optional())),ZY=U.union([U.string(),U.instanceof(Uint8Array),U.instanceof(ArrayBuffer),U.custom(y$,{message:"Must be a Buffer"})]),l9=U.record(U.string(),U.string()),o$=U.object({type:U.literal("text"),text:U.string(),providerOptions:A.optional()}),BN=U.object({type:U.literal("image"),image:U.union([ZY,U.instanceof(URL),l9]),mediaType:U.string().optional(),providerOptions:A.optional()}),r$=U.discriminatedUnion("type",[U.object({type:U.literal("data"),data:ZY}),U.object({type:U.literal("url"),url:U.instanceof(URL)}),U.object({type:U.literal("reference"),reference:l9}),U.object({type:U.literal("text"),text:U.string()})]),ZN=U.discriminatedUnion("type",[U.object({type:U.literal("data"),data:ZY}),U.object({type:U.literal("url"),url:U.instanceof(URL)})]),s$=U.object({type:U.literal("file"),data:U.union([r$,ZY,U.instanceof(URL),l9]),filename:U.string().optional(),mediaType:U.string(),providerOptions:A.optional()}),KN=U.object({type:U.literal("reasoning"),text:U.string(),providerOptions:A.optional()}),ON=U.object({type:U.literal("custom"),kind:U.string().transform((Y)=>Y),providerOptions:A.optional()}),qN=U.object({type:U.literal("reasoning-file"),data:U.union([ZN,ZY,U.instanceof(URL)]),mediaType:U.string(),providerOptions:A.optional()}),FN=U.object({type:U.literal("tool-call"),toolCallId:U.string(),toolName:U.string(),input:U.unknown(),providerOptions:A.optional(),providerExecuted:U.boolean().optional()}),jN=U.discriminatedUnion("type",[U.object({type:U.literal("text"),value:U.string(),providerOptions:A.optional()}),U.object({type:U.literal("json"),value:_1,providerOptions:A.optional()}),U.object({type:U.literal("execution-denied"),reason:U.string().optional(),providerOptions:A.optional()}),U.object({type:U.literal("error-text"),value:U.string(),providerOptions:A.optional()}),U.object({type:U.literal("error-json"),value:_1,providerOptions:A.optional()}),U.object({type:U.literal("content"),value:U.array(U.union([U.object({type:U.literal("text"),text:U.string(),providerOptions:A.optional()}),U.object({type:U.literal("file"),data:r$,mediaType:U.string(),filename:U.string().optional(),providerOptions:A.optional()}),U.object({type:U.literal("file-data"),data:U.string(),mediaType:U.string(),filename:U.string().optional(),providerOptions:A.optional()}),U.object({type:U.literal("file-url"),url:U.string(),mediaType:U.string().optional(),providerOptions:A.optional()}),U.object({type:U.literal("file-id"),fileId:U.union([U.string(),U.record(U.string(),U.string())]),providerOptions:A.optional()}),U.object({type:U.literal("file-reference"),providerReference:U.record(U.string(),U.string()),providerOptions:A.optional()}),U.object({type:U.literal("image-data"),data:U.string(),mediaType:U.string(),providerOptions:A.optional()}),U.object({type:U.literal("image-url"),url:U.string(),providerOptions:A.optional()}),U.object({type:U.literal("image-file-id"),fileId:U.union([U.string(),U.record(U.string(),U.string())]),providerOptions:A.optional()}),U.object({type:U.literal("image-file-reference"),providerReference:U.record(U.string(),U.string()),providerOptions:A.optional()}),U.object({type:U.literal("custom"),providerOptions:A.optional()})]))})]),a$=U.object({type:U.literal("tool-result"),toolCallId:U.string(),toolName:U.string(),output:jN,providerOptions:A.optional()}),DN=U.object({type:U.literal("tool-approval-request"),approvalId:U.string(),toolCallId:U.string()}),PN=U.object({type:U.literal("tool-approval-response"),approvalId:U.string(),approved:U.boolean(),reason:U.string().optional()}),MN=U.object({role:U.literal("system"),content:U.string(),providerOptions:A.optional()}),wN=U.object({role:U.literal("user"),content:U.union([U.string(),U.array(U.union([o$,BN,s$]))]),providerOptions:A.optional()}),EN=U.object({role:U.literal("assistant"),content:U.union([U.string(),U.array(U.union([o$,ON,s$,KN,qN,FN,a$,DN]))]),providerOptions:A.optional()}),AN=U.object({role:U.literal("tool"),content:U.array(U.union([a$,PN])),providerOptions:A.optional()}),fO=U.union([MN,wN,EN,AN]);var TN={};gL(TN,{array:()=>IN,choice:()=>SN,json:()=>kN,object:()=>_N,text:()=>CN});function RN(Y){let X=["ROOT"],J=-1,Q=null,G=0;function $(N){return N>="0"&&N<="9"||N>="A"&&N<="F"||N>="a"&&N<="f"}function W(N,O,Z){switch(N){case'"':{J=O,X.pop(),X.push(Z),X.push("INSIDE_STRING");break}case"f":case"t":case"n":{J=O,Q=O,X.pop(),X.push(Z),X.push("INSIDE_LITERAL");break}case"-":{X.pop(),X.push(Z),X.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=O,X.pop(),X.push(Z),X.push("INSIDE_NUMBER");break}case"{":{J=O,X.pop(),X.push(Z),X.push("INSIDE_OBJECT_START");break}case"[":{J=O,X.pop(),X.push(Z),X.push("INSIDE_ARRAY_START");break}}}function z(N,O){switch(N){case",":{X.pop(),X.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{J=O,X.pop();break}}}function L(N,O){switch(N){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=O,X.pop();break}}}for(let N=0;N<Y.length;N++){let O=Y[N];switch(X[X.length-1]){case"ROOT":W(O,N,"FINISH");break;case"INSIDE_OBJECT_START":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}case"}":{J=N,X.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(O){case":":{X.pop(),X.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{W(O,N,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{z(O,N);break}case"INSIDE_STRING":{switch(O){case'"':{X.pop(),J=N;break}case"\\":{X.push("INSIDE_STRING_ESCAPE");break}default:J=N}break}case"INSIDE_ARRAY_START":{switch(O){case"]":{J=N,X.pop();break}default:{J=N,W(O,N,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(O){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=N,X.pop();break}default:{J=N;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{W(O,N,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{if(X.pop(),O==="u")G=0,X.push("INSIDE_STRING_UNICODE_ESCAPE");else J=N;break}case"INSIDE_STRING_UNICODE_ESCAPE":{if($(O)){if(G++,G===4)X.pop(),J=N}break}case"INSIDE_NUMBER":{switch(O){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=N;break}case"e":case"E":case"-":case".":break;case",":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")L(O,N);if(X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")z(O,N);break}case"}":{if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")z(O,N);break}case"]":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")L(O,N);break}default:{X.pop();break}}break}case"INSIDE_LITERAL":{let V=Y.substring(Q,N+1);if(!"false".startsWith(V)&&!"true".startsWith(V)&&!"null".startsWith(V)){if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")z(O,N);else if(X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")L(O,N)}else J=N;break}}}let H=Y.slice(0,J+1);for(let N=X.length-1;N>=0;N--)switch(X[N]){case"INSIDE_STRING":{H+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{H+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{H+="]";break}case"INSIDE_LITERAL":{let Z=Y.substring(Q,Y.length);if("true".startsWith(Z))H+="true".slice(Z.length);else if("false".startsWith(Z))H+="false".slice(Z.length);else if("null".startsWith(Z))H+="null".slice(Z.length)}}return H}async function W8(Y){if(Y===void 0)return{value:void 0,state:"undefined-input"};let X=await Z1({text:Y});if(X.success)return{value:X.value,state:"successful-parse"};if(X=await Z1({text:RN(Y)}),X.success)return{value:X.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var CN=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:Y}){return Y},async parsePartialOutput({text:Y}){return{partial:Y}},createElementStreamTransform(){return}}),_N=({schema:Y,name:X,description:J})=>{let Q=$8(Y);return{name:"object",responseFormat:p9(Q.jsonSchema).then((G)=>({type:"json",schema:G,...X!=null&&{name:X},...J!=null&&{description:J}})),async parseCompleteOutput({text:G},$){let W=await Z1({text:G});if(!W.success)throw new K1({message:"No object generated: could not parse the response.",cause:W.error,text:G,response:$.response,usage:$.usage,finishReason:$.finishReason});let z=await NY({value:W.value,schema:Q});if(!z.success)throw new K1({message:"No object generated: response did not match schema.",cause:z.error,text:G,response:$.response,usage:$.usage,finishReason:$.finishReason});return z.value},async parsePartialOutput({text:G}){let $=await W8(G);switch($.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:$.value}}},createElementStreamTransform(){return}}},IN=({element:Y,name:X,description:J})=>{let Q=$8(Y);return{name:"array",responseFormat:p9(Q.jsonSchema).then((G)=>{let{$schema:$,definitions:W,$defs:z,...L}=G;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",...W!=null&&{definitions:W},...z!=null&&{$defs:z},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 Z1({text:G});if(!W.success)throw new K1({message:"No object generated: could not parse the response.",cause:W.error,text:G,response:$.response,usage:$.usage,finishReason:$.finishReason});let z=W.value;if(z==null||typeof z!=="object"||!("elements"in z)||!Array.isArray(z.elements))throw new K1({message:"No object generated: response did not match schema.",cause:new p0({value:z,cause:"response must be an object with an elements array"}),text:G,response:$.response,usage:$.usage,finishReason:$.finishReason});let L=[];for(let H of z.elements){let N=await NY({value:H,schema:Q});if(!N.success)throw new K1({message:"No object generated: response did not match schema.",cause:N.error,text:G,response:$.response,usage:$.usage,finishReason:$.finishReason});L.push(N.value)}return L},async parsePartialOutput({text:G}){let $=await W8(G);switch($.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let W=$.value;if(W==null||typeof W!=="object"||!("elements"in W)||!Array.isArray(W.elements))return;let z=$.state==="repaired-parse"&&W.elements.length>0?W.elements.slice(0,-1):W.elements,L=[];for(let H of z){let N=await NY({value:H,schema:Q});if(N.success)L.push(N.value)}return{partial:L}}}},createElementStreamTransform(){let G=0;return new TransformStream({transform({partialOutput:$},W){if($!=null)for(;G<$.length;G++)W.enqueue($[G])}})}}},SN=({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},G){let $=await Z1({text:Q});if(!$.success)throw new K1({message:"No object generated: could not parse the response.",cause:$.error,text:Q,response:G.response,usage:G.usage,finishReason:G.finishReason});let W=$.value;if(W==null||typeof W!=="object"||!("result"in W)||typeof W.result!=="string"||!Y.includes(W.result))throw new K1({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:G.response,usage:G.usage,finishReason:G.finishReason});return W.result},async parsePartialOutput({text:Q}){let G=await W8(Q);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let $=G.value;if($==null||typeof $!=="object"||!("result"in $)||typeof $.result!=="string")return;let W=Y.filter((z)=>z.startsWith($.result));if(G.state==="successful-parse")return W.includes($.result)?{partial:$.result}:void 0;else return W.length===1?{partial:W[0]}:void 0}}},createElementStreamTransform(){return}}},kN=({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 G=await Z1({text:J});if(!G.success)throw new K1({message:"No object generated: could not parse the response.",cause:G.error,text:J,response:Q.response,usage:Q.usage,finishReason:Q.finishReason});return G.value},async parsePartialOutput({text:J}){let Q=await W8(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 pO=W0({prefix:"aitxt",size:24}),lO=W0({prefix:"call",size:24});var iO=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(),_1.optional()),pO=Q8(()=>VY(z.union([z.looseObject({type:z.literal("text-start"),id:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("text-delta"),id:z.string(),delta:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("text-end"),id:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("error"),errorText:z.string()}),z.looseObject({type:z.literal("tool-input-start"),toolCallId:z.string(),toolName:z.string(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional(),toolMetadata: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:A.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:A.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(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}),z.looseObject({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("tool-output-available"),toolCallId:z.string(),output:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional(),toolMetadata: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:A.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:A.optional()}),z.looseObject({type:z.literal("reasoning-delta"),id:z.string(),delta:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("reasoning-end"),id:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerMetadata:A.optional()}),z.looseObject({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("file"),url:z.string(),mediaType:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("reasoning-file"),url:z.string(),mediaType:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.custom((Y)=>typeof Y==="string"&&Y.startsWith("data-"),{message:'Type must start with "data-"'}),id:z.string().optional(),data:z.unknown(),transient:z.boolean().optional()}),z.looseObject({type:z.literal("start-step")}),z.looseObject({type:z.literal("finish-step")}),z.looseObject({type:z.literal("start"),messageId:z.string().optional(),messageMetadata:z.unknown().optional()}),z.looseObject({type:z.literal("finish"),finishReason:z.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:z.unknown().optional()}),z.looseObject({type:z.literal("abort"),reason:z.string().optional()}),z.looseObject({type:z.literal("message-metadata"),messageMetadata:z.unknown()})])));var dO=W0({prefix:"aitxt",size:24}),iO=W0({prefix:"call",size:24});var nO=W0({prefix:"aitxt",size:24}),oO=W0({prefix:"call",size:24});var M0=z.record(z.string(),_1.optional()),CN=z.record(z.string(),z.string()),sO=Q8(()=>VY(z.array(z.object({id:z.string(),role:z.enum(["system","user","assistant"]),metadata:z.unknown().optional(),parts:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:A.optional()}),z.object({type:z.literal("reasoning"),id:z.string().optional(),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:A.optional()}),z.object({type:z.literal("custom"),kind:z.string(),providerMetadata:A.optional()}),z.object({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:A.optional()}),z.object({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:A.optional()}),z.object({type:z.literal("file"),mediaType:z.string(),filename:z.string().optional(),url:z.string(),providerReference:CN.optional(),providerMetadata:A.optional()}),z.object({type:z.literal("reasoning-file"),mediaType:z.string(),url:z.string(),providerMetadata:A.optional()}),z.object({type:z.literal("step-start")}),z.object({type:z.string().startsWith("data-"),id:z.string().optional(),data:z.unknown()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("input-streaming"),input:z.unknown().optional(),providerExecuted:z.boolean().optional(),callProviderMetadata:A.optional(),output:z.never().optional(),errorText:z.never().optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("input-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),reason:z.never().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.boolean(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("output-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata: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:A.optional(),resultProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("output-denied"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("input-streaming"),providerExecuted:z.boolean().optional(),callProviderMetadata:A.optional(),input:z.unknown().optional(),output:z.never().optional(),errorText:z.never().optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("input-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),reason:z.never().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.boolean(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("output-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata: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:A.optional(),resultProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:M0.optional(),state:z.literal("output-denied"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})})]))}).superRefine((Y,X)=>{if(Y.role!=="assistant"&&Y.parts.length===0)X.addIssue({origin:"array",code:"too_small",minimum:1,inclusive:!0,input:Y.parts,path:["parts"],message:"Message must contain at least one part"})})).nonempty("Messages array must not be empty")));var tO=W0({prefix:"call",size:24});var Yq=W0({prefix:"call",size:24});var Jq=W0({prefix:"aiobj",size:24});function r$(Y){return({url:X,abortSignal:J})=>zN({url:X,maxBytes:Y==null?void 0:Y.maxBytes,abortSignal:J})}var Gq=W0({prefix:"aiobj",size:24});var $q=r$();var _N="AI_NoSuchProviderError",IN=`vercel.ai.error.${_N}`,SN=Symbol.for(IN),kN;kN=SN;var zq=W0({prefix:"call",size:24});var Uq=r$();class _0 extends t1{name="ProviderResponseStreamError";constructor(Y,X){super({message:Y,url:"",requestBodyValues:void 0,cause:X?.cause,isRetryable:!0})}}var w0={};X9(w0,{toWebSocketUrl:()=>sN,streamResponsesWebSocket:()=>YB,parseRateLimitSignal:()=>OY,normalizeHeaders:()=>aN,isUpgradeFailure:()=>tN,isAbortError:()=>o9,connectResponsesWebSocket:()=>eN,PROTOCOL_HEADER:()=>QW,OpenAIWebSocket:()=>w0});function KY(Y){let X=Number(Y.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(X)?X:void 0}function z8(Y,X,J=!1){let G=Buffer.from(Y.slice(0,X)).toString("latin1").split(`\r
196
- `),$=G[0]??"",W=KY($);if(W===void 0||W===101)return;let U=Object.fromEntries(G.slice(1).flatMap((V)=>{let K=V.indexOf(":");return K===-1?[]:[[V.slice(0,K).trim().toLowerCase(),V.slice(K+1).trim()]]})),H=Y.slice(X+4),L=U["content-length"],N=Number(L);if(!J&&(L===void 0||Number.isFinite(N)&&H.length<N))return;let O=Buffer.from(H).toString("utf8"),Z=(()=>{try{let V=JSON.parse(O);return R(V)?V:void 0}catch{return}})();return{message:`WS upgrade failed: ${$}`,status:W,status_code:W,headers:U,body:O,...R(Z?.error)?{error:Z.error}:{}}}var bN="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",s$=["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 d9{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,G=J.port?Number(J.port):J.protocol==="https:"?443:80,$=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),U=Buffer.from(W).toString("base64"),H=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(U+bN));this.expectedAccept=Buffer.from(new Uint8Array(H)).toString("base64");let L={};for(let[Z,V]of Object.entries(X))L[Z.toLowerCase()]=V;let N=[`GET ${$} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${U}`];for(let Z of s$)if(L[Z]!==void 0)N.push(`${xN(Z)}: ${L[Z]}`);for(let[Z,V]of Object.entries(X))if(!s$.includes(Z.toLowerCase())&&Z.toLowerCase()!=="content-length")N.push(`${Z}: ${V}`);let O=`${N.join(`\r
195
+ `)}})}};var BY=U.record(U.string(),_1.optional()),oO=Q8(()=>VY(U.union([U.looseObject({type:U.literal("text-start"),id:U.string(),providerMetadata:A.optional()}),U.looseObject({type:U.literal("text-delta"),id:U.string(),delta:U.string(),providerMetadata:A.optional()}),U.looseObject({type:U.literal("text-end"),id:U.string(),providerMetadata:A.optional()}),U.looseObject({type:U.literal("error"),errorText:U.string()}),U.looseObject({type:U.literal("tool-input-start"),toolCallId:U.string(),toolName:U.string(),providerExecuted:U.boolean().optional(),providerMetadata:A.optional(),toolMetadata:BY.optional(),dynamic:U.boolean().optional(),title:U.string().optional()}),U.looseObject({type:U.literal("tool-input-delta"),toolCallId:U.string(),inputTextDelta:U.string()}),U.looseObject({type:U.literal("tool-input-available"),toolCallId:U.string(),toolName:U.string(),input:U.unknown(),providerExecuted:U.boolean().optional(),providerMetadata:A.optional(),toolMetadata:BY.optional(),dynamic:U.boolean().optional(),title:U.string().optional()}),U.looseObject({type:U.literal("tool-input-error"),toolCallId:U.string(),toolName:U.string(),input:U.unknown(),providerExecuted:U.boolean().optional(),providerMetadata:A.optional(),toolMetadata:BY.optional(),dynamic:U.boolean().optional(),errorText:U.string(),title:U.string().optional()}),U.looseObject({type:U.literal("tool-approval-request"),approvalId:U.string(),toolCallId:U.string(),isAutomatic:U.boolean().optional(),signature:U.string().optional()}),U.looseObject({type:U.literal("tool-approval-response"),approvalId:U.string(),approved:U.boolean(),reason:U.string().optional(),providerExecuted:U.boolean().optional(),providerMetadata:A.optional()}),U.looseObject({type:U.literal("tool-output-available"),toolCallId:U.string(),output:U.unknown(),providerExecuted:U.boolean().optional(),providerMetadata:A.optional(),toolMetadata:BY.optional(),dynamic:U.boolean().optional(),preliminary:U.boolean().optional()}),U.looseObject({type:U.literal("tool-output-error"),toolCallId:U.string(),errorText:U.string(),providerExecuted:U.boolean().optional(),providerMetadata:A.optional(),toolMetadata:BY.optional(),dynamic:U.boolean().optional()}),U.looseObject({type:U.literal("tool-output-denied"),toolCallId:U.string()}),U.looseObject({type:U.literal("reasoning-start"),id:U.string(),providerMetadata:A.optional()}),U.looseObject({type:U.literal("reasoning-delta"),id:U.string(),delta:U.string(),providerMetadata:A.optional()}),U.looseObject({type:U.literal("reasoning-end"),id:U.string(),providerMetadata:A.optional()}),U.looseObject({type:U.literal("custom"),kind:U.string().transform((Y)=>Y),providerMetadata:A.optional()}),U.looseObject({type:U.literal("source-url"),sourceId:U.string(),url:U.string(),title:U.string().optional(),providerMetadata:A.optional()}),U.looseObject({type:U.literal("source-document"),sourceId:U.string(),mediaType:U.string(),title:U.string(),filename:U.string().optional(),providerMetadata:A.optional()}),U.looseObject({type:U.literal("file"),url:U.string(),mediaType:U.string(),providerMetadata:A.optional()}),U.looseObject({type:U.literal("reasoning-file"),url:U.string(),mediaType:U.string(),providerMetadata:A.optional()}),U.looseObject({type:U.custom((Y)=>typeof Y==="string"&&Y.startsWith("data-"),{message:'Type must start with "data-"'}),id:U.string().optional(),data:U.unknown(),transient:U.boolean().optional()}),U.looseObject({type:U.literal("start-step")}),U.looseObject({type:U.literal("finish-step")}),U.looseObject({type:U.literal("start"),messageId:U.string().optional(),messageMetadata:U.unknown().optional()}),U.looseObject({type:U.literal("finish"),finishReason:U.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:U.unknown().optional()}),U.looseObject({type:U.literal("abort"),reason:U.string().optional()}),U.looseObject({type:U.literal("message-metadata"),messageMetadata:U.unknown()})])));var sO=W0({prefix:"aitxt",size:24}),aO=W0({prefix:"call",size:24});var tO=W0({prefix:"aitxt",size:24}),eO=W0({prefix:"call",size:24});var M0=U.record(U.string(),_1.optional()),bN=U.record(U.string(),U.string()),Xq=Q8(()=>VY(U.array(U.object({id:U.string(),role:U.enum(["system","user","assistant"]),metadata:U.unknown().optional(),parts:U.array(U.union([U.object({type:U.literal("text"),text:U.string(),state:U.enum(["streaming","done"]).optional(),providerMetadata:A.optional()}),U.object({type:U.literal("reasoning"),id:U.string().optional(),text:U.string(),state:U.enum(["streaming","done"]).optional(),providerMetadata:A.optional()}),U.object({type:U.literal("custom"),kind:U.string(),providerMetadata:A.optional()}),U.object({type:U.literal("source-url"),sourceId:U.string(),url:U.string(),title:U.string().optional(),providerMetadata:A.optional()}),U.object({type:U.literal("source-document"),sourceId:U.string(),mediaType:U.string(),title:U.string(),filename:U.string().optional(),providerMetadata:A.optional()}),U.object({type:U.literal("file"),mediaType:U.string(),filename:U.string().optional(),url:U.string(),providerReference:bN.optional(),providerMetadata:A.optional()}),U.object({type:U.literal("reasoning-file"),mediaType:U.string(),url:U.string(),providerMetadata:A.optional()}),U.object({type:U.literal("step-start")}),U.object({type:U.string().startsWith("data-"),id:U.string().optional(),data:U.unknown()}),U.object({type:U.literal("dynamic-tool"),toolName:U.string(),toolCallId:U.string(),toolMetadata:M0.optional(),state:U.literal("input-streaming"),input:U.unknown().optional(),providerExecuted:U.boolean().optional(),callProviderMetadata:A.optional(),output:U.never().optional(),errorText:U.never().optional(),approval:U.never().optional()}),U.object({type:U.literal("dynamic-tool"),toolName:U.string(),toolCallId:U.string(),toolMetadata:M0.optional(),state:U.literal("input-available"),input:U.unknown(),providerExecuted:U.boolean().optional(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:A.optional(),approval:U.never().optional()}),U.object({type:U.literal("dynamic-tool"),toolName:U.string(),toolCallId:U.string(),toolMetadata:M0.optional(),state:U.literal("approval-requested"),input:U.unknown(),providerExecuted:U.boolean().optional(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:A.optional(),approval:U.object({id:U.string(),approved:U.never().optional(),reason:U.never().optional(),isAutomatic:U.boolean().optional(),signature:U.string().optional()})}),U.object({type:U.literal("dynamic-tool"),toolName:U.string(),toolCallId:U.string(),toolMetadata:M0.optional(),state:U.literal("approval-responded"),input:U.unknown(),providerExecuted:U.boolean().optional(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:A.optional(),approval:U.object({id:U.string(),approved:U.boolean(),reason:U.string().optional(),isAutomatic:U.boolean().optional(),signature:U.string().optional()})}),U.object({type:U.literal("dynamic-tool"),toolName:U.string(),toolCallId:U.string(),toolMetadata:M0.optional(),state:U.literal("output-available"),input:U.unknown(),providerExecuted:U.boolean().optional(),output:U.unknown(),errorText:U.never().optional(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),preliminary:U.boolean().optional(),approval:U.object({id:U.string(),approved:U.literal(!0),reason:U.string().optional(),isAutomatic:U.boolean().optional(),signature:U.string().optional()}).optional()}),U.object({type:U.literal("dynamic-tool"),toolName:U.string(),toolCallId:U.string(),toolMetadata:M0.optional(),state:U.literal("output-error"),input:U.unknown().optional(),rawInput:U.unknown().optional(),providerExecuted:U.boolean().optional(),output:U.never().optional(),errorText:U.string(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),approval:U.object({id:U.string(),approved:U.literal(!0),reason:U.string().optional(),isAutomatic:U.boolean().optional(),signature:U.string().optional()}).optional()}),U.object({type:U.literal("dynamic-tool"),toolName:U.string(),toolCallId:U.string(),toolMetadata:M0.optional(),state:U.literal("output-denied"),input:U.unknown(),providerExecuted:U.boolean().optional(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:A.optional(),approval:U.object({id:U.string(),approved:U.literal(!1),reason:U.string().optional(),isAutomatic:U.boolean().optional(),signature:U.string().optional()})}),U.object({type:U.string().startsWith("tool-"),toolCallId:U.string(),toolMetadata:M0.optional(),state:U.literal("input-streaming"),providerExecuted:U.boolean().optional(),callProviderMetadata:A.optional(),input:U.unknown().optional(),output:U.never().optional(),errorText:U.never().optional(),approval:U.never().optional()}),U.object({type:U.string().startsWith("tool-"),toolCallId:U.string(),toolMetadata:M0.optional(),state:U.literal("input-available"),providerExecuted:U.boolean().optional(),input:U.unknown(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:A.optional(),approval:U.never().optional()}),U.object({type:U.string().startsWith("tool-"),toolCallId:U.string(),toolMetadata:M0.optional(),state:U.literal("approval-requested"),input:U.unknown(),providerExecuted:U.boolean().optional(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:A.optional(),approval:U.object({id:U.string(),approved:U.never().optional(),reason:U.never().optional(),isAutomatic:U.boolean().optional(),signature:U.string().optional()})}),U.object({type:U.string().startsWith("tool-"),toolCallId:U.string(),toolMetadata:M0.optional(),state:U.literal("approval-responded"),input:U.unknown(),providerExecuted:U.boolean().optional(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:A.optional(),approval:U.object({id:U.string(),approved:U.boolean(),reason:U.string().optional(),isAutomatic:U.boolean().optional(),signature:U.string().optional()})}),U.object({type:U.string().startsWith("tool-"),toolCallId:U.string(),toolMetadata:M0.optional(),state:U.literal("output-available"),providerExecuted:U.boolean().optional(),input:U.unknown(),output:U.unknown(),errorText:U.never().optional(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),preliminary:U.boolean().optional(),approval:U.object({id:U.string(),approved:U.literal(!0),reason:U.string().optional(),isAutomatic:U.boolean().optional(),signature:U.string().optional()}).optional()}),U.object({type:U.string().startsWith("tool-"),toolCallId:U.string(),toolMetadata:M0.optional(),state:U.literal("output-error"),providerExecuted:U.boolean().optional(),input:U.unknown().optional(),rawInput:U.unknown().optional(),output:U.never().optional(),errorText:U.string(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),approval:U.object({id:U.string(),approved:U.literal(!0),reason:U.string().optional(),isAutomatic:U.boolean().optional(),signature:U.string().optional()}).optional()}),U.object({type:U.string().startsWith("tool-"),toolCallId:U.string(),toolMetadata:M0.optional(),state:U.literal("output-denied"),providerExecuted:U.boolean().optional(),input:U.unknown(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:A.optional(),approval:U.object({id:U.string(),approved:U.literal(!1),reason:U.string().optional(),isAutomatic:U.boolean().optional(),signature:U.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 Qq=W0({prefix:"call",size:24});var $q=W0({prefix:"call",size:24});var zq=W0({prefix:"aiobj",size:24});function t$(Y){return({url:X,abortSignal:J})=>NN({url:X,maxBytes:Y==null?void 0:Y.maxBytes,abortSignal:J})}var Hq=W0({prefix:"aiobj",size:24});var Lq=t$();var xN="AI_NoSuchProviderError",vN=`vercel.ai.error.${xN}`,hN=Symbol.for(vN),gN;gN=hN;var Nq=W0({prefix:"call",size:24});var Bq=t$();class _0 extends t1{name="ProviderResponseStreamError";constructor(Y,X){super({message:Y,url:"",requestBodyValues:void 0,cause:X?.cause,isRetryable:!0})}}var w0={};X9(w0,{toWebSocketUrl:()=>XB,streamResponsesWebSocket:()=>$B,parseRateLimitSignal:()=>OY,normalizeHeaders:()=>JB,isUpgradeFailure:()=>QB,isAbortError:()=>o9,connectResponsesWebSocket:()=>GB,PROTOCOL_HEADER:()=>WW,OpenAIWebSocket:()=>w0});function KY(Y){let X=Number(Y.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(X)?X:void 0}function z8(Y,X,J=!1){let G=Buffer.from(Y.slice(0,X)).toString("latin1").split(`\r
196
+ `),$=G[0]??"",W=KY($);if(W===void 0||W===101)return;let z=Object.fromEntries(G.slice(1).flatMap((V)=>{let K=V.indexOf(":");return K===-1?[]:[[V.slice(0,K).trim().toLowerCase(),V.slice(K+1).trim()]]})),L=Y.slice(X+4),H=z["content-length"],N=Number(H);if(!J&&(H===void 0||Number.isFinite(N)&&L.length<N))return;let O=Buffer.from(L).toString("utf8"),Z=(()=>{try{let V=JSON.parse(O);return R(V)?V:void 0}catch{return}})();return{message:`WS upgrade failed: ${$}`,status:W,status_code:W,headers:z,body:O,...R(Z?.error)?{error:Z.error}:{}}}var yN="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",e$=["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 d9{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,G=J.port?Number(J.port):J.protocol==="https:"?443:80,$=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),z=Buffer.from(W).toString("base64"),L=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(z+yN));this.expectedAccept=Buffer.from(new Uint8Array(L)).toString("base64");let H={};for(let[Z,V]of Object.entries(X))H[Z.toLowerCase()]=V;let N=[`GET ${$} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${z}`];for(let Z of e$)if(H[Z]!==void 0)N.push(`${fN(Z)}: ${H[Z]}`);for(let[Z,V]of Object.entries(X))if(!e$.includes(Z.toLowerCase())&&Z.toLowerCase()!=="content-length")N.push(`${Z}: ${V}`);let O=`${N.join(`\r
197
197
  `)}\r
198
198
  \r
199
- `;try{this.log("connect_start",{host:Q,port:G,tls:J.protocol==="https:"});let Z=globalThis.Bun?.connect;if(!Z)throw Error("Bun.connect is not available");this.socket=await Z({hostname:Q,port:G,tls:J.protocol==="https:"?{serverName:Q}:void 0,socket:{open:(V)=>{this.socket=V,this.enqueueWrite(new TextEncoder().encode(O))},data:(V,K)=>this.onData(K),drain:()=>this.flushWrites(),error:(V,K)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let j=K instanceof Error?K.message:String(K);this.log("socket_error",{message:j}),this.emit("error",{message:j})},close:()=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close"),this.emit("close",{code:1006,reason:"socket closed"})}}})}catch(Z){this.readyState=3;let V=Z instanceof Error?Z.message:String(Z);this.log("connect_exception",{message:V}),this.emit("error",{message:V})}}onData(Y){if(this.rxBuffer=vN(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
199
+ `;try{this.log("connect_start",{host:Q,port:G,tls:J.protocol==="https:"});let Z=globalThis.Bun?.connect;if(!Z)throw Error("Bun.connect is not available");this.socket=await Z({hostname:Q,port:G,tls:J.protocol==="https:"?{serverName:Q}:void 0,socket:{open:(V)=>{this.socket=V,this.enqueueWrite(new TextEncoder().encode(O))},data:(V,K)=>this.onData(K),drain:()=>this.flushWrites(),error:(V,K)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let j=K instanceof Error?K.message:String(K);this.log("socket_error",{message:j}),this.emit("error",{message:j})},close:()=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close"),this.emit("close",{code:1006,reason:"socket closed"})}}})}catch(Z){this.readyState=3;let V=Z instanceof Error?Z.message:String(Z);this.log("connect_exception",{message:V}),this.emit("error",{message:V})}}onData(Y){if(this.rxBuffer=mN(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),G=Q.split(`\r
202
202
  `)[0]??"",$=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=KY(G);if(W!==101){if(W===void 0){this.readyState=3;try{this.socket?.end()}catch{}this.log("upgrade_failed",{statusLine:G}),this.emit("error",{message:`WS upgrade failed: ${G}`});return}if(!this.emitRejectedUpgrade())return;try{this.socket?.end()}catch{}return}if(!$||$[1]!==this.expectedAccept){this.readyState=3;try{this.socket?.end()}catch{}this.log("accept_mismatch",{statusLine:G}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(J+4),this.log("open",{statusLine:G}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let X=Buffer.from(this.rxBuffer).indexOf(`\r
203
203
  \r
204
- `);if(X===-1)return!1;let J=z8(this.rxBuffer,X,Y);if(!J)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:J.status,partial:Y}),this.emit("error",J),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let X=Y[0],J=Y[1],Q=(X&128)!==0,G=X&15,$=(J&128)!==0,W=J&127,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 L=0;L<8;L++)W=W*256+Y[2+L];U=10}if($)U+=4;if(Y.length<U+W)return;let H=Y.slice(U,U+W);this.rxBuffer=Y.slice(U+W),this.handleFrame(Q,G,H)}}handleFrame(Y,X,J){if(X===9){this.writeFrame(10,J);return}if(X===10)return;if(X===8){let G=1005,$="";if(J.length>=2)G=J[0]<<8|J[1],$=Buffer.from(J.slice(2)).toString("utf-8");this.readyState=3;try{this.socket?.end()}catch{}this.log("close_frame",{code:G,reason:$}),this.emit("close",{code:G,reason:$});return}if(X===1||X===2)this.fragOpcode=X,this.fragChunks=[J];else if(X===0)this.fragChunks.push(J);if(!Y)return;let Q=hN(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let G=Buffer.from(Q).toString("utf-8");this.emit("message",{data:G})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),G;if(J<126)G=[128|Y,128|J];else if(J<65536)G=[128|Y,254,J>>8&255,J&255];else{G=[128|Y,255];for(let U=7;U>=0;U--)G.push(J/2**(8*U)&255)}let $=new Uint8Array(J);for(let U=0;U<J;U++)$[U]=X[U]^Q[U%4];let W=new Uint8Array(G.length+4+J);W.set(G,0),W.set(Q,G.length),W.set($,G.length+4);try{this.enqueueWrite(W)}catch{}}enqueueWrite(Y){this.writeQueue.push(Y),this.flushWrites()}flushWrites(){let Y=this.socket;if(!Y)return;while(this.writeQueue.length>0){let X=this.writeQueue[0],J=Y.write(X);if(J<X.length){this.writeQueue[0]=X.slice(J),this.log("write_backpressure",{written:J,remaining:X.length-J});return}this.writeQueue.shift()}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return t0({component:"raw-ws-bun",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function xN(Y){return Y}function vN(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function hN(Y){let X=0;for(let G of Y)X+=G.length;let J=new Uint8Array(X),Q=0;for(let G of Y)J.set(G,Q),Q+=G.length;return J}import{connect as gN}from"node:net";import{connect as yN}from"node:tls";var fN="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",a$=["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 i9{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,G=J.port?Number(J.port):J.protocol==="https:"?443:80,$=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),U=Buffer.from(W).toString("base64"),H=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(U+fN));this.expectedAccept=Buffer.from(new Uint8Array(H)).toString("base64");let L={};for(let[Z,V]of Object.entries(X))L[Z.toLowerCase()]=V;let N=[`GET ${$} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${U}`];for(let Z of a$)if(L[Z]!==void 0)N.push(`${mN(Z)}: ${L[Z]}`);for(let[Z,V]of Object.entries(X))if(!a$.includes(Z.toLowerCase())&&Z.toLowerCase()!=="content-length")N.push(`${Z}: ${V}`);let O=`${N.join(`\r
204
+ `);if(X===-1)return!1;let J=z8(this.rxBuffer,X,Y);if(!J)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:J.status,partial:Y}),this.emit("error",J),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let X=Y[0],J=Y[1],Q=(X&128)!==0,G=X&15,$=(J&128)!==0,W=J&127,z=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],z=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];z=10}if($)z+=4;if(Y.length<z+W)return;let L=Y.slice(z,z+W);this.rxBuffer=Y.slice(z+W),this.handleFrame(Q,G,L)}}handleFrame(Y,X,J){if(X===9){this.writeFrame(10,J);return}if(X===10)return;if(X===8){let G=1005,$="";if(J.length>=2)G=J[0]<<8|J[1],$=Buffer.from(J.slice(2)).toString("utf-8");this.readyState=3;try{this.socket?.end()}catch{}this.log("close_frame",{code:G,reason:$}),this.emit("close",{code:G,reason:$});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=cN(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let G=Buffer.from(Q).toString("utf-8");this.emit("message",{data:G})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),G;if(J<126)G=[128|Y,128|J];else if(J<65536)G=[128|Y,254,J>>8&255,J&255];else{G=[128|Y,255];for(let z=7;z>=0;z--)G.push(J/2**(8*z)&255)}let $=new Uint8Array(J);for(let z=0;z<J;z++)$[z]=X[z]^Q[z%4];let W=new Uint8Array(G.length+4+J);W.set(G,0),W.set(Q,G.length),W.set($,G.length+4);try{this.enqueueWrite(W)}catch{}}enqueueWrite(Y){this.writeQueue.push(Y),this.flushWrites()}flushWrites(){let Y=this.socket;if(!Y)return;while(this.writeQueue.length>0){let X=this.writeQueue[0],J=Y.write(X);if(J<X.length){this.writeQueue[0]=X.slice(J),this.log("write_backpressure",{written:J,remaining:X.length-J});return}this.writeQueue.shift()}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return t0({component:"raw-ws-bun",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function fN(Y){return Y}function mN(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function cN(Y){let X=0;for(let G of Y)X+=G.length;let J=new Uint8Array(X),Q=0;for(let G of Y)J.set(G,Q),Q+=G.length;return J}import{connect as uN}from"node:net";import{connect as pN}from"node:tls";var lN="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",YW=["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 i9{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,G=J.port?Number(J.port):J.protocol==="https:"?443:80,$=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),z=Buffer.from(W).toString("base64"),L=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(z+lN));this.expectedAccept=Buffer.from(new Uint8Array(L)).toString("base64");let H={};for(let[Z,V]of Object.entries(X))H[Z.toLowerCase()]=V;let N=[`GET ${$} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${z}`];for(let Z of YW)if(H[Z]!==void 0)N.push(`${dN(Z)}: ${H[Z]}`);for(let[Z,V]of Object.entries(X))if(!YW.includes(Z.toLowerCase())&&Z.toLowerCase()!=="content-length")N.push(`${Z}: ${V}`);let O=`${N.join(`\r
205
205
  `)}\r
206
206
  \r
207
- `;try{this.log("connect_start",{host:Q,port:G,tls:J.protocol==="https:"});let Z=()=>{this.socket?.write(O)},V=J.protocol==="https:"?yN({host:Q,port:G,servername:Q},Z):gN({host:Q,port:G},Z);this.socket=V,V.on("data",(K)=>{this.onData(typeof K==="string"?Buffer.from(K,"binary"):K)}),V.on("error",(K)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let j=K instanceof Error?K.message:String(K);this.log("socket_error",{message:j}),this.emit("error",{message:j})}),V.on("close",(K)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close",{hadError:K}),this.emit("close",{code:1006,reason:"socket closed"})})}catch(Z){this.readyState=3,this.log("connect_exception",{message:Z instanceof Error?Z.message:String(Z)}),this.emit("error",{message:Z instanceof Error?Z.message:String(Z)})}}onData(Y){if(this.rxBuffer=cN(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
207
+ `;try{this.log("connect_start",{host:Q,port:G,tls:J.protocol==="https:"});let Z=()=>{this.socket?.write(O)},V=J.protocol==="https:"?pN({host:Q,port:G,servername:Q},Z):uN({host:Q,port:G},Z);this.socket=V,V.on("data",(K)=>{this.onData(typeof K==="string"?Buffer.from(K,"binary"):K)}),V.on("error",(K)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let j=K instanceof Error?K.message:String(K);this.log("socket_error",{message:j}),this.emit("error",{message:j})}),V.on("close",(K)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close",{hadError:K}),this.emit("close",{code:1006,reason:"socket closed"})})}catch(Z){this.readyState=3,this.log("connect_exception",{message:Z instanceof Error?Z.message:String(Z)}),this.emit("error",{message:Z instanceof Error?Z.message:String(Z)})}}onData(Y){if(this.rxBuffer=iN(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),G=Q.split(`\r
210
210
  `)[0]??"",$=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=KY(G);if(W!==101){if(W===void 0){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:G}),this.emit("error",{message:`WS upgrade failed: ${G}`});return}if(!this.emitRejectedUpgrade())return;this.socket?.destroy?.();return}if(!$||$[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:G}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(J+4),this.log("open",{statusLine:G}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let X=Buffer.from(this.rxBuffer).indexOf(`\r
211
211
  \r
212
- `);if(X===-1)return!1;let J=z8(this.rxBuffer,X,Y);if(!J)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:J.status,partial:Y}),this.emit("error",J),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let X=Y[0],J=Y[1],Q=(X&128)!==0,G=X&15,$=(J&128)!==0,W=J&127,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 L=0;L<8;L++)W=W*256+Y[2+L];U=10}if($)U+=4;if(Y.length<U+W)return;let H=Y.slice(U,U+W);this.rxBuffer=Y.slice(U+W),this.handleFrame(Q,G,H)}}handleFrame(Y,X,J){if(X===9){this.writeFrame(10,J);return}if(X===10)return;if(X===8){let G=1005,$="";if(J.length>=2)G=J[0]<<8|J[1],$=Buffer.from(J.slice(2)).toString("utf-8");this.readyState=3;try{this.socket?.end()}catch{}this.emit("close",{code:G,reason:$});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=uN(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let G=Buffer.from(Q).toString("utf-8");this.emit("message",{data:G})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),G;if(J<126)G=[128|Y,128|J];else if(J<65536)G=[128|Y,254,J>>8&255,J&255];else{G=[128|Y,255];for(let U=7;U>=0;U--)G.push(J/2**(8*U)&255)}let $=new Uint8Array(J);for(let U=0;U<J;U++)$[U]=X[U]^Q[U%4];let W=new Uint8Array(G.length+4+J);W.set(G,0),W.set(Q,G.length),W.set($,G.length+4);try{this.socket?.write(W)}catch{}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return t0({component:"raw-ws-node",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function mN(Y){return Y}function cN(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function uN(Y){let X=0;for(let G of Y)X+=G.length;let J=new Uint8Array(X),Q=0;for(let G of Y)J.set(G,Q),Q+=G.length;return J}function pN(){return typeof globalThis.Bun?.connect==="function"}var t$=pN()?d9:i9;function U8(Y){return process.env[Y]??process.env[Y.toLowerCase()]}function lN(Y){let X=U8("NO_PROXY");if(!X)return!1;let J=Y.hostname.toLowerCase(),Q=X.split(",").map((G)=>G.trim().toLowerCase()).filter(Boolean);for(let G of Q){if(G==="*")return!0;if(G.startsWith(".")){if(J===G.slice(1)||J.endsWith(G))return!0}else if(J===G||J.endsWith(`.${G}`))return!0}return!1}function dN(Y){let X=new URL(Y);if(lN(X))return;if(X.protocol==="http:")return U8("HTTP_PROXY");if(X.protocol==="https:")return U8("HTTPS_PROXY")??U8("HTTP_PROXY");return}var e$={getProxyForUrl:dN};var iN=N0("quota"),QW="responses_websockets=2026-02-06",YW=["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"],nN=new Set([z1,"x-opencode-title"]);function oN(Y){let X=new Map;for(let Q of Object.keys(Y))X.set(Q.toLowerCase(),Q);let J={};for(let Q of YW){let G=X.get(Q),$=G===void 0?void 0:Y[G];if(G!==void 0&&$!==void 0)J[G]=$}for(let[Q,G]of Object.entries(Y))if(!YW.includes(Q.toLowerCase()))J[Q]=G;return J}function rN(Y){let X={};for(let[J,Q]of Object.entries(Y)){if(nN.has(J.toLowerCase()))continue;X[J]=Q}return X}function sN(Y){return Y.replace(/^http/,"ws")}function aN(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 o9(Y){return Y instanceof DOMException&&Y.name==="AbortError"}var GW=new WeakSet;function tN(Y){return typeof Y==="object"&&Y!==null&&GW.has(Y)}function XW(Y,X){let J=Error(Y,X===void 0?void 0:{cause:X});return GW.add(J),J}function eN(Y){return new Promise((X,J)=>{if(Y.signal?.aborted){J(n9(Y.signal));return}let Q={...Y.headers,"openai-beta":Y.headers["openai-beta"]??QW},G=Q[z1]??Q["session-id"];delete Q["content-length"],Q=oN(rN(Q));let $=typeof Bun>"u"?void 0:e$.getProxyForUrl(Y.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),W=!0,U=Y.rawWebSocket?new t$(Y.url,Q,{sessionID:G}):new globalThis.WebSocket(Y.url,{headers:Q,...$?{proxy:$}:{},perMessageDeflate:W}),H=Y.timeout?setTimeout(()=>{L(),U.close(),J(Error("WebSocket connect timed out"))},Y.timeout):void 0;function L(){if(H)clearTimeout(H);U.removeEventListener("open",N),U.removeEventListener("error",O),U.removeEventListener("close",Z),Y.signal?.removeEventListener("abort",V)}function N(){L(),X(U)}function O(K){L(),J(XW(W1(K),K))}function Z(K){L(),J(XW(WW("WebSocket closed before open",K.code,K.reason)))}function V(){L(),U.close(),J(n9(Y.signal))}U.addEventListener("open",N,{once:!0}),U.addEventListener("error",O,{once:!0}),U.addEventListener("close",Z,{once:!0}),Y.signal?.addEventListener("abort",V,{once:!0})})}function YB(Y){let X=new TextEncoder,J=Y.socket,Q,G=()=>{},$=!1,W=!1,U=!1,H,L=new Set;function N(){if(H)clearTimeout(H);G(),Y.signal?.removeEventListener("abort",f)}function O(x=J){x.close()}function Z(){N(),Q?.enqueue(X.encode(`data: [DONE]
212
+ `);if(X===-1)return!1;let J=z8(this.rxBuffer,X,Y);if(!J)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:J.status,partial:Y}),this.emit("error",J),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let X=Y[0],J=Y[1],Q=(X&128)!==0,G=X&15,$=(J&128)!==0,W=J&127,z=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],z=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];z=10}if($)z+=4;if(Y.length<z+W)return;let L=Y.slice(z,z+W);this.rxBuffer=Y.slice(z+W),this.handleFrame(Q,G,L)}}handleFrame(Y,X,J){if(X===9){this.writeFrame(10,J);return}if(X===10)return;if(X===8){let G=1005,$="";if(J.length>=2)G=J[0]<<8|J[1],$=Buffer.from(J.slice(2)).toString("utf-8");this.readyState=3;try{this.socket?.end()}catch{}this.emit("close",{code:G,reason:$});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=nN(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let G=Buffer.from(Q).toString("utf-8");this.emit("message",{data:G})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),G;if(J<126)G=[128|Y,128|J];else if(J<65536)G=[128|Y,254,J>>8&255,J&255];else{G=[128|Y,255];for(let z=7;z>=0;z--)G.push(J/2**(8*z)&255)}let $=new Uint8Array(J);for(let z=0;z<J;z++)$[z]=X[z]^Q[z%4];let W=new Uint8Array(G.length+4+J);W.set(G,0),W.set(Q,G.length),W.set($,G.length+4);try{this.socket?.write(W)}catch{}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return t0({component:"raw-ws-node",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function dN(Y){return Y}function iN(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function nN(Y){let X=0;for(let G of Y)X+=G.length;let J=new Uint8Array(X),Q=0;for(let G of Y)J.set(G,Q),Q+=G.length;return J}function oN(){return typeof globalThis.Bun?.connect==="function"}var XW=oN()?d9:i9;function U8(Y){return process.env[Y]??process.env[Y.toLowerCase()]}function rN(Y){let X=U8("NO_PROXY");if(!X)return!1;let J=Y.hostname.toLowerCase(),Q=X.split(",").map((G)=>G.trim().toLowerCase()).filter(Boolean);for(let G of Q){if(G==="*")return!0;if(G.startsWith(".")){if(J===G.slice(1)||J.endsWith(G))return!0}else if(J===G||J.endsWith(`.${G}`))return!0}return!1}function sN(Y){let X=new URL(Y);if(rN(X))return;if(X.protocol==="http:")return U8("HTTP_PROXY");if(X.protocol==="https:")return U8("HTTPS_PROXY")??U8("HTTP_PROXY");return}var JW={getProxyForUrl:sN};var aN=N0("quota"),WW="responses_websockets=2026-02-06",QW=["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"],tN=new Set([z1,"x-opencode-title"]);function eN(Y){let X=new Map;for(let Q of Object.keys(Y))X.set(Q.toLowerCase(),Q);let J={};for(let Q of QW){let G=X.get(Q),$=G===void 0?void 0:Y[G];if(G!==void 0&&$!==void 0)J[G]=$}for(let[Q,G]of Object.entries(Y))if(!QW.includes(Q.toLowerCase()))J[Q]=G;return J}function YB(Y){let X={};for(let[J,Q]of Object.entries(Y)){if(tN.has(J.toLowerCase()))continue;X[J]=Q}return X}function XB(Y){return Y.replace(/^http/,"ws")}function JB(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 o9(Y){return Y instanceof DOMException&&Y.name==="AbortError"}var zW=new WeakSet;function QB(Y){return typeof Y==="object"&&Y!==null&&zW.has(Y)}function GW(Y,X){let J=Error(Y,X===void 0?void 0:{cause:X});return zW.add(J),J}function GB(Y){return new Promise((X,J)=>{if(Y.signal?.aborted){J(n9(Y.signal));return}let Q={...Y.headers,"openai-beta":Y.headers["openai-beta"]??WW},G=Q[z1]??Q["session-id"];delete Q["content-length"],Q=eN(YB(Q));let $=typeof Bun>"u"?void 0:JW.getProxyForUrl(Y.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),W=!0,z=Y.rawWebSocket?new XW(Y.url,Q,{sessionID:G}):new globalThis.WebSocket(Y.url,{headers:Q,...$?{proxy:$}:{},perMessageDeflate:W}),L=Y.timeout?setTimeout(()=>{H(),z.close(),J(Error("WebSocket connect timed out"))},Y.timeout):void 0;function H(){if(L)clearTimeout(L);z.removeEventListener("open",N),z.removeEventListener("error",O),z.removeEventListener("close",Z),Y.signal?.removeEventListener("abort",V)}function N(){H(),X(z)}function O(K){H(),J(GW(W1(K),K))}function Z(K){H(),J(GW(HW("WebSocket closed before open",K.code,K.reason)))}function V(){H(),z.close(),J(n9(Y.signal))}z.addEventListener("open",N,{once:!0}),z.addEventListener("error",O,{once:!0}),z.addEventListener("close",Z,{once:!0}),Y.signal?.addEventListener("abort",V,{once:!0})})}function $B(Y){let X=new TextEncoder,J=Y.socket,Q,G=()=>{},$=!1,W=!1,z=!1,L,H=new Set;function N(){if(L)clearTimeout(L);G(),Y.signal?.removeEventListener("abort",f)}function O(x=J){x.close()}function Z(){N(),Q?.enqueue(X.encode(`data: [DONE]
213
213
 
214
- `)),Q?.close()}function V(x){j(x,x)}function K(x){if(U){j(Error(x.message,{cause:x}),new _0(x.message,{cause:x}));return}V(x)}function j(x,y){if($)return;$=!0,N(),Y.onConnectionInvalid?.(y),Q?.error(x)}function M(x){if($)return;if(!Y.idleTimeout)return;if(H)clearTimeout(H);H=setTimeout(()=>K(new _0(x)),Y.idleTimeout)}async function I(x){if($)return;if(typeof x.data!=="string"){K(new _0("Unexpected binary WebSocket frame"));return}let y=x.data,u=(()=>{try{let d=JSON.parse(y);return typeof d==="object"&&d!==null?d:void 0}catch{return}})();if(u?.type==="codex.rate_limits"){iN.debug("codex.rate_limits frame received",{pid:process.pid}),M("idle timeout waiting for websocket");let d=JW(u);Y.onQuota?.(d);return}let L0=!U?OY(u):void 0;if(L0&&u){$=!0,N(),Y.onRateLimitReached?.(L0.window,L0.resetAt),Y.onTerminal?.(u),Y.onFirstEvent?.(),Q?.error(new _0(`OpenAI account rate limit reached at admission (${L0.window})`));return}if(u?.type==="error"&&Y.onRetryableTerminal){if(G(),H)clearTimeout(H);H=void 0;try{let d=await Y.onRetryableTerminal(u);if($){if(d)O(d);return}if(d){K0(d);return}}catch(d){K(new _0(d instanceof Error?d.message:String(d),{cause:d}));return}}let Y0=$B(u,y);if(Y0&&u){if(!W)Y.onFirstEvent?.(Y0);$=!0,N(),Y.onTerminal?.(u);let d=new t1({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(R(u)&&u.type==="response.failed"){let d=R(u.response)?u.response.failed:void 0,g0=R(d)?d.rate_limit_reached_type:void 0;if(typeof g0==="string"){if($=!0,N(),Y.onRateLimitReached?.(g0),Y.onTerminal?.(u),!U)Y.onFirstEvent?.(),Q?.error(new _0(`OpenAI account rate limit reached mid-stream (${g0})`));else Z();return}}if(u)XB(u,Y.sessionID),QB(u,L);let Q0=u?o8(u):u;if(!Q0){if(!W)Y.onFirstEvent?.();M("idle timeout waiting for websocket");return}let q1=Q0===u?y:JSON.stringify(Q0);if(!W)Y.onFirstEvent?.();if(Q?.enqueue(X.encode(`${q1.split(/\r?\n/).map((d)=>`data: ${d}`).join(`
214
+ `)),Q?.close()}function V(x){j(x,x)}function K(x){if(z){j(Error(x.message,{cause:x}),new _0(x.message,{cause:x}));return}V(x)}function j(x,y){if($)return;$=!0,N(),Y.onConnectionInvalid?.(y),Q?.error(x)}function M(x){if($)return;if(!Y.idleTimeout)return;if(L)clearTimeout(L);L=setTimeout(()=>K(new _0(x)),Y.idleTimeout)}async function I(x){if($)return;if(typeof x.data!=="string"){K(new _0("Unexpected binary WebSocket frame"));return}let y=x.data,u=(()=>{try{let d=JSON.parse(y);return typeof d==="object"&&d!==null?d:void 0}catch{return}})();if(u?.type==="codex.rate_limits"){aN.debug("codex.rate_limits frame received",{pid:process.pid}),M("idle timeout waiting for websocket");let d=$W(u);Y.onQuota?.(d);return}let L0=!z?OY(u):void 0;if(L0&&u){$=!0,N(),Y.onRateLimitReached?.(L0.window,L0.resetAt),Y.onTerminal?.(u),Y.onFirstEvent?.(),Q?.error(new _0(`OpenAI account rate limit reached at admission (${L0.window})`));return}if(u?.type==="error"&&Y.onRetryableTerminal){if(G(),L)clearTimeout(L);L=void 0;try{let d=await Y.onRetryableTerminal(u);if($){if(d)O(d);return}if(d){K0(d);return}}catch(d){K(new _0(d instanceof Error?d.message:String(d),{cause:d}));return}}let Y0=LB(u,y);if(Y0&&u){if(!W)Y.onFirstEvent?.(Y0);$=!0,N(),Y.onTerminal?.(u);let d=new t1({message:Y0.message,url:J.url,requestBodyValues:Y.body,statusCode:Y0.status,responseHeaders:Y0.headers,responseBody:Y0.body});Q?.error(z?Error(d.message,{cause:d}):d);return}if(R(u)&&u.type==="response.failed"){let d=R(u.response)?u.response.failed:void 0,g0=R(d)?d.rate_limit_reached_type:void 0;if(typeof g0==="string"){if($=!0,N(),Y.onRateLimitReached?.(g0),Y.onTerminal?.(u),!z)Y.onFirstEvent?.(),Q?.error(new _0(`OpenAI account rate limit reached mid-stream (${g0})`));else Z();return}}if(u)WB(u,Y.sessionID),UB(u,H);let Q0=u?o8(u):u;if(!Q0){if(!W)Y.onFirstEvent?.();M("idle timeout waiting for websocket");return}let q1=Q0===u?y: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(M("idle timeout waiting for websocket"),!Q0)return;if(Q0.type==="response.completed"||Q0.type==="response.done"){$=!0,GB(Q0,L),Y.onComplete?.(Q0,L),Y.onTerminal?.(Q0),Z();return}if(Q0.type==="response.failed"||Q0.type==="response.incomplete"||Q0.type==="error")$=!0,Y.onTerminal?.(Q0),Z()}function E(x){K(new _0(W1(x),{cause:x}))}function b(x){if($)return;K(new _0(WW("WebSocket closed before response.completed",x.code,x.reason)))}function f(){let x=n9(Y.signal);if($)return;$=!0,N(),O(),Y.onAbort?.(x),Q?.error(x)}function l(x){if($)return;$=!0,N(),O(),Y.onAbort?.(WB(x))}function K0(x){G(),J=x,J.addEventListener("message",I),J.addEventListener("error",E,{once:!0}),J.addEventListener("close",b,{once:!0}),G=()=>{J.removeEventListener("message",I),J.removeEventListener("error",E),J.removeEventListener("close",b)};let{background:y,...u}=Y.body;M("idle timeout sending websocket request");try{J.send(JSON.stringify({type:"response.create",...u})),M("idle timeout waiting for websocket")}catch(L0){if($)return;V(new _0(L0 instanceof Error?L0.message:String(L0),{cause:L0}))}}return new Response(new ReadableStream({start(x){if(Q=x,Y.signal?.addEventListener("abort",f,{once:!0}),Y.signal?.aborted){f();return}K0(J)},cancel(x){l(x)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function XB(Y,X){if(!JB(Y))return;await t0({component:"ws",event:"provider_native_web_search_event",sessionID:X,serverEventType:Y.type,itemType:R(Y.item)?Y.item.type:void 0,serverEvent:Y})}function JB(Y){if(typeof Y.type==="string"&&(Y.type.startsWith("response.web_search_call.")||Y.type.startsWith("response.web_search_preview_call.")))return!0;if(R(Y.item)&&typeof Y.item.type==="string")return Y.item.type==="web_search_call"||Y.item.type==="web_search_preview_call";return!1}function QB(Y,X){if(Y.type!=="response.output_item.done")return;if(!R(Y.item))return;$W(Y.item,X)}function GB(Y,X){let J=Y.response;if(!R(J)||!Array.isArray(J.output))return;for(let Q of J.output)if(R(Q))$W(Q,X)}function $W(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 $B(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:R(Y.headers)?Object.fromEntries(Object.entries(Y.headers).flatMap(([Q,G])=>typeof G==="string"||typeof G==="number"||typeof G==="boolean"?[[Q,String(G)]]:[])):void 0,body:X,message:R(Y.error)&&typeof Y.error.message==="string"?Y.error.message:`${J}`}}function OY(Y){if(typeof Y==="string")try{return OY(JSON.parse(Y))}catch{return}if(!R(Y))return;let X=OY(Y.cause);if(X)return X;let J=OY(Y.body);if(J)return J;let Q=R(Y.error)?Y.error:Y,G=typeof Q.type==="string"?Q.type:void 0,$=Y.status??Y.status_code;if(G!=="usage_limit_reached"&&$!==429)return;let{resets_at:W,resets_in_seconds:U}=Q,H=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:G??"primary",resetAt:H}}function WB(Y){if(o9(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function n9(Y){let X=Y?.reason;if(o9(X))return X;if(zB(X))return X;return new DOMException(X instanceof Error?X.message:"Aborted","AbortError")}function zB(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function WW(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 s9="x-opencode-title",H8="x-openai-auth-quota-account",r9=new Set([s9,z1,H8,"x-opencode-session"]),HB=15000,LB=300000,VB=3300000,zW="websocket_connection_limit_reached";function NB(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 UB("sha256").update(Q).digest("hex").slice(0,12)}function BB(Y){let X=Y?.httpFetch??globalThis.fetch,J=new Map,Q=Y?.connectTimeout??HB,G=Y?.idleTimeout??LB,$=Y?.maxConnectionAge??VB,W=Y?.streamRetries??5,U=Y?.firstEventGraceMs??250,H=Y?.rawWebSocket??!1,L=Y?.onQuota,N=Y?.onRateLimitReached,O=setInterval(()=>j(),Math.min(G,60000));if(typeof O==="object"&&"unref"in O&&typeof O.unref==="function")O.unref();function Z(E,b,f){if(!b||!f)return f;a9(E,UW(b));let l=new Headers(f.headers),K0=l.get("x-codex-turn-metadata");if(!K0)return f;let x=OW(K0,E.turnID,E.turnStartedAt);if(!x)return f;return l.set("x-codex-turn-metadata",x),{...f,headers:l}}async function V(E,b){let f=E instanceof URL?E.toString():typeof E==="string"?E:E.url,l=w0.normalizeHeaders(b?.headers),K0=jW(b),x=xY(K0);if(b?.method!=="POST"||!new URL(f).pathname.endsWith("/responses"))return X(E,x);let y=(()=>{try{if(typeof b?.body!=="string")return;let r=JSON.parse(b.body);return typeof r==="object"&&r!==null?r:void 0}catch{return}})();if(!y?.stream)return X(E,x);if(l[s9]==="true")return X(E,x);let u=l[z1]??l["x-session-affinity"]??l["session-id"],L0=u;if(!u)return X(E,x);let Y0=w0.normalizeHeaders(K0?.headers),Q0=NB(Y0),q1=`${u}:${Q0}:conversation`,d=typeof l[H8]==="string"?l[H8]:void 0,g0=N?(r,O0)=>N(r,d,O0):void 0,h=J.get(q1)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};if(J.set(q1,h),h.fallback)return X(E,Z(h,y,x));if(h.busy)return X(E,Z(h,y,x));h.busy=!0,h.lastUsedAt=Date.now();try{let r=UW(y),O0=w0.normalizeHeaders(K0?.headers),B8=typeof O0.authorization==="string"&&O0.authorization.startsWith("Bearer ")?O0.authorization.slice(7):"",S1=typeof O0["chatgpt-account-id"]==="string"?O0["chatgpt-account-id"]:void 0,wY=L?(G0)=>L(G0,B8,d,S1):void 0,n0=!h.socket&&!h.continuation?PB(O0):O0;if(h.socket=await OB(h,Y?.url??f,n0,Q,$,H,b?.signal),AB(h,r))await qB(h,r,G,{signal:b?.signal??void 0,sessionID:L0,url:Y?.url??f,headers:K0?.headers,onRateLimitReached:g0});let G1=()=>{},o0=()=>{},F1=new Promise((G0,I0)=>{G1=G0,o0=I0}),Z8=EB(h,r),r0=qY(KW(h,Z8,r)),P0=typeof r0.previous_response_id==="string";await y1({sessionID:L0,transport:"websocket",phase:"main",bodyText:JSON.stringify(r0),url:Y?.url??f,method:K0?.method,headers:K0?.headers});let y0=w0.streamResponsesWebSocket({socket:h.socket,body:r0,sessionID:L0??void 0,idleTimeout:G,signal:b?.signal??void 0,onQuota:wY,onRateLimitReached:g0,onFirstEvent:(G0)=>G1(G0??!0),onComplete:(G0,I0)=>{let k1=VW(G0);t0({component:"ws-pool",event:"main_completed",sessionID:L0,responseID:LW(G0),usage:k1}),ZW(h,r,G0,I0,P0)},onTerminal:(G0)=>{if(h.busy=!1,h.lastUsedAt=Date.now(),h.streamFailures=0,G0.type!=="response.completed"&&G0.type!=="response.done")h.continuation=void 0,Q1(h)},onConnectionInvalid:()=>{if(h.busy=!1,h.lastUsedAt=Date.now(),!h.fallback)K(h);h.continuation=void 0,Q1(h),G1(!1)},onAbort:(G0)=>{h.busy=!1,h.lastUsedAt=Date.now(),h.streamFailures=0,h.continuation=void 0,Q1(h),o0(G0)},onRetryableTerminal:async(G0)=>{let I0=HW(G0);if(!I0)return;throw h.fallback=!0,I0}}),f0=await ZB(F1,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(!h.fallback)return y0;return X(E,Z(h,y,x))}catch(r){if(h.busy=!1,h.lastUsedAt=Date.now(),w0.isAbortError(r))throw h.streamFailures=0,h.continuation=void 0,Q1(h),r;let O0=w0.parseRateLimitSignal(r);if(O0)g0?.(O0.window,O0.resetAt);if(w0.isUpgradeFailure(r)&&!H)h.fallback=!0;if(K(h),h.continuation=void 0,Q1(h),h.fallback)return X(E,Z(h,y,x));return KB(new _0(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[b,f]of J){if(f.busy)continue;if(E-f.lastUsedAt<G)continue;Q1(f),J.delete(b)}}function M(){clearInterval(O);for(let E of J.values())Q1(E);J.clear()}function I(E){let b=`${E}:`;for(let[f,l]of J){if(!f.startsWith(b))continue;Q1(l),J.delete(f)}}return Object.assign(V,{close:M,remove:I})}function HW(Y){if(Y.type!=="error"||!R(Y.error)||Y.error.code!==zW)return;return Error(typeof Y.error.message==="string"?Y.error.message:zW)}async function ZB(Y,X){if(X<=0)return!1;return new Promise((J,Q)=>{let G=setTimeout(()=>J(!1),X);Y.then(($)=>{clearTimeout(G),J($)},($)=>{clearTimeout(G),Q($)})})}function KB(Y){return new Response(new ReadableStream({start(X){X.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function OB(Y,X,J,Q,G,$,W){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<G)return Y.socket;Q1(Y);let U=await w0.connectResponsesWebSocket({url:w0.toWebSocketUrl(X),headers:J,timeout:Q,rawWebSocket:$,signal:W??void 0});return Y.connectedAt=Date.now(),U}function Q1(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function qB(Y,X,J,Q){if(!Y.socket||!Array.isArray(X.input)||X.input.length===0)return;let G=jB(X);await y1({sessionID:Q.sessionID,transport:"websocket",phase:"prewarm",bodyText:JSON.stringify(G),url:Q.url,method:"POST",headers:Q.headers});let $=w0.streamResponsesWebSocket({socket:Y.socket,body:G,sessionID:Q.sessionID,idleTimeout:J,signal:Q.signal,onRateLimitReached:Q.onRateLimitReached,onComplete:(W,U)=>{t0({component:"ws-pool",event:"prewarm_completed",sessionID:Q.sessionID,responseID:LW(W),usage:VW(W)}),ZW(Y,G,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=HW(W);if(!U)return;throw Y.fallback=!0,U}});await FB($)}function LW(Y){let X=Y.response;if(!R(X))return;return typeof X.id==="string"?X.id:void 0}function VW(Y){let X=Y.response;if(!R(X))return;return R(X.usage)?X.usage:void 0}async function FB(Y){let X=Y.body?.getReader();if(!X)return;while(!0)if((await X.read()).done)return}function jB(Y){return qY({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:DB(Y.client_metadata)})}function NW(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 DB(Y){if(!R(Y))return Y;if(typeof Y["x-codex-turn-metadata"]!=="string")return Y;try{let X=JSON.parse(Y["x-codex-turn-metadata"]);if(!R(X))return Y;return{...Y,"x-codex-turn-metadata":NW(X),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function PB(Y){let X=Y["x-codex-turn-metadata"];if(!X)return Y;try{let J=JSON.parse(X);if(!R(J))return Y;return{...Y,"x-codex-turn-metadata":NW(J)}}catch{return Y}}var BW=["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 UW(Y){let X={...Y};if(Array.isArray(Y.input))X.input=Y.input.map(MB);return X}function qY(Y){let X={};for(let J of BW)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 MB(Y){if(!R(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 ZW(Y,X,J,Q,G){let $=J.response,W=R($)&&typeof $.id==="string"?$.id:void 0;if(!W||!Array.isArray(X.input)){Y.continuation=void 0;return}let U=G?new Set(Y.continuation?.finalizedCallIds):new Set;for(let H of Q)U.add(H);Y.continuation={responseID:W,input:X.input,signature:t9(X),finalizedCallIds:U}}function a9(Y,X,J=X){let Q=Array.isArray(X.input)?X.input:[],G=Array.isArray(J.input)?J.input:Q,$=t9(J),W=Y.turnInput&&Y.turnSignature===$?wB(Y.turnInput,G):void 0,U=W===void 0?Q:G.slice(W);if(U.length>0&&U.some(qW)||!Y.turnID)Y.turnID=E1(),Y.turnStartedAt=Date.now();Y.turnInput=G.slice(),Y.turnSignature=$}function KW(Y,X,J=X){a9(Y,X,J);let Q=X.client_metadata;if(!R(Q)||typeof Q["x-codex-turn-metadata"]!=="string")return X;let G=OW(Q["x-codex-turn-metadata"],Y.turnID,Y.turnStartedAt);if(!G)return X;return{...X,client_metadata:{...Q,"x-codex-turn-metadata":G}}}function OW(Y,X,J){let Q;try{Q=JSON.parse(Y)}catch{return}if(!R(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 wB(Y,X){if(Y.length>X.length)return;for(let J=0;J<Y.length;J++)if(e0(Y[J])!==e0(X[J]))return;return Y.length}function EB(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!J||!Y.continuation)return X;if(Y.continuation.signature!==t9(X))return Y.continuation=void 0,X;if(!FW(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),G=TB(Q,Y.continuation.finalizedCallIds);if(G.length===0)return X;return{...X,previous_response_id:Y.continuation.responseID,input:G}}function AB(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!Y.continuation)return!0;if(!J)return!1;if(!FW(Y.continuation.input,J))return!0;return J.slice(Y.continuation.input.length).some(qW)}function qW(Y){if(!R(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function TB(Y,X){return Y.filter((J)=>{if(!R(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 t9(Y){return e0(RB(Object.fromEntries(Object.entries(Y).filter(([X])=>X!=="input"&&X!=="stream"&&X!=="background"&&X!=="previous_response_id"&&X!=="generate"))))}function RB(Y){if(!R(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 FW(Y,X){if(Y.length>=X.length)return!1;for(let J=0;J<Y.length;J++)if(e0(Y[J])!==e0(X[J]))return!1;return!0}function jW(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let X=new Headers(Y.headers);for(let J of r9)X.delete(J);return{...Y,headers:X}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((X)=>!r9.has(X[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([X])=>!r9.has(X.toLowerCase())))}}var xB=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),vB=new Set(["gpt-5.6"]),hB=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),gB="opencode-oauth-dummy-key",yB="terminal_resize_reflow",JX="0.144.0",fB=`codex_exec/${JX} (Debian 12.0.0; aarch64) unknown (codex_exec; ${JX})`,mB="seccomp",cB="main-refresh",uB=120000,pB=90000,lB=4000,DW=50,PW=3,dB=25,iB=60000,nB="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",MW=!1,wW=N0("models"),EW=!1,AW=!1;class GX 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 TW(Y,X,J,Q){let G=(J?.refresh?.refreshBeforeExpiryMinutes??240)*60000;return!Y||!X||X-Q<=G}function oB(Y){return async(X)=>{if(X==="main"){let U=await Y.loadAccounts(Y.accountStoragePath),H=await Y.getAuth();if(H.type!=="oauth")throw new d0("non_oauth_account","Main OpenAI account is not authenticated with OAuth.");if(TW(H.access,H.expires,U,Y.now()))H={type:"oauth",...await Y.refreshMainWithLease()};if(!H.access)throw new d0("token_unavailable","Main OpenAI account has no usable access token.");let L=i1(H.access),N=L?n1(L):void 0,O=await Y.loadAccounts(Y.accountStoragePath);return{accountKey:X,label:"Main account",accessToken:H.access,chatgptAccountId:N??O?.mainAccountId}}let J=await Y.loadAccounts(Y.accountStoragePath),Q=J?.accounts.find((U)=>U.id===X);if(!J||!Q)throw new 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 G=Q;if(TW(G.access,G.expires,J,Y.now()))G=await Y.refreshFallbackAccount(G,J);if(!G.access)throw new d0("token_unavailable",`Fallback account ${X} has no usable access token.`);let $=await Y.loadAccounts(Y.accountStoragePath),W=$?.accounts.find((U)=>U.id===X);if(!$||!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:G.label??X,accessToken:G.access,chatgptAccountId:W.accountId}}}function rB(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function YX(Y){return Y instanceof GX}function RW(){throw Error(nB)}function sB(Y){return Math.floor(Math.random()*Y)}function aB(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 tB(Y,X,J){let Q=Y.get(X);if(Q)return Q;let G=E1(),$={threadID:G,turnID:E1(),windowID:`${G}:0`};return Y.set(X,$),J?.(),$}function z5(){return bB(CY(),"openai-auth-sessions.json")}function eB(){let Y=new Map;try{let X=JSON.parse(_B(z5(),"utf8"));if(!R(X.sessions))return Y;for(let[J,Q]of Object.entries(X.sessions)){if(!R(Q)||typeof Q.threadID!=="string")continue;Y.set(J,{threadID:Q.threadID,turnID:E1(),windowID:`${Q.threadID}:0`})}}catch{}return Y}function YZ(Y){let X=z5(),J=`${X}.tmp-${process.pid}`;try{CB(CY(),{recursive:!0});let Q={version:1,sessions:Object.fromEntries([...Y.entries()].map(([G,$])=>[G,{threadID:$.threadID}]))};kB(J,`${JSON.stringify(Q,null,2)}
218
- `,"utf8"),IB(J,X)}catch{}}function CW(Y,X){return R(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===X}function XZ(Y,X){if(Y.length>X.length)return!1;for(let J=0;J<Y.length;J++)if(e0(Y[J])!==e0(X[J]))return!1;return!0}function JZ(Y,X){if(!Y.input)return X.length>0;if(!XZ(Y.input,X))return!0;return X.slice(Y.input.length).some((Q)=>CW(Q,"user")||CW(Q,"developer"))}function QZ(Y,X){let J=Array.isArray(X?.input)?X.input:void 0;if(J&&(JZ(Y,J)||!Y.turnID))Y.turnID=E1(),Y.turnStartedAt=Date.now();else if(!Y.turnStartedAt)Y.turnStartedAt=Date.now();if(J)Y.input=J}function GZ(Y){if(!Y.metadata)return{init:Y.init};let X=aB(Y.init?.body);if(!Y.websocket)QZ(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:mB,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",yB),Y.headers.set("x-codex-turn-metadata",J),Y.headers.set("user-agent",fB),Y.headers.set("version",JX),Y.dumpSessionID)Y.headers.set(z1,Y.dumpSessionID);let Q=X;if(!Q)return{init:Y.init};let G=Y.responsesLite&&typeof Q.model==="string"&&hB.has(Q.model);if(G&&!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(VZ);if(HZ(Q),LZ(Q),BJ(Q),zZ(Q),G)UZ(Q);let $={...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($["x-codex-turn-metadata"]=J,$["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=$,Y.headers.delete("content-length"),Y.headers.delete("Content-Length"),{init:{...Y.init,body:JSON.stringify(qY(Q))}}}function $Z(Y,X){return Y.find((J)=>J.enabled!==!1&&i0(J)&&(J.id===X||J.accountId===X))}function _W(Y,X){if(!X)return Y;let J={...Y};for(let Q of["resetCreditsAvailable","resetCreditsApplicable"]){let G=X[Q];if(J[Q]===void 0&&G!==void 0)J[Q]=G}return J}function L8(Y,X){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:X}}function U5(Y,X,J=Date.now(),Q=X.mainAccountId){let G=Y.getMain(),$=G?.quota;return{main:{quota:$?{...$,checkedAt:G.checkedAt,primary:L8($.primary,G.checkedAt),secondary:L8($.secondary,G.checkedAt)}:null,...typeof Q==="string"?{mainAccountId:Q}:{},killed:!1,...$?.resetCreditsAvailable!==void 0?{resetCredits:$.resetCreditsAvailable}:{}},fallbacks:X.accounts.filter((W)=>W.enabled).map((W)=>{let U=Y.getFallback(W.id),H=U?.quota;return{id:W.id,label:W.label,accountId:U?.accountId??W.accountId,quota:H?{...H,checkedAt:U.checkedAt,primary:L8(H.primary,U.checkedAt),secondary:L8(H.secondary,U.checkedAt)}:null,killed:!1,enabled:!0,...H?.resetCreditsAvailable!==void 0?{resetCredits:H.resetCreditsAvailable}:{}}}),route:X.routing?.mode??"main-first",lastUpdated:J}}function wF(Y,X,J,Q=Date.now()){return{...U5(Y,X,Q),activeId:J}}function IW(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 WZ(Y,X){if(!(Y instanceof Request))return X;let J=new Request(Y,X),Q=J.method.toUpperCase(),G=Q==="GET"||Q==="HEAD"||J.body===null?void 0:await J.text();return{method:J.method,headers:new Headers(J.headers),body:G,signal:J.signal,cache:J.cache,credentials:J.credentials,integrity:J.integrity,keepalive:J.keepalive,mode:J.mode,redirect:J.redirect,referrer:J.referrer,referrerPolicy:J.referrerPolicy}}function SW(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}function zZ(Y){if(!A0().webSearch)return;if(!Array.isArray(Y.tools)||Y.tools.length===0)return;if(Y.tools.some((X)=>R(X)&&X.type==="web_search"))return;Y.tools=[...Y.tools,{type:"web_search",external_web_access:!1,search_content_types:["text","image"]}]}function QX(Y){if(Array.isArray(Y)){for(let X of Y)QX(X);return}if(!R(Y))return;if(Y.type==="input_image")delete Y.detail;for(let X of Object.values(Y))QX(X)}function UZ(Y){let X=R(Y.reasoning)?{...Y.reasoning}:{};X.context="all_turns",Y.reasoning=X,Y.parallel_tool_calls=!1;let J=Array.isArray(Y.input)?Y.input:[];QX(J);let G=[{type:"additional_tools",role:"developer",tools:Array.isArray(Y.tools)?Y.tools.filter(($)=>!(R($)&&$.type==="web_search")):[]}];if(typeof Y.instructions==="string"&&Y.instructions.length>0)G.push({type:"message",role:"developer",content:[{type:"input_text",text:Y.instructions}]});Y.input=[...G,...J],delete Y.tools,delete Y.instructions}function HZ(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(R(X)&&X.type==="function"&&X.name==="web_search"))}function LZ(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(R(X)&&X.type==="function"&&X.name==="websearch_web_search_exa"))}function VZ(Y){if(!R(Y))return Y;if(Y.type!=="function")return Y;let X=R(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:H,...L}=Y.parameters;return L})():Y.parameters,{type:J,name:Q,description:G,strict:$,parameters:W,...U}=Y;return{type:J,name:Q,description:G,strict:$??!1,parameters:X,...U}}async function NZ(Y,X={}){let J=X.codexApiEndpoint??A0().codexApiEndpoint,Q=crypto.randomUUID(),G=eB(),$=()=>YZ(G),W=!1,U=[],H=null,L=null,N,O=new b8;async function Z(V,K){let j=Y.client.session;if(typeof j?.promptAsync==="function"){let M=await PJ(Y.client,V),I={noReply:!0,parts:[{type:"text",text:K,ignored:!0}]};if(M?.agent)I.agent=M.agent;if(M?.model)I.model=M.model;if(M?.variant)I.variant=M.variant;await j.promptAsync({path:{id:V},body:I});return}}return{async dispose(){O.stop();for(let V of U)V.close();if(U.length=0,L){await L.stop().catch(()=>{});let V=globalThis;if(V.__openaiAuthRpcServer===L)V.__openaiAuthRpcServer=void 0;L=null}},async event(V){if(V.event.type!=="session.deleted")return;let K=V.event.properties.info,j=G.get(K.id);if(j)H?.cacheKeepManager?.remove(j.threadID);if(G.delete(K.id))$();if(N){let M=(await D0($0()))?.accounts;await Q5(K.id,M,N)}for(let M of U)M.remove(K.id)},provider:{id:"openai",async models(V,K){if(K.auth?.type!=="oauth")return V.models;let j=await D0($0()),M=!j||nW(j),I=M?null:await qJ();if(!M&&I&&!EW)EW=!0,wW.debug("restoring OAuth model costs from models.dev catalog");if(!M&&!I&&!AW)AW=!0,wW.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(V.models).filter(([,E])=>{if(E.options.reasoningMode==="pro")return!1;if(xB.has(E.api.id))return!0;if(vB.has(E.api.id))return!1;let f=E.api.id.match(/^gpt-(\d+\.\d+)/)?.[1];return f?parseFloat(f)>5.4:!1}).map(([E,b])=>[E,{...b,cost:M?{input:0,output:0,cache:{read:0,write:0}}:I?.[b.api.id]??I?.[E]??b.cost,limit:b.id.includes("gpt-5.5")?{context:400000,input:272000,output:128000}:b.id.includes("gpt-5.6")?{context:372000,input:244000,output:128000}:b.limit}]))}},tool:{web_search:VJ},auth:{provider:"openai",async loader(V){let K=await V();if(K.type!=="oauth")return{};await rW({type:"oauth",access:K.access??"",refresh:K.refresh??"",expires:K.expires??0},$0());let j=await D0($0()).catch((B)=>{let q=$0();throw Error(`OpenAI auth store at ${q} is corrupt or unreadable: ${B instanceof Error?B.message:String(B)}. Fix or remove it to continue.`,{cause:B})}),M;async function I(){let B=$0();try{let q=SB(B);if(M?.path===B&&M.mtimeMs===q.mtimeMs&&M.size===q.size)return M.storage;let D=await D0(B);return M={path:B,mtimeMs:q.mtimeMs,size:q.size,storage:D},D}catch{return M=void 0,D0(B)}}function E(){M=void 0}if(j&&K.access){let B=V8({id_token:"",access_token:K.access,refresh_token:K.refresh??""});if(B&&B!==j.mainAccountId)await J0((q)=>{return q.mainAccountId=B,q},$0()),j.mainAccountId=B,E()}let b=j?.logging?.level;if(b&&typeof b==="string")kY(b);let f=N0("transport"),l=N0("quota"),K0=N0("refresh"),x=N0("accounts");f.info("codex auth loader ready",{codexApiEndpoint:J,transport:A0().rawWebSocket?"raw-websocket":A0().webSockets?"websocket":"http",webSearch:A0().webSearch});let y=new iW({storage:j,fetchQuotaFn:void 0}),u,L0=0,Y0=new sW({refreshFn:(B)=>I1({refreshToken:B.refreshToken,fetchImpl:B.fetchImpl,now:B.now}),quotaManager:y,onFallbackStorageChanged:E});if(j&&j.accounts.length>0)Y0.startBackgroundRefresh();let Q0=N0("cachekeep"),q1=j?.cachekeep?.enabled===!0,d=j?.cachekeep?.subagents===!0,g0=j?.cachekeep?.sustain===!0,h=sX(j),r;async function O0(B){await new Promise((q)=>setTimeout(q,B))}async function B8(B){let q;for(let D=1;D<=PW;D++)try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:B.refresh,access:B.access,expires:B.expires}});return}catch(T){if(q=T,D<PW)await O0(dB*D)}throw new GX(q)}async function S1(B){await J0((q)=>{return q.refresh=q.refresh??{},B(q),q},$0()),E()}async function wY(B){let q=Date.now()+lB;while(Date.now()<q){await new Promise((S)=>setTimeout(S,DW+sB(DW)));let D=await V();if(D.type!=="oauth"||!D.access)continue;if((D.access!==B.access||D.refresh!==B.refresh||(D.expires??0)>(B.expires??0)+60000)&&(!D.expires||D.expires>Date.now()))return K0.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:D.expires?D.expires-Date.now():void 0}),{access:D.access,refresh:D.refresh??B.refresh??"",expires:D.expires??0}}return null}async function n0(){if(!r)r=(async()=>{let B=await V();if(B.type!=="oauth")throw Error("not oauth");if(!B.refresh)throw Error("Token refresh failed: missing refresh token");let q=kW(B.refresh),D=await D0($0()),T=D?.refresh?.mainLastRefreshError;if(T&&xW(T,B.refresh,Date.now()))throw Error(vW(T,Date.now()));if(D?.refresh?.mainRefreshLeaseUntil&&D.refresh.mainRefreshLeaseUntil>Date.now()&&D.refresh.mainRefreshLeaseTokenHash===q){let _=await wY(B);if(_)return _;throw Error("Codex OAuth refresh is already in progress")}let S=await bY({name:cB,ttlMs:uB,path:$0(),renew:!0});if(!S){let _=await wY(B);if(_)return _;throw Error("Codex OAuth refresh is already in progress")}let C=crypto.randomUUID(),w=q;try{await S1((g)=>{g.refresh=g.refresh??{},g.refresh.mainRefreshLeaseId=C,g.refresh.mainRefreshLeaseUntil=Date.now()+pB,g.refresh.mainRefreshLeaseTokenHash=q});let _=await D0($0());if(_?.refresh?.mainRefreshLeaseId!==C||_.refresh.mainRefreshLeaseTokenHash!==q)throw Error("Codex OAuth refresh is already in progress");let P=await I1({refreshToken:B.refresh,fetchImpl:fetch,now:Date.now});return await B8(P),await S1((g)=>{if(g.refresh=g.refresh??{},g.refresh.mainLastRefreshError=void 0,g.refresh.mainRefreshLeaseId===C)g.refresh.mainRefreshLeaseId=void 0,g.refresh.mainRefreshLeaseUntil=void 0,g.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),w=void 0,P}catch(_){if(B.refresh&&!YX(_))await S1((P)=>{P.refresh=P.refresh??{},P.refresh.mainLastRefreshError=bW({error:_,now:Date.now(),refreshToken:B.refresh??"",previous:P.refresh.mainLastRefreshError})}).catch(()=>{});throw _}finally{if(w)await S1((_)=>{if(_.refresh?.mainRefreshLeaseId===C&&_.refresh.mainRefreshLeaseTokenHash===w)_.refresh.mainRefreshLeaseId=void 0,_.refresh.mainRefreshLeaseUntil=void 0,_.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await S.release().catch(()=>{})}})().finally(()=>{r=void 0});return r}let G1=globalThis;G1.__openaiAuthCacheKeepManager?.stop();let o0=new y8({fetchImpl:fetch,getMainToken:async()=>{let B=await V();if(B.type!=="oauth")throw Error("not oauth");if(!B.access||(B.expires??0)<Date.now())try{return(await n0()).access}catch(q){if(YX(q))throw q;if(B.access)return B.access;throw Error("main token refresh failed")}return B.access},refreshFallback:async(B)=>{let q=await I(),D=q?$Z(q.accounts,B):void 0;if(!D)throw Error(`fallback account ${B} not found`);let T=await Y0.refreshAccount(D,q??{version:1,accounts:[D]});if(!T.access)throw Error(`no access token for ${B}`);return T.access},codexResponsesUrl:J,logger:Q0,now:Date.now,getWindow:()=>h,getSustain:()=>g0});G1.__openaiAuthCacheKeepManager=o0;async function F1(B,q,D,T,S=!1){if(Object.keys(B).length===0&&!S)return;let C=Date.now(),w=B,_={quota:w,refreshAfter:C+300000,checkedAt:C},P;if(D&&D!=="main"){let k=q?i1(q):null,X0=k?n1(k):void 0,q0=y.peekFallbackForPolicy(D)?.quota,m0=_W(w,q0);_={..._,quota:m0},y.setFallback(D,_,q,S,X0)}else{if(P=T,!P&&q){let q0=i1(q);P=q0?n1(q0):void 0}if(P&&u&&P!==u){l.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:P,currentMainIdentity:u});return}let k=y.peekMainForPolicy(P)?.quota,X0=_W(w,k);_={..._,quota:X0},y.setMain(q,_,P,S)}l.debug("quota pushed",{pid:process.pid,accountId:D??"main",snapshot:_.quota});let g=await I();await y0(y,g,D&&D!=="main"?g?.mainAccountId:P)}function Z8(B,q,D){let T=B==="main"?y.peekMainForPolicy()?.quota:y.peekFallbackForPolicy(B)?.quota;return dW(T,q,Date.now(),iB,D)}let r0=X.experimentalWebSockets?O1.createWebSocketFetch({httpFetch:fetch,rawWebSocket:A0().rawWebSocket,onQuota:(B,q,D,T)=>{F1(B,q,D,!D||D==="main"?T:void 0,!0)},onRateLimitReached:(B,q,D)=>{if(!q)l.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:B});let T=q??"main",S=Z8(T,B,D);y.markRateLimited(T,S),l.debug("mid-stream rate limit mark",{pid:process.pid,accountId:T,window:B})}}):void 0;if(r0)U.push(r0),W=!0;let P0=aW();N=P0;async function y0(B,q,D=q?.mainAccountId){if(!q)return;await X5(U5(B,q,Date.now(),D),P0)}async function f0(B,q,D,T,S){let C={activeId:D,route:T,updatedAt:Date.now()};if(B){if(await N8({sessionId:B,...C},S,P0),q&&q!==B){if(T==="sticky-balanced"){let w=(await w1(P0)).stickyAssignments?.[MY(q)]?.accountId,_=S===void 0||w==="main"||S.some((P)=>P.enabled!==!1&&P.id===w);if(!w||!_)return;await N8({sessionId:q,activeId:w,route:T,updatedAt:Date.now()},S,P0);return}await N8({sessionId:q,...C},S,P0)}return}await J5(C,P0)}H={accountStoragePath:$0(),quotaManager:y,loadAccounts:D0,client:Y.client,resolveResetTarget:oB({getAuth:V,refreshMainWithLease:n0,refreshFallbackAccount:(B,q)=>Y0.refreshAccount(B,q),loadAccounts:D0,accountStoragePath:$0(),now:Date.now}),...rB(),cacheKeepManager:o0,setCacheKeepEnabled:(B)=>{q1=B},setCacheKeepSubagents:(B)=>{d=B},setCacheKeepSustain:(B)=>{g0=B},setCacheKeepWindow:(B)=>{h=B},clearStickyRouting:(B)=>$5(B,P0),getStickyRouting:async(B)=>Y5(await w1(P0),B),refreshSidebar:async()=>{let B=await D0($0());await y0(y,B)},refreshAllQuota:async()=>v1({getAuth:V,codexRefreshFn:I1,refreshMainWithLease:n0,fallbackManager:Y0,quotaManager:y,loadAccounts:D0,writeSidebarState:y0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:$0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:i0,whamFn:$1}),refreshResetTargetQuota:async(B)=>{return(await v1({getAuth:V,codexRefreshFn:I1,refreshMainWithLease:n0,fallbackManager:Y0,quotaManager:y,loadAccounts:D0,writeSidebarState:y0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:$0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:i0,whamFn:$1,respectBackoff:!1},{accountKey:B})).find((D)=>D.account===B)??{account:B,ok:!1,error:"targeted quota refresh returned no result"}}};let G0=null;if(Y.directory){let B=await W5(Y.directory),q=globalThis;if(q.__openaiAuthRpcServer)await q.__openaiAuthRpcServer.stop().catch(()=>{}),q.__openaiAuthRpcServer=void 0;try{G0=await CJ({dir:B.dir,secureDir:B.secureDir,sweepRoot:B.sweepRoot,drain:wJ,apply:async(D)=>{let T={...H,sessionId:D.sessionId},S=await k8(D.command,D.arguments,T);return{text:S.text,knobs:S.knobs}}}),q.__openaiAuthRpcServer=G0,L=G0}catch{}}async function I0(B,q,D,T,S="main"){let C=IW(B,q);if(C.delete("x-api-key"),C.delete("api-key"),C.set("authorization",`Bearer ${D}`),T)C.set("ChatGPT-Account-Id",T);C.set(O1.QUOTA_ACCOUNT_HEADER,S);let w=SW(C),_=w?tB(G,w,$):void 0,P=B instanceof URL?B:new URL(typeof B==="string"?B:B.url),g=P.pathname.includes("/v1/responses")||P.pathname.includes("/chat/completions")?new URL(J):P,X0=GZ({init:{...q,headers:C},headers:C,metadata:_,installationID:Q,websocket:Boolean(r0&&P.pathname.endsWith("/responses")),responsesLite:X.responsesLite??!1,dumpSessionID:w}).init,q0=q1,m0=new Headers(X0?.headers),z0=rX({enabled:q0,includeSubagents:d,headers:m0,body:X0?.body});if(q0)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&&P.pathname.endsWith("/responses")){if(f.debug("WS transport",{pid:process.pid,pathname:P.pathname,accountId:S}),z0)o0.track(z0.sessionKey,z0.bodyText,S,T,z0.replayHeaders,z0.isSubagent);return r0(g,X0)}let Z0=O1.withoutInternalHeaders(X0);if(typeof Z0?.body!=="string")return fetch(g,Z0);if(z0)o0.track(z0.sessionKey,z0.bodyText,S,T,z0.replayHeaders,z0.isSubagent);f.debug("HTTP transport",{pid:process.pid,pathname:P.pathname,accountId:S});try{let S0=await fetch(g,Z0);return await y1({sessionID:w,transport:"http",phase:"http",bodyText:Z0.body,accountId:S,url:g.toString(),method:Z0.method,headers:Z0.headers,status:S0.status}),NJ(S0)}catch(S0){throw await y1({sessionID:w,transport:"http",phase:"http",bodyText:Z0.body,accountId:S,url:g.toString(),method:Z0.method,headers:Z0.headers,error:S0 instanceof Error?S0.message:String(S0)}),S0}}function k1(B,q){if((q?.method??(B instanceof Request?B.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof q?.body!=="string")return!1;try{let T=B instanceof URL?B.toString():typeof B==="string"?B:B.url;return new URL(T).pathname.endsWith("/responses")}catch{return!1}}function H5(B){return y.peekMainForPolicy(B)?.quota}function $X(B,q){for(let D of[B?.primary?.checkedAt,B?.secondary?.checkedAt,B?.checkedAt,q])if(typeof D==="number"&&Number.isFinite(D))return D;return}function o1(B,q,D,T,S){let C=$X(B,q),w=$X(D),_=T===S&&D!=null&&(B===void 0||w!==void 0&&(C===void 0||w>C));return{quota:_?D:B,quotaCheckedAt:_?w:C,source:_?"file":"memory"}}function WX(B,q,D,T,S){let C=B?.quota,w=o1(C,B?.checkedAt,q,T,S),_=w.source,P=w.quota;if(!eW(P,D))return{exhausted:!1};let g=tW(P,D);if(!g)return{exhausted:!1};return{exhausted:!0,source:_,...g}}function zX(B,q){l.debug("admission skip: exhausted account",{accountId:B,source:q.source,resetsAt:q.resetsAt})}function L5(B,q="killswitch",D){let T=Date.now(),S=y.getMain()?.quota,C=(B?.accounts??[]).filter((k)=>k.enabled!==!1&&i0(k)).map((k)=>({accountId:k.id,quota:y.getFallback(k.id)?.quota})),w=oW(S,C,T,B);if(q==="quota-exhausted"&&D!==void 0)w=Math.max(1,Math.ceil((D-T)/1000));else if(q==="mid-stream-rate-limit"&&D!==void 0){let k=Math.max(1,Math.ceil((D-T)/1000));w=Math.min(w,k)}let _=Math.floor(w/60),P=w%60,g=q==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${_}m ${P}s.`:q==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${_}m ${P}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${_}m ${P}s.`;return new Response(JSON.stringify({error:{message:g,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(w)}})}function UX(B){let q=B?.resetCreditsAvailable;return typeof q==="number"&&Number.isFinite(q)?q:void 0}async function V5(B){let q=DY(B.storage),D=Date.now(),T=y.peekMainForPolicy(B.mainAccountIdentity),S=o1(T?.quota,T?.checkedAt,B.sidebarState.main.quota,B.sidebarState.main.mainAccountId,B.mainAccountIdentity),C=q?PY(T?.quota,B.storage,void 0,D):void 0,w=[{accountId:"main",wireAccountId:B.mainAccountIdentity,access:B.primaryAccess,keepwarmAccountKey:"main",quota:S.quota,quotaCheckedAt:S.quotaCheckedAt,reservePercent:XX(B.storage),configuredOrder:0,resetCreditsApplicable:UX(S.quota),killswitchPasses:C}],_=await Y0.getUsableFallbackAccounts(B.storage);for(let P of _){if(!P.access)continue;let g=B.sidebarState.fallbacks.find((m0)=>m0.id===P.id),k=y.peekFallbackForPolicy(P.id,P.accountId),X0=o1(k?.quota,k?.checkedAt,g?.quota,g?.accountId,P.accountId),q0=q?PY(k?.quota,B.storage,P.id,D):void 0;w.push({accountId:P.id,wireAccountId:P.accountId,access:P.access,keepwarmAccountKey:P.id,fallback:P,quota:X0.quota,quotaCheckedAt:X0.quotaCheckedAt,reservePercent:XX(B.storage,P.id),configuredOrder:w.length,resetCreditsApplicable:UX(X0.quota),killswitchPasses:q0})}return w}function HX(B,q,D,T,S){let C=DY(S)?B.killswitchPasses:void 0;if(B.accountId==="main"){let g=y.peekMainForPolicy(B.wireAccountId),k=o1(g?.quota,g?.checkedAt,q.main.quota,q.main.mainAccountId,B.wireAccountId);return c8({quota:k.quota,quotaCheckedAt:k.quotaCheckedAt,status:D,now:T,killswitchPasses:C})}let w=q.fallbacks.find((g)=>g.id===B.accountId),_=y.peekFallbackForPolicy(B.accountId,B.wireAccountId),P=o1(_?.quota,_?.checkedAt,w?.quota,w?.accountId,B.wireAccountId);return c8({quota:P.quota,quotaCheckedAt:P.quotaCheckedAt,status:D,now:T,killswitchPasses:C})}function N5(B){return B.accountId==="main"?"main":B.keepwarmAccountKey}function LX(B){return y.isRateLimited(N5(B))}async function K8(B){let q=B.candidates.filter((P)=>!LX(P)),D=new Map(q.map((P)=>[P.accountId,P])),T=Object.fromEntries(q.map((P)=>[P.accountId,P.quotaCheckedAt])),S=Object.fromEntries(q.map((P)=>[P.accountId,P.wireAccountId])),C=new Set(B.excludeAccountIds),w,_=await G5({sessionId:B.sessionId,requestBytes:B.requestBytes,now:B.now,validPinnedAccountIds:[...D.keys()],excludeAccountIds:B.excludeAccountIds,quotaCheckedAtByAccount:T,wireAccountIdByAccount:S,choose:(P)=>{let g=q.filter((X0)=>!C.has(X0.accountId));if(g.length===0)return;let k=QJ({candidates:g,pendingBytes:P,requestBytes:B.requestBytes,now:B.now,onEmptyWeightedSet:()=>{x.debug("sticky routing: no fresh weighted candidates; using configured order")}});if(!k)return;return w={accountId:k.accountId,source:k.source,pendingBytes:P.get(k.accountId)??0},k}},P0);if(w&&_?.accountId===w.accountId)x.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:MY(B.sessionId),accountId:w.accountId,source:w.source,requestBytes:B.requestBytes,pendingBytes:w.pendingBytes});return _?D.get(_.accountId):void 0}async function B5(B,q){let D=await Y0.getUsableFallbackAccounts(B),T=[];for(let k of D)if(k.access)T.push({access:k.access,accountId:k.accountId,keepwarmAccountKey:k.id,quotaAccountId:k.id,fallback:k});let S=T.filter((k)=>!y.isRateLimited(k.quotaAccountId)),C=DY(B)?S.filter((k)=>PY(y.peekFallbackForPolicy(k.quotaAccountId,k.accountId)?.quota,B,k.quotaAccountId,Date.now())):S,w=new Map(q.fallbacks.map((k)=>[k.id,{quota:k.quota,accountId:k.accountId}])),_=[],P=[],g=Date.now();for(let k of C){let X0=w.get(k.quotaAccountId),q0=WX(y.peekFallbackForPolicy(k.quotaAccountId,k.accountId),X0?.quota,g,X0?.accountId,k.accountId);if(q0.exhausted)P.push({candidate:k,decision:q0});else _.push(k)}return{current:C,retained:_,skipped:P}}function VX(B,q){if(B.retained.length===0&&!q)return B.current;for(let{candidate:D,decision:T}of B.skipped)zX(D.quotaAccountId,T);return B.retained}async function NX(B,q){try{let D=h1(B.headers);await F1(D,q.access,q.quotaAccountId,void 0,FY(B.headers))}catch{}}async function Z5(B,q,D,T){for(let S of T){let C;try{C=await I0(B,q,S.access,S.accountId,S.keepwarmAccountKey)}catch(w){if(w instanceof DOMException&&w.name==="AbortError")throw w;if(q?.signal?.aborted)throw w;throw x.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:S.quotaAccountId}),w}if(!jY(C.status,D))return Y0.markUsed(S.fallback),{response:C,accessToken:S.access,quotaAccountId:S.quotaAccountId,activeId:S.keepwarmAccountKey};await NX(C,S),C.body?.cancel().catch(()=>{})}return}async function K5(B,q,D,T,S){if(!k1(B,q))return{response:D};if(!S.length)return{response:D};let C=D,w;for(let _ of S){let P;try{P=await I0(B,q,_.access,_.accountId,_.keepwarmAccountKey)}catch(g){if(g instanceof DOMException&&g.name==="AbortError")throw g;if(q?.signal?.aborted)throw g;return x.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:_.quotaAccountId}),{response:C,...w}}if(C.body?.cancel().catch(()=>{}),C=P,w={accessToken:_.access,accountId:_.quotaAccountId},!jY(P.status,T))return Y0.markUsed(_.fallback),{response:P,...w};await NX(P,_)}return{response:C,...w}}if(!MW){if(MW=!0,j){let B=[];for(let q of j.accounts)if(i0(q))B.push(q);y.seedFallbacksFromAccounts(B)}y0(y,j).catch(()=>{}),v1({getAuth:V,codexRefreshFn:I1,refreshMainWithLease:n0,fallbackManager:Y0,quotaManager:y,loadAccounts:D0,writeSidebarState:y0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:$0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:i0,whamFn:$1,respectBackoff:!0}).catch((B)=>l.warn("boot quota seed failed",{pid:process.pid,error:W1(B)}))}return O.start(async()=>{let q=(await lX({getAuth:V,codexRefreshFn:I1,refreshMainWithLease:n0,fallbackManager:Y0,quotaManager:y,loadAccounts:D0,writeSidebarState:(D,T)=>O.isStopped()?Promise.resolve():y0(D,T),client:Y.client,fetchImpl:fetch,now:Date.now,configPath:$0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:i0,whamFn:$1,readSidebarState:()=>w1(P0)})).filter((D)=>!D.ok);if(q.length>0)l.warn("background quota refresh completed with failures",{pid:process.pid,failures:q})},(B)=>{l.warn("background quota refresh failed",{pid:process.pid,error:B instanceof Error?B.message:String(B)})}),{apiKey:gB,async fetch(B,q){let D=IW(B,q),T=SW(D),S=D.get("x-parent-session-id")?.trim()||void 0,C=await I(),w=await V(),_=++L0;if(w.type!=="oauth")return fetch(B,q);q=await WZ(B,q);let P=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(YX(e))throw e}}P=w.access??"";let k=w.accountId??(P?n1(i1(P)??{}):void 0);if(_===L0)u=k;let X0=C?.routing?.mode??"main-first",q0,z0=await(()=>{return q0??=w1(P0),q0})();if(X0==="sticky-balanced"&&T&&k1(B,q)&&typeof q?.body==="string"){let e=Buffer.byteLength(q.body,"utf8"),V0=await V5({storage:C,sidebarState:z0,primaryAccess:P,mainAccountIdentity:k}),H0=await K8({sessionId:T,requestBytes:e,candidates:V0,now:Date.now()});if(H0){let jX=LX(H0)?{action:"migrate",reason:"exhausted"}:HX(H0,z0,void 0,Date.now(),C);if(jX.action==="migrate"){let E0=await K8({sessionId:T,requestBytes:e,candidates:V0,excludeAccountIds:[H0.accountId],now:Date.now()});if(E0)x.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:MY(T),fromAccountId:H0.accountId,toAccountId:E0.accountId,reason:jX.reason}),H0=E0}let c0=await I0(B,q,H0.access,H0.wireAccountId,H0.keepwarmAccountKey),DX=async(E0,j1)=>{try{let O5=h1(E0.headers);await F1(O5,j1.access,j1.accountId==="main"?void 0:j1.accountId,j1.accountId==="main"?j1.wireAccountId:void 0,FY(E0.headers))}catch{}};await DX(c0,H0);let PX=HX(H0,z0,c0.status,Date.now(),C);if((c0.status===401||c0.status===403||c0.status===429)&&PX.action==="migrate"){let E0=await K8({sessionId:T,requestBytes:e,candidates:V0,excludeAccountIds:[H0.accountId],now:Date.now()});if(E0){x.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:MY(T),fromAccountId:H0.accountId,toAccountId:E0.accountId,reason:PX.reason});let j1=c0;c0=await I0(B,q,E0.access,E0.wireAccountId,E0.keepwarmAccountKey),j1.body?.cancel().catch(()=>{}),H0=E0,await DX(c0,H0)}}if(H0.fallback&&!jY(c0.status,C))Y0.markUsed(H0.fallback);return await f0(T,S,H0.accountId,X0,C?.accounts).catch(()=>{}),c0}}let Z0=WX(y.peekMainForPolicy(k),z0.main.quota,Date.now(),z0.main.mainAccountId,k),S0=DY(C)&&!PY(H5(k),C,void 0,Date.now()),EY=y.isRateLimited("main"),BX,O8=()=>{return BX??=B5(C,z0),BX},s0,b1,ZX=!1,AY;if(X0==="fallback-first"&&k1(B,q)){ZX=!0;let e=await O8();AY=VX(e,!S0&&!EY&&!Z0.exhausted);let V0=await Z5(B,q,C,AY);if(V0)s0=V0.response,b1={accessToken:V0.accessToken,accountId:V0.quotaAccountId,activeId:V0.activeId}}if(!s0){let e=Z0.exhausted&&k1(B,q)&&(await O8()).retained.length>0;if(S0||EY||e){let V0=S0?"killswitch":EY?"mid-stream-rate-limit":"quota-exhausted";if(V0==="quota-exhausted"&&Z0.exhausted)zX("main",Z0);x.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:V0}),s0=L5(C,V0,V0==="quota-exhausted"&&Z0.exhausted?Z0.resetAtMs:EY?y.rateLimitedUntil("main"):void 0)}else s0=await I0(B,q,P,k,"main")}let KX=Boolean(b1),r1=s0,OX=b1?.accessToken??P,qX=b1?.accountId,FX=b1?.activeId??"main";if(!b1&&!ZX&&jY(s0.status,C)){x.debug("reactive fallback triggered",{pid:process.pid,status:s0.status}),AY??=VX(await O8(),!1);let e=await K5(B,q,s0,C,AY),V0=e.response;if(V0!==s0){if(KX=!0,r1=V0,OX=e.accessToken??P,qX=e.accountId,e.accountId)FX=e.accountId}}try{let e=h1(r1.headers);if(KX)await F1(e,OX,qX,void 0,FY(r1.headers));else await F1(e,P,void 0,k,FY(r1.headers))}catch{}return await f0(T,S,FX,X0,C?.accounts).catch(()=>{}),r1},async dispose(){if(O.stop(),o0.stop(),G1.__openaiAuthCacheKeepManager===o0)G1.__openaiAuthCacheKeepManager=void 0;if(Y0.stopBackgroundRefresh(),L){await L.stop().catch(()=>{});let B=globalThis;if(B.__openaiAuthRpcServer===L)B.__openaiAuthRpcServer=void 0;L=null}}}},methods:[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:async()=>{let{redirectUri:V}=await cW(),K=await yW(),j=gW(crypto.getRandomValues(new Uint8Array(32)).buffer),M=fW(V,K,j),I=uW(K,j);return{url:M,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let E=await I,b=V8(E);return{type:"success",refresh:E.refresh_token,access:E.access_token,expires:Date.now()+(E.expires_in??3600)*1000,accountId:b}}finally{mW(j)}}}}},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:async()=>{let{deviceData:V,url:K,instructions:j}=await pW();return{url:K,instructions:j,method:"auto",async callback(){try{let M=await lW(V);return{type:"success",refresh:M.refresh_token,access:M.access_token,expires:Date.now()+(M.expires_in??3600)*1000,accountId:V8(M)}}catch{return{type:"failed"}}}}}},{label:"Manually enter API Key",type:"api"}]},"chat.headers":async(V,K)=>{if(V.model.providerID!=="openai")return;if(K.headers.originator="opencode",K.headers["User-Agent"]=`${hW} (${e9.platform()} ${e9.release()}; ${e9.arch()})`,K.headers["session-id"]=V.sessionID,W&&V.agent==="title")K.headers[O1.TITLE_HEADER]="true"},"chat.params":async(V,K)=>{if(V.model.providerID!=="openai")return;K.maxOutputTokens=void 0},config:async(V)=>{V.command={...V.command??{},[A8]:{template:A8,description:"Show current OpenAI Codex OAuth quota usage for all accounts."},[T8]:{template:T8,description:"Manage OpenAI accounts — add, switch, remove, or reorder."},[R8]:{template:R8,description:"Show or change OpenAI account routing between main-first, fallback-first, and sticky-balanced."},[C8]:{template:C8,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."},[_8]:{template:_8,description:"Show or toggle OpenAI Codex request dump capture for debugging."},[I8]:{template:I8,description:"Show or change the plugin log level (error, warn, info, debug, trace)."},[S8]:{template:S8,description:"Keep Codex prompt cache alive during idle by shadow-replaying the last request."},[M1]:{template:M1,description:"Spend one reset credit on an exhausted Codex account."}}},"command.execute.before":async(V)=>{if(!uX.includes(V.command))return;if(!H)await Z(V.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),RW();let K=V.command,j={...H,sessionId:V.sessionID,notify:(I)=>{a8(I,V.sessionID)}},M=await k8(K,V.arguments,j);if(EJ(V.sessionID))a8(M,V.sessionID);else await Z(V.sessionID,M.text);RW()}}}var BZ=async(Y)=>{let X=A0();return NZ(Y,{codexApiEndpoint:X.codexApiEndpoint,experimentalWebSockets:X.webSockets,responsesLite:X.responsesLite})},EF={id:"cortexkit-openai-auth",server:BZ};export{SW as resolveSidebarSessionId,i1 as parseJwtClaims,_W as mergePushedQuotaMetadata,$Z as findCachekeepFallbackAccount,n1 as extractAccountIdFromClaims,EF as default,oB as createResetTargetResolver,wF as buildSidebarState,U5 as buildSidebarMachineState,rB as buildResetRedemptionDeps,d0 as ResetTargetResolutionError,BZ as OpenAIAuthPlugin,uB as MAIN_REFRESH_LOCK_TTL_MS,pB as MAIN_REFRESH_LEASE_TTL_MS,NZ as CodexAuthPlugin,GX as AuthPersistError};
217
+ `)),W=!0,Q0.type!=="response.created"&&Q0.type!=="response.in_progress")z=!0;if(M("idle timeout waiting for websocket"),!Q0)return;if(Q0.type==="response.completed"||Q0.type==="response.done"){$=!0,HB(Q0,H),Y.onComplete?.(Q0,H),Y.onTerminal?.(Q0),Z();return}if(Q0.type==="response.failed"||Q0.type==="response.incomplete"||Q0.type==="error")$=!0,Y.onTerminal?.(Q0),Z()}function E(x){K(new _0(W1(x),{cause:x}))}function b(x){if($)return;K(new _0(HW("WebSocket closed before response.completed",x.code,x.reason)))}function f(){let x=n9(Y.signal);if($)return;$=!0,N(),O(),Y.onAbort?.(x),Q?.error(x)}function l(x){if($)return;$=!0,N(),O(),Y.onAbort?.(VB(x))}function K0(x){G(),J=x,J.addEventListener("message",I),J.addEventListener("error",E,{once:!0}),J.addEventListener("close",b,{once:!0}),G=()=>{J.removeEventListener("message",I),J.removeEventListener("error",E),J.removeEventListener("close",b)};let{background:y,...u}=Y.body;M("idle timeout sending websocket request");try{J.send(JSON.stringify({type:"response.create",...u})),M("idle timeout waiting for websocket")}catch(L0){if($)return;V(new _0(L0 instanceof Error?L0.message:String(L0),{cause:L0}))}}return new Response(new ReadableStream({start(x){if(Q=x,Y.signal?.addEventListener("abort",f,{once:!0}),Y.signal?.aborted){f();return}K0(J)},cancel(x){l(x)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function WB(Y,X){if(!zB(Y))return;await t0({component:"ws",event:"provider_native_web_search_event",sessionID:X,serverEventType:Y.type,itemType:R(Y.item)?Y.item.type:void 0,serverEvent:Y})}function zB(Y){if(typeof Y.type==="string"&&(Y.type.startsWith("response.web_search_call.")||Y.type.startsWith("response.web_search_preview_call.")))return!0;if(R(Y.item)&&typeof Y.item.type==="string")return Y.item.type==="web_search_call"||Y.item.type==="web_search_preview_call";return!1}function UB(Y,X){if(Y.type!=="response.output_item.done")return;if(!R(Y.item))return;UW(Y.item,X)}function HB(Y,X){let J=Y.response;if(!R(J)||!Array.isArray(J.output))return;for(let Q of J.output)if(R(Q))UW(Q,X)}function UW(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 LB(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:R(Y.headers)?Object.fromEntries(Object.entries(Y.headers).flatMap(([Q,G])=>typeof G==="string"||typeof G==="number"||typeof G==="boolean"?[[Q,String(G)]]:[])):void 0,body:X,message:R(Y.error)&&typeof Y.error.message==="string"?Y.error.message:`${J}`}}function OY(Y){if(typeof Y==="string")try{return OY(JSON.parse(Y))}catch{return}if(!R(Y))return;let X=OY(Y.cause);if(X)return X;let J=OY(Y.body);if(J)return J;let Q=R(Y.error)?Y.error:Y,G=typeof Q.type==="string"?Q.type:void 0,$=Y.status??Y.status_code;if(G!=="usage_limit_reached"&&$!==429)return;let{resets_at:W,resets_in_seconds:z}=Q,L=typeof W==="number"&&Number.isFinite(W)&&W>0?W*1000:typeof z==="number"&&Number.isFinite(z)&&z>0?Date.now()+z*1000:void 0;return{window:G??"primary",resetAt:L}}function VB(Y){if(o9(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function n9(Y){let X=Y?.reason;if(o9(X))return X;if(NB(X))return X;return new DOMException(X instanceof Error?X.message:"Aborted","AbortError")}function NB(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function HW(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 s9="x-opencode-title",H8="x-openai-auth-quota-account",r9=new Set([s9,z1,H8,"x-opencode-session"]),ZB=15000,KB=300000,OB=3300000,LW="websocket_connection_limit_reached";function qB(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 BB("sha256").update(Q).digest("hex").slice(0,12)}function FB(Y){let X=Y?.httpFetch??globalThis.fetch,J=new Map,Q=Y?.connectTimeout??ZB,G=Y?.idleTimeout??KB,$=Y?.maxConnectionAge??OB,W=Y?.streamRetries??5,z=Y?.firstEventGraceMs??250,L=Y?.rawWebSocket??!1,H=Y?.onQuota,N=Y?.onRateLimitReached,O=setInterval(()=>j(),Math.min(G,60000));if(typeof O==="object"&&"unref"in O&&typeof O.unref==="function")O.unref();function Z(E,b,f){if(!b||!f)return f;a9(E,VW(b));let l=new Headers(f.headers),K0=l.get("x-codex-turn-metadata");if(!K0)return f;let x=jW(K0,E.turnID,E.turnStartedAt);if(!x)return f;return l.set("x-codex-turn-metadata",x),{...f,headers:l}}async function V(E,b){let f=E instanceof URL?E.toString():typeof E==="string"?E:E.url,l=w0.normalizeHeaders(b?.headers),K0=MW(b),x=xY(K0);if(b?.method!=="POST"||!new URL(f).pathname.endsWith("/responses"))return X(E,x);let y=(()=>{try{if(typeof b?.body!=="string")return;let r=JSON.parse(b.body);return typeof r==="object"&&r!==null?r:void 0}catch{return}})();if(!y?.stream)return X(E,x);if(l[s9]==="true")return X(E,x);let u=l[z1]??l["x-session-affinity"]??l["session-id"],L0=u;if(!u)return X(E,x);let Y0=w0.normalizeHeaders(K0?.headers),Q0=qB(Y0),q1=`${u}:${Q0}:conversation`,d=typeof l[H8]==="string"?l[H8]:void 0,g0=N?(r,O0)=>N(r,d,O0):void 0,h=J.get(q1)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};if(J.set(q1,h),h.fallback)return X(E,Z(h,y,x));if(h.busy)return X(E,Z(h,y,x));h.busy=!0,h.lastUsedAt=Date.now();try{let r=VW(y),O0=w0.normalizeHeaders(K0?.headers),B8=typeof O0.authorization==="string"&&O0.authorization.startsWith("Bearer ")?O0.authorization.slice(7):"",S1=typeof O0["chatgpt-account-id"]==="string"?O0["chatgpt-account-id"]:void 0,wY=H?(G0)=>H(G0,B8,d,S1):void 0,n0=!h.socket&&!h.continuation?TB(O0):O0;if(h.socket=await PB(h,Y?.url??f,n0,Q,$,L,b?.signal),IB(h,r))await MB(h,r,G,{signal:b?.signal??void 0,sessionID:L0,url:Y?.url??f,headers:K0?.headers,onRateLimitReached:g0});let G1=()=>{},o0=()=>{},F1=new Promise((G0,I0)=>{G1=G0,o0=I0}),Z8=_B(h,r),r0=qY(FW(h,Z8,r)),P0=typeof r0.previous_response_id==="string";await y1({sessionID:L0,transport:"websocket",phase:"main",bodyText:JSON.stringify(r0),url:Y?.url??f,method:K0?.method,headers:K0?.headers});let y0=w0.streamResponsesWebSocket({socket:h.socket,body:r0,sessionID:L0??void 0,idleTimeout:G,signal:b?.signal??void 0,onQuota:wY,onRateLimitReached:g0,onFirstEvent:(G0)=>G1(G0??!0),onComplete:(G0,I0)=>{let k1=ZW(G0);t0({component:"ws-pool",event:"main_completed",sessionID:L0,responseID:BW(G0),usage:k1}),qW(h,r,G0,I0,P0)},onTerminal:(G0)=>{if(h.busy=!1,h.lastUsedAt=Date.now(),h.streamFailures=0,G0.type!=="response.completed"&&G0.type!=="response.done")h.continuation=void 0,Q1(h)},onConnectionInvalid:()=>{if(h.busy=!1,h.lastUsedAt=Date.now(),!h.fallback)K(h);h.continuation=void 0,Q1(h),G1(!1)},onAbort:(G0)=>{h.busy=!1,h.lastUsedAt=Date.now(),h.streamFailures=0,h.continuation=void 0,Q1(h),o0(G0)},onRetryableTerminal:async(G0)=>{let I0=NW(G0);if(!I0)return;throw h.fallback=!0,I0}}),f0=await jB(F1,z);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(!h.fallback)return y0;return X(E,Z(h,y,x))}catch(r){if(h.busy=!1,h.lastUsedAt=Date.now(),w0.isAbortError(r))throw h.streamFailures=0,h.continuation=void 0,Q1(h),r;let O0=w0.parseRateLimitSignal(r);if(O0)g0?.(O0.window,O0.resetAt);if(w0.isUpgradeFailure(r)&&!L)h.fallback=!0;if(K(h),h.continuation=void 0,Q1(h),h.fallback)return X(E,Z(h,y,x));return DB(new _0(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[b,f]of J){if(f.busy)continue;if(E-f.lastUsedAt<G)continue;Q1(f),J.delete(b)}}function M(){clearInterval(O);for(let E of J.values())Q1(E);J.clear()}function I(E){let b=`${E}:`;for(let[f,l]of J){if(!f.startsWith(b))continue;Q1(l),J.delete(f)}}return Object.assign(V,{close:M,remove:I})}function NW(Y){if(Y.type!=="error"||!R(Y.error)||Y.error.code!==LW)return;return Error(typeof Y.error.message==="string"?Y.error.message:LW)}async function jB(Y,X){if(X<=0)return!1;return new Promise((J,Q)=>{let G=setTimeout(()=>J(!1),X);Y.then(($)=>{clearTimeout(G),J($)},($)=>{clearTimeout(G),Q($)})})}function DB(Y){return new Response(new ReadableStream({start(X){X.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function PB(Y,X,J,Q,G,$,W){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<G)return Y.socket;Q1(Y);let z=await w0.connectResponsesWebSocket({url:w0.toWebSocketUrl(X),headers:J,timeout:Q,rawWebSocket:$,signal:W??void 0});return Y.connectedAt=Date.now(),z}function Q1(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function MB(Y,X,J,Q){if(!Y.socket||!Array.isArray(X.input)||X.input.length===0)return;let G=EB(X);await y1({sessionID:Q.sessionID,transport:"websocket",phase:"prewarm",bodyText:JSON.stringify(G),url:Q.url,method:"POST",headers:Q.headers});let $=w0.streamResponsesWebSocket({socket:Y.socket,body:G,sessionID:Q.sessionID,idleTimeout:J,signal:Q.signal,onRateLimitReached:Q.onRateLimitReached,onComplete:(W,z)=>{t0({component:"ws-pool",event:"prewarm_completed",sessionID:Q.sessionID,responseID:BW(W),usage:ZW(W)}),qW(Y,G,W,z,!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 z=NW(W);if(!z)return;throw Y.fallback=!0,z}});await wB($)}function BW(Y){let X=Y.response;if(!R(X))return;return typeof X.id==="string"?X.id:void 0}function ZW(Y){let X=Y.response;if(!R(X))return;return R(X.usage)?X.usage:void 0}async function wB(Y){let X=Y.body?.getReader();if(!X)return;while(!0)if((await X.read()).done)return}function EB(Y){return qY({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:AB(Y.client_metadata)})}function KW(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 AB(Y){if(!R(Y))return Y;if(typeof Y["x-codex-turn-metadata"]!=="string")return Y;try{let X=JSON.parse(Y["x-codex-turn-metadata"]);if(!R(X))return Y;return{...Y,"x-codex-turn-metadata":KW(X),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function TB(Y){let X=Y["x-codex-turn-metadata"];if(!X)return Y;try{let J=JSON.parse(X);if(!R(J))return Y;return{...Y,"x-codex-turn-metadata":KW(J)}}catch{return Y}}var OW=["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 VW(Y){let X={...Y};if(Array.isArray(Y.input))X.input=Y.input.map(RB);return X}function qY(Y){let X={};for(let J of OW)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 RB(Y){if(!R(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 qW(Y,X,J,Q,G){let $=J.response,W=R($)&&typeof $.id==="string"?$.id:void 0;if(!W||!Array.isArray(X.input)){Y.continuation=void 0;return}let z=G?new Set(Y.continuation?.finalizedCallIds):new Set;for(let L of Q)z.add(L);Y.continuation={responseID:W,input:X.input,signature:t9(X),finalizedCallIds:z}}function a9(Y,X,J=X){let Q=Array.isArray(X.input)?X.input:[],G=Array.isArray(J.input)?J.input:Q,$=t9(J),W=Y.turnInput&&Y.turnSignature===$?CB(Y.turnInput,G):void 0,z=W===void 0?Q:G.slice(W);if(z.length>0&&z.some(DW)||!Y.turnID)Y.turnID=E1(),Y.turnStartedAt=Date.now();Y.turnInput=G.slice(),Y.turnSignature=$}function FW(Y,X,J=X){a9(Y,X,J);let Q=X.client_metadata;if(!R(Q)||typeof Q["x-codex-turn-metadata"]!=="string")return X;let G=jW(Q["x-codex-turn-metadata"],Y.turnID,Y.turnStartedAt);if(!G)return X;return{...X,client_metadata:{...Q,"x-codex-turn-metadata":G}}}function jW(Y,X,J){let Q;try{Q=JSON.parse(Y)}catch{return}if(!R(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 CB(Y,X){if(Y.length>X.length)return;for(let J=0;J<Y.length;J++)if(e0(Y[J])!==e0(X[J]))return;return Y.length}function _B(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!J||!Y.continuation)return X;if(Y.continuation.signature!==t9(X))return Y.continuation=void 0,X;if(!PW(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),G=SB(Q,Y.continuation.finalizedCallIds);if(G.length===0)return X;return{...X,previous_response_id:Y.continuation.responseID,input:G}}function IB(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!Y.continuation)return!0;if(!J)return!1;if(!PW(Y.continuation.input,J))return!0;return J.slice(Y.continuation.input.length).some(DW)}function DW(Y){if(!R(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function SB(Y,X){return Y.filter((J)=>{if(!R(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 t9(Y){return e0(kB(Object.fromEntries(Object.entries(Y).filter(([X])=>X!=="input"&&X!=="stream"&&X!=="background"&&X!=="previous_response_id"&&X!=="generate"))))}function kB(Y){if(!R(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 PW(Y,X){if(Y.length>=X.length)return!1;for(let J=0;J<Y.length;J++)if(e0(Y[J])!==e0(X[J]))return!1;return!0}function MW(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let X=new Headers(Y.headers);for(let J of r9)X.delete(J);return{...Y,headers:X}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((X)=>!r9.has(X[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([X])=>!r9.has(X.toLowerCase())))}}var fB=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),mB=new Set(["gpt-5.6"]),cB=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),uB="opencode-oauth-dummy-key",pB="terminal_resize_reflow",JX="0.144.0",lB=`codex_exec/${JX} (Debian 12.0.0; aarch64) unknown (codex_exec; ${JX})`,dB="seccomp",iB="main-refresh",nB=120000,oB=90000,rB=4000,wW=50,EW=3,sB=25,aB=60000,tB="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",AW=!1,TW=N0("models"),RW=!1,CW=!1;class GX 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 _W(Y,X,J,Q){let G=(J?.refresh?.refreshBeforeExpiryMinutes??240)*60000;return!Y||!X||X-Q<=G}function eB(Y){return async(X)=>{if(X==="main"){let z=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(_W(L.access,L.expires,z,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=i1(L.access),N=H?n1(H):void 0,O=await Y.loadAccounts(Y.accountStoragePath);return{accountKey:X,label:"Main account",accessToken:L.access,chatgptAccountId:N??O?.mainAccountId}}let J=await Y.loadAccounts(Y.accountStoragePath),Q=J?.accounts.find((z)=>z.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 G=Q;if(_W(G.access,G.expires,J,Y.now()))G=await Y.refreshFallbackAccount(G,J);if(!G.access)throw new d0("token_unavailable",`Fallback account ${X} has no usable access token.`);let $=await Y.loadAccounts(Y.accountStoragePath),W=$?.accounts.find((z)=>z.id===X);if(!$||!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:G.label??X,accessToken:G.access,chatgptAccountId:W.accountId}}}function YZ(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function YX(Y){return Y instanceof GX}function IW(){throw Error(tB)}function XZ(Y){return Math.floor(Math.random()*Y)}function JZ(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 QZ(Y,X,J){let Q=Y.get(X);if(Q)return Q;let G=E1(),$={threadID:G,turnID:E1(),windowID:`${G}:0`};return Y.set(X,$),J?.(),$}function L5(){return yB(CY(),"openai-auth-sessions.json")}function GZ(){let Y=new Map;try{let X=JSON.parse(xB(L5(),"utf8"));if(!R(X.sessions))return Y;for(let[J,Q]of Object.entries(X.sessions)){if(!R(Q)||typeof Q.threadID!=="string")continue;Y.set(J,{threadID:Q.threadID,turnID:E1(),windowID:`${Q.threadID}:0`})}}catch{}return Y}function $Z(Y){let X=L5(),J=`${X}.tmp-${process.pid}`;try{bB(CY(),{recursive:!0});let Q={version:1,sessions:Object.fromEntries([...Y.entries()].map(([G,$])=>[G,{threadID:$.threadID}]))};gB(J,`${JSON.stringify(Q,null,2)}
218
+ `,"utf8"),vB(J,X)}catch{}}function SW(Y,X){return R(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===X}function WZ(Y,X){if(Y.length>X.length)return!1;for(let J=0;J<Y.length;J++)if(e0(Y[J])!==e0(X[J]))return!1;return!0}function zZ(Y,X){if(!Y.input)return X.length>0;if(!WZ(Y.input,X))return!0;return X.slice(Y.input.length).some((Q)=>SW(Q,"user")||SW(Q,"developer"))}function UZ(Y,X){let J=Array.isArray(X?.input)?X.input:void 0;if(J&&(zZ(Y,J)||!Y.turnID))Y.turnID=E1(),Y.turnStartedAt=Date.now();else if(!Y.turnStartedAt)Y.turnStartedAt=Date.now();if(J)Y.input=J}function HZ(Y){if(!Y.metadata)return{init:Y.init};let X=JZ(Y.init?.body);if(!Y.websocket)UZ(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:dB,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",pB),Y.headers.set("x-codex-turn-metadata",J),Y.headers.set("user-agent",lB),Y.headers.set("version",JX),Y.dumpSessionID)Y.headers.set(z1,Y.dumpSessionID);let Q=X;if(!Q)return{init:Y.init};let G=Y.responsesLite&&typeof Q.model==="string"&&cB.has(Q.model);if(G&&!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(OZ);if(ZZ(Q),KZ(Q),OJ(Q),NZ(Q),G)BZ(Q);let $={...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($["x-codex-turn-metadata"]=J,$["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=$,Y.headers.delete("content-length"),Y.headers.delete("Content-Length"),{init:{...Y.init,body:JSON.stringify(qY(Q))}}}function LZ(Y,X){return Y.find((J)=>J.enabled!==!1&&i0(J)&&(J.id===X||J.accountId===X))}function kW(Y,X){if(!X)return Y;let J={...Y};for(let Q of["resetCreditsAvailable","resetCreditsApplicable"]){let G=X[Q];if(J[Q]===void 0&&G!==void 0)J[Q]=G}return J}function L8(Y,X){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:X}}function V5(Y,X,J=Date.now(),Q=X.mainAccountId){let G=Y.getMain(),$=G?.quota;return{main:{quota:$?{...$,checkedAt:G.checkedAt,primary:L8($.primary,G.checkedAt),secondary:L8($.secondary,G.checkedAt)}:null,...typeof Q==="string"?{mainAccountId:Q}:{},killed:!1,...$?.resetCreditsAvailable!==void 0?{resetCredits:$.resetCreditsAvailable}:{}},fallbacks:X.accounts.filter((W)=>W.enabled).map((W)=>{let z=Y.getFallback(W.id),L=z?.quota;return{id:W.id,label:W.label,accountId:z?.accountId??W.accountId,quota:L?{...L,checkedAt:z.checkedAt,primary:L8(L.primary,z.checkedAt),secondary:L8(L.secondary,z.checkedAt)}:null,killed:!1,enabled:!0,...L?.resetCreditsAvailable!==void 0?{resetCredits:L.resetCreditsAvailable}:{}}}),route:X.routing?.mode??"main-first",lastUpdated:J}}function CF(Y,X,J,Q=Date.now()){return{...V5(Y,X,Q),activeId:J}}function bW(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 VZ(Y,X){if(!(Y instanceof Request))return X;let J=new Request(Y,X),Q=J.method.toUpperCase(),G=Q==="GET"||Q==="HEAD"||J.body===null?void 0:await J.text();return{method:J.method,headers:new Headers(J.headers),body:G,signal:J.signal,cache:J.cache,credentials:J.credentials,integrity:J.integrity,keepalive:J.keepalive,mode:J.mode,redirect:J.redirect,referrer:J.referrer,referrerPolicy:J.referrerPolicy}}function xW(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}function NZ(Y){if(!A0().webSearch)return;if(!Array.isArray(Y.tools)||Y.tools.length===0)return;if(Y.tools.some((X)=>R(X)&&X.type==="web_search"))return;Y.tools=[...Y.tools,{type:"web_search",external_web_access:!1,search_content_types:["text","image"]}]}function QX(Y){if(Array.isArray(Y)){for(let X of Y)QX(X);return}if(!R(Y))return;if(Y.type==="input_image")delete Y.detail;for(let X of Object.values(Y))QX(X)}function BZ(Y){let X=R(Y.reasoning)?{...Y.reasoning}:{};X.context="all_turns",Y.reasoning=X,Y.parallel_tool_calls=!1;let J=Array.isArray(Y.input)?Y.input:[];QX(J);let G=[{type:"additional_tools",role:"developer",tools:Array.isArray(Y.tools)?Y.tools.filter(($)=>!(R($)&&$.type==="web_search")):[]}];if(typeof Y.instructions==="string"&&Y.instructions.length>0)G.push({type:"message",role:"developer",content:[{type:"input_text",text:Y.instructions}]});Y.input=[...G,...J],delete Y.tools,delete Y.instructions}function ZZ(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(R(X)&&X.type==="function"&&X.name==="web_search"))}function KZ(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(R(X)&&X.type==="function"&&X.name==="websearch_web_search_exa"))}function OZ(Y){if(!R(Y))return Y;if(Y.type!=="function")return Y;let X=R(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:L,...H}=Y.parameters;return H})():Y.parameters,{type:J,name:Q,description:G,strict:$,parameters:W,...z}=Y;return{type:J,name:Q,description:G,strict:$??!1,parameters:X,...z}}async function qZ(Y,X={}){let J=X.codexApiEndpoint??A0().codexApiEndpoint,Q=crypto.randomUUID(),G=GZ(),$=()=>$Z(G),W=!1,z=[],L=null,H=null,N,O=new b8;async function Z(V,K){let j=Y.client.session;if(typeof j?.promptAsync==="function"){let M=await EJ(Y.client,V),I={noReply:!0,parts:[{type:"text",text:K,ignored:!0}]};if(M?.agent)I.agent=M.agent;if(M?.model)I.model=M.model;if(M?.variant)I.variant=M.variant;await j.promptAsync({path:{id:V},body:I});return}}return{async dispose(){O.stop();for(let V of z)V.close();if(z.length=0,H){await H.stop().catch(()=>{});let V=globalThis;if(V.__openaiAuthRpcServer===H)V.__openaiAuthRpcServer=void 0;H=null}},async event(V){if(V.event.type!=="session.deleted")return;let K=V.event.properties.info,j=G.get(K.id);if(j)L?.cacheKeepManager?.remove(j.threadID);if(G.delete(K.id))$();if(N){let M=(await D0($0()))?.accounts;await W5(K.id,M,N)}for(let M of z)M.remove(K.id)},provider:{id:"openai",async models(V,K){if(K.auth?.type!=="oauth")return V.models;let j=await D0($0()),M=!j||sW(j),I=M?null:await DJ();if(!M&&I&&!RW)RW=!0,TW.debug("restoring OAuth model costs from models.dev catalog");if(!M&&!I&&!CW)CW=!0,TW.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(V.models).filter(([,E])=>{if(E.options.reasoningMode==="pro")return!1;if(fB.has(E.api.id))return!0;if(mB.has(E.api.id))return!1;let f=E.api.id.match(/^gpt-(\d+\.\d+)/)?.[1];return f?parseFloat(f)>5.4:!1}).map(([E,b])=>[E,{...b,cost:M?{input:0,output:0,cache:{read:0,write:0}}:I?.[b.api.id]??I?.[E]??b.cost,limit:b.id.includes("gpt-5.5")?{context:400000,input:272000,output:128000}:b.id.includes("gpt-5.6")?{context:372000,input:244000,output:128000}:b.limit}]))}},tool:{web_search:ZJ},auth:{provider:"openai",async loader(V){let K=await V();if(K.type!=="oauth")return{};await tW({type:"oauth",access:K.access??"",refresh:K.refresh??"",expires:K.expires??0},$0());let j=await D0($0()).catch((B)=>{let q=$0();throw Error(`OpenAI auth store at ${q} is corrupt or unreadable: ${B instanceof Error?B.message:String(B)}. Fix or remove it to continue.`,{cause:B})}),M;async function I(){let B=$0();try{let q=hB(B);if(M?.path===B&&M.mtimeMs===q.mtimeMs&&M.size===q.size)return M.storage;let D=await D0(B);return M={path:B,mtimeMs:q.mtimeMs,size:q.size,storage:D},D}catch{return M=void 0,D0(B)}}function E(){M=void 0}if(j&&K.access){let B=V8({id_token:"",access_token:K.access,refresh_token:K.refresh??""});if(B&&B!==j.mainAccountId)await J0((q)=>{return q.mainAccountId=B,q},$0()),j.mainAccountId=B,E()}let b=j?.logging?.level;if(b&&typeof b==="string")kY(b);let f=N0("transport"),l=N0("quota"),K0=N0("refresh"),x=N0("accounts");f.info("codex auth loader ready",{codexApiEndpoint:J,transport:A0().rawWebSocket?"raw-websocket":A0().webSockets?"websocket":"http",webSearch:A0().webSearch});let y=new rW({storage:j,fetchQuotaFn:void 0}),u,L0=0,Y0=new eW({refreshFn:(B)=>I1({refreshToken:B.refreshToken,fetchImpl:B.fetchImpl,now:B.now}),quotaManager:y,onFallbackStorageChanged:E});if(j&&j.accounts.length>0)Y0.startBackgroundRefresh();let Q0=N0("cachekeep"),q1=j?.cachekeep?.enabled===!0,d=j?.cachekeep?.subagents===!0,g0=j?.cachekeep?.sustain===!0,h=sX(j),r;async function O0(B){await new Promise((q)=>setTimeout(q,B))}async function B8(B){let q;for(let D=1;D<=EW;D++)try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:B.refresh,access:B.access,expires:B.expires}});return}catch(T){if(q=T,D<EW)await O0(sB*D)}throw new GX(q)}async function S1(B){await J0((q)=>{return q.refresh=q.refresh??{},B(q),q},$0()),E()}async function wY(B){let q=Date.now()+rB;while(Date.now()<q){await new Promise((S)=>setTimeout(S,wW+XZ(wW)));let D=await V();if(D.type!=="oauth"||!D.access)continue;if((D.access!==B.access||D.refresh!==B.refresh||(D.expires??0)>(B.expires??0)+60000)&&(!D.expires||D.expires>Date.now()))return K0.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:D.expires?D.expires-Date.now():void 0}),{access:D.access,refresh:D.refresh??B.refresh??"",expires:D.expires??0}}return null}async function n0(){if(!r)r=(async()=>{let B=await V();if(B.type!=="oauth")throw Error("not oauth");if(!B.refresh)throw Error("Token refresh failed: missing refresh token");let q=vW(B.refresh),D=await D0($0()),T=D?.refresh?.mainLastRefreshError;if(T&&gW(T,B.refresh,Date.now()))throw Error(yW(T,Date.now()));if(D?.refresh?.mainRefreshLeaseUntil&&D.refresh.mainRefreshLeaseUntil>Date.now()&&D.refresh.mainRefreshLeaseTokenHash===q){let _=await wY(B);if(_)return _;throw Error("Codex OAuth refresh is already in progress")}let S=await bY({name:iB,ttlMs:nB,path:$0(),renew:!0});if(!S){let _=await wY(B);if(_)return _;throw Error("Codex OAuth refresh is already in progress")}let C=crypto.randomUUID(),w=q;try{await S1((g)=>{g.refresh=g.refresh??{},g.refresh.mainRefreshLeaseId=C,g.refresh.mainRefreshLeaseUntil=Date.now()+oB,g.refresh.mainRefreshLeaseTokenHash=q});let _=await D0($0());if(_?.refresh?.mainRefreshLeaseId!==C||_.refresh.mainRefreshLeaseTokenHash!==q)throw Error("Codex OAuth refresh is already in progress");let P=await I1({refreshToken:B.refresh,fetchImpl:fetch,now:Date.now});return await B8(P),await S1((g)=>{if(g.refresh=g.refresh??{},g.refresh.mainLastRefreshError=void 0,g.refresh.mainRefreshLeaseId===C)g.refresh.mainRefreshLeaseId=void 0,g.refresh.mainRefreshLeaseUntil=void 0,g.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),w=void 0,P}catch(_){if(B.refresh&&!YX(_))await S1((P)=>{P.refresh=P.refresh??{},P.refresh.mainLastRefreshError=hW({error:_,now:Date.now(),refreshToken:B.refresh??"",previous:P.refresh.mainLastRefreshError})}).catch(()=>{});throw _}finally{if(w)await S1((_)=>{if(_.refresh?.mainRefreshLeaseId===C&&_.refresh.mainRefreshLeaseTokenHash===w)_.refresh.mainRefreshLeaseId=void 0,_.refresh.mainRefreshLeaseUntil=void 0,_.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await S.release().catch(()=>{})}})().finally(()=>{r=void 0});return r}let G1=globalThis;G1.__openaiAuthCacheKeepManager?.stop();let o0=new y8({fetchImpl:fetch,getMainToken:async()=>{let B=await V();if(B.type!=="oauth")throw Error("not oauth");if(!B.access||(B.expires??0)<Date.now())try{return(await n0()).access}catch(q){if(YX(q))throw q;if(B.access)return B.access;throw Error("main token refresh failed")}return B.access},refreshFallback:async(B)=>{let q=await I(),D=q?LZ(q.accounts,B):void 0;if(!D)throw Error(`fallback account ${B} not found`);let T=await Y0.refreshAccount(D,q??{version:1,accounts:[D]});if(!T.access)throw Error(`no access token for ${B}`);return T.access},codexResponsesUrl:J,logger:Q0,now:Date.now,getWindow:()=>h,getSustain:()=>g0});G1.__openaiAuthCacheKeepManager=o0;async function F1(B,q,D,T,S=!1){if(Object.keys(B).length===0&&!S)return;let C=Date.now(),w=B,_={quota:w,refreshAfter:C+300000,checkedAt:C},P;if(D&&D!=="main"){let k=q?i1(q):null,X0=k?n1(k):void 0,q0=y.peekFallbackForPolicy(D)?.quota,m0=kW(w,q0);_={..._,quota:m0},y.setFallback(D,_,q,S,X0)}else{if(P=T,!P&&q){let q0=i1(q);P=q0?n1(q0):void 0}if(P&&u&&P!==u){l.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:P,currentMainIdentity:u});return}let k=y.peekMainForPolicy(P)?.quota,X0=kW(w,k);_={..._,quota:X0},y.setMain(q,_,P,S)}l.debug("quota pushed",{pid:process.pid,accountId:D??"main",snapshot:_.quota});let g=await I();await y0(y,g,D&&D!=="main"?g?.mainAccountId:P)}function Z8(B,q,D){let T=B==="main"?y.peekMainForPolicy()?.quota:y.peekFallbackForPolicy(B)?.quota;return oW(T,q,Date.now(),aB,D)}let r0=X.experimentalWebSockets?O1.createWebSocketFetch({httpFetch:fetch,rawWebSocket:A0().rawWebSocket,onQuota:(B,q,D,T)=>{F1(B,q,D,!D||D==="main"?T:void 0,!0)},onRateLimitReached:(B,q,D)=>{if(!q)l.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:B});let T=q??"main",S=Z8(T,B,D);y.markRateLimited(T,S),l.debug("mid-stream rate limit mark",{pid:process.pid,accountId:T,window:B})}}):void 0;if(r0)z.push(r0),W=!0;let P0=Y5();N=P0;async function y0(B,q,D=q?.mainAccountId){if(!q)return;await G5(V5(B,q,Date.now(),D),P0)}async function f0(B,q,D,T,S){let C={activeId:D,route:T,updatedAt:Date.now()};if(B){if(await N8({sessionId:B,...C},S,P0),q&&q!==B){if(T==="sticky-balanced"){let w=(await w1(P0)).stickyAssignments?.[MY(q)]?.accountId,_=S===void 0||w==="main"||S.some((P)=>P.enabled!==!1&&P.id===w);if(!w||!_)return;await N8({sessionId:q,activeId:w,route:T,updatedAt:Date.now()},S,P0);return}await N8({sessionId:q,...C},S,P0)}return}await $5(C,P0)}L={accountStoragePath:$0(),quotaManager:y,loadAccounts:D0,client:Y.client,resolveResetTarget:eB({getAuth:V,refreshMainWithLease:n0,refreshFallbackAccount:(B,q)=>Y0.refreshAccount(B,q),loadAccounts:D0,accountStoragePath:$0(),now:Date.now}),...YZ(),cacheKeepManager:o0,setCacheKeepEnabled:(B)=>{q1=B},setCacheKeepSubagents:(B)=>{d=B},setCacheKeepSustain:(B)=>{g0=B},setCacheKeepWindow:(B)=>{h=B},clearStickyRouting:(B)=>U5(B,P0),getStickyRouting:async(B)=>Q5(await w1(P0),B),refreshSidebar:async()=>{let B=await D0($0());await y0(y,B)},refreshAllQuota:async()=>v1({getAuth:V,codexRefreshFn:I1,refreshMainWithLease:n0,fallbackManager:Y0,quotaManager:y,loadAccounts:D0,writeSidebarState:y0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:$0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:i0,whamFn:$1}),refreshResetTargetQuota:async(B)=>{return(await v1({getAuth:V,codexRefreshFn:I1,refreshMainWithLease:n0,fallbackManager:Y0,quotaManager:y,loadAccounts:D0,writeSidebarState:y0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:$0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:i0,whamFn:$1,respectBackoff:!1},{accountKey:B})).find((D)=>D.account===B)??{account:B,ok:!1,error:"targeted quota refresh returned no result"}}};let G0=null;if(Y.directory){let B=await H5(Y.directory),q=globalThis;if(q.__openaiAuthRpcServer)await q.__openaiAuthRpcServer.stop().catch(()=>{}),q.__openaiAuthRpcServer=void 0;try{G0=await SJ({dir:B.dir,secureDir:B.secureDir,sweepRoot:B.sweepRoot,drain:TJ,apply:async(D)=>{let T={...L,sessionId:D.sessionId},S=await k8(D.command,D.arguments,T);return{text:S.text,knobs:S.knobs}}}),q.__openaiAuthRpcServer=G0,H=G0}catch{}}async function I0(B,q,D,T,S="main"){let C=bW(B,q);if(C.delete("x-api-key"),C.delete("api-key"),C.set("authorization",`Bearer ${D}`),T)C.set("ChatGPT-Account-Id",T);C.set(O1.QUOTA_ACCOUNT_HEADER,S);let w=xW(C),_=w?QZ(G,w,$):void 0,P=B instanceof URL?B:new URL(typeof B==="string"?B:B.url),g=P.pathname.includes("/v1/responses")||P.pathname.includes("/chat/completions")?new URL(J):P,X0=HZ({init:{...q,headers:C},headers:C,metadata:_,installationID:Q,websocket:Boolean(r0&&P.pathname.endsWith("/responses")),responsesLite:X.responsesLite??!1,dumpSessionID:w}).init,q0=q1,m0=new Headers(X0?.headers),z0=rX({enabled:q0,includeSubagents:d,headers:m0,body:X0?.body});if(q0)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&&P.pathname.endsWith("/responses")){if(f.debug("WS transport",{pid:process.pid,pathname:P.pathname,accountId:S}),z0)o0.track(z0.sessionKey,z0.bodyText,S,T,z0.replayHeaders,z0.isSubagent);return r0(g,X0)}let Z0=O1.withoutInternalHeaders(X0);if(typeof Z0?.body!=="string")return fetch(g,Z0);if(z0)o0.track(z0.sessionKey,z0.bodyText,S,T,z0.replayHeaders,z0.isSubagent);f.debug("HTTP transport",{pid:process.pid,pathname:P.pathname,accountId:S});try{let S0=await fetch(g,Z0);return await y1({sessionID:w,transport:"http",phase:"http",bodyText:Z0.body,accountId:S,url:g.toString(),method:Z0.method,headers:Z0.headers,status:S0.status}),KJ(S0)}catch(S0){throw await y1({sessionID:w,transport:"http",phase:"http",bodyText:Z0.body,accountId:S,url:g.toString(),method:Z0.method,headers:Z0.headers,error:S0 instanceof Error?S0.message:String(S0)}),S0}}function k1(B,q){if((q?.method??(B instanceof Request?B.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof q?.body!=="string")return!1;try{let T=B instanceof URL?B.toString():typeof B==="string"?B:B.url;return new URL(T).pathname.endsWith("/responses")}catch{return!1}}function N5(B){return y.peekMainForPolicy(B)?.quota}function $X(B,q){for(let D of[B?.primary?.checkedAt,B?.secondary?.checkedAt,B?.checkedAt,q])if(typeof D==="number"&&Number.isFinite(D))return D;return}function o1(B,q,D,T,S){let C=$X(B,q),w=$X(D),_=T===S&&D!=null&&(B===void 0||w!==void 0&&(C===void 0||w>C));return{quota:_?D:B,quotaCheckedAt:_?w:C,source:_?"file":"memory"}}function WX(B,q,D,T,S){let C=B?.quota,w=o1(C,B?.checkedAt,q,T,S),_=w.source,P=w.quota;if(!J5(P,D))return{exhausted:!1};let g=X5(P,D);if(!g)return{exhausted:!1};return{exhausted:!0,source:_,...g}}function zX(B,q){l.debug("admission skip: exhausted account",{accountId:B,source:q.source,resetsAt:q.resetsAt})}function B5(B,q="killswitch",D){let T=Date.now(),S=y.getMain()?.quota,C=(B?.accounts??[]).filter((k)=>k.enabled!==!1&&i0(k)).map((k)=>({accountId:k.id,quota:y.getFallback(k.id)?.quota})),w=aW(S,C,T,B);if(q==="quota-exhausted"&&D!==void 0)w=Math.max(1,Math.ceil((D-T)/1000));else if(q==="mid-stream-rate-limit"&&D!==void 0){let k=Math.max(1,Math.ceil((D-T)/1000));w=Math.min(w,k)}let _=Math.floor(w/60),P=w%60,g=q==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${_}m ${P}s.`:q==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${_}m ${P}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${_}m ${P}s.`;return new Response(JSON.stringify({error:{message:g,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(w)}})}function UX(B){let q=B?.resetCreditsAvailable;return typeof q==="number"&&Number.isFinite(q)?q:void 0}async function Z5(B){let q=DY(B.storage),D=Date.now(),T=y.peekMainForPolicy(B.mainAccountIdentity),S=o1(T?.quota,T?.checkedAt,B.sidebarState.main.quota,B.sidebarState.main.mainAccountId,B.mainAccountIdentity),C=q?PY(T?.quota,B.storage,void 0,D):void 0,w=[{accountId:"main",wireAccountId:B.mainAccountIdentity,access:B.primaryAccess,keepwarmAccountKey:"main",quota:S.quota,quotaCheckedAt:S.quotaCheckedAt,reservePercent:XX(B.storage),configuredOrder:0,resetCreditsApplicable:UX(S.quota),killswitchPasses:C}],_=await Y0.getUsableFallbackAccounts(B.storage);for(let P of _){if(!P.access)continue;let g=B.sidebarState.fallbacks.find((m0)=>m0.id===P.id),k=y.peekFallbackForPolicy(P.id,P.accountId),X0=o1(k?.quota,k?.checkedAt,g?.quota,g?.accountId,P.accountId),q0=q?PY(k?.quota,B.storage,P.id,D):void 0;w.push({accountId:P.id,wireAccountId:P.accountId,access:P.access,keepwarmAccountKey:P.id,fallback:P,quota:X0.quota,quotaCheckedAt:X0.quotaCheckedAt,reservePercent:XX(B.storage,P.id),configuredOrder:w.length,resetCreditsApplicable:UX(X0.quota),killswitchPasses:q0})}return w}function HX(B,q,D,T,S){let C=DY(S)?B.killswitchPasses:void 0;if(B.accountId==="main"){let g=y.peekMainForPolicy(B.wireAccountId),k=o1(g?.quota,g?.checkedAt,q.main.quota,q.main.mainAccountId,B.wireAccountId);return c8({quota:k.quota,quotaCheckedAt:k.quotaCheckedAt,status:D,now:T,killswitchPasses:C})}let w=q.fallbacks.find((g)=>g.id===B.accountId),_=y.peekFallbackForPolicy(B.accountId,B.wireAccountId),P=o1(_?.quota,_?.checkedAt,w?.quota,w?.accountId,B.wireAccountId);return c8({quota:P.quota,quotaCheckedAt:P.quotaCheckedAt,status:D,now:T,killswitchPasses:C})}function K5(B){return B.accountId==="main"?"main":B.keepwarmAccountKey}function LX(B){return y.isRateLimited(K5(B))}async function K8(B){let q=B.candidates.filter((P)=>!LX(P)),D=new Map(q.map((P)=>[P.accountId,P])),T=Object.fromEntries(q.map((P)=>[P.accountId,P.quotaCheckedAt])),S=Object.fromEntries(q.map((P)=>[P.accountId,P.wireAccountId])),C=new Set(B.excludeAccountIds),w,_=await z5({sessionId:B.sessionId,requestBytes:B.requestBytes,now:B.now,validPinnedAccountIds:[...D.keys()],excludeAccountIds:B.excludeAccountIds,quotaCheckedAtByAccount:T,wireAccountIdByAccount:S,choose:(P)=>{let g=q.filter((X0)=>!C.has(X0.accountId));if(g.length===0)return;let k=QJ({candidates:g,pendingBytes:P,requestBytes:B.requestBytes,now:B.now,onEmptyWeightedSet:()=>{x.debug("sticky routing: no fresh weighted candidates; using configured order")}});if(!k)return;return w={accountId:k.accountId,source:k.source,pendingBytes:P.get(k.accountId)??0},k}},P0);if(w&&_?.accountId===w.accountId)x.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:MY(B.sessionId),accountId:w.accountId,source:w.source,requestBytes:B.requestBytes,pendingBytes:w.pendingBytes});return _?D.get(_.accountId):void 0}async function O5(B,q){let D=await Y0.getUsableFallbackAccounts(B),T=[];for(let k of D)if(k.access)T.push({access:k.access,accountId:k.accountId,keepwarmAccountKey:k.id,quotaAccountId:k.id,fallback:k});let S=T.filter((k)=>!y.isRateLimited(k.quotaAccountId)),C=DY(B)?S.filter((k)=>PY(y.peekFallbackForPolicy(k.quotaAccountId,k.accountId)?.quota,B,k.quotaAccountId,Date.now())):S,w=new Map(q.fallbacks.map((k)=>[k.id,{quota:k.quota,accountId:k.accountId}])),_=[],P=[],g=Date.now();for(let k of C){let X0=w.get(k.quotaAccountId),q0=WX(y.peekFallbackForPolicy(k.quotaAccountId,k.accountId),X0?.quota,g,X0?.accountId,k.accountId);if(q0.exhausted)P.push({candidate:k,decision:q0});else _.push(k)}return{current:C,retained:_,skipped:P}}function VX(B,q){if(B.retained.length===0&&!q)return B.current;for(let{candidate:D,decision:T}of B.skipped)zX(D.quotaAccountId,T);return B.retained}async function NX(B,q){try{let D=h1(B.headers);await F1(D,q.access,q.quotaAccountId,void 0,FY(B.headers))}catch{}}async function q5(B,q,D,T){for(let S of T){let C;try{C=await I0(B,q,S.access,S.accountId,S.keepwarmAccountKey)}catch(w){if(w instanceof DOMException&&w.name==="AbortError")throw w;if(q?.signal?.aborted)throw w;throw x.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:S.quotaAccountId}),w}if(!jY(C.status,D))return Y0.markUsed(S.fallback),{response:C,accessToken:S.access,quotaAccountId:S.quotaAccountId,activeId:S.keepwarmAccountKey};await NX(C,S),C.body?.cancel().catch(()=>{})}return}async function F5(B,q,D,T,S){if(!k1(B,q))return{response:D};if(!S.length)return{response:D};let C=D,w;for(let _ of S){let P;try{P=await I0(B,q,_.access,_.accountId,_.keepwarmAccountKey)}catch(g){if(g instanceof DOMException&&g.name==="AbortError")throw g;if(q?.signal?.aborted)throw g;return x.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:_.quotaAccountId}),{response:C,...w}}if(C.body?.cancel().catch(()=>{}),C=P,w={accessToken:_.access,accountId:_.quotaAccountId},!jY(P.status,T))return Y0.markUsed(_.fallback),{response:P,...w};await NX(P,_)}return{response:C,...w}}if(!AW){if(AW=!0,j){let B=[];for(let q of j.accounts)if(i0(q))B.push(q);y.seedFallbacksFromAccounts(B)}y0(y,j).catch(()=>{}),v1({getAuth:V,codexRefreshFn:I1,refreshMainWithLease:n0,fallbackManager:Y0,quotaManager:y,loadAccounts:D0,writeSidebarState:y0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:$0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:i0,whamFn:$1,respectBackoff:!0}).catch((B)=>l.warn("boot quota seed failed",{pid:process.pid,error:W1(B)}))}return O.start(async()=>{let q=(await lX({getAuth:V,codexRefreshFn:I1,refreshMainWithLease:n0,fallbackManager:Y0,quotaManager:y,loadAccounts:D0,writeSidebarState:(D,T)=>O.isStopped()?Promise.resolve():y0(D,T),client:Y.client,fetchImpl:fetch,now:Date.now,configPath:$0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:i0,whamFn:$1,readSidebarState:()=>w1(P0)})).filter((D)=>!D.ok);if(q.length>0)l.warn("background quota refresh completed with failures",{pid:process.pid,failures:q})},(B)=>{l.warn("background quota refresh failed",{pid:process.pid,error:B instanceof Error?B.message:String(B)})}),{apiKey:uB,async fetch(B,q){let D=bW(B,q),T=xW(D),S=D.get("x-parent-session-id")?.trim()||void 0,C=await I(),w=await V(),_=++L0;if(w.type!=="oauth")return fetch(B,q);q=await VZ(B,q);let P=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(YX(e))throw e}}P=w.access??"";let k=w.accountId??(P?n1(i1(P)??{}):void 0);if(_===L0)u=k;let X0=C?.routing?.mode??"main-first",q0,z0=await(()=>{return q0??=w1(P0),q0})();if(X0==="sticky-balanced"&&T&&k1(B,q)&&typeof q?.body==="string"){let e=Buffer.byteLength(q.body,"utf8"),V0=await Z5({storage:C,sidebarState:z0,primaryAccess:P,mainAccountIdentity:k}),H0=await K8({sessionId:T,requestBytes:e,candidates:V0,now:Date.now()});if(H0){let jX=LX(H0)?{action:"migrate",reason:"exhausted"}:HX(H0,z0,void 0,Date.now(),C);if(jX.action==="migrate"){let E0=await K8({sessionId:T,requestBytes:e,candidates:V0,excludeAccountIds:[H0.accountId],now:Date.now()});if(E0)x.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:MY(T),fromAccountId:H0.accountId,toAccountId:E0.accountId,reason:jX.reason}),H0=E0}let c0=await I0(B,q,H0.access,H0.wireAccountId,H0.keepwarmAccountKey),DX=async(E0,j1)=>{try{let j5=h1(E0.headers);await F1(j5,j1.access,j1.accountId==="main"?void 0:j1.accountId,j1.accountId==="main"?j1.wireAccountId:void 0,FY(E0.headers))}catch{}};await DX(c0,H0);let PX=HX(H0,z0,c0.status,Date.now(),C);if((c0.status===401||c0.status===403||c0.status===429)&&PX.action==="migrate"){let E0=await K8({sessionId:T,requestBytes:e,candidates:V0,excludeAccountIds:[H0.accountId],now:Date.now()});if(E0){x.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:MY(T),fromAccountId:H0.accountId,toAccountId:E0.accountId,reason:PX.reason});let j1=c0;c0=await I0(B,q,E0.access,E0.wireAccountId,E0.keepwarmAccountKey),j1.body?.cancel().catch(()=>{}),H0=E0,await DX(c0,H0)}}if(H0.fallback&&!jY(c0.status,C))Y0.markUsed(H0.fallback);return await f0(T,S,H0.accountId,X0,C?.accounts).catch(()=>{}),c0}}let Z0=WX(y.peekMainForPolicy(k),z0.main.quota,Date.now(),z0.main.mainAccountId,k),S0=DY(C)&&!PY(N5(k),C,void 0,Date.now()),EY=y.isRateLimited("main"),BX,O8=()=>{return BX??=O5(C,z0),BX},s0,b1,ZX=!1,AY;if(X0==="fallback-first"&&k1(B,q)){ZX=!0;let e=await O8();AY=VX(e,!S0&&!EY&&!Z0.exhausted);let V0=await q5(B,q,C,AY);if(V0)s0=V0.response,b1={accessToken:V0.accessToken,accountId:V0.quotaAccountId,activeId:V0.activeId}}if(!s0){let e=Z0.exhausted&&k1(B,q)&&(await O8()).retained.length>0;if(S0||EY||e){let V0=S0?"killswitch":EY?"mid-stream-rate-limit":"quota-exhausted";if(V0==="quota-exhausted"&&Z0.exhausted)zX("main",Z0);x.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:V0}),s0=B5(C,V0,V0==="quota-exhausted"&&Z0.exhausted?Z0.resetAtMs:EY?y.rateLimitedUntil("main"):void 0)}else s0=await I0(B,q,P,k,"main")}let KX=Boolean(b1),r1=s0,OX=b1?.accessToken??P,qX=b1?.accountId,FX=b1?.activeId??"main";if(!b1&&!ZX&&jY(s0.status,C)){x.debug("reactive fallback triggered",{pid:process.pid,status:s0.status}),AY??=VX(await O8(),!1);let e=await F5(B,q,s0,C,AY),V0=e.response;if(V0!==s0){if(KX=!0,r1=V0,OX=e.accessToken??P,qX=e.accountId,e.accountId)FX=e.accountId}}try{let e=h1(r1.headers);if(KX)await F1(e,OX,qX,void 0,FY(r1.headers));else await F1(e,P,void 0,k,FY(r1.headers))}catch{}return await f0(T,S,FX,X0,C?.accounts).catch(()=>{}),r1},async dispose(){if(O.stop(),o0.stop(),G1.__openaiAuthCacheKeepManager===o0)G1.__openaiAuthCacheKeepManager=void 0;if(Y0.stopBackgroundRefresh(),H){await H.stop().catch(()=>{});let B=globalThis;if(B.__openaiAuthRpcServer===H)B.__openaiAuthRpcServer=void 0;H=null}}}},methods:[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:async()=>{let{redirectUri:V}=await lW(),K=await cW(),j=mW(crypto.getRandomValues(new Uint8Array(32)).buffer),M=uW(V,K,j),I=dW(K,j);return{url:M,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let E=await I,b=V8(E);return{type:"success",refresh:E.refresh_token,access:E.access_token,expires:Date.now()+(E.expires_in??3600)*1000,accountId:b}}finally{pW(j)}}}}},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:async()=>{let{deviceData:V,url:K,instructions:j}=await iW();return{url:K,instructions:j,method:"auto",async callback(){try{let M=await nW(V);return{type:"success",refresh:M.refresh_token,access:M.access_token,expires:Date.now()+(M.expires_in??3600)*1000,accountId:V8(M)}}catch{return{type:"failed"}}}}}},{label:"Manually enter API Key",type:"api"}]},"chat.headers":async(V,K)=>{if(V.model.providerID!=="openai")return;if(K.headers.originator="opencode",K.headers["User-Agent"]=`${fW} (${e9.platform()} ${e9.release()}; ${e9.arch()})`,K.headers["session-id"]=V.sessionID,W&&V.agent==="title")K.headers[O1.TITLE_HEADER]="true"},"chat.params":async(V,K)=>{if(V.model.providerID!=="openai")return;K.maxOutputTokens=void 0},config:async(V)=>{V.command={...V.command??{},[A8]:{template:A8,description:"Show current OpenAI Codex OAuth quota usage for all accounts."},[T8]:{template:T8,description:"Manage OpenAI accounts — add, switch, remove, or reorder."},[R8]:{template:R8,description:"Show or change OpenAI account routing between main-first, fallback-first, and sticky-balanced."},[C8]:{template:C8,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."},[_8]:{template:_8,description:"Show or toggle OpenAI Codex request dump capture for debugging."},[I8]:{template:I8,description:"Show or change the plugin log level (error, warn, info, debug, trace)."},[S8]:{template:S8,description:"Keep Codex prompt cache alive during idle by shadow-replaying the last request."},[M1]:{template:M1,description:"Spend one reset credit on an exhausted Codex account."}}},"command.execute.before":async(V)=>{if(!uX.includes(V.command))return;if(!L)await Z(V.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),IW();let K=V.command,j={...L,sessionId:V.sessionID,notify:(I)=>{a8(I,V.sessionID)}},M=await k8(K,V.arguments,j);if(RJ(V.sessionID))a8(M,V.sessionID);else await Z(V.sessionID,M.text);IW()}}}var FZ=async(Y)=>{let X=A0();return qZ(Y,{codexApiEndpoint:X.codexApiEndpoint,experimentalWebSockets:X.webSockets,responsesLite:X.responsesLite})},_F={id:"cortexkit-openai-auth",server:FZ};export{xW as resolveSidebarSessionId,i1 as parseJwtClaims,kW as mergePushedQuotaMetadata,LZ as findCachekeepFallbackAccount,n1 as extractAccountIdFromClaims,_F as default,eB as createResetTargetResolver,CF as buildSidebarState,V5 as buildSidebarMachineState,YZ as buildResetRedemptionDeps,d0 as ResetTargetResolutionError,FZ as OpenAIAuthPlugin,nB as MAIN_REFRESH_LOCK_TTL_MS,oB as MAIN_REFRESH_LEASE_TTL_MS,qZ as CodexAuthPlugin,GX as AuthPersistError};