@cortexkit/opencode-openai-auth 0.5.2 → 0.6.1

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.
Files changed (50) hide show
  1. package/README.md +2 -1
  2. package/dist/cli.js +1 -1
  3. package/dist/commands.d.ts +31 -0
  4. package/dist/core/accounts.d.ts +39 -0
  5. package/dist/core/oauth.d.ts +1 -1
  6. package/dist/core/refresh-all-quota.d.ts +3 -0
  7. package/dist/core/reset-credits.d.ts +114 -0
  8. package/dist/index-87145jkw.js +2 -0
  9. package/dist/index-cxze8h26.js +89 -0
  10. package/dist/{index-rfgyxxxq.js → index-dz9a4xwy.js} +1 -1
  11. package/dist/{index-zkzb0twr.js → index-e08r33g5.js} +2 -2
  12. package/dist/{index-s5fbqqwx.js → index-hxpv25e8.js} +1 -1
  13. package/dist/index-meg0ng0z.js +2 -0
  14. package/dist/{index-vrdc90yd.js → index-n00ybbbq.js} +1 -1
  15. package/dist/{index-6rnw2cgs.js → index-nwy7ec7p.js} +1 -1
  16. package/dist/{index-wpd7mg3p.js → index-s2vhsb2v.js} +1 -1
  17. package/dist/index.d.ts +30 -1
  18. package/dist/index.js +120 -70
  19. package/dist/quota-normalize-vf2pj6n7.js +1 -0
  20. package/dist/quota-normalize.d.ts +1 -0
  21. package/dist/rpc/port-file.js +1 -1
  22. package/dist/rpc/protocol.d.ts +1 -1
  23. package/dist/rpc/rpc-client.d.ts +2 -1
  24. package/dist/rpc/rpc-client.js +1 -1
  25. package/dist/rpc/rpc-dir.js +1 -1
  26. package/dist/rpc/rpc-server.d.ts +1 -0
  27. package/dist/sidebar-state.d.ts +2 -0
  28. package/dist/sidebar-state.js +1 -1
  29. package/dist/{token-5hdnazxp.js → token-esc14v6e.js} +1 -1
  30. package/dist/token-util-qkpkvy5t.js +1 -0
  31. package/dist/tui-preferences.js +1 -1
  32. package/dist/version.d.ts +1 -1
  33. package/package.json +3 -3
  34. package/src/rpc/protocol.ts +1 -0
  35. package/src/rpc/rpc-client.ts +7 -3
  36. package/src/rpc/rpc-server.ts +24 -4
  37. package/src/sidebar-state.ts +62 -3
  38. package/src/tui/command-dialogs.tsx +245 -0
  39. package/src/tui-compiled/rpc/protocol.ts +1 -0
  40. package/src/tui-compiled/rpc/rpc-client.ts +7 -3
  41. package/src/tui-compiled/sidebar-state.ts +62 -3
  42. package/src/tui-compiled/tui/command-dialogs.tsx +162 -1
  43. package/src/tui-compiled/tui.tsx +1 -1
  44. package/src/tui-compiled/util/error.ts +9 -0
  45. package/src/tui.tsx +4 -1
  46. package/dist/index-2ng03cby.js +0 -2
  47. package/dist/index-qhvsskdz.js +0 -89
  48. package/dist/index-wnxfzjfr.js +0 -2
  49. package/dist/quota-normalize-n02dfdx0.js +0 -1
  50. package/dist/token-util-3d2nj45d.js +0 -1
package/dist/index.js CHANGED
@@ -1,168 +1,218 @@
1
- import{d as M1,e as zY,f as PG}from"./index-2ng03cby.js";import{A as a0,B as x1,C as Y8,D as UW,E as HW,G as j1,H as LW,I as L1,J as M0,K as J0,L as KY,M as UY,N as g9,O as HY,P as NW,Q as VW,R as BW,h as sG,i as aG,j as tG,k as eG,l as YW,m as XW,n as JW,o as NY,p as VY,q as eY,s as QW,t as $W,u as GW,v as WW,w as zW,x as KW,y as WX,z as zX}from"./index-qhvsskdz.js";import{T as P8,W as LY,X as ZW,_ as N1,ca as OW,da as FW,ea as qW,ja as jW,ka as X8,la as DW,ma as PW,na as wW,oa as EW}from"./index-wnxfzjfr.js";import{ta as PY}from"./index-vrdc90yd.js";import{ua as dX,va as iX}from"./index-zkzb0twr.js";import{xa as DY,ya as MX,za as H0}from"./index-s5fbqqwx.js";import{Ca as MW}from"./index-rfgyxxxq.js";import{Fa as g8}from"./index-wpd7mg3p.js";import{mkdirSync as MN,readFileSync as AN,renameSync as RN,statSync as TN,writeFileSync as CN}from"node:fs";import v9 from"node:os";import{join as _N}from"node:path";import{readFileSync as vW}from"node:fs";import{homedir as hW,tmpdir as gW}from"node:os";import{join as qY}from"node:path";var yW="https://chatgpt.com/backend-api/codex/responses",fW="openai-auth.json",u0={noWebSearch:"CORTEXKIT_OPENAI_AUTH_NO_WEB_SEARCH",webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",responsesLite:"CORTEXKIT_OPENAI_AUTH_RESPONSES_LITE",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",codexApiEndpoint:"CORTEXKIT_OPENAI_AUTH_CODEX_ENDPOINT",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function jY(){let Y=process.env[u0.configDir]?.trim();if(Y)return Y;return qY(process.env.XDG_CONFIG_HOME||qY(hW(),".config"),"opencode")}function K0(){return process.env[u0.configFile]?.trim()||qY(jY(),fW)}function mW(){try{let Y=JSON.parse(vW(K0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function $X(Y){let X=process.env[Y];if(X===void 0)return;let J=X.trim().toLowerCase();if(J==="1"||J==="true"||J==="yes"||J==="on")return!0;if(J===""||J==="0"||J==="false"||J==="no"||J==="off")return!1;return}function FY(Y,X,J){let Q=$X(Y);if(Q!==void 0)return Q;if(typeof X==="boolean")return X;return J}function cW(){let Y=mW(),X=$X(u0.noWebSearch),J=X!==void 0?!X:typeof Y.webSearch==="boolean"?Y.webSearch:!0,Q;if(Y.dump!==void 0&&Y.dump!==null){if(typeof Y.dump==="object")Q=Y.dump.enabled;else if(typeof Y.dump==="boolean")Q=Y.dump}return{webSearch:J,webSockets:FY(u0.webSockets,Y.webSockets,!1),rawWebSocket:FY(u0.rawWebSocket,Y.rawWebSocket,!1),responsesLite:FY(u0.responsesLite,Y.responsesLite,!1),dump:FY(u0.dump,Q,!1),dumpDir:process.env[u0.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():qY(gW(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[u0.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():yW)}}var W8;function P0(){if(!W8)W8=cW();return W8}var z8="openai-quota",K8="openai-account",U8="openai-routing",H8="openai-killswitch",L8="openai-dump",N8="openai-logging",V8="openai-cachekeep",KX=["openai-quota","openai-account","openai-routing","openai-killswitch","openai-dump","openai-logging","openai-cachekeep"],G0=H0("commands");function GX(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 uW(Y){let X=await Y.refreshAllQuota?.(),J=Y.quotaManager.getMain(),Q=["## OpenAI Quota",""];if(J?.quota){let W=J.quota;Q.push("### Main account");for(let K of["primary","secondary"]){let U=W[K];if(U){let H=Math.round(U.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(`- ${K}: ${N} ${H}% used (${Math.round(U.remainingPercent)}% remaining)`)}}if(W.resetCreditsAvailable!==void 0)Q.push(`- resets: ${W.resetCreditsAvailable}`)}else Q.push("No main quota snapshot available. Send a request first.");let G=[...Y.quotaManager.getAllFallbacks().entries()].filter(([,W])=>W);if(G.length>0){Q.push(""),Q.push("### Fallback accounts");for(let[W,K]of G){if(!K?.quota)continue;Q.push(`**${W}**`);for(let U of["primary","secondary"]){let H=K.quota[U];if(H){let N=Math.round(H.usedPercent);Q.push(` - ${U}: ${N}% used (${Math.round(H.remainingPercent)}% remaining)`)}}if(K.quota.resetCreditsAvailable!==void 0)Q.push(` - resets: ${K.quota.resetCreditsAvailable}`)}}if(X?.length){let W=X.filter((K)=>!K.ok);if(W.length>0){Q.push("");for(let K of W)Q.push(`- ${K.account}: fetch failed — Refresh to retry`)}}return{command:"openai-quota",text:Q.join(`
2
- `),knobs:{}}}async function pW(Y,X){let J=Y.trim().split(/\s+/).filter(Boolean),Q=await X.loadAccounts(X.accountStoragePath)??{version:1,accounts:[]},$=Q.accounts??[];if(J.length===0){let G=["## OpenAI Accounts",""];if($.length===0)G.push("No accounts configured. Use `/login openai` to add your main account, or `/openai-account add` to add a fallback account.");else{let W=Q.routing?.mode??"main-first";G.push(`Routing: \`${W}\` (set with \`/openai-routing\`). Modes: main-first, fallback-first, or sticky-balanced. \`/openai-routing reset\` clears this session's pin.`),G.push("");for(let K of $){let U=K.type??"oauth";G.push(`- \`${K.id}\` (${U})`)}}return G.push(""),G.push("Commands: `/openai-account add [label]` | `/openai-account remove <id>`"),{command:"openai-account",text:G.join(`
3
- `),knobs:{accounts:$}}}if(J[0]==="remove"&&J[1]){let G=J[1],W=!1,K=await J0((U)=>{let H=U.accounts.findIndex((N)=>N.id===G);if(H===-1)return U;return W=!0,U.accounts.splice(H,1),U},X.accountStoragePath);if(!W)return{command:"openai-account",text:`## Account Not Found
1
+ import{d as x1,e as FY,f as XW}from"./index-87145jkw.js";import{A as $1,B as R1,C as Q1,D as lW,E as dW,G as u0,H as iW,I as F1,J as y0,K as q0,L as J0,M as jY,N as DY,O as XX,P as PY,Q as nW,R as oW,S as rW,h as SW,i as kW,j as bW,k as xW,l as vW,m as hW,n as gW,o as l1,p as d1,q as V8,s as yW,t as fW,u as mW,v as cW,w as uW,x as pW,y as fX,z as mX}from"./index-cxze8h26.js";import{$ as D1,U as f8,X as MY,Y as sW,da as aW,ea as tW,fa as eW,ka as Y5,la as N8,ma as X5,na as J5,oa as Q5,pa as $5}from"./index-meg0ng0z.js";import{ua as bY}from"./index-n00ybbbq.js";import{va as AJ,wa as TJ}from"./index-e08r33g5.js";import{Aa as L0,ya as kY,za as $J}from"./index-hxpv25e8.js";import{Da as G5}from"./index-dz9a4xwy.js";import{Ga as X9}from"./index-s2vhsb2v.js";import{mkdirSync as RB,readFileSync as CB,renameSync as _B,statSync as IB,writeFileSync as SB}from"node:fs";import e9 from"node:os";import{join as kB}from"node:path";import{readFileSync as O5}from"node:fs";import{homedir as q5,tmpdir as F5}from"node:os";import{join as RY}from"node:path";var j5="https://chatgpt.com/backend-api/codex/responses",D5="openai-auth.json",o0={noWebSearch:"CORTEXKIT_OPENAI_AUTH_NO_WEB_SEARCH",webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",responsesLite:"CORTEXKIT_OPENAI_AUTH_RESPONSES_LITE",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",codexApiEndpoint:"CORTEXKIT_OPENAI_AUTH_CODEX_ENDPOINT",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function CY(){let Y=process.env[o0.configDir]?.trim();if(Y)return Y;return RY(process.env.XDG_CONFIG_HOME||RY(q5(),".config"),"opencode")}function $0(){return process.env[o0.configFile]?.trim()||RY(CY(),D5)}function P5(){try{let Y=JSON.parse(O5($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 M5(){let Y=P5(),X=MX(o0.noWebSearch),J=X!==void 0?!X:typeof Y.webSearch==="boolean"?Y.webSearch:!0,Q;if(Y.dump!==void 0&&Y.dump!==null){if(typeof Y.dump==="object")Q=Y.dump.enabled;else if(typeof Y.dump==="boolean")Q=Y.dump}return{webSearch:J,webSockets:TY(o0.webSockets,Y.webSockets,!1),rawWebSocket:TY(o0.rawWebSocket,Y.rawWebSocket,!1),responsesLite:TY(o0.responsesLite,Y.responsesLite,!1),dump:TY(o0.dump,Q,!1),dumpDir:process.env[o0.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():RY(F5(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[o0.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():j5)}}var q8;function M0(){if(!q8)q8=M5();return q8}var F8="/backend-api/wham/rate-limit-reset-credits",w5=`https://chatgpt.com${F8}`,RX=`${F8}/consume`,E5=`https://chatgpt.com${RX}`,A5=300000,T5=60000,R5=15000,C5=60000;class _0 extends Error{kind;cooldownUntil;constructor(Y,X,J){super(X);this.name="ResetRedemptionError",this.kind=Y,this.cooldownUntil=J}}class q1 extends Error{kind;status;constructor(Y,X,J){super(X);this.name="ResetCreditError",this.kind=Y,this.status=J}}function 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<A5}function IY(Y,X){if(!y0(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(!y0(X))return;let Q=kX(Y),$=Q[X]??{},G=$.lastOutcome;delete $.inFlight,$.lastOutcome={code:"ambiguous_local",at:J,...G?{previousOutcome:{code:G.code,at:G.at}}:{}},Q[X]=$}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 _5(Y,X){if(!y0(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 I5(Y,X){let J;if(await Y.mutateAccountsFn((Q)=>{let $=Y.now(),G=IY(Q,X);if(J=xX(G,$),J.kind==="corrupt")bX(Q,X,$);return Q},Y.configPath),!J)throw Error("corrupt reset state mutation did not run");return J}async function S5(Y,X,J){if(!y0(X))return{kind:"fresh",beforeState:void 0};let Q;if(await Y.mutateAccountsFn(($)=>{let G=Y.now(),W=IY($,X),U=_X(W),L=j8(W?.inFlight);if(IX(W)&&!L)return bX($,X,G),Q={kind:"corrupt",beforeState:U},$;if(W?.cooldownUntil!==void 0&&W.cooldownUntil>G)return Q={kind:"cooldown",beforeState:U,cooldownUntil:W.cooldownUntil},$;if(L&&SX(L,G))return Q={kind:"claim",beforeState:U,claim:{inFlight:L,selectedCredit:{id:L.creditId}}},$;if(L)return Q={kind:"expired_unreconciled",beforeState:U,claim:{inFlight:L,selectedCredit:{id:L.creditId}}},$;let H=SY(J);if(!H)return Q={kind:"fresh",beforeState:U},$;let N={redeemRequestId:Y.randomUUID(),creditId:H.id,startedAt:G},O=kX($);return O[X]={...W,inFlight:N},Q={kind:"claim",beforeState:U,claim:{inFlight:N,selectedCredit:H}},$},Y.configPath),!Q)throw Error("reset claim mutation did not run");return Q}async function k5(Y,X,J,Q){if(!y0(X))return;if(!M8(Q.kind))return;await Y.mutateAccountsFn(($)=>{let G=IY($,X),W=j8(G?.inFlight);if(!G||!W||W.redeemRequestId!==J.redeemRequestId||W.creditId!==J.creditId)return $;let U=Y.now();if(delete G.inFlight,G.lastOutcome={code:Q.kind,at:U},Q.kind==="reset"||Q.kind==="already_redeemed")G.cooldownUntil=U+C5;else delete G.cooldownUntil;return $},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 b5(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(w5,{method:"GET",headers:CX(X,F8,J),signal:AbortSignal.timeout(R5)})}catch{throw new q1("http_error","reset credit list request failed")}if(!Q.ok)throw new q1("http_error",`reset credit list request failed: ${Q.status}`,Q.status);let $;try{$=await Q.json()}catch{throw new q1("invalid_response","reset credit list response was not valid JSON",Q.status)}if(!_Y($))throw new q1("invalid_response","reset credit list response was not an object",Q.status);return{credits:(Array.isArray($.credits)?$.credits:[]).flatMap((W)=>{let U=b5(W);return U===void 0?[]:[U]}),availableCount:typeof $.available_count==="number"&&Number.isFinite($.available_count)?$.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 x5(Y,X,J,Q,$){let G;try{G=await Y(E5,{method:"POST",headers:{...CX(X,RX,J),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:$,credit_id:Q}),signal:AbortSignal.timeout(T5)})}catch(H){return{kind:"ambiguous",raw:H}}let W;try{W=await G.text()}catch(H){return G.ok?{kind:"ambiguous",raw:H}:{kind:"http_error",raw:H,status:G.status}}let U=W,L=!1;try{U=JSON.parse(W),L=!0}catch{}if(!G.ok)return{kind:"http_error",raw:U,status:G.status};if(!L||!_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 _0("cooldown_active","reset credit redemption is cooling down",Y.cooldownUntil);throw Error(`unexpected reset state decision: ${Y.kind}`)}function AX(){throw new _0("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 v5(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(!y0(X.accountKey))throw new _0("invalid_account_key","the reset account key is reserved");let J=await Y.resolveTarget(X.accountKey);if(J.chatgptAccountId!==X.expectedChatgptAccountId)throw new _0("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let Q=J.accountKey==="main"?void 0:J.chatgptAccountId,$=await _5(Y,X.accountKey);if($.kind==="corrupt"){if($=await I5(Y,X.accountKey),$.kind==="corrupt")return TX(J,$.beforeState)}if($.kind==="cooldown")EX($);let G;if($.kind==="claim")G=$.claim;else if($.kind==="expired_unreconciled"){if(!X.retry)AX();G=$.claim}else{if(X.retry)throw new _0("retry_without_inflight","there is no active reset credit redemption to retry");let[L,H]=await Promise.all([Y.fetchUsage(J),P8(Y.fetchImpl,J.accessToken,Q)]),N=D8(L,Y.hasActiveRateLimitMark(X.accountKey),L.resetCreditsApplicable??0,Y.now());if(!N.ok)throw new _0(N.reason==="not exhausted"?"not_exhausted":"no_applicable_credits",N.reason);if(!SY(H.credits))throw new _0("no_eligible_credit","no eligible reset credit was returned");let O=await S5(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 _0("no_eligible_credit","no eligible reset credit was available while claiming");G=O.claim}let W=await x5(Y.fetchImpl,J.accessToken,Q,G.inFlight.creditId,G.inFlight.redeemRequestId),U=!1;try{await k5(Y,X.accountKey,G.inFlight,W)}catch{U=M8(W.kind)}return{target:J,selectedCredit:G.selectedCredit,beforeState:$.beforeState,outcome:W,retrySafety:U?"The server returned a terminal result, but the state write failed. A retry within five minutes reuses the same request and credit identifiers.":v5(W),...U?{finalizeStateWriteFailed:!0}:{}}}function C(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",j1="openai-reset",cX=["openai-quota","openai-account","openai-routing","openai-killswitch","openai-dump","openai-logging","openai-cachekeep","openai-reset"],i=L0("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 h5(Y){let X=await Y.refreshAllQuota?.(),J=Y.quotaManager.getMain(),Q=["## OpenAI Quota",""];if(J?.quota){let W=J.quota;Q.push("### Main account");for(let U of["primary","secondary"]){let L=W[U];if(L){let H=Math.round(L.usedPercent),N="█".repeat(Math.max(0,Math.min(Math.round(H/10),10)))+"░".repeat(Math.max(0,10-Math.min(Math.round(H/10),10)));Q.push(`- ${U}: ${N} ${H}% used (${Math.round(L.remainingPercent)}% remaining)`)}}if(W.resetCreditsAvailable!==void 0)Q.push(`- resets: ${W.resetCreditsAvailable}`)}else Q.push("No main quota snapshot available. Send a request first.");let G=[...Y.quotaManager.getAllFallbacks().entries()].filter(([,W])=>W);if(G.length>0){Q.push(""),Q.push("### Fallback accounts");for(let[W,U]of G){if(!U?.quota)continue;Q.push(`**${W}**`);for(let L of["primary","secondary"]){let H=U.quota[L];if(H){let N=Math.round(H.usedPercent);Q.push(` - ${L}: ${N}% used (${Math.round(H.remainingPercent)}% remaining)`)}}if(U.quota.resetCreditsAvailable!==void 0)Q.push(` - resets: ${U.quota.resetCreditsAvailable}`)}}if(X?.length){let W=X.filter((U)=>!U.ok);if(W.length>0){Q.push("");for(let U of W)Q.push(`- ${U.account}: fetch failed — Refresh to retry`)}}return{command:"openai-quota",text:Q.join(`
2
+ `),knobs:{}}}function k1(Y){return{id:Y.id,type:Y.type??"oauth",enabled:Y.enabled,label:Y.label}}async function g5(Y,X){let J=Y.trim().split(/\s+/).filter(Boolean),Q=await X.loadAccounts(X.accountStoragePath)??{version:1,accounts:[]},$=Q.accounts??[];if(J.length===0){let G=["## OpenAI Accounts",""];if($.length===0)G.push("No accounts configured. Use `/login openai` to add your main account, or `/openai-account add` to add a fallback account.");else{let W=Q.routing?.mode??"main-first";G.push(`Routing: \`${W}\` (set with \`/openai-routing\`). Modes: main-first, fallback-first, or sticky-balanced. \`/openai-routing reset\` clears this session's pin.`),G.push("");for(let U of $){let L=U.type??"oauth";G.push(`- \`${U.id}\` (${L})`)}}return G.push(""),G.push("Commands: `/openai-account add [label]` | `/openai-account remove <id>`"),{command:"openai-account",text:G.join(`
3
+ `),knobs:{accounts:$.map(k1)}}}if(J[0]==="remove"&&J[1]){let G=J[1],W=!1,U=await J0((L)=>{let H=L.accounts.findIndex((N)=>N.id===G);if(H===-1)return L;return W=!0,L.accounts.splice(H,1),L},X.accountStoragePath);if(!W)return{command:"openai-account",text:`## Account Not Found
4
4
 
5
- No account with id \`${G}\` exists.`,knobs:{accounts:K.accounts}};return G0.info("account removed",{id:G}),X.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Account Removed
5
+ No account with id \`${G}\` exists.`,knobs:{accounts:U.accounts.map(k1)}};return i.info("account removed",{id:G}),X.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Account Removed
6
6
 
7
- Removed account \`${G}\`.`,knobs:{accounts:K.accounts}}}if(J[0]==="order"&&J.length>=3){let G=!1,W=await J0((K)=>{let U=K.accounts.findIndex((O)=>O.id===J[1]),H=K.accounts.findIndex((O)=>O.id===J[2]);if(U===-1||H===-1)return K;G=!0;let N=K.accounts[U];return K.accounts[U]=K.accounts[H],K.accounts[H]=N,K},X.accountStoragePath);if(!G)return{command:"openai-account",text:`## Invalid Order
7
+ Removed account \`${G}\`.`,knobs:{accounts:U.accounts.map(k1)}}}if(J[0]==="order"&&J.length>=3){let G=!1,W=await J0((U)=>{let L=U.accounts.findIndex((O)=>O.id===J[1]),H=U.accounts.findIndex((O)=>O.id===J[2]);if(L===-1||H===-1)return U;G=!0;let N=U.accounts[L];return U.accounts[L]=U.accounts[H],U.accounts[H]=N,U},X.accountStoragePath);if(!G)return{command:"openai-account",text:`## Invalid Order
8
8
 
9
- Both account IDs must exist.`,knobs:{accounts:W.accounts}};return G0.info("accounts reordered",{a:J[1],b:J[2]}),X.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Accounts Reordered
9
+ Both account IDs must exist.`,knobs:{accounts:W.accounts.map(k1)}};return i.info("accounts reordered",{a:J[1],b:J[2]}),X.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Accounts Reordered
10
10
 
11
- Swapped positions of \`${J[1]}\` and \`${J[2]}\`.`,knobs:{accounts:W.accounts}}}if(J[0]==="add"){let G=J.includes("--headless"),W=J.filter((L)=>L!=="add"&&L!=="--headless"),K=W.length>0?W.join(" "):void 0,{url:U,instructions:H,completion:N}=await zX({label:K,headless:G}),O=X.notify,B=X.sessionId;if(N.then(async(L)=>{let Z=!1;if(await J0((j)=>{if(L.accountId&&j.mainAccountId&&L.accountId===j.mainAccountId)return Z=!0,j;return WX(j.accounts,L),j},X.accountStoragePath),Z){G0.warn("account add rejected (main identity)",{id:L.id,sessionId:B}),O?.({command:"openai-account",text:`## Add Failed
11
+ Swapped positions of \`${J[1]}\` and \`${J[2]}\`.`,knobs:{accounts:W.accounts.map(k1)}}}if(J[0]==="add"){let G=J.includes("--headless"),W=J.filter((V)=>V!=="add"&&V!=="--headless"),U=W.length>0?W.join(" "):void 0,{url:L,instructions:H,completion:N}=await mX({label:U,headless:G}),O=X.notify,Z=X.sessionId;if(N.then(async(V)=>{let K=!1;if(await J0((j)=>{if(V.accountId&&j.mainAccountId&&V.accountId===j.mainAccountId)return K=!0,j;return 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
- ${"That account is already your main account — not added as a fallback."}`,knobs:{}});return}G0.info("account added",{id:L.id,label:L.label}),X.refreshSidebar?.().catch(()=>{}),O?.({command:"openai-account",text:`## Account Added
13
+ ${"That account is already your main account — not added as a fallback."}`,knobs:{}});return}i.info("account added",{id:V.id,label:V.label}),X.refreshSidebar?.().catch(()=>{}),O?.({command:"openai-account",text:`## Account Added
14
14
 
15
- Added account \`${L.id}\`${L.label?` ("${L.label}")`:""}.
15
+ Added account \`${V.id}\`${V.label?` ("${V.label}")`:""}.
16
16
 
17
- Run \`/openai-account\` to confirm.`,knobs:{}})}).catch((L)=>{let Z=L instanceof Error?L.message:String(L??"unknown error");G0.warn("account add failed",{error:Z,sessionId:B}),O?.({command:"openai-account",text:`## Add Failed
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: ${Z}`,knobs:{}})}),G){let L=H.match(/Enter code: (.+)/)?.[1]??H;return{command:"openai-account",text:`## Device Code
19
+ Account add failed: ${K}`,knobs:{}})}),G){let V=H.match(/Enter code: (.+)/)?.[1]??H;return{command:"openai-account",text:`## Device Code
20
20
 
21
21
  1. Open this verification URL:
22
22
 
23
- ${U}
23
+ ${L}
24
24
 
25
- 2. Enter the code: **${L}**
25
+ 2. Enter the code: **${V}**
26
26
 
27
27
  ${H}
28
28
 
29
- The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{verificationUrl:U,userCode:L,instructions:H}}}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
- ${U}
33
+ ${L}
34
34
 
35
35
  ${H}
36
36
 
37
- The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{url:U,instructions:H}}}return{command:"openai-account",text:"## Account Commands\n\n- `/openai-account` — show accounts\n- `/openai-account add [label]` — add a new account\n- `/openai-account remove <id>` — remove\n- `/openai-account order <a> <b>` — swap fallback positions\n\nRouting modes are `main-first`, `fallback-first`, and `sticky-balanced`. `/openai-routing reset` clears the current session pin.",knobs:{accounts:$}}}async function lW(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),$=(await X.loadAccounts(X.accountStoragePath)??{version:1,accounts:[]}).routing?.mode??"main-first";if(J.length===1&&J[0]==="reset"){if(!X.sessionId)return{command:"openai-routing",text:`## OpenAI Routing Reset
37
+ The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{url:L,instructions:H}}}return{command:"openai-account",text:"## Account Commands\n\n- `/openai-account` — show accounts\n- `/openai-account add [label]` — add a new account\n- `/openai-account remove <id>` — remove\n- `/openai-account order <a> <b>` — swap fallback positions\n\nRouting modes are `main-first`, `fallback-first`, and `sticky-balanced`. `/openai-routing reset` clears the current session pin.",knobs:{accounts:$.map(k1)}}}async function y5(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),$=(await X.loadAccounts(X.accountStoragePath)??{version:1,accounts:[]}).routing?.mode??"main-first";if(J.length===1&&J[0]==="reset"){if(!X.sessionId)return{command:"openai-routing",text:`## OpenAI Routing Reset
38
38
 
39
39
  No current session is available, so no pin was changed.`,knobs:{mode:$}};if(!X.clearStickyRouting)return{command:"openai-routing",text:`## OpenAI Routing Reset
40
40
 
41
- This runtime cannot clear the current session pin.`,knobs:{mode:$}};return await X.clearStickyRouting(X.sessionId),G0.info("routing session pin cleared"),{command:"openai-routing",text:`## OpenAI Routing Reset
41
+ This runtime cannot clear the current session pin.`,knobs:{mode:$}};return await X.clearStickyRouting(X.sessionId),i.info("routing session pin cleared"),{command:"openai-routing",text:`## OpenAI Routing Reset
42
42
 
43
- This session's pin was cleared. The next request may choose the same account if it remains the best selection.`,knobs:{mode:$}}}if(J.length===1&&(J[0]==="main-first"||J[0]==="fallback-first"||J[0]==="sticky-balanced")){let K=J[0];return await J0((U)=>{return U.routing={...U.routing??{},mode:K},U},X.accountStoragePath),G0.info("routing mode changed",{mode:K}),{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:$}}}if(J.length===1&&(J[0]==="main-first"||J[0]==="fallback-first"||J[0]==="sticky-balanced")){let U=J[0];return await J0((L)=>{return L.routing={...L.routing??{},mode:U},L},X.accountStoragePath),i.info("routing mode changed",{mode:U}),{command:"openai-routing",text:`## OpenAI Routing Updated
44
44
 
45
- Mode: \`${K}\`
46
- - ${GX(K)}
45
+ Mode: \`${U}\`
46
+ - ${hX(U)}
47
47
 
48
- Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:K}}}let G=$==="sticky-balanced"&&X.sessionId?await X.getStickyRouting?.(X.sessionId):void 0,W=$==="sticky-balanced"?G?`
48
+ Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:U}}}let G=$==="sticky-balanced"&&X.sessionId?await X.getStickyRouting?.(X.sessionId):void 0,W=$==="sticky-balanced"?G?`
49
49
  - Session pin: \`${G}\`. Use \`/openai-routing reset\` to clear it.`:`
50
50
  - Session pin: none yet. A request will choose one when a usable account is available.`:"";return{command:"openai-routing",text:`## OpenAI Routing
51
51
 
52
52
  - Mode: \`${$}\`
53
- - ${GX($)}${W}
53
+ - ${hX($)}${W}
54
54
 
55
- Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:$}}}async function dW(Y,X){let J=await X.loadAccounts(X.accountStoragePath)??{version:1,accounts:[]},Q=J.killswitch??{},$=(J.accounts??[]).filter((W)=>W.enabled!==!1).map((W)=>W.id),G=Y.trim().toLowerCase().split(/\s+/).filter(Boolean);if(G.length===0){let W=Q.enabled===!0,K=["## Killswitch","",`Status: **${W?"ON":"OFF"}**`];if(W){K.push(""),K.push("| Account | primary threshold | secondary threshold |"),K.push("| ------- | ------------ | ------------ |");let U=Q.main??{},H=U.primary??U["5h"]??L1.primary,N=U.secondary??U["1w"]??L1.secondary;K.push(`| main | ≥ ${H}% | ≥ ${N}% |`);for(let O of $){let B=Q.accounts?.[O]??Q.main??{},L=B.primary??B["5h"]??L1.primary,Z=B.secondary??B["1w"]??L1.secondary;K.push(`| ${O} | ≥ ${L}% | ≥ ${Z}% |`)}}return K.push(""),K.push("Commands: `/openai-killswitch on` | `/openai-killswitch off` | `/openai-killswitch set <acct>:<5h>,<1w> ...`"),{command:"openai-killswitch",text:K.join(`
56
- `),knobs:{config:Q,accountIds:$}}}if(G[0]==="on"){let W={...Q,enabled:!0,main:Q.main??{primary:L1.primary,secondary:L1.secondary}};return await J0((K)=>{return K.killswitch=W,K},X.accountStoragePath),G0.info("killswitch enabled"),{command:"openai-killswitch",text:"## Killswitch Enabled",knobs:{config:W,accountIds:$}}}if(G[0]==="off"){let W={...Q,enabled:!1};return await J0((K)=>{return K.killswitch=W,K},X.accountStoragePath),G0.info("killswitch disabled"),{command:"openai-killswitch",text:"## Killswitch Disabled",knobs:{config:W,accountIds:$}}}if(G[0]==="set"&&G.length>1){let W={...Q,enabled:!0,accounts:{...Q.accounts??{}}};for(let K=1;K<G.length;K++){let U=G[K]?.match(/^([^:]+):(\d+),(\d+)$/);if(!U)continue;let[,H,N,O]=U,B={primary:Number.parseInt(N,10),secondary:Number.parseInt(O,10)};if(H==="main")W.main=B;else if(H==="all"){W.main=B;for(let L of $)W.accounts[L]=B}else W.accounts[H]=B}return await J0((K)=>{return K.killswitch=W,K},X.accountStoragePath),G0.info("killswitch thresholds updated",{count:G.length-1}),{command:"openai-killswitch",text:"## Killswitch Updated",knobs:{config:W,accountIds:$}}}return{command:"openai-killswitch",text:"Usage: `/openai-killswitch`, `/openai-killswitch on`, `/openai-killswitch off`, `/openai-killswitch set <acct>:<5h>,<1w> ...`",knobs:{config:Q,accountIds:$}}}async function iW(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),Q=P0(),$=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:$}}}async function f5(Y,X){let J=await X.loadAccounts(X.accountStoragePath)??{version:1,accounts:[]},Q=J.killswitch??{},$=(J.accounts??[]).filter((W)=>W.enabled!==!1).map((W)=>W.id),G=Y.trim().toLowerCase().split(/\s+/).filter(Boolean);if(G.length===0){let W=Q.enabled===!0,U=["## Killswitch","",`Status: **${W?"ON":"OFF"}**`];if(W){U.push(""),U.push("| Account | primary threshold | secondary threshold |"),U.push("| ------- | ------------ | ------------ |");let L=Q.main??{},H=L.primary??L["5h"]??F1.primary,N=L.secondary??L["1w"]??F1.secondary;U.push(`| main | ≥ ${H}% | ≥ ${N}% |`);for(let O of $){let Z=Q.accounts?.[O]??Q.main??{},V=Z.primary??Z["5h"]??F1.primary,K=Z.secondary??Z["1w"]??F1.secondary;U.push(`| ${O} | ≥ ${V}% | ≥ ${K}% |`)}}return U.push(""),U.push("Commands: `/openai-killswitch on` | `/openai-killswitch off` | `/openai-killswitch set <acct>:<5h>,<1w> ...`"),{command:"openai-killswitch",text:U.join(`
56
+ `),knobs:{config:Q,accountIds:$}}}if(G[0]==="on"){let W={...Q,enabled:!0,main:Q.main??{primary:F1.primary,secondary:F1.secondary}};return await J0((U)=>{return U.killswitch=W,U},X.accountStoragePath),i.info("killswitch enabled"),{command:"openai-killswitch",text:"## Killswitch Enabled",knobs:{config:W,accountIds:$}}}if(G[0]==="off"){let W={...Q,enabled:!1};return await J0((U)=>{return U.killswitch=W,U},X.accountStoragePath),i.info("killswitch disabled"),{command:"openai-killswitch",text:"## Killswitch Disabled",knobs:{config:W,accountIds:$}}}if(G[0]==="set"&&G.length>1){let W={...Q,enabled:!0,accounts:{...Q.accounts??{}}};for(let U=1;U<G.length;U++){let L=G[U]?.match(/^([^:]+):(\d+),(\d+)$/);if(!L)continue;let[,H,N,O]=L,Z={primary:Number.parseInt(N,10),secondary:Number.parseInt(O,10)};if(H==="main")W.main=Z;else if(H==="all"){W.main=Z;for(let V of $)W.accounts[V]=Z}else W.accounts[H]=Z}return await J0((U)=>{return U.killswitch=W,U},X.accountStoragePath),i.info("killswitch thresholds updated",{count:G.length-1}),{command:"openai-killswitch",text:"## Killswitch Updated",knobs:{config:W,accountIds:$}}}return{command:"openai-killswitch",text:"Usage: `/openai-killswitch`, `/openai-killswitch on`, `/openai-killswitch off`, `/openai-killswitch set <acct>:<5h>,<1w> ...`",knobs:{config:Q,accountIds:$}}}async function m5(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),Q=M0(),$=Q.dump;if(J.length===0)return{command:"openai-dump",text:`## Request Dump
57
57
 
58
58
  - Enabled: ${$?"ON":"OFF"}
59
59
  - Directory: ${Q.dumpDir}
60
60
 
61
- Usage: \`/openai-dump on\` or \`/openai-dump off\``,knobs:{enabled:$}};if(J[0]==="on")return await J0((G)=>{return G.dump={...G.dump??{},enabled:!0},G},X.accountStoragePath),G0.info("request dump enabled"),{command:"openai-dump",text:`## Request Dump Enabled
61
+ Usage: \`/openai-dump on\` or \`/openai-dump off\``,knobs:{enabled:$}};if(J[0]==="on")return await J0((G)=>{return G.dump={...G.dump??{},enabled:!0},G},X.accountStoragePath),i.info("request dump enabled"),{command:"openai-dump",text:`## Request Dump Enabled
62
62
 
63
63
  Dump directory: ${Q.dumpDir}
64
64
 
65
- Warning: body dumps may contain prompt/session content. Turn this off after debugging.`,knobs:{enabled:!0}};if(J[0]==="off")return await J0((G)=>{return G.dump={...G.dump??{},enabled:!1},G},X.accountStoragePath),G0.info("request dump disabled"),{command:"openai-dump",text:"## Request Dump Disabled",knobs:{enabled:!1}};return{command:"openai-dump",text:"Usage: `/openai-dump`, `/openai-dump on`, or `/openai-dump off`.",knobs:{enabled:$}}}async function nW(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((G)=>{return G.dump={...G.dump??{},enabled:!1},G},X.accountStoragePath),i.info("request dump disabled"),{command:"openai-dump",text:"## Request Dump Disabled",knobs:{enabled:!1}};return{command:"openai-dump",text:"Usage: `/openai-dump`, `/openai-dump on`, or `/openai-dump off`.",knobs:{enabled:$}}}async function c5(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((K)=>`\`${K}\``).join(", ")}
69
+ Valid levels: ${Q.map((U)=>`\`${U}\``).join(", ")}
70
70
 
71
- Usage: \`/openai-logging <level>\``,knobs:{level:W}}}let $=J[0];if($&&Q.includes($)){let G=$;return DY(G),await J0((W)=>{return W.logging={...W.logging??{},level:G},W},X.accountStoragePath),G0.info("log level changed",{level:G}),{command:"openai-logging",text:`## Logging Updated
71
+ Usage: \`/openai-logging <level>\``,knobs:{level:W}}}let $=J[0];if($&&Q.includes($)){let G=$;return kY(G),await J0((W)=>{return W.logging={...W.logging??{},level:G},W},X.accountStoragePath),i.info("log level changed",{level:G}),{command:"openai-logging",text:`## Logging Updated
72
72
 
73
73
  Level set to \`${G}\`.`,knobs:{level:G}}}return{command:"openai-logging",text:`## Invalid Level
74
74
 
75
- Valid levels: ${Q.map((G)=>`\`${G}\``).join(", ")}`,knobs:{level:"info"}}}function oW(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 rW(Y,X){let J=X.cacheKeepManager,Q=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),$=await X.loadAccounts(X.accountStoragePath),G=$?.cachekeep?.enabled===!0;if(Q.length===0||Q[0]==="status"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
75
+ Valid levels: ${Q.map((G)=>`\`${G}\``).join(", ")}`,knobs:{level:"info"}}}function u5(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 p5(Y,X){let J=X.cacheKeepManager,Q=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),$=await X.loadAccounts(X.accountStoragePath),G=$?.cachekeep?.enabled===!0;if(Q.length===0||Q[0]==="status"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
76
76
 
77
- Status: **not available** (manager not wired)`,knobs:{}};let K=J.status(),U=K.window,H=U?`${String(U.startHour).padStart(2,"0")}-${String(U.endHour).padStart(2,"0")}`:"always (no window)",N=["## Cachekeep","",`Status: **${G?"ON":"OFF"}**`,`Timer: **${K.running?"armed":"idle"}**`,`Subagent warming: **${$?.cachekeep?.subagents===!0?"ON":"OFF"}**`,`Idle policy: **sustain ${K.sustain?"ON":"OFF"} (main only)**`,`Window: **${H}**`];if(N.push(`Tracked sessions: **${K.tracked}**`),K.targets.length>0){N.push("");for(let B of K.targets){let L=B.sessionKey.length>12?`${B.sessionKey.slice(0,12)}…`:B.sessionKey,Z=Math.ceil((B.cacheExpiresAt-K.generatedAt)/1000);N.push(`- \`${L}\` (${B.accountId??"main"}) — expires in ${Z}s`+(B.lastWarmedAt?`, last warm ${Math.ceil((K.generatedAt-B.lastWarmedAt)/1000)}s ago`:"")+(B.backoffUntil&&B.backoffUntil>K.generatedAt?`, backoff ${Math.ceil((B.backoffUntil-K.generatedAt)/1000)}s`:""))}}N.push(""),N.push(`TTL: ${Math.round(K.ttlMs/1000)}s | Lead: ${Math.round(K.leadMs/1000)}s | Max idle warm: ${Math.round(K.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,...K.targets.map((B)=>B.lastWarmedAt??0));return{command:"openai-cachekeep",text:N.join(`
78
- `),knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:K.sustain,window:U,running:K.running,tracked:K.tracked,lastWarmAt:O||void 0,generatedAt:K.generatedAt,maxIdleWarmMs:K.maxIdleWarmMs,maxSubagentIdleMs:K.maxSubagentIdleMs}}}if(Q[0]==="on"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
77
+ Status: **not available** (manager not wired)`,knobs:{}};let U=J.status(),L=U.window,H=L?`${String(L.startHour).padStart(2,"0")}-${String(L.endHour).padStart(2,"0")}`:"always (no window)",N=["## Cachekeep","",`Status: **${G?"ON":"OFF"}**`,`Timer: **${U.running?"armed":"idle"}**`,`Subagent warming: **${$?.cachekeep?.subagents===!0?"ON":"OFF"}**`,`Idle policy: **sustain ${U.sustain?"ON":"OFF"} (main only)**`,`Window: **${H}**`];if(N.push(`Tracked sessions: **${U.tracked}**`),U.targets.length>0){N.push("");for(let Z of U.targets){let V=Z.sessionKey.length>12?`${Z.sessionKey.slice(0,12)}…`:Z.sessionKey,K=Math.ceil((Z.cacheExpiresAt-U.generatedAt)/1000);N.push(`- \`${V}\` (${Z.accountId??"main"}) — expires in ${K}s`+(Z.lastWarmedAt?`, last warm ${Math.ceil((U.generatedAt-Z.lastWarmedAt)/1000)}s ago`:"")+(Z.backoffUntil&&Z.backoffUntil>U.generatedAt?`, backoff ${Math.ceil((Z.backoffUntil-U.generatedAt)/1000)}s`:""))}}N.push(""),N.push(`TTL: ${Math.round(U.ttlMs/1000)}s | Lead: ${Math.round(U.leadMs/1000)}s | Max idle warm: ${Math.round(U.maxIdleWarmMs/60000)}min`),N.push(""),N.push("Commands: `/openai-cachekeep on` | `/openai-cachekeep off` | `/openai-cachekeep sustain on` | `/openai-cachekeep sustain off` | `/openai-cachekeep HH-HH` | `/openai-cachekeep window clear` | `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off` | `/openai-cachekeep`");let O=Math.max(0,...U.targets.map((Z)=>Z.lastWarmedAt??0));return{command:"openai-cachekeep",text:N.join(`
78
+ `),knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:U.sustain,window:L,running:U.running,tracked:U.tracked,lastWarmAt:O||void 0,generatedAt:U.generatedAt,maxIdleWarmMs:U.maxIdleWarmMs,maxSubagentIdleMs:U.maxSubagentIdleMs}}}if(Q[0]==="on"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
79
79
 
80
- Cannot start: manager not wired.`,knobs:{}};await J0((H)=>{return H.cachekeep={...H.cachekeep??{},enabled:!0},H},X.accountStoragePath),G0.info("cachekeep enabled"),X.setCacheKeepEnabled?.(!0),J.start();let K=J.status(),U=Math.max(0,...K.targets.map((H)=>H.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 U=J.status(),L=Math.max(0,...U.targets.map((H)=>H.lastWarmedAt??0));return{command:"openai-cachekeep",text:`## Cachekeep Enabled
81
81
 
82
- TTL: ${Math.round(K.ttlMs/1000)}s | Max idle warm ${Math.round(K.maxIdleWarmMs/60000)}min`,knobs:{enabled:!0,subagents:$?.cachekeep?.subagents===!0,sustain:K.sustain,window:K.window,running:K.running,tracked:K.tracked,lastWarmAt:U||void 0,generatedAt:K.generatedAt,maxIdleWarmMs:K.maxIdleWarmMs,maxSubagentIdleMs:K.maxSubagentIdleMs}}}if(Q[0]==="off")return await J0((K)=>{return K.cachekeep={...K.cachekeep??{},enabled:!1},K},X.accountStoragePath),G0.info("cachekeep disabled"),X.setCacheKeepEnabled?.(!1),J?.stop(),{command:"openai-cachekeep",text:"## Cachekeep Disabled",knobs:{enabled:!1,sustain:$?.cachekeep?.sustain===!0,running:!1,tracked:0}};if(Q[0]==="sustain"){let K=Q[1];if(Q.length!==2||K!=="on"&&K!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep sustain on` | `/openai-cachekeep sustain off`",knobs:{}};let U=K==="on";await J0((N)=>{return N.cachekeep={...N.cachekeep??{},sustain:U},N},X.accountStoragePath),G0.info(`cachekeep sustain ${U?"enabled":"disabled"}`),X.setCacheKeepSustain?.(U);let H=J?.status();return{command:"openai-cachekeep",text:U?`## Cachekeep Sustain Enabled
82
+ TTL: ${Math.round(U.ttlMs/1000)}s | Max idle warm ${Math.round(U.maxIdleWarmMs/60000)}min`,knobs:{enabled:!0,subagents:$?.cachekeep?.subagents===!0,sustain:U.sustain,window:U.window,running:U.running,tracked:U.tracked,lastWarmAt:L||void 0,generatedAt:U.generatedAt,maxIdleWarmMs:U.maxIdleWarmMs,maxSubagentIdleMs:U.maxSubagentIdleMs}}}if(Q[0]==="off")return await J0((U)=>{return U.cachekeep={...U.cachekeep??{},enabled:!1},U},X.accountStoragePath),i.info("cachekeep disabled"),X.setCacheKeepEnabled?.(!1),J?.stop(),{command:"openai-cachekeep",text:"## Cachekeep Disabled",knobs:{enabled:!1,sustain:$?.cachekeep?.sustain===!0,running:!1,tracked:0}};if(Q[0]==="sustain"){let U=Q[1];if(Q.length!==2||U!=="on"&&U!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep sustain on` | `/openai-cachekeep sustain off`",knobs:{}};let L=U==="on";await J0((N)=>{return N.cachekeep={...N.cachekeep??{},sustain:L},N},X.accountStoragePath),i.info(`cachekeep sustain ${L?"enabled":"disabled"}`),X.setCacheKeepSustain?.(L);let H=J?.status();return{command:"openai-cachekeep",text:L?`## Cachekeep Sustain Enabled
83
83
 
84
84
  Sustain keeps main-agent sessions warming past the idle cap for this process. Clock windows still apply.
85
85
 
86
86
  Before enabling sustain with Magic Context, set a non-expiring \`cache_ttl\` for models used by main sessions; elapsed-time cold-cache assumptions are no longer valid.`:`## Cachekeep Sustain Disabled
87
87
 
88
- Main-agent sessions again stop warming at the configured idle cap.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:U,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 K=Q[1];if(!K||K!=="on"&&K!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off`",knobs:{}};let U=K==="on";await J0((N)=>{return N.cachekeep={...N.cachekeep??{},subagents:U},N},X.accountStoragePath),G0.info(U?"cachekeep subagent warming enabled":"cachekeep subagent warming disabled"),X.setCacheKeepSubagents?.(U);let H=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Subagent Warming
88
+ Main-agent sessions again stop warming at the configured idle cap.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:L,window:H?.window,running:H?.running??!1,tracked:H?.tracked??0,generatedAt:H?.generatedAt??Date.now(),maxIdleWarmMs:H?.maxIdleWarmMs??3600000,maxSubagentIdleMs:H?.maxSubagentIdleMs??1800000}}}if(Q[0]==="subagents"){let U=Q[1];if(!U||U!=="on"&&U!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off`",knobs:{}};let L=U==="on";await J0((N)=>{return N.cachekeep={...N.cachekeep??{},subagents:L},N},X.accountStoragePath),i.info(L?"cachekeep subagent warming enabled":"cachekeep subagent warming disabled"),X.setCacheKeepSubagents?.(L);let H=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Subagent Warming
89
89
 
90
- Subagent warming: **${U?"ON":"OFF"}**`,knobs:{enabled:G,subagents:U,sustain:H?.sustain??$?.cachekeep?.sustain===!0,window:H?.window,running:H?.running??!1,tracked:H?.tracked??0,generatedAt:H?.generatedAt??Date.now(),maxIdleWarmMs:H?.maxIdleWarmMs??3600000,maxSubagentIdleMs:H?.maxSubagentIdleMs??1800000}}}if(Q[0]==="window"){let K=Q[1];if(K==="clear"||K==="off"){await J0((H)=>{if(H.cachekeep)delete H.cachekeep.startHour,delete H.cachekeep.endHour;return H},X.accountStoragePath),X.setCacheKeepWindow?.(void 0),G0.info("cachekeep window cleared");let U=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Cleared
90
+ Subagent warming: **${L?"ON":"OFF"}**`,knobs:{enabled:G,subagents:L,sustain:H?.sustain??$?.cachekeep?.sustain===!0,window:H?.window,running:H?.running??!1,tracked:H?.tracked??0,generatedAt:H?.generatedAt??Date.now(),maxIdleWarmMs:H?.maxIdleWarmMs??3600000,maxSubagentIdleMs:H?.maxSubagentIdleMs??1800000}}}if(Q[0]==="window"){let U=Q[1];if(U==="clear"||U==="off"){await J0((H)=>{if(H.cachekeep)delete H.cachekeep.startHour,delete H.cachekeep.endHour;return H},X.accountStoragePath),X.setCacheKeepWindow?.(void 0),i.info("cachekeep window cleared");let L=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Cleared
91
91
 
92
- Cachekeep will now warm on every tick (within idle caps).`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:U?.sustain??$?.cachekeep?.sustain===!0,window:void 0,running:U?.running??!1,tracked:U?.tracked??0,generatedAt:U?.generatedAt??Date.now(),maxIdleWarmMs:U?.maxIdleWarmMs??3600000,maxSubagentIdleMs:U?.maxSubagentIdleMs??1800000}}}return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep window clear`",knobs:{}}}let W=Q[0];if(W&&/^\d{1,2}-\d{1,2}$/.test(W)){let K=oW(W);if(!K.ok)return{command:"openai-cachekeep",text:`## Cachekeep Window Invalid
92
+ Cachekeep will now warm on every tick (within idle caps).`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:L?.sustain??$?.cachekeep?.sustain===!0,window:void 0,running:L?.running??!1,tracked:L?.tracked??0,generatedAt:L?.generatedAt??Date.now(),maxIdleWarmMs:L?.maxIdleWarmMs??3600000,maxSubagentIdleMs:L?.maxSubagentIdleMs??1800000}}}return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep window clear`",knobs:{}}}let W=Q[0];if(W&&/^\d{1,2}-\d{1,2}$/.test(W)){let U=u5(W);if(!U.ok)return{command:"openai-cachekeep",text:`## Cachekeep Window Invalid
93
93
 
94
- ${K.reason}`,knobs:{}};let{startHour:U,endHour:H}=K;await J0((B)=>{return B.cachekeep={...B.cachekeep??{},startHour:U,endHour:H},B},X.accountStoragePath),X.setCacheKeepWindow?.({startHour:U,endHour:H}),G0.info("cachekeep window set",{startHour:U,endHour:H});let N=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Set
94
+ ${U.reason}`,knobs:{}};let{startHour:L,endHour:H}=U;await J0((Z)=>{return Z.cachekeep={...Z.cachekeep??{},startHour:L,endHour:H},Z},X.accountStoragePath),X.setCacheKeepWindow?.({startHour:L,endHour:H}),i.info("cachekeep window set",{startHour:L,endHour:H});let N=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Set
95
95
 
96
- Warming limited to **${`${String(U).padStart(2,"0")}-${String(H).padStart(2,"0")}`}** local hours.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:N?.sustain??$?.cachekeep?.sustain===!0,window:{startHour:U,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:{}}}async function B8(Y,X,J){switch(Y){case"openai-quota":return uW(J);case"openai-account":return pW(X,J);case"openai-routing":return lW(X,J);case"openai-killswitch":return dW(X,J);case"openai-dump":return iW(X,J);case"openai-logging":return nW(X,J);case"openai-cachekeep":return rW(X,J);default:throw Error(`unhandled command: ${Y}`)}}var sW=H0("quota");async function f1(Y,X={}){let J=Y.whamFn;if(!J)throw Error("whamFn is required for refreshAllQuota");let Q=[],$=Y.logger??sW,G=(L)=>{Q.push(L);let Z={pid:process.pid,accountId:L.account,status:L.ok?"ok":"error",...L.error?{error:L.error}:{}};if(L.ok)$.debug("quota refresh succeeded",Z);else $.warn("quota refresh failed",Z)},W=Y.skipFresherThanMs,K=!1,U;if(W!==void 0)try{U=await(Y.readSidebarState??N1)()}catch{}let H=new Map(U?.fallbacks.map((L)=>[L.id,L])??[]),N=(...L)=>W!==void 0&&L.some((Z)=>typeof Z==="number"&&Number.isFinite(Z)&&Z<=Y.now()&&Y.now()-Z<W),O=await Y.loadAccounts(Y.configPath).catch(()=>{return}),B=O?.mainAccountId??Y.storageMainAccountId;if(!X.accountKey||X.accountKey==="main")try{let L=await Y.getAuth();if(L.type==="oauth"){let Z=U&&B!==void 0&&U.main.mainAccountId===B?U.main.quota:void 0;if(N(Y.quotaManager.peekMainForPolicy(B)?.checkedAt,Z?.primary?.checkedAt,Z?.secondary?.checkedAt,Z?.checkedAt))G({account:"main",ok:!0});else{if(!L.access||(L.expires??0)<Y.now()){let P=await Y.refreshMainWithLease();L={...L,access:P.access,expires:P.expires}}if(L.access)if(Y.respectBackoff&&Y.quotaManager.isBackedOff())G({account:"main",ok:!0});else{let P=await J({accessToken:L.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:B,accountKey:"main"});Y.quotaManager.setMain(L.access,{quota:P,refreshAfter:Y.now()+300000,checkedAt:Y.now()},B,!0),K=!0,G({account:"main",ok:!0})}else G({account:"main",ok:!1,error:"no access token"})}}else G({account:"main",ok:!1,error:"auth type is not oauth"})}catch(L){G({account:"main",ok:!1,error:a0(L)})}if(O)for(let L of O.accounts){if(X.accountKey&&(X.accountKey==="main"||L.id!==X.accountKey))continue;if(L.enabled===!1||!Y.isOAuthAccountFn(L)){if(X.accountKey)G({account:L.id,ok:!1,error:"account is not an enabled OAuth fallback"});continue}try{let Z=H.get(L.id),j=L.accountId,P=Z&&j!==void 0&&Z.accountId===j?Z.quota:void 0;if(N(Y.quotaManager.peekFallbackForPolicy(L.id,j)?.checkedAt,P?.primary?.checkedAt,P?.secondary?.checkedAt,P?.checkedAt)){G({account:L.id,ok:!0});continue}if(Y.respectBackoff&&Y.quotaManager.isFallbackBackedOff(L.id,L.access)){G({account:L.id,ok:!0});continue}let S;try{S=await Y.fallbackManager.refreshAccount(L,O)}catch{S=L}if(!S.access){G({account:L.id,ok:!1,error:"no access token"});continue}let E=await J({accessToken:S.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:S.accountId,accountKey:L.id});Y.quotaManager.setFallback(L.id,{quota:E,refreshAfter:Y.now()+300000,checkedAt:Y.now()},S.access,!0,S.accountId),K=!0,G({account:L.id,ok:!0})}catch(Z){G({account:L.id,ok:!1,error:a0(Z)})}}if(X.accountKey&&X.accountKey!=="main"&&!Q.some((L)=>L.account===X.accountKey))Q.push({account:X.accountKey,ok:!1,error:"account not found"});if(W===void 0||K){let L=await Y.loadAccounts(Y.configPath);await Y.writeSidebarState(Y.quotaManager,L)}return Q}var aW=300000,tW=30000,eW=240000,Y5="bg-quota-refresh",X5=120000;function J5(Y,X){return PY({name:Y5,ttlMs:X5,path:Y,renew:!0,...X})}function UX(Y,X=f1,J=()=>J5(Y.configPath)){return Q5(Y,X,J)}async function Q5(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:eW})}finally{await Q?.release().catch(()=>{})}}class Z8{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)*tW);if(this.timer=this.setIntervalFn(()=>{let Q=this.run;if(this.stopped||!Q||this.tickPromise)return;let $=Q().catch((G)=>{try{this.onError?.(G)}catch{}}).finally(()=>{if(this.tickPromise===$)this.tickPromise=void 0});this.tickPromise=$},aW+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 I(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}function O8(Y){if(typeof Y!=="string")return!1;try{let X=JSON.parse(Y);return I(X)&&I(X.client_metadata)&&X.client_metadata.ws_request_header_x_openai_internal_codex_responses_lite==="true"}catch{return!1}}function F8(Y){if(typeof Y!=="string")return Y;try{let X=JSON.parse(Y);if(!I(X)||!I(X.client_metadata))return Y;if(!(("x-codex-turn-metadata"in X.client_metadata)||("x-codex-ws-stream-request-start-ms"in X.client_metadata)||("ws_request_header_x_openai_internal_codex_responses_lite"in X.client_metadata)))return Y;let J={...X.client_metadata};return delete J["x-codex-turn-metadata"],delete J["x-codex-ws-stream-request-start-ms"],delete J.ws_request_header_x_openai_internal_codex_responses_lite,JSON.stringify({...X,client_metadata:J})}catch{return Y}}function wY(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"),O8(Y.body))X.set("x-openai-internal-codex-responses-lite","true");return{...Y,headers:X,body:F8(Y.body)}}function BX(Y){if(!Y.enabled||typeof Y.body!=="string")return;let X=Y.headers.has("x-parent-session-id");if(X&&!Y.includeSubagents)return;let J=Y.headers.get("session-id")??Y.headers.get("x-opencode-session")??Y.headers.get("x-session-affinity")??void 0;if(!J)return;let Q={};for(let $ of["session-id","x-session-affinity","x-parent-session-id","user-agent","version","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-client-request-id","thread-id","x-openai-internal-codex-responses-lite"]){let G=Y.headers.get($);if(G)Q[$]=G}return{sessionKey:J,bodyText:Y.body,replayHeaders:Q,isSubagent:X}}function ZX(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 HX(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 $5=300000,OX=1800000,LX=2*OX+900000,G5=3600000,NX=1800000,VX=60000,W5=32,z5=8388608,q8=600000;function FX(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 K5(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 U5(Y,X){return FX(Y)?OX:X}function j8(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function qX(Y){if(!Y||typeof Y!=="object")return j8();let X=Y,J=Number(X.input_tokens)||Number(X.prompt_tokens)||0,Q=Number(X.output_tokens)||Number(X.completion_tokens)||0,$=X.input_tokens_details??X.prompt_tokens_details,G=Number($?.cached_tokens)||Number(X.cached_tokens)||0,W=J>0?G/J:null;return{input_tokens:J,output_tokens:Q,cached_tokens:G,hit_rate:W}}function H5(Y){try{let X=JSON.parse(Y);return qX(X.usage)}catch{return j8()}}function L5(Y){let X,J=[],Q,$=()=>{if(!J.length)return;let G=J.join(`
97
- `).trim();J=[];let W=X;if(X=void 0,!G||G==="[DONE]")return;try{let K=JSON.parse(G),U=K.type??W;if(U!=="response.completed"&&U!=="response.done")return;let H=K.response;Q=qX(H?.usage??K.usage)}catch{}};for(let G of Y.split(/\r?\n/)){if(G===""){$();continue}if(G.startsWith("event:")){X=G.slice(6).trim();continue}if(G.startsWith("data:"))J.push(G.slice(5).trim())}return $(),Q??j8()}class D8{targets=new Map;fetchImpl;getMainToken;refreshFallback;codexResponsesUrl;log;now;ttlMs;leadMs;maxIdleWarmMs;maxSubagentIdleMs;tickIntervalMs;maxTargets;maxBytes;getWindow;getSustain;timer=null;startedAt=null;totalBytes=0;tickInFlight=!1;disposed=!1;abortController=new AbortController;logPayload(Y={}){return{pid:process.pid,...Y}}constructor(Y){this.fetchImpl=Y.fetchImpl,this.getMainToken=Y.getMainToken,this.refreshFallback=Y.refreshFallback,this.codexResponsesUrl=Y.codexResponsesUrl,this.log=Y.logger,this.now=Y.now,this.ttlMs=Y.ttlMs??$5,this.tickIntervalMs=Y.tickIntervalMs??VX,this.leadMs=Y.leadMs??this.tickIntervalMs+15000;let X=Y.maxIdleWarmMs??Y.maxDurationMs;this.maxIdleWarmMs=typeof X==="number"&&Number.isFinite(X)&&X>0?X:G5;let J=Y.maxSubagentIdleMs??NX;this.maxSubagentIdleMs=typeof J==="number"&&Number.isFinite(J)&&J>0?J:NX,this.tickIntervalMs=Y.tickIntervalMs??VX,this.maxTargets=Y.maxTargets??W5,this.maxBytes=Y.maxBytes??z5,this.getWindow=Y.getWindow,this.getSustain=Y.getSustain}track(Y,X,J,Q,$={},G=!1){this.pruneStale();let W=X.length;if(W>this.maxBytes){this.log.debug("cachekeep track skipped (body exceeds maxBytes)",this.logPayload({sessionKey:Y,bodyBytes:W,maxBytes:this.maxBytes}));return}let K=this.getWindow?.();if(K&&!HX(K,new Date(this.now()))){this.log.debug("cachekeep track skipped (outside window)",this.logPayload({sessionKey:Y,startHour:K.startHour,endHour:K.endHour}));return}if(this.targets.has(Y)){let N=this.targets.get(Y);if(N)this.totalBytes-=N.bodyText.length;this.targets.delete(Y)}else this.log.debug("cachekeep captured target",this.logPayload({sessionKey:Y,accountId:J}));while(this.targets.size>=this.maxTargets||this.totalBytes+W>this.maxBytes&&this.targets.size>0){let N,O=Number.POSITIVE_INFINITY;for(let[L,Z]of this.targets){let j=Math.max(Z.lastRealRequestAt,Z.lastWarmedAt??0);if(j<O)N=L,O=j}if(N===void 0)break;let B=this.targets.get(N);if(B)this.totalBytes-=B.bodyText.length;this.targets.delete(N)}let U=U5(X,this.ttlMs),H={bodyText:X,accountId:J||void 0,chatgptAccountId:Q,route:"main",ttlMs:U,cacheExpiresAt:this.now()+U,warmCount:0,lastRealRequestAt:this.now(),replayHeaders:$,isSubagent:G,is56:FX(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-LX;for(let[$,G]of this.targets){let W,K;if(this.isGpt56Subagent(G))W=Q,K=LX;else W=G.isSubagent?J:X,K=G.isSubagent?this.maxSubagentIdleMs:this.maxIdleWarmMs;if(!(G.isSubagent!==!0&&this.getSustain?.()===!0)&&G.lastRealRequestAt<W)this.log.debug("cachekeep pruned idle target",this.logPayload({sessionKey:$,accountId:G.accountId??"main",lastRealRequestAt:G.lastRealRequestAt,maxIdleWarmMs:K})),this.totalBytes-=G.bodyText.length,this.targets.delete($)}}start(){if(this.disposed=!1,this.timer)return;if(this.startedAt=this.now(),this.log.debug("cachekeep started",this.logPayload({ttlMs:this.ttlMs,leadMs:this.leadMs,maxIdleWarmMs:this.maxIdleWarmMs})),this.timer=setInterval(()=>{this.tick().catch(()=>{})},this.tickIntervalMs),"unref"in this.timer)this.timer.unref()}stop(){if(this.disposed=!0,this.abortController.abort(),this.abortController=new AbortController,this.timer)clearInterval(this.timer),this.timer=null;this.startedAt=null,this.targets.clear(),this.totalBytes=0,this.log.debug("cachekeep stopped",this.logPayload())}remove(Y){let X=this.targets.get(Y);if(X)this.totalBytes-=X.bodyText.length,this.targets.delete(Y),this.log.debug("cachekeep removed target",this.logPayload({sessionKey:Y}))}status(){let Y=this.now(),X=Array.from(this.targets.entries()).map(([J,Q])=>({sessionKey:J,accountId:Q.accountId,route:Q.route,cacheExpiresAt:Q.cacheExpiresAt,lastRealRequestAt:Q.lastRealRequestAt,lastWarmedAt:Q.lastWarmedAt,backoffUntil:Q.backoffUntil,bodyBytes:Q.bodyText.length}));return{running:this.timer!=null,tracked:this.targets.size,generatedAt:Y,startedAt:this.startedAt,maxIdleWarmMs:this.maxIdleWarmMs,maxSubagentIdleMs:this.maxSubagentIdleMs,ttlMs:this.ttlMs,leadMs:this.leadMs,sustain:this.getSustain?.()===!0,window:this.getWindow?.(),targets:X}}async tick(){if(this.tickInFlight)return;this.tickInFlight=!0;try{this.pruneStale();let Y=this.getWindow?.();if(Y&&!HX(Y,new Date(this.now())))return;let X=this.now(),J=X+this.leadMs;for(let[Q,$]of this.targets)if($.backoffUntil&&X>=$.backoffUntil&&$.cacheExpiresAt<=J)await this.prewarm(Q,$);for(let[Q,$]of this.targets){if($.backoffUntil&&X<$.backoffUntil)continue;if($.cacheExpiresAt<=J)await this.prewarm(Q,$)}}finally{this.tickInFlight=!1}}async prewarm(Y,X){let J;try{if(X.accountId&&X.accountId!=="main")J=await this.refreshFallback(X.accountId);else J=await this.getMainToken()}catch($){if(!this.disposed&&this.targets.get(Y)===X)X.backoffUntil=this.now()+q8;this.log.debug("cachekeep skip (no token)",this.logPayload({sessionKey:Y,accountId:X.accountId??"main",error:$ instanceof Error?$.message:String($)}));return}if(this.disposed||this.targets.get(Y)!==X)return;let Q={...X.replayHeaders,authorization:`Bearer ${J}`,"content-type":"application/json"};if(X.chatgptAccountId)Q["ChatGPT-Account-Id"]=X.chatgptAccountId;else delete Q["ChatGPT-Account-Id"];try{let $=K5(X.bodyText),G;try{let j=JSON.parse($);G={warmBodyKeys:Object.keys(j),stream:j.stream,max_output_tokens:j.max_output_tokens,store:j.store,has_stream_options:"stream_options"in j,has_max_tokens:"max_tokens"in j,model:j.model}}catch{}this.log.debug("cachekeep warm request",this.logPayload({...G,headerKeys:Object.keys(Q),hasChatGptAccountId:"ChatGPT-Account-Id"in Q}));let W=wY({method:"POST",headers:Q,body:$,signal:AbortSignal.any([AbortSignal.timeout(30000),this.abortController.signal])}),K=await this.fetchImpl(this.codexResponsesUrl,W),U="";try{U=await K.text()}catch{}if(this.disposed||this.targets.get(Y)!==X)return;if(!K.ok){X.backoffUntil=this.now()+q8,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",status:K.status,error:`HTTP ${K.status}`,responseBody:U.slice(0,600)}));return}let H=K.headers.get("content-type")??"",N=H.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(U.slice(0,200));this.log.debug("cachekeep warm response",this.logPayload({status:K.status,contentType:H,bodyLen:U.length,isSse:N}));let O=N?L5(U):H5(U),B=M1(K.headers),L=B.primary?.usedPercent??null,Z=B.secondary?.usedPercent??null;if(this.log.debug("cachekeep fired",this.logPayload({session:Y,accountId:X.accountId??"main",input_tokens:O.input_tokens,cached_tokens:O.cached_tokens,hit_rate:O.hit_rate,output_tokens:O.output_tokens,quota_primary_pct:L,quota_secondary_pct:Z})),X.cacheExpiresAt=this.now()+X.ttlMs,X.lastWarmedAt=this.now(),X.backoffUntil=void 0,X.warmCount+=1,this.isGpt56Subagent(X)&&X.warmCount>=2){if(this.targets.get(Y)===X)this.totalBytes-=X.bodyText.length,this.targets.delete(Y);return}}catch($){if(this.disposed||this.targets.get(Y)!==X)return;X.backoffUntil=this.now()+q8,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",error:$ instanceof Error?$.message:String($)}))}}}var PX=900000,N5=0.016666666666666666,jX=0.000001;function w8(Y,X){for(let J of[Y?.primary?.checkedAt,Y?.checkedAt,X])if(typeof J==="number"&&Number.isFinite(J))return J;return}function E8(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let X=w8(Y.quota,Y.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||Y.now-X>PX)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let J=P8(Y.quota).sort((Q,$)=>{let G=Q.windowMs,W=$.windowMs,K=typeof G==="number"&&Number.isFinite(G),U=typeof W==="number"&&Number.isFinite(W);if(K!==U)return K?-1:1;if(K&&U)return W-G;return 0});for(let{key:Q,window:$}of J)if(Number.isFinite($.remainingPercent)&&$.remainingPercent<=0)return{action:"migrate",reason:"exhausted",windowKey:Q,...typeof $.resetsAt==="string"?{resetsAt:$.resetsAt}:{}};if(Y.status===void 0||Y.status===0||!Number.isFinite(Y.status)||Y.status>=500&&Y.status<=599||Y.status===429)return{action:"retain",reason:"transient"};return{action:"retain",reason:"healthy"}}function V5(Y,X,J){let Q=Math.max(0,Y.remainingPercent-X);if(Q<=0)return 0;if(!Y.resetsAt)return Q;let $=Date.parse(Y.resetsAt);if(!Number.isFinite($)||$<=J)return Q;let G=Math.max(($-J)/3600000,N5);return Q/G}function DX(Y,X){if(Y<X)return-1;if(Y>X)return 1;return 0}function B5(Y,X){if(!Y.quota)return;let J=w8(Y.quota,Y.quotaCheckedAt);if(J===void 0||X-J>PX)return;let Q=P8(Y.quota).map(({key:G,window:W})=>{return V5(W,Y.reservePercent[G]??0,X)}),$=Q.length>0?Math.min(...Q):0;return $>0?{candidate:Y,quotaCheckedAt:J,weight:$}:void 0}function wX(Y){let X=Y.candidates.filter(($)=>$.killswitchPasses!==!1);if(Y.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if(X.length===0)return;let J=X.map(($)=>B5($,Y.now)).filter(($)=>$!==void 0);if(J.length>0){J.sort((G,W)=>{let K=((Y.pendingBytes.get(G.candidate.accountId)??0)+Y.requestBytes)/Math.max(G.weight,jX),U=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,jX);return K-U||G.candidate.configuredOrder-W.candidate.configuredOrder||DX(G.candidate.accountId,W.candidate.accountId)});let $=J[0];if($)return{accountId:$.candidate.accountId,quotaCheckedAt:$.quotaCheckedAt,source:"weighted"}}Y.onEmptyWeightedSet?.();let Q=[...X].sort(($,G)=>{let W=($.resetCreditsApplicable??0)>0?1:0;return((G.resetCreditsApplicable??0)>0?1:0)-W||$.configuredOrder-G.configuredOrder||DX($.accountId,G.accountId)})[0];if(!Q)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Q.accountId,quotaCheckedAt:w8(Q.quota,Q.quotaCheckedAt),source:"mode-fallback"}}import{createHash as Z5}from"node:crypto";import{chmod as O5,mkdir as F5,writeFile as M8}from"node:fs/promises";import{join as q5}from"node:path";var T8=H0("dump"),t0="x-cortexkit-openai-auth-dump-session",EX=0,A1=new Map,j5=100;function A8(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function D5(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 AX(Y){return Z5("sha256").update(Y).digest("hex")}function R8(Y){return AX(JSON.stringify(Y))}function RX(Y){try{let X=JSON.parse(Y);return X!=null&&typeof X==="object"&&!Array.isArray(X)?X:void 0}catch{return}}function P5(Y,X){if(Y===void 0)return null;if(Y===X)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:Y.length,currentBytes:X.length};let J=0;while(J<Y.length&&J<X.length&&Y[J]===X[J])J++;let Q=Y.length-1,$=X.length-1;while(Q>=J&&$>=J&&Y[Q]===X[$])Q--,$--;return{changed:!0,firstByte:J,lastPreviousByte:Q,lastCurrentByte:$,changedPreviousBytes:Q-J+1,changedCurrentBytes:$-J+1,previousBytes:Y.length,currentBytes:X.length}}function w5(Y,X){if(!A1.has(Y))while(A1.size>=j5){let J=A1.keys().next().value;if(J===void 0)break;A1.delete(J)}A1.set(Y,X)}function E5(Y){if(Y===void 0)return;return Object.fromEntries(new Headers(Y).entries())}function C8(Y){if(Array.isArray(Y))return Y.map(C8);if(Y==null||typeof Y!=="object")return Y;let X={};for(let[J,Q]of Object.entries(Y)){let $=J.toLowerCase();if($==="authorization"||$==="chatgpt-account-id"||$==="cookie"||$==="set-cookie"){X[J]="[redacted]";continue}X[J]=C8(Q)}return X}function M5(Y){let X=RX(Y);if(X===void 0)return Y;let J=MX(X),Q=JSON.stringify(J);if(Q===void 0)return Y;return JSON.stringify(X)===Q?Y:Q}function A5(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function R5(Y){let X=RX(Y);if(!X)return{parseable:!1};let J=Array.isArray(X.input)?X.input:[],Q=Array.isArray(X.tools)?X.tools:[],$=Q.map(A5),G=X.client_metadata!=null&&typeof X.client_metadata==="object"&&!Array.isArray(X.client_metadata)?X.client_metadata:void 0;return{parseable:!0,model:typeof X.model==="string"?X.model:void 0,stream:X.stream,generate:X.generate,store:X.store,previousResponseID:typeof X.previous_response_id==="string"?X.previous_response_id:void 0,promptCacheKey:typeof X.prompt_cache_key==="string"?X.prompt_cache_key:void 0,reasoning:X.reasoning,inputCount:J.length,inputHash:R8(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:R8(J[0]),toolsCount:Q.length,toolTypes:$,toolsHash:R8(Q),hasWebSearch:$.includes("web_search"),clientMetadataKeys:G?Object.keys(G).sort():[]}}async function R1(Y){let X=P0();if(!X.dump)return;EX++;let J=Y.sessionID?.trim()||"session-unknown",Q=`${new Date().toISOString().replace(/[:.]/g,"-")}-${String(EX).padStart(5,"0")}-${D5(J)}-${Y.transport}-${Y.phase}`,$=q5(X.dumpDir,Q),G={body:`${$}.body.json`,metadata:`${$}.meta.json`,request:`${$}.request.json`},W=`${Y.transport}:${J}`,K=A1.get(W);try{await F5(X.dumpDir,{recursive:!0,mode:448}),await O5(X.dumpDir,448).catch(()=>{});let U=M5(Y.bodyText),H={id:Q,createdAt:new Date().toISOString(),session:A8(J),transport:Y.transport,phase:Y.phase,accountId:Y.accountId,status:Y.status,error:Y.error,bodyBytes:Y.bodyText.length,bodyHash:AX(Y.bodyText),diff:P5(K,Y.bodyText),body:R5(Y.bodyText),files:G};await Promise.all([M8(G.body,U,{encoding:"utf8",mode:384}),M8(G.metadata,`${JSON.stringify(H,null,2)}
98
- `,{encoding:"utf8",mode:384}),M8(G.request,`${JSON.stringify(C8({url:Y.url,method:Y.method,accountId:Y.accountId,headers:E5(Y.headers)}),null,2)}
99
- `,{encoding:"utf8",mode:384})]),T8.debug("dumped request",{id:Q,session:A8(J),body:G.body,meta:G.metadata}),w5(W,Y.bodyText)}catch(U){T8.warn("request dump failed",{session:A8(J),error:U instanceof Error?U.message:String(U)})}}async function p0(Y){if(!P0().dump)return;T8.debug("diagnostic",Y)}import{tool as m1}from"@opencode-ai/plugin";var EY="ws_",_X=new Map,IX=m1({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:m1.schema.string().optional(),query:m1.schema.string().optional(),queries:m1.schema.array(m1.schema.string()).optional()},async execute(Y){return{title:"OpenAI Web Search",output:JSON.stringify({action:Y}),metadata:{action:Y}}}});function I8(Y){if(T5(Y))return;if(!_5(Y))return Y;let X=Y.item;return _X.set(X.id,X),{...Y,item:{type:"function_call",id:X.id,call_id:X.id,name:"web_search",arguments:JSON.stringify(I(X.action)?X.action:{})}}}function SX(Y){if(!Y.body)return Y;if(!(Y.headers.get("content-type")??"").includes("text/event-stream"))return Y;return new Response(C5(Y.body),{status:Y.status,statusText:Y.statusText,headers:Y.headers})}function kX(Y){if(!Array.isArray(Y.input))return!1;let X=!1,J=new Map,Q=[],$=new Map,G=new Map;for(let W of Y.input)if(I(W)&&typeof W.call_id==="string"&&W.call_id.startsWith(EY)){if(W.type==="function_call")$.set(W.call_id,W);else if(W.type==="function_call_output"&&typeof W.output==="string")G.set(W.call_id,W.output)}for(let W of Y.input){if(I5(W)){J.set(W.call_id,W),X=!0;continue}if(S5(W,J)){Q.push(_8(W.call_id,W.output,J.get(W.call_id))),X=!0;continue}if(k5(W)){let K=_X.get(W.id);if(K)Q.push(_8(W.id,K));else{let U=$.get(W.id),H=G.get(W.id);if(U||H)Q.push(_8(W.id,H,U));else Q.push(W)}X=!0;continue}Q.push(W)}if(X)Y.input=Q;return X}function T5(Y){if(typeof Y.type==="string"&&Y.type.startsWith("response.web_search_call."))return!0;return Y.type==="response.output_item.added"&&I(Y.item)&&Y.item.type==="web_search_call"}function C5(Y){let X=new TextDecoder,J=new TextEncoder,Q="";return Y.pipeThrough(new TransformStream({transform($,G){Q+=X.decode($,{stream:!0});let W=TX(Q);while(W){let K=Q.slice(0,W.index);Q=Q.slice(W.index+W.length);let U=CX(K);if(U)G.enqueue(J.encode(U));W=TX(Q)}},flush($){if(Q+=X.decode(),!Q)return;let G=CX(Q);if(G)$.enqueue(J.encode(G))}}))}function TX(Y){let X=Y.indexOf(`
96
+ Warming limited to **${`${String(L).padStart(2,"0")}-${String(H).padStart(2,"0")}`}** local hours.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:N?.sustain??$?.cachekeep?.sustain===!0,window:{startHour:L,endHour:H},running:N?.running??!1,tracked:N?.tracked??0,generatedAt:N?.generatedAt??Date.now(),maxIdleWarmMs:N?.maxIdleWarmMs??3600000,maxSubagentIdleMs:N?.maxSubagentIdleMs??1800000}}}return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep`, `/openai-cachekeep on`, `/openai-cachekeep off`, `/openai-cachekeep sustain on`, `/openai-cachekeep sustain off`, `/openai-cachekeep HH-HH`, `/openai-cachekeep window clear`, `/openai-cachekeep subagents on`, `/openai-cachekeep subagents off`",knobs:{}}}function uX(Y){let X=[Y.primary?.usedPercent,Y.secondary?.usedPercent].filter((J)=>J!==void 0);return X.length>0?Math.max(...X):void 0}function l5(Y,X){let J=[Y.primary,Y.secondary].filter(($)=>$!==void 0),Q=J.filter(($)=>s1($,X));return(Q.length>0?Q:J).sort(($,G)=>G.usedPercent-$.usedPercent)[0]?.resetsAt}function d5(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([Q1({accessToken:J.accessToken,fetchImpl:X.fetchImpl,now:X.now,accountId:J.chatgptAccountId}),P8(X.fetchImpl,J.accessToken,Q)]),W=SY(G.credits),U=G.availableCount??$.resetCreditsAvailable??0,L=$.resetCreditsApplicable??0,H=D8($,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:uX($),resetTime:l5($,X.now()),availableCount:U,applicableAvailableCount:L,eligible:N===void 0,reason:N,selectedCreditId:W?.id,selectedCreditExpiresAt:W?.expiresAt}}catch(J){return i.warn("reset preview row failed",{accountKey:Y,error:J?.message??String(J)}),{accountKey:Y,label:Y==="main"?"Main account":Y,eligible:!1,reason:J?.message??String(J)}}}function i5(Y){let X=["## Reset credits","","Select an account to fetch a fresh confirmation preview:",""];for(let J of Y){let Q=J.usedPercent===void 0?"quota unavailable":`${J.usedPercent}% used`,$=J.availableCount===void 0?"credits unavailable":`${J.applicableAvailableCount??0}/${J.availableCount} applicable/available`,G=J.eligible?`eligible · credit ${J.selectedCreditId} expires ${J.selectedCreditExpiresAt}`:J.reason;X.push(`- **${J.label}** (\`${J.accountKey}\`) — ${Q}; ${$}; ${G}`)}return X.push(""),X.push("Command: `/openai-reset select <encodedAccountKey>`"),X.join(`
97
+ `)}function 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 w0(Y,X,J,Q={}){return{command:j1,text:J,knobs:{stage:"result",accountKey:Y,code:X,...Q}}}function n5(Y,X,J){if(X instanceof _0){let $={identity_mismatch:"The account identity changed before redemption. Reopen the reset account list.",invalid_account_key:"The selected account key is reserved. Reopen the reset account list.",cooldown_active:"This account just reset — re-checking quota. Wait for the cooldown before another redemption.",expired_unreconciled:"The previous attempt outcome is unknown — retry replays the same identifiers, or wait until quota reflects the earlier attempt.",retry_without_inflight:"There is no active reset redemption to retry. Reopen the account list.",not_exhausted:"No credit was spent: the fresh account state is not exhausted.",no_applicable_credits:"No credit was spent: no applicable credits are available.",no_eligible_credit:"No credit was spent: no eligible credit was returned."};return w0(Y,X.kind,`## Reset credit
99
+
100
+ ${$[X.kind]}
101
+
102
+ Code: \`${X.kind}\``,{cooldownUntil:X.cooldownUntil,...X.kind==="expired_unreconciled"?{chatgptAccountId:J,retryGuidance:"Retry replays the same request and credit identifiers from the previous attempt."}:{}})}let Q=X?.code;if(Q==="unknown_account"||Q==="disabled_account"||Q==="non_oauth_account"||Q==="token_unavailable")return w0(Y,Q,`## Reset credit
103
+
104
+ ${{unknown_account:"Account unavailable: the selected account no longer exists. Reopen the reset account list.",disabled_account:"Account unavailable: the selected account is disabled. Reopen the reset account list.",non_oauth_account:"Account unavailable: the selected account is not authenticated with OAuth. Reopen the reset account list.",token_unavailable:"Authentication problem: the selected account token is unavailable. Reauthenticate the account before retrying."}[Q]}
105
+
106
+ Code: \`${Q}\``);if(X instanceof q1)return w0(Y,X.kind,`## Reset credit
107
+
108
+ No redemption was attempted: reset credit availability could not be loaded.
109
+
110
+ Code: \`${X.kind}\``);return i.warn("reset command failed before a known result",{accountKey:Y,error:X?.message??String(X)}),w0(Y,"error",`## Reset credit
111
+
112
+ The reset request failed before a known result: internal command failure — see plugin log.`)}async function o5(Y,X,J){let{accountKey:Q}=Y.target,$=Y.outcome.kind;if(Y.finalizeStateWriteFailed)return w0(Q,$,`## Reset credit result
113
+
114
+ Account: **${Y.target.label}** (\`${Q}\`)
115
+
116
+ The server outcome recorded as \`${$}\`, but the state write failed. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing.`,{stateWriteFailed:!0,retryGuidance:Y.retrySafety,chatgptAccountId:J});if($==="reset"||$==="already_redeemed"){let W={account:Q,ok:!1,error:"targeted quota refresh did not complete"};try{W=await X.refreshResetTargetQuota(Q)}catch(V){W.error=V?.message??String(V)}let U=!W.ok&&W.error!==void 0;if(U)i.warn("reset quota re-check failed",{accountKey:Q,error:W.error});let L=Q==="main"?X.quotaManager.getMain():X.quotaManager.getFallback(Q),H=W.ok&&d5(L?.quota,X.now()),N=L?.quota.resetCreditsApplicable,O=H?"Post-verification: **window fresh**.":`Post-verification: **window not yet refreshed** (server code \`${$}\`).`,Z=U?`
117
+
118
+ quota re-check failed — see log.`:"";return w0(Q,$,`## Reset credit result
119
+
120
+ Account: **${Y.target.label}** (\`${Q}\`)
121
+
122
+ Code: \`${$}\`
123
+
124
+ ${O}${Z}${N===void 0?"":`
125
+
126
+ Remaining applicable credits: **${N}**`}`,{verifiedFresh:H,afterUsedPercent:uX(L?.quota??{}),remainingCredits:N})}if($==="ambiguous_local")return w0(Q,$,`## Reset credit result
127
+
128
+ Account: **${Y.target.label}** (\`${Q}\`)
129
+
130
+ Code: \`${$}\`
131
+
132
+ ${Y.retrySafety}`,{retryGuidance:Y.retrySafety});if($==="ambiguous"||$==="http_error"){let W=J?`/openai-reset retry ${encodeURIComponent(Q)} ${encodeURIComponent(J)}`:"/openai-reset";return w0(Q,$,`## Reset credit result
133
+
134
+ Account: **${Y.target.label}** (\`${Q}\`)
135
+
136
+ The redemption outcome is unknown (\`${$}\`).
137
+
138
+ Retry with \`${W}\`. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing.`,{retryGuidance:Y.retrySafety,chatgptAccountId:J})}let G={nothing_to_reset:"The server found no exhausted quota window to reset. No reset was confirmed. A new attempt starts fresh and must pass the current preconditions.",no_credit:"The server found no usable reset credit. No reset was confirmed. A new attempt starts fresh and must pass the current preconditions."};return w0(Q,$,`## Reset credit result
139
+
140
+ Account: **${Y.target.label}** (\`${Q}\`)
141
+
142
+ Code: \`${$}\`
143
+
144
+ ${G[$]??"The server returned a no-op result. No reset was confirmed."}`)}async function r5(Y,X){let J=[X.resolveResetTarget?void 0:"resolveResetTarget",X.fetchImpl?void 0:"fetchImpl",X.now?void 0:"now",X.randomUUID?void 0:"randomUUID",X.refreshResetTargetQuota?void 0:"refreshResetTargetQuota"].filter((W)=>W!==void 0);if(J.length>0)return i.warn("reset command dependencies unwired",{missingDeps:J}),{command:j1,text:`## Reset credit
145
+
146
+ Unavailable: reset command runtime dependencies are not wired.`,knobs:{}};let Q=X,$=Y.trim().split(/\s+/).filter(Boolean),G=$[0];if(!G||G==="refresh"){let U=["main",...((await X.loadAccounts(X.accountStoragePath))?.accounts??[]).filter((H)=>H.enabled!==!1&&H.type==="oauth").map((H)=>H.id)];i.debug("reset accounts stage requested",{accountKeys:U});let L=await Promise.all(U.map((H)=>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:j1,text:i5(L),knobs:{stage:"accounts",accounts:L}}}if(G==="select"){let W=w8($[1]);if(!W||!y0(W)||$.length!==2)return w0("","invalid_command","Usage: `/openai-reset select <encodedAccountKey>`");let U=await gX(W,Q);if(!U.eligible)return w0(W,"not_eligible",yX(U));return{command:j1,text:yX(U),knobs:{stage:"confirm",preview:U}}}if(G==="confirm"||G==="retry"){let W=w8($[1]),U=w8($[2]);if(!W||!y0(W)||!U||$.length!==3)return w0(W??"","invalid_command",`Usage: \`/openai-reset ${G} <encodedAccountKey> <encodedChatgptAccountId>\``);i.info("reset redemption decision",{accountKey:W,action:G}),i.debug("reset redemption identity binding",{accountKey:W,expectedChatgptAccountId:U});try{let L=await vX({configPath:X.accountStoragePath,mutateAccountsFn:J0,loadAccountsFn:X.loadAccounts,now:Q.now,randomUUID:Q.randomUUID,fetchImpl:Q.fetchImpl,resolveTarget:Q.resolveResetTarget,fetchUsage:(H)=>Q1({accessToken:H.accessToken,fetchImpl:Q.fetchImpl,now:Q.now,accountId:H.chatgptAccountId}),hasActiveRateLimitMark:(H)=>X.quotaManager.isRateLimited(H)},{accountKey:W,expectedChatgptAccountId:U,retry:G==="retry"});return i.info("reset redemption outcome",{accountKey:W,code:L.outcome.kind}),o5(L,Q,U)}catch(L){let H=n5(W,L,U);return i.info("reset redemption outcome",{accountKey:W,code:H.knobs.code}),H}}return w0("","invalid_command","Usage: `/openai-reset` | `/openai-reset select <encodedAccountKey>` | `/openai-reset confirm <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset retry <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset refresh`")}var s5=new Set(["access","refresh","apikey","authheader","password","secret"]);function a5(Y){let X=Y.toLowerCase().replace(/[-_]/g,"");if(s5.has(X))return!0;return X.endsWith("token")}function E8(Y,X,J){if(Array.isArray(Y))return Y.map(($,G)=>E8($,`${X}[${G}]`,J));if(!C(Y))return Y;let Q={};for(let[$,G]of Object.entries(Y)){if(a5($)){J.push(`${X}.${$}`);continue}Q[$]=E8(G,`${X}.${$}`,J)}return Q}async function k8(Y,X,J){let Q=await t5(Y,X,J),$=[],G=E8(Q.knobs,"knobs",$);if($.length>0)return i.warn("credential-shaped knob stripped before RPC",{command:Y,fields:$}),{...Q,knobs:G};return Q}async function t5(Y,X,J){switch(Y){case"openai-quota":return h5(J);case"openai-account":return g5(X,J);case"openai-routing":return y5(X,J);case"openai-killswitch":return f5(X,J);case"openai-dump":return m5(X,J);case"openai-logging":return c5(X,J);case"openai-cachekeep":return p5(X,J);case"openai-reset":return r5(X,J);default:throw Error(`unhandled command: ${Y}`)}}var e5=L0("quota");async function b1(Y,X={}){let J=Y.whamFn;if(!J)throw Error("whamFn is required for refreshAllQuota");let Q=[],$=Y.logger??e5,G=(V)=>{Q.push(V);let K={pid:process.pid,accountId:V.account,status:V.ok?"ok":"error",...V.error?{error:V.error}:{}};if(V.ok)$.debug("quota refresh succeeded",K);else $.warn("quota refresh failed",K)},W=Y.skipFresherThanMs,U=!1,L;if(W!==void 0)try{L=await(Y.readSidebarState??D1)()}catch{}let H=new Map(L?.fallbacks.map((V)=>[V.id,V])??[]),N=(...V)=>W!==void 0&&V.some((K)=>typeof K==="number"&&Number.isFinite(K)&&K<=Y.now()&&Y.now()-K<W),O=await Y.loadAccounts(Y.configPath).catch(()=>{return}),Z=O?.mainAccountId??Y.storageMainAccountId;if(!X.accountKey||X.accountKey==="main")try{let V=await Y.getAuth();if(V.type==="oauth"){let K=L&&Z!==void 0&&L.main.mainAccountId===Z?L.main.quota:void 0;if(N(Y.quotaManager.peekMainForPolicy(Z)?.checkedAt,K?.primary?.checkedAt,K?.secondary?.checkedAt,K?.checkedAt))G({account:"main",ok:!0});else{if(!V.access||(V.expires??0)<Y.now()){let M=await Y.refreshMainWithLease();V={...V,access:M.access,expires:M.expires}}if(V.access)if(Y.respectBackoff&&Y.quotaManager.isBackedOff())G({account:"main",ok:!0});else{let M=await J({accessToken:V.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:Z,accountKey:"main"});Y.quotaManager.setMain(V.access,{quota:M,refreshAfter:Y.now()+300000,checkedAt:Y.now()},Z,!0),U=!0,G({account:"main",ok:!0})}else G({account:"main",ok:!1,error:"no access token"})}}else G({account:"main",ok:!1,error:"auth type is not oauth"})}catch(V){G({account:"main",ok:!1,error:$1(V)})}if(O)for(let V of O.accounts){if(X.accountKey&&(X.accountKey==="main"||V.id!==X.accountKey))continue;if(V.enabled===!1||!Y.isOAuthAccountFn(V)){if(X.accountKey)G({account:V.id,ok:!1,error:"account is not an enabled OAuth fallback"});continue}try{let K=H.get(V.id),j=V.accountId,M=K&&j!==void 0&&K.accountId===j?K.quota:void 0;if(N(Y.quotaManager.peekFallbackForPolicy(V.id,j)?.checkedAt,M?.primary?.checkedAt,M?.secondary?.checkedAt,M?.checkedAt)){G({account:V.id,ok:!0});continue}if(Y.respectBackoff&&Y.quotaManager.isFallbackBackedOff(V.id,V.access)){G({account:V.id,ok:!0});continue}let I;try{I=await Y.fallbackManager.refreshAccount(V,O)}catch{I=V}if(!I.access){G({account:V.id,ok:!1,error:"no access token"});continue}let E=await J({accessToken:I.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:I.accountId,accountKey:V.id});Y.quotaManager.setFallback(V.id,{quota:E,refreshAfter:Y.now()+300000,checkedAt:Y.now()},I.access,!0,I.accountId),U=!0,G({account:V.id,ok:!0})}catch(K){G({account:V.id,ok:!1,error:$1(K)})}}if(X.accountKey&&X.accountKey!=="main"&&!Q.some((V)=>V.account===X.accountKey))Q.push({account:X.accountKey,ok:!1,error:"account not found"});if(W===void 0||U){let V=await Y.loadAccounts(Y.configPath);await Y.writeSidebarState(Y.quotaManager,V)}return Q}var Y2=300000,X2=30000,J2=240000,Q2="bg-quota-refresh",$2=120000;function G2(Y,X){return bY({name:Q2,ttlMs:$2,path:Y,renew:!0,...X})}function pX(Y,X=b1,J=()=>G2(Y.configPath)){return W2(Y,X,J)}async function W2(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:J2})}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)*X2);if(this.timer=this.setIntervalFn(()=>{let Q=this.run;if(this.stopped||!Q||this.tickPromise)return;let $=Q().catch((G)=>{try{this.onError?.(G)}catch{}}).finally(()=>{if(this.tickPromise===$)this.tickPromise=void 0});this.tickPromise=$},Y2+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 C(X)&&C(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(!C(X)||!C(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 oX(Y){if(!Y.enabled||typeof Y.body!=="string")return;let X=Y.headers.has("x-parent-session-id");if(X&&!Y.includeSubagents)return;let J=Y.headers.get("session-id")??Y.headers.get("x-opencode-session")??Y.headers.get("x-session-affinity")??void 0;if(!J)return;let Q={};for(let $ of["session-id","x-session-affinity","x-parent-session-id","user-agent","version","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-client-request-id","thread-id","x-openai-internal-codex-responses-lite"]){let G=Y.headers.get($);if(G)Q[$]=G}return{sessionKey:J,bodyText:Y.body,replayHeaders:Q,isSubagent:X}}function rX(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 lX(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 z2=300000,sX=1800000,dX=2*sX+900000,U2=3600000,iX=1800000,nX=60000,H2=32,L2=8388608,h8=600000;function aX(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 V2(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 N2(Y,X){return aX(Y)?sX:X}function g8(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function tX(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,$=X.input_tokens_details??X.prompt_tokens_details,G=Number($?.cached_tokens)||Number(X.cached_tokens)||0,W=J>0?G/J:null;return{input_tokens:J,output_tokens:Q,cached_tokens:G,hit_rate:W}}function B2(Y){try{let X=JSON.parse(Y);return tX(X.usage)}catch{return g8()}}function Z2(Y){let X,J=[],Q,$=()=>{if(!J.length)return;let G=J.join(`
147
+ `).trim();J=[];let W=X;if(X=void 0,!G||G==="[DONE]")return;try{let U=JSON.parse(G),L=U.type??W;if(L!=="response.completed"&&L!=="response.done")return;let H=U.response;Q=tX(H?.usage??U.usage)}catch{}};for(let G of Y.split(/\r?\n/)){if(G===""){$();continue}if(G.startsWith("event:")){X=G.slice(6).trim();continue}if(G.startsWith("data:"))J.push(G.slice(5).trim())}return $(),Q??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??z2,this.tickIntervalMs=Y.tickIntervalMs??nX,this.leadMs=Y.leadMs??this.tickIntervalMs+15000;let X=Y.maxIdleWarmMs??Y.maxDurationMs;this.maxIdleWarmMs=typeof X==="number"&&Number.isFinite(X)&&X>0?X:U2;let J=Y.maxSubagentIdleMs??iX;this.maxSubagentIdleMs=typeof J==="number"&&Number.isFinite(J)&&J>0?J:iX,this.tickIntervalMs=Y.tickIntervalMs??nX,this.maxTargets=Y.maxTargets??H2,this.maxBytes=Y.maxBytes??L2,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&&!lX(U,new Date(this.now()))){this.log.debug("cachekeep track skipped (outside window)",this.logPayload({sessionKey:Y,startHour:U.startHour,endHour:U.endHour}));return}if(this.targets.has(Y)){let N=this.targets.get(Y);if(N)this.totalBytes-=N.bodyText.length;this.targets.delete(Y)}else this.log.debug("cachekeep captured target",this.logPayload({sessionKey:Y,accountId:J}));while(this.targets.size>=this.maxTargets||this.totalBytes+W>this.maxBytes&&this.targets.size>0){let N,O=Number.POSITIVE_INFINITY;for(let[V,K]of this.targets){let j=Math.max(K.lastRealRequestAt,K.lastWarmedAt??0);if(j<O)N=V,O=j}if(N===void 0)break;let Z=this.targets.get(N);if(Z)this.totalBytes-=Z.bodyText.length;this.targets.delete(N)}let L=N2(X,this.ttlMs),H={bodyText:X,accountId:J||void 0,chatgptAccountId:Q,route:"main",ttlMs:L,cacheExpiresAt:this.now()+L,warmCount:0,lastRealRequestAt:this.now(),replayHeaders:$,isSubagent:G,is56:aX(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-dX;for(let[$,G]of this.targets){let W,U;if(this.isGpt56Subagent(G))W=Q,U=dX;else W=G.isSubagent?J:X,U=G.isSubagent?this.maxSubagentIdleMs:this.maxIdleWarmMs;if(!(G.isSubagent!==!0&&this.getSustain?.()===!0)&&G.lastRealRequestAt<W)this.log.debug("cachekeep pruned idle target",this.logPayload({sessionKey:$,accountId:G.accountId??"main",lastRealRequestAt:G.lastRealRequestAt,maxIdleWarmMs:U})),this.totalBytes-=G.bodyText.length,this.targets.delete($)}}start(){if(this.disposed=!1,this.timer)return;if(this.startedAt=this.now(),this.log.debug("cachekeep started",this.logPayload({ttlMs:this.ttlMs,leadMs:this.leadMs,maxIdleWarmMs:this.maxIdleWarmMs})),this.timer=setInterval(()=>{this.tick().catch(()=>{})},this.tickIntervalMs),"unref"in this.timer)this.timer.unref()}stop(){if(this.disposed=!0,this.abortController.abort(),this.abortController=new AbortController,this.timer)clearInterval(this.timer),this.timer=null;this.startedAt=null,this.targets.clear(),this.totalBytes=0,this.log.debug("cachekeep stopped",this.logPayload())}remove(Y){let X=this.targets.get(Y);if(X)this.totalBytes-=X.bodyText.length,this.targets.delete(Y),this.log.debug("cachekeep removed target",this.logPayload({sessionKey:Y}))}status(){let Y=this.now(),X=Array.from(this.targets.entries()).map(([J,Q])=>({sessionKey:J,accountId:Q.accountId,route:Q.route,cacheExpiresAt:Q.cacheExpiresAt,lastRealRequestAt:Q.lastRealRequestAt,lastWarmedAt:Q.lastWarmedAt,backoffUntil:Q.backoffUntil,bodyBytes:Q.bodyText.length}));return{running:this.timer!=null,tracked:this.targets.size,generatedAt:Y,startedAt:this.startedAt,maxIdleWarmMs:this.maxIdleWarmMs,maxSubagentIdleMs:this.maxSubagentIdleMs,ttlMs:this.ttlMs,leadMs:this.leadMs,sustain:this.getSustain?.()===!0,window:this.getWindow?.(),targets:X}}async tick(){if(this.tickInFlight)return;this.tickInFlight=!0;try{this.pruneStale();let Y=this.getWindow?.();if(Y&&!lX(Y,new Date(this.now())))return;let X=this.now(),J=X+this.leadMs;for(let[Q,$]of this.targets)if($.backoffUntil&&X>=$.backoffUntil&&$.cacheExpiresAt<=J)await this.prewarm(Q,$);for(let[Q,$]of this.targets){if($.backoffUntil&&X<$.backoffUntil)continue;if($.cacheExpiresAt<=J)await this.prewarm(Q,$)}}finally{this.tickInFlight=!1}}async prewarm(Y,X){let J;try{if(X.accountId&&X.accountId!=="main")J=await this.refreshFallback(X.accountId);else J=await this.getMainToken()}catch($){if(!this.disposed&&this.targets.get(Y)===X)X.backoffUntil=this.now()+h8;this.log.debug("cachekeep skip (no token)",this.logPayload({sessionKey:Y,accountId:X.accountId??"main",error:$ instanceof Error?$.message:String($)}));return}if(this.disposed||this.targets.get(Y)!==X)return;let Q={...X.replayHeaders,authorization:`Bearer ${J}`,"content-type":"application/json"};if(X.chatgptAccountId)Q["ChatGPT-Account-Id"]=X.chatgptAccountId;else delete Q["ChatGPT-Account-Id"];try{let $=V2(X.bodyText),G;try{let j=JSON.parse($);G={warmBodyKeys:Object.keys(j),stream:j.stream,max_output_tokens:j.max_output_tokens,store:j.store,has_stream_options:"stream_options"in j,has_max_tokens:"max_tokens"in j,model:j.model}}catch{}this.log.debug("cachekeep warm request",this.logPayload({...G,headerKeys:Object.keys(Q),hasChatGptAccountId:"ChatGPT-Account-Id"in Q}));let W=xY({method:"POST",headers:Q,body:$,signal:AbortSignal.any([AbortSignal.timeout(30000),this.abortController.signal])}),U=await this.fetchImpl(this.codexResponsesUrl,W),L="";try{L=await U.text()}catch{}if(this.disposed||this.targets.get(Y)!==X)return;if(!U.ok){X.backoffUntil=this.now()+h8,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",status:U.status,error:`HTTP ${U.status}`,responseBody:L.slice(0,600)}));return}let H=U.headers.get("content-type")??"",N=H.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(L.slice(0,200));this.log.debug("cachekeep warm response",this.logPayload({status:U.status,contentType:H,bodyLen:L.length,isSse:N}));let O=N?Z2(L):B2(L),Z=x1(U.headers),V=Z.primary?.usedPercent??null,K=Z.secondary?.usedPercent??null;if(this.log.debug("cachekeep fired",this.logPayload({session:Y,accountId:X.accountId??"main",input_tokens:O.input_tokens,cached_tokens:O.cached_tokens,hit_rate:O.hit_rate,output_tokens:O.output_tokens,quota_primary_pct:V,quota_secondary_pct:K})),X.cacheExpiresAt=this.now()+X.ttlMs,X.lastWarmedAt=this.now(),X.backoffUntil=void 0,X.warmCount+=1,this.isGpt56Subagent(X)&&X.warmCount>=2){if(this.targets.get(Y)===X)this.totalBytes-=X.bodyText.length,this.targets.delete(Y);return}}catch($){if(this.disposed||this.targets.get(Y)!==X)return;X.backoffUntil=this.now()+h8,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",error:$ instanceof Error?$.message:String($)}))}}}var XJ=900000,K2=0.016666666666666666,eX=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>XJ)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let J=f8(Y.quota).sort((Q,$)=>{let G=Q.windowMs,W=$.windowMs,U=typeof G==="number"&&Number.isFinite(G),L=typeof W==="number"&&Number.isFinite(W);if(U!==L)return U?-1:1;if(U&&L)return W-G;return 0});for(let{key:Q,window:$}of J)if(Number.isFinite($.remainingPercent)&&$.remainingPercent<=0)return{action:"migrate",reason:"exhausted",windowKey:Q,...typeof $.resetsAt==="string"?{resetsAt:$.resetsAt}:{}};if(Y.status===void 0||Y.status===0||!Number.isFinite(Y.status)||Y.status>=500&&Y.status<=599||Y.status===429)return{action:"retain",reason:"transient"};return{action:"retain",reason:"healthy"}}function O2(Y,X,J){let Q=Math.max(0,Y.remainingPercent-X);if(Q<=0)return 0;if(!Y.resetsAt)return Q;let $=Date.parse(Y.resetsAt);if(!Number.isFinite($)||$<=J)return Q;let G=Math.max(($-J)/3600000,K2);return Q/G}function YJ(Y,X){if(Y<X)return-1;if(Y>X)return 1;return 0}function q2(Y,X){if(!Y.quota)return;let J=m8(Y.quota,Y.quotaCheckedAt);if(J===void 0||X-J>XJ)return;let Q=f8(Y.quota).map(({key:G,window:W})=>{return O2(W,Y.reservePercent[G]??0,X)}),$=Q.length>0?Math.min(...Q):0;return $>0?{candidate:Y,quotaCheckedAt:J,weight:$}:void 0}function JJ(Y){let X=Y.candidates.filter(($)=>$.killswitchPasses!==!1);if(Y.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if(X.length===0)return;let J=X.map(($)=>q2($,Y.now)).filter(($)=>$!==void 0);if(J.length>0){J.sort((G,W)=>{let U=((Y.pendingBytes.get(G.candidate.accountId)??0)+Y.requestBytes)/Math.max(G.weight,eX),L=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,eX);return U-L||G.candidate.configuredOrder-W.candidate.configuredOrder||YJ(G.candidate.accountId,W.candidate.accountId)});let $=J[0];if($)return{accountId:$.candidate.accountId,quotaCheckedAt:$.quotaCheckedAt,source:"weighted"}}Y.onEmptyWeightedSet?.();let Q=[...X].sort(($,G)=>{let W=($.resetCreditsApplicable??0)>0?1:0;return((G.resetCreditsApplicable??0)>0?1:0)-W||$.configuredOrder-G.configuredOrder||YJ($.accountId,G.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 F2}from"node:crypto";import{chmod as j2,mkdir as D2,writeFile as u8}from"node:fs/promises";import{join as P2}from"node:path";var d8=L0("dump"),G1="x-cortexkit-openai-auth-dump-session",QJ=0,v1=new Map,M2=100;function p8(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function w2(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 GJ(Y){return F2("sha256").update(Y).digest("hex")}function l8(Y){return GJ(JSON.stringify(Y))}function WJ(Y){try{let X=JSON.parse(Y);return X!=null&&typeof X==="object"&&!Array.isArray(X)?X:void 0}catch{return}}function E2(Y,X){if(Y===void 0)return null;if(Y===X)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:Y.length,currentBytes:X.length};let J=0;while(J<Y.length&&J<X.length&&Y[J]===X[J])J++;let Q=Y.length-1,$=X.length-1;while(Q>=J&&$>=J&&Y[Q]===X[$])Q--,$--;return{changed:!0,firstByte:J,lastPreviousByte:Q,lastCurrentByte:$,changedPreviousBytes:Q-J+1,changedCurrentBytes:$-J+1,previousBytes:Y.length,currentBytes:X.length}}function A2(Y,X){if(!v1.has(Y))while(v1.size>=M2){let J=v1.keys().next().value;if(J===void 0)break;v1.delete(J)}v1.set(Y,X)}function T2(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 $=J.toLowerCase();if($==="authorization"||$==="chatgpt-account-id"||$==="cookie"||$==="set-cookie"){X[J]="[redacted]";continue}X[J]=i8(Q)}return X}function R2(Y){let X=WJ(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 C2(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function _2(Y){let X=WJ(Y);if(!X)return{parseable:!1};let J=Array.isArray(X.input)?X.input:[],Q=Array.isArray(X.tools)?X.tools:[],$=Q.map(C2),G=X.client_metadata!=null&&typeof X.client_metadata==="object"&&!Array.isArray(X.client_metadata)?X.client_metadata:void 0;return{parseable:!0,model:typeof X.model==="string"?X.model:void 0,stream:X.stream,generate:X.generate,store:X.store,previousResponseID:typeof X.previous_response_id==="string"?X.previous_response_id:void 0,promptCacheKey:typeof X.prompt_cache_key==="string"?X.prompt_cache_key:void 0,reasoning:X.reasoning,inputCount:J.length,inputHash:l8(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:l8(J[0]),toolsCount:Q.length,toolTypes:$,toolsHash:l8(Q),hasWebSearch:$.includes("web_search"),clientMetadataKeys:G?Object.keys(G).sort():[]}}async function h1(Y){let X=M0();if(!X.dump)return;QJ++;let J=Y.sessionID?.trim()||"session-unknown",Q=`${new Date().toISOString().replace(/[:.]/g,"-")}-${String(QJ).padStart(5,"0")}-${w2(J)}-${Y.transport}-${Y.phase}`,$=P2(X.dumpDir,Q),G={body:`${$}.body.json`,metadata:`${$}.meta.json`,request:`${$}.request.json`},W=`${Y.transport}:${J}`,U=v1.get(W);try{await D2(X.dumpDir,{recursive:!0,mode:448}),await j2(X.dumpDir,448).catch(()=>{});let L=R2(Y.bodyText),H={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:GJ(Y.bodyText),diff:E2(U,Y.bodyText),body:_2(Y.bodyText),files:G};await Promise.all([u8(G.body,L,{encoding:"utf8",mode:384}),u8(G.metadata,`${JSON.stringify(H,null,2)}
148
+ `,{encoding:"utf8",mode:384}),u8(G.request,`${JSON.stringify(i8({url:Y.url,method:Y.method,accountId:Y.accountId,headers:T2(Y.headers)}),null,2)}
149
+ `,{encoding:"utf8",mode:384})]),d8.debug("dumped request",{id:Q,session:p8(J),body:G.body,meta:G.metadata}),A2(W,Y.bodyText)}catch(L){d8.warn("request dump failed",{session:p8(J),error:L instanceof Error?L.message:String(L)})}}async function r0(Y){if(!M0().dump)return;d8.debug("diagnostic",Y)}import{tool as a1}from"@opencode-ai/plugin";var vY="ws_",HJ=new Map,LJ=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(I2(Y))return;if(!k2(Y))return Y;let X=Y.item;return HJ.set(X.id,X),{...Y,item:{type:"function_call",id:X.id,call_id:X.id,name:"web_search",arguments:JSON.stringify(C(X.action)?X.action:{})}}}function VJ(Y){if(!Y.body)return Y;if(!(Y.headers.get("content-type")??"").includes("text/event-stream"))return Y;return new Response(S2(Y.body),{status:Y.status,statusText:Y.statusText,headers:Y.headers})}function NJ(Y){if(!Array.isArray(Y.input))return!1;let X=!1,J=new Map,Q=[],$=new Map,G=new Map;for(let W of Y.input)if(C(W)&&typeof W.call_id==="string"&&W.call_id.startsWith(vY)){if(W.type==="function_call")$.set(W.call_id,W);else if(W.type==="function_call_output"&&typeof W.output==="string")G.set(W.call_id,W.output)}for(let W of Y.input){if(b2(W)){J.set(W.call_id,W),X=!0;continue}if(x2(W,J)){Q.push(n8(W.call_id,W.output,J.get(W.call_id))),X=!0;continue}if(v2(W)){let U=HJ.get(W.id);if(U)Q.push(n8(W.id,U));else{let L=$.get(W.id),H=G.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 I2(Y){if(typeof Y.type==="string"&&Y.type.startsWith("response.web_search_call."))return!0;return Y.type==="response.output_item.added"&&C(Y.item)&&Y.item.type==="web_search_call"}function S2(Y){let X=new TextDecoder,J=new TextEncoder,Q="";return Y.pipeThrough(new TransformStream({transform($,G){Q+=X.decode($,{stream:!0});let W=zJ(Q);while(W){let U=Q.slice(0,W.index);Q=Q.slice(W.index+W.length);let L=UJ(U);if(L)G.enqueue(J.encode(L));W=zJ(Q)}},flush($){if(Q+=X.decode(),!Q)return;let G=UJ(Q);if(G)$.enqueue(J.encode(G))}}))}function zJ(Y){let X=Y.indexOf(`
100
150
 
101
151
  `),J=Y.indexOf(`\r
102
152
  \r
103
- `);if(X===-1)return J===-1?void 0:{index:J,length:4};if(J===-1||X<J)return{index:X,length:2};return{index:J,length:4}}function CX(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 UJ(Y){let X=Y.split(/\r?\n/).filter((J)=>J.startsWith("data:")).map((J)=>J.slice(5).trimStart()).join(`
104
154
  `);if(!X)return`${Y}
105
155
 
106
156
  `;if(X==="[DONE]")return`data: [DONE]
107
157
 
108
- `;try{let J=JSON.parse(X);if(!I(J))return`${Y}
158
+ `;try{let J=JSON.parse(X);if(!C(J))return`${Y}
109
159
 
110
- `;let Q=I8(J);if(!Q)return"";return`data: ${JSON.stringify(Q)}
160
+ `;let Q=o8(J);if(!Q)return"";return`data: ${JSON.stringify(Q)}
111
161
 
112
162
  `}catch{return`${Y}
113
163
 
114
- `}}function _5(Y){return Y.type==="response.output_item.done"&&I(Y.item)&&Y.item.type==="web_search_call"&&typeof Y.item.id==="string"}function I5(Y){return I(Y)&&Y.type==="function_call"&&Y.name==="web_search"&&typeof Y.call_id==="string"&&Y.call_id.startsWith(EY)}function S5(Y,X){return I(Y)&&Y.type==="function_call_output"&&typeof Y.call_id==="string"&&typeof Y.output==="string"&&Y.call_id.startsWith(EY)&&X.has(Y.call_id)}function k5(Y){return I(Y)&&Y.type==="item_reference"&&typeof Y.id==="string"&&Y.id.startsWith(EY)}function _8(Y,X,J){let Q=b5(X),$=I(Q?.action)?Q.action:x5(J?.arguments);return{type:"web_search_call",status:"completed",...$?{action:$}:{}}}function b5(Y){if(I(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return I(X)?X:void 0}catch{return}}function x5(Y){if(I(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return I(X)?X:void 0}catch{return}}import{readFile as v5}from"node:fs/promises";import{homedir as h5}from"node:os";import{join as bX}from"node:path";var g5="https://models.dev/api.json",y5="OPENCODE_OPENAI_AUTH_MODELS_CACHE",f5="OPENCODE_MODELS_PATH",m5="OPENCODE_DISABLE_MODELS_FETCH",c5=1e4,u5=300000;function e0(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function xX(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function S8(Y){let{input:X,output:J}=Y;if(typeof X!=="number"||!Number.isFinite(X)||X<0)return null;if(typeof J!=="number"||!Number.isFinite(J)||J<0)return null;let Q=xX(Y.cache_read),$=xX(Y.cache_write);if(Q===null||$===null)return null;return{input:X,output:J,cache:{read:Q,write:$}}}function p5(Y){let X=e0(Y);if(!X)return null;let J=S8(X);if(!J)return null;let Q=J;if(Array.isArray(X.tiers)){let W=[];for(let K of X.tiers){let U=e0(K);if(!U)continue;let H=e0(U.tier),N=H?.size;if(H?.type!=="context")continue;if(typeof N!=="number"||!Number.isFinite(N)||N<=0)continue;let O=S8(U);if(!O)continue;W.push({...O,tier:{type:"context",size:N}})}if(W.length>0)Q.tiers=W}let $=e0(X.context_over_200k),G=$?S8($):null;if(G)Q.experimentalOver200K=G;return Q}function vX(Y){let X=e0(Y),J=e0(X?.openai),Q=e0(J?.models);if(!Q)return null;let $={};for(let[G,W]of Object.entries(Q)){let K=e0(W),U=p5(K?.cost);if(U)$[G]=U}return Object.keys($).length>0?$:null}function l5(){let Y=process.env[y5]?.trim();if(Y)return Y;let X=process.env[f5]?.trim();if(X)return X;let J=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||bX(h5(),".cache");return bX(J,"opencode","models.json")}function d5(){let Y=process.env[m5]?.toLowerCase();return Y==="true"||Y==="1"}async function i5(){try{let Y=vX(JSON.parse(await v5(l5(),"utf8")));if(Y)return Y}catch{}if(d5())return null;try{let Y=await fetch(g5,{signal:AbortSignal.timeout(c5)});if(!Y.ok)return null;return vX(await Y.json())}catch{return null}}var T1;function hX(){let Y=Date.now();if(T1&&T1.expiresAt>Y)return T1.promise;let X={expiresAt:Y+u5,promise:i5()};return T1=X,X.promise.then((J)=>{if(J===null&&T1===X)T1=void 0}),X.promise}function C1(Y){return typeof Y==="object"&&Y!==null}function n5(Y){if(Array.isArray(Y))return Y;if(C1(Y)&&Array.isArray(Y.data))return Y.data;return[]}function o5(Y){if(!C1(Y)||!C1(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function gX(Y){if(!C1(Y)||!C1(Y.info))return null;let X=Y.info,J=C1(X.model)?X.model:void 0,Q=typeof X.agent==="string"?X.agent:void 0,$=typeof J?.providerID==="string"?J.providerID:typeof X.providerID==="string"?X.providerID:void 0,G=typeof J?.modelID==="string"?J.modelID:typeof X.modelID==="string"?X.modelID:void 0,W=typeof J?.variant==="string"?J.variant:typeof X.variant==="string"?X.variant:void 0;if(!Q&&(!$||!G)&&!W)return null;let K={};if(Q)K.agent=Q;if($&&G)K.model={providerID:$,modelID:G};if(W)K.variant=W;return K}function yX(Y,X){return{agent:Y.agent??X.agent,model:Y.model??X.model,variant:Y.variant??X.variant}}function fX(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function mX(Y,X){if(!Y||!X)return null;let J=Y;if(typeof J.session?.messages!=="function")return null;let Q=[];try{Q=n5(await Promise.resolve(J.session.messages({path:{id:X},query:{limit:100}})))}catch{return null}if(Q.length===0)return null;let $={};for(let G=Q.length-1;G>=0;G--){if(o5(Q[G])!=="assistant")continue;let W=gX(Q[G]);if(!W)continue;if($=yX($,W),fX($))return $}for(let G=Q.length-1;G>=0;G--){let W=gX(Q[G]);if(!W)continue;if($=yX($,W),fX($))return $}if(!$.agent&&!$.model&&!$.variant)return null;return $}var Y1=[],r5=1,k8=0,cX=new Map;function b8(Y,X){if(Y1.push({id:r5++,type:"open-dialog",payload:Y,sessionId:X}),Y1.length>100)Y1=Y1.slice(Y1.length-100)}function uX(Y=0,X){let J=Date.now();if(k8=J,X!==void 0)cX.set(X,J);let Q=($)=>X===void 0||$.sessionId===void 0||$.sessionId===X;if(Y>0)Y1=Y1.filter(($)=>{if($.id>Y)return!0;if(X===void 0)return!1;return $.sessionId!==X});return Y1.filter(($)=>$.id>Y&&Q($))}function pX(Y){let X=Date.now();if(Y!==void 0){let J=cX.get(Y)??0;return J>0&&X-J<3000}return k8>0&&X-k8<3000}import{randomBytes as s5,timingSafeEqual as a5}from"node:crypto";import{unlink as t5}from"node:fs/promises";import{createServer as e5}from"node:http";import{join as Y2}from"node:path";var lX=H0("rpc");function X2(Y){return new Promise((X,J)=>{let Q=[],$=0;Y.on("data",(G)=>{if($+=G.length,$>1e6){Y.destroy(),J(Error("body too large"));return}Q.push(G)}),Y.on("end",()=>X(Buffer.concat(Q).toString("utf8"))),Y.on("error",J)})}function J2(Y,X){if(!Y?.startsWith("Bearer "))return!1;let J=Buffer.from(Y.slice(7)),Q=Buffer.from(X);return J.length===Q.length&&a5(J,Q)}async function nX(Y){let X=s5(32).toString("hex"),J=Y.timeoutMs??2000,Q=e5((W,K)=>{W.setTimeout(J,()=>{W.socket.destroy()}),$(W,K)});Q.requestTimeout=J,Q.headersTimeout=J;async function $(W,K){let U=(H,N)=>{if(K.headersSent||K.writableEnded||K.destroyed)return;K.writeHead(H,{"content-type":"application/json"}),K.end(JSON.stringify(N))};try{let H=W.url??"";if(W.method==="GET"&&H==="/health")return U(200,{ok:!0});if(W.method!=="POST"||!H.startsWith("/rpc/"))return U(404,{error:"not found"});if(!J2(W.headers.authorization,X))return U(401,{error:"unauthorized"});let N=H.slice(5),O=await X2(W),B=JSON.parse(O||"{}");if(N==="pending-notifications"){let L=Y.drain(Number(B.lastReceivedId??0),typeof B.sessionId==="string"?B.sessionId:void 0);return U(200,{messages:L})}if(N==="apply"){let L=await Y.apply(B);return U(200,L)}return U(404,{error:"unknown method"})}catch(H){U(500,{error:H instanceof Error?H.message:String(H)})}}let G=await new Promise((W,K)=>{Q.on("error",K),Q.listen(0,"127.0.0.1",()=>{let U=Q.address();if(U&&typeof U==="object")W(U.port);else K(Error("no port"))})});if(Q.unref(),Y.sweepRoot)try{await iX(Y.sweepRoot,Y.dir)}catch(W){lX.warn("rpc state sweep failed",{pid:process.pid,error:W instanceof Error?W.message:String(W)})}try{await dX(Y.dir,{port:G,token:X,pid:process.pid},{secureDir:Y.secureDir}),lX.debug("rpc server pid",{pid:process.pid,rpcPort:G})}catch(W){throw await new Promise((K)=>Q.close(()=>K())),W}return{port:G,token:X,async stop(){await new Promise((W)=>Q.close(()=>W())),await t5(Y2(Y.dir,`port-${process.pid}.json`)).catch(()=>{})}}}function l0(Y){return JSON.stringify(x8(Y))??"undefined"}function x8(Y){if(Array.isArray(Y))return Y.map(x8);if(!I(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((X)=>[X,x8(Y[X])]))}function V1(){let Y=crypto.getRandomValues(new Uint8Array(16)),X=Date.now();Y[0]=X/1099511627776&255,Y[1]=X/4294967296&255,Y[2]=X/16777216&255,Y[3]=X/65536&255,Y[4]=X/256&255,Y[5]=X&255,Y[6]=(Y[6]??0)&15|112,Y[8]=(Y[8]??0)&63|128;let J=Array.from(Y,(Q)=>Q.toString(16).padStart(2,"0")).join("");return`${J.slice(0,8)}-${J.slice(8,12)}-${J.slice(12,16)}-${J.slice(16,20)}-${J.slice(20)}`}var z1={};g8(z1,{withoutInternalHeaders:()=>yG,sanitizeHttpFallbackBody:()=>F8,orderCodexBody:()=>WY,hasWebSocketResponsesLiteMetadata:()=>O8,createWebSocketFetch:()=>UN,applyTurnId:()=>xG,advanceTurn:()=>b9,TITLE_HEADER:()=>k9,QUOTA_ACCOUNT_HEADER:()=>aY,OpenAIWebSocketPool:()=>z1,CODEX_BODY_KEY_ORDER:()=>kG});import{createHash as $N}from"node:crypto";var MJ="vercel.ai.error",Q2=Symbol.for(MJ),oX,rX,f=class Y extends(rX=Error,oX=Q2,rX){constructor({name:X,message:J,cause:Q}){super(J);this[oX]=!0,this.name=X,this.cause=Q}static isInstance(X){return Y.hasMarker(X,MJ)}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}},AJ="AI_APICallError",RJ=`vercel.ai.error.${AJ}`,$2=Symbol.for(RJ),sX,aX,c1=class extends(aX=f,sX=$2,aX){constructor({message:Y,url:X,requestBodyValues:J,statusCode:Q,responseHeaders:$,responseBody:G,cause:W,isRetryable:K=Q!=null&&(Q===408||Q===409||Q===429||Q>=500),data:U}){super({name:AJ,message:Y,cause:W});this[sX]=!0,this.url=X,this.requestBodyValues=J,this.statusCode=Q,this.responseHeaders=$,this.responseBody=G,this.isRetryable=K,this.data=U}static isInstance(Y){return f.hasMarker(Y,RJ)}},TJ="AI_EmptyResponseBodyError",CJ=`vercel.ai.error.${TJ}`,G2=Symbol.for(CJ),tX,eX,W2=class extends(eX=f,tX=G2,eX){constructor({message:Y="Empty response body"}={}){super({name:TJ,message:Y});this[tX]=!0}static isInstance(Y){return f.hasMarker(Y,CJ)}};function v8(Y){if(Y==null)return"unknown error";if(typeof Y==="string")return Y;if(Y instanceof Error)return Y.toString();return JSON.stringify(Y)}var _J="AI_InvalidArgumentError",IJ=`vercel.ai.error.${_J}`,z2=Symbol.for(IJ),YJ,XJ,SJ=class extends(XJ=f,YJ=z2,XJ){constructor({message:Y,cause:X,argument:J}){super({name:_J,message:Y,cause:X});this[YJ]=!0,this.argument=J}static isInstance(Y){return f.hasMarker(Y,IJ)}},kJ="AI_InvalidPromptError",bJ=`vercel.ai.error.${kJ}`,K2=Symbol.for(bJ),JJ,QJ,U2=class extends(QJ=f,JJ=K2,QJ){constructor({prompt:Y,message:X,cause:J}){super({name:kJ,message:`Invalid prompt: ${X}`,cause:J});this[JJ]=!0,this.prompt=Y}static isInstance(Y){return f.hasMarker(Y,bJ)}},xJ="AI_InvalidResponseDataError",vJ=`vercel.ai.error.${xJ}`,H2=Symbol.for(vJ),$J,GJ,L2=class extends(GJ=f,$J=H2,GJ){constructor({data:Y,message:X=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:xJ,message:X});this[$J]=!0,this.data=Y}static isInstance(Y){return f.hasMarker(Y,vJ)}},hJ="AI_JSONParseError",gJ=`vercel.ai.error.${hJ}`,N2=Symbol.for(gJ),WJ,zJ,MY=class extends(zJ=f,WJ=N2,zJ){constructor({text:Y,cause:X}){super({name:hJ,message:`JSON parsing failed: Text: ${Y}.
115
- Error message: ${v8(X)}`,cause:X});this[WJ]=!0,this.text=Y}static isInstance(Y){return f.hasMarker(Y,gJ)}},yJ="AI_LoadAPIKeyError",fJ=`vercel.ai.error.${yJ}`,V2=Symbol.for(fJ),KJ,UJ,B2=class extends(UJ=f,KJ=V2,UJ){constructor({message:Y}){super({name:yJ,message:Y});this[KJ]=!0}static isInstance(Y){return f.hasMarker(Y,fJ)}},mJ="AI_LoadSettingError",cJ=`vercel.ai.error.${mJ}`,Z2=Symbol.for(cJ),HJ,LJ,O2=class extends(LJ=f,HJ=Z2,LJ){constructor({message:Y}){super({name:mJ,message:Y});this[HJ]=!0}static isInstance(Y){return f.hasMarker(Y,cJ)}},uJ="AI_NoContentGeneratedError",pJ=`vercel.ai.error.${uJ}`,F2=Symbol.for(pJ),NJ,VJ,q2=class extends(VJ=f,NJ=F2,VJ){constructor({message:Y="No content generated."}={}){super({name:uJ,message:Y});this[NJ]=!0}static isInstance(Y){return f.hasMarker(Y,pJ)}},lJ="AI_NoSuchModelError",dJ=`vercel.ai.error.${lJ}`,j2=Symbol.for(dJ),BJ,ZJ,D2=class extends(ZJ=f,BJ=j2,ZJ){constructor({errorName:Y=lJ,modelId:X,modelType:J,message:Q=`No such ${J}: ${X}`}){super({name:Y,message:Q});this[BJ]=!0,this.modelId=X,this.modelType=J}static isInstance(Y){return f.hasMarker(Y,dJ)}},iJ="AI_NoSuchProviderReferenceError",nJ=`vercel.ai.error.${iJ}`,P2=Symbol.for(nJ),OJ,FJ,w2=class extends(FJ=f,OJ=P2,FJ){constructor({provider:Y,reference:X,message:J=`No provider reference found for provider '${Y}'. Available providers: ${Object.keys(X).join(", ")}`}){super({name:iJ,message:J});this[OJ]=!0,this.provider=Y,this.reference=X}static isInstance(Y){return f.hasMarker(Y,nJ)}},oJ="AI_TooManyEmbeddingValuesForCallError",rJ=`vercel.ai.error.${oJ}`,E2=Symbol.for(rJ),qJ,jJ,M2=class extends(jJ=f,qJ=E2,jJ){constructor(Y){super({name:oJ,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[qJ]=!0,this.provider=Y.provider,this.modelId=Y.modelId,this.maxEmbeddingsPerCall=Y.maxEmbeddingsPerCall,this.values=Y.values}static isInstance(Y){return f.hasMarker(Y,rJ)}},sJ="AI_TypeValidationError",aJ=`vercel.ai.error.${sJ}`,A2=Symbol.for(aJ),DJ,PJ,v0=class Y extends(PJ=f,DJ=A2,PJ){constructor({value:X,cause:J,context:Q}){let $="Type validation failed";if(Q==null?void 0:Q.field)$+=` for ${Q.field}`;if((Q==null?void 0:Q.entityName)||(Q==null?void 0:Q.entityId)){$+=" (";let G=[];if(Q.entityName)G.push(Q.entityName);if(Q.entityId)G.push(`id: "${Q.entityId}"`);$+=G.join(", "),$+=")"}super({name:sJ,message:`${$}: Value: ${JSON.stringify(X)}.
116
- Error message: ${v8(J)}`,cause:J});this[DJ]=!0,this.value=X,this.context=Q}static isInstance(X){return f.hasMarker(X,aJ)}static wrap({value:X,cause:J,context:Q}){var $,G,W;if(Y.isInstance(J)&&J.value===X&&(($=J.context)==null?void 0:$.field)===(Q==null?void 0:Q.field)&&((G=J.context)==null?void 0:G.entityName)===(Q==null?void 0:Q.entityName)&&((W=J.context)==null?void 0:W.entityId)===(Q==null?void 0:Q.entityId))return J;return new Y({value:X,cause:J,context:Q})}},tJ="AI_UnsupportedFunctionalityError",eJ=`vercel.ai.error.${tJ}`,R2=Symbol.for(eJ),wJ,EJ,T2=class extends(EJ=f,wJ=R2,EJ){constructor({functionality:Y,message:X=`'${Y}' functionality not supported.`}){super({name:tJ,message:X});this[wJ]=!0,this.functionality=Y}static isInstance(Y){return f.hasMarker(Y,eJ)}};var qB=Object.freeze({status:"aborted"});function q(Y,X,J){function Q(K,U){var H;Object.defineProperty(K,"_zod",{value:K._zod??{},enumerable:!1}),(H=K._zod).traits??(H.traits=new Set),K._zod.traits.add(Y),X(K,U);for(let N in W.prototype)if(!(N in K))Object.defineProperty(K,N,{value:W.prototype[N].bind(K)});K._zod.constr=W,K._zod.def=U}let $=J?.Parent??Object;class G extends ${}Object.defineProperty(G,"name",{value:Y});function W(K){var U;let H=J?.Parent?new G:this;Q(H,K),(U=H._zod).deferred??(U.deferred=[]);for(let N of H._zod.deferred)N();return H}return Object.defineProperty(W,"init",{value:Q}),Object.defineProperty(W,Symbol.hasInstance,{value:(K)=>{if(J?.Parent&&K instanceof J.Parent)return!0;return K?._zod?.traits?.has(Y)}}),Object.defineProperty(W,"name",{value:Y}),W}var jB=Symbol("zod_brand");class d0 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class u1 extends Error{constructor(Y){super(`Encountered unidirectional transform during encode: ${Y}`);this.name="ZodEncodeError"}}var AY={};function h0(Y){if(Y)Object.assign(AY,Y);return AY}var c={};g8(c,{unwrapMessage:()=>p1,uint8ArrayToHex:()=>e2,uint8ArrayToBase64url:()=>a2,uint8ArrayToBase64:()=>z6,stringifyPrimitive:()=>Q6,shallowClone:()=>X6,safeExtend:()=>d2,required:()=>o2,randomString:()=>y2,propertyKeyTypes:()=>m8,promiseAllObject:()=>g2,primitiveTypes:()=>J6,prefixIssues:()=>n0,pick:()=>u2,partial:()=>n2,optionalKeys:()=>c8,omit:()=>p2,objectClone:()=>x2,numKeys:()=>f2,nullish:()=>d1,normalizeParams:()=>v,mergeDefs:()=>J1,merge:()=>i2,jsonStringifyReplacer:()=>_1,joinValues:()=>b2,issue:()=>S1,isPlainObject:()=>Q1,isObject:()=>B1,hexToUint8Array:()=>t2,getSizableOrigin:()=>G6,getParsedType:()=>m2,getLengthableOrigin:()=>n1,getEnumValues:()=>l1,getElementAtPath:()=>h2,floatSafeRemainder:()=>y8,finalizeIssue:()=>_0,extend:()=>l2,escapeRegex:()=>i0,esc:()=>RY,defineLazy:()=>l,createTransparentProxy:()=>c2,cloneDef:()=>v2,clone:()=>C0,cleanRegex:()=>i1,cleanEnum:()=>r2,captureStackTrace:()=>TY,cached:()=>I1,base64urlToUint8Array:()=>s2,base64ToUint8Array:()=>W6,assignProp:()=>X1,assertNotEqual:()=>_2,assertNever:()=>S2,assertIs:()=>I2,assertEqual:()=>C2,assert:()=>k2,allowsEval:()=>f8,aborted:()=>$1,NUMBER_FORMAT_RANGES:()=>u8,Class:()=>K6,BIGINT_FORMAT_RANGES:()=>$6});function C2(Y){return Y}function _2(Y){return Y}function I2(Y){}function S2(Y){throw Error()}function k2(Y){}function l1(Y){let X=Object.values(Y).filter((Q)=>typeof Q==="number");return Object.entries(Y).filter(([Q,$])=>X.indexOf(+Q)===-1).map(([Q,$])=>$)}function b2(Y,X="|"){return Y.map((J)=>Q6(J)).join(X)}function _1(Y,X){if(typeof X==="bigint")return X.toString();return X}function I1(Y){return{get value(){{let J=Y();return Object.defineProperty(this,"value",{value:J}),J}throw Error("cached value already set")}}}function d1(Y){return Y===null||Y===void 0}function i1(Y){let X=Y.startsWith("^")?1:0,J=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(X,J)}function y8(Y,X){let J=(Y.toString().split(".")[1]||"").length,Q=X.toString(),$=(Q.split(".")[1]||"").length;if($===0&&/\d?e-\d?/.test(Q)){let U=Q.match(/\d?e-(\d?)/);if(U?.[1])$=Number.parseInt(U[1])}let G=J>$?J:$,W=Number.parseInt(Y.toFixed(G).replace(".","")),K=Number.parseInt(X.toFixed(G).replace(".",""));return W%K/10**G}var Y6=Symbol("evaluating");function l(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($){Object.defineProperty(Y,X,{value:$})},configurable:!0})}function x2(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function X1(Y,X,J){Object.defineProperty(Y,X,{value:J,writable:!0,enumerable:!0,configurable:!0})}function J1(...Y){let X={};for(let J of Y){let Q=Object.getOwnPropertyDescriptors(J);Object.assign(X,Q)}return Object.defineProperties({},X)}function v2(Y){return J1(Y._zod.def)}function h2(Y,X){if(!X)return Y;return X.reduce((J,Q)=>J?.[Q],Y)}function g2(Y){let X=Object.keys(Y),J=X.map((Q)=>Y[Q]);return Promise.all(J).then((Q)=>{let $={};for(let G=0;G<X.length;G++)$[X[G]]=Q[G];return $})}function y2(Y=10){let J="";for(let Q=0;Q<Y;Q++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function RY(Y){return JSON.stringify(Y)}var TY="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function B1(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var f8=I1(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function Q1(Y){if(B1(Y)===!1)return!1;let X=Y.constructor;if(X===void 0)return!0;let J=X.prototype;if(B1(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function X6(Y){if(Q1(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function f2(Y){let X=0;for(let J in Y)if(Object.prototype.hasOwnProperty.call(Y,J))X++;return X}var m2=(Y)=>{let X=typeof Y;switch(X){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(Y)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(Y))return"array";if(Y===null)return"null";if(Y.then&&typeof Y.then==="function"&&Y.catch&&typeof Y.catch==="function")return"promise";if(typeof Map<"u"&&Y instanceof Map)return"map";if(typeof Set<"u"&&Y instanceof Set)return"set";if(typeof Date<"u"&&Y instanceof Date)return"date";if(typeof File<"u"&&Y instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${X}`)}},m8=new Set(["string","number","symbol"]),J6=new Set(["string","number","bigint","boolean","symbol","undefined"]);function i0(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function C0(Y,X,J){let Q=new Y._zod.constr(X??Y._zod.def);if(!X||J?.parent)Q._zod.parent=Y;return Q}function v(Y){let X=Y;if(!X)return{};if(typeof X==="string")return{error:()=>X};if(X?.message!==void 0){if(X?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");X.error=X.message}if(delete X.message,typeof X.error==="string")return{...X,error:()=>X.error};return X}function c2(Y){let X;return new Proxy({},{get(J,Q,$){return X??(X=Y()),Reflect.get(X,Q,$)},set(J,Q,$,G){return X??(X=Y()),Reflect.set(X,Q,$,G)},has(J,Q){return X??(X=Y()),Reflect.has(X,Q)},deleteProperty(J,Q){return X??(X=Y()),Reflect.deleteProperty(X,Q)},ownKeys(J){return X??(X=Y()),Reflect.ownKeys(X)},getOwnPropertyDescriptor(J,Q){return X??(X=Y()),Reflect.getOwnPropertyDescriptor(X,Q)},defineProperty(J,Q,$){return X??(X=Y()),Reflect.defineProperty(X,Q,$)}})}function Q6(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function c8(Y){return Object.keys(Y).filter((X)=>{return Y[X]._zod.optin==="optional"&&Y[X]._zod.optout==="optional"})}var u8={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},$6={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function u2(Y,X){let J=Y._zod.def,Q=J1(Y._zod.def,{get shape(){let $={};for(let G in X){if(!(G in J.shape))throw Error(`Unrecognized key: "${G}"`);if(!X[G])continue;$[G]=J.shape[G]}return X1(this,"shape",$),$},checks:[]});return C0(Y,Q)}function p2(Y,X){let J=Y._zod.def,Q=J1(Y._zod.def,{get shape(){let $={...Y._zod.def.shape};for(let G in X){if(!(G in J.shape))throw Error(`Unrecognized key: "${G}"`);if(!X[G])continue;delete $[G]}return X1(this,"shape",$),$},checks:[]});return C0(Y,Q)}function l2(Y,X){if(!Q1(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 $=J1(Y._zod.def,{get shape(){let G={...Y._zod.def.shape,...X};return X1(this,"shape",G),G},checks:[]});return C0(Y,$)}function d2(Y,X){if(!Q1(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 X1(this,"shape",Q),Q},checks:Y._zod.def.checks};return C0(Y,J)}function i2(Y,X){let J=J1(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape,...X._zod.def.shape};return X1(this,"shape",Q),Q},get catchall(){return X._zod.def.catchall},checks:[]});return C0(Y,J)}function n2(Y,X,J){let Q=J1(X._zod.def,{get shape(){let $=X._zod.def.shape,G={...$};if(J)for(let W in J){if(!(W in $))throw Error(`Unrecognized key: "${W}"`);if(!J[W])continue;G[W]=Y?new Y({type:"optional",innerType:$[W]}):$[W]}else for(let W in $)G[W]=Y?new Y({type:"optional",innerType:$[W]}):$[W];return X1(this,"shape",G),G},checks:[]});return C0(X,Q)}function o2(Y,X,J){let Q=J1(X._zod.def,{get shape(){let $=X._zod.def.shape,G={...$};if(J)for(let W in J){if(!(W in G))throw Error(`Unrecognized key: "${W}"`);if(!J[W])continue;G[W]=new Y({type:"nonoptional",innerType:$[W]})}else for(let W in $)G[W]=new Y({type:"nonoptional",innerType:$[W]});return X1(this,"shape",G),G},checks:[]});return C0(X,Q)}function $1(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 n0(Y,X){return X.map((J)=>{var Q;return(Q=J).path??(Q.path=[]),J.path.unshift(Y),J})}function p1(Y){return typeof Y==="string"?Y:Y?.message}function _0(Y,X,J){let Q={...Y,path:Y.path??[]};if(!Y.message){let $=p1(Y.inst?._zod.def?.error?.(Y))??p1(X?.error?.(Y))??p1(J.customError?.(Y))??p1(J.localeError?.(Y))??"Invalid input";Q.message=$}if(delete Q.inst,delete Q.continue,!X?.reportInput)delete Q.input;return Q}function G6(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function n1(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function S1(...Y){let[X,J,Q]=Y;if(typeof X==="string")return{message:X,code:"custom",input:J,inst:Q};return{...X}}function r2(Y){return Object.entries(Y).filter(([X,J])=>{return Number.isNaN(Number.parseInt(X,10))}).map((X)=>X[1])}function W6(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 z6(Y){let X="";for(let J=0;J<Y.length;J++)X+=String.fromCharCode(Y[J]);return btoa(X)}function s2(Y){let X=Y.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-X.length%4)%4);return W6(X+J)}function a2(Y){return z6(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function t2(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 e2(Y){return Array.from(Y).map((X)=>X.toString(16).padStart(2,"0")).join("")}class K6{constructor(...Y){}}var U6=(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,_1,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},CY=q("$ZodError",U6),p8=q("$ZodError",U6,{Parent:Error});function H6(Y,X=(J)=>J.message){let J={},Q=[];for(let $ of Y.issues)if($.path.length>0)J[$.path[0]]=J[$.path[0]]||[],J[$.path[0]].push(X($));else Q.push(X($));return{formErrors:Q,fieldErrors:J}}function L6(Y,X){let J=X||function(G){return G.message},Q={_errors:[]},$=(G)=>{for(let W of G.issues)if(W.code==="invalid_union"&&W.errors.length)W.errors.map((K)=>$({issues:K}));else if(W.code==="invalid_key")$({issues:W.issues});else if(W.code==="invalid_element")$({issues:W.issues});else if(W.path.length===0)Q._errors.push(J(W));else{let K=Q,U=0;while(U<W.path.length){let H=W.path[U];if(U!==W.path.length-1)K[H]=K[H]||{_errors:[]};else K[H]=K[H]||{_errors:[]},K[H]._errors.push(J(W));K=K[H],U++}}};return $(Y),Q}var _Y=(Y)=>(X,J,Q,$)=>{let G=Q?Object.assign(Q,{async:!1}):{async:!1},W=X._zod.run({value:J,issues:[]},G);if(W instanceof Promise)throw new d0;if(W.issues.length){let K=new($?.Err??Y)(W.issues.map((U)=>_0(U,G,h0())));throw TY(K,$?.callee),K}return W.value};var IY=(Y)=>async(X,J,Q,$)=>{let G=Q?Object.assign(Q,{async:!0}):{async:!0},W=X._zod.run({value:J,issues:[]},G);if(W instanceof Promise)W=await W;if(W.issues.length){let K=new($?.Err??Y)(W.issues.map((U)=>_0(U,G,h0())));throw TY(K,$?.callee),K}return W.value};var o1=(Y)=>(X,J,Q)=>{let $=Q?{...Q,async:!1}:{async:!1},G=X._zod.run({value:J,issues:[]},$);if(G instanceof Promise)throw new d0;return G.issues.length?{success:!1,error:new(Y??CY)(G.issues.map((W)=>_0(W,$,h0())))}:{success:!0,data:G.value}},N6=o1(p8),r1=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{async:!0}):{async:!0},G=X._zod.run({value:J,issues:[]},$);if(G instanceof Promise)G=await G;return G.issues.length?{success:!1,error:new Y(G.issues.map((W)=>_0(W,$,h0())))}:{success:!0,data:G.value}},V6=r1(p8),B6=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return _Y(Y)(X,J,$)};var Z6=(Y)=>(X,J,Q)=>{return _Y(Y)(X,J,Q)};var O6=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return IY(Y)(X,J,$)};var F6=(Y)=>async(X,J,Q)=>{return IY(Y)(X,J,Q)};var q6=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return o1(Y)(X,J,$)};var j6=(Y)=>(X,J,Q)=>{return o1(Y)(X,J,Q)};var D6=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return r1(Y)(X,J,$)};var P6=(Y)=>async(X,J,Q)=>{return r1(Y)(X,J,Q)};var w6=/^[cC][^\s-]{8,}$/,E6=/^[0-9a-z]+$/,M6=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,A6=/^[0-9a-vA-V]{20}$/,R6=/^[A-Za-z0-9]{27}$/,T6=/^[a-zA-Z0-9_-]{21}$/,C6=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var _6=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,l8=(Y)=>{if(!Y)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${Y}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var I6=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function S6(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var k6=/^(?:(?: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])$/,b6=/^(([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}|:))$/,x6=/^((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])$/,v6=/^(([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])$/,h6=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,d8=/^[A-Za-z0-9_-]*$/,g6=/^(?=.{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 y6=/^\+(?:[0-9]){6,14}[0-9]$/,f6="(?:(?:\\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])))",m6=new RegExp(`^${f6}$`);function c6(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 u6(Y){return new RegExp(`^${c6(Y)}$`)}function p6(Y){let X=c6({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(`^${f6}T(?:${Q})$`)}var l6=(Y)=>{let X=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${X}$`)};var d6=/^-?\d+$/,i6=/^-?\d+(?:\.\d+)?/,n6=/^(?:true|false)$/i,o6=/^null$/i;var r6=/^[^A-Z]*$/,s6=/^[^a-z]*$/;var L0=q("$ZodCheck",(Y,X)=>{var J;Y._zod??(Y._zod={}),Y._zod.def=X,(J=Y._zod).onattach??(J.onattach=[])}),a6={number:"number",bigint:"bigint",object:"date"},i8=q("$ZodCheckLessThan",(Y,X)=>{L0.init(Y,X);let J=a6[typeof X.value];Y._zod.onattach.push((Q)=>{let $=Q._zod.bag,G=(X.inclusive?$.maximum:$.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(X.value<G)if(X.inclusive)$.maximum=X.value;else $.exclusiveMaximum=X.value}),Y._zod.check=(Q)=>{if(X.inclusive?Q.value<=X.value:Q.value<X.value)return;Q.issues.push({origin:J,code:"too_big",maximum:X.value,input:Q.value,inclusive:X.inclusive,inst:Y,continue:!X.abort})}}),n8=q("$ZodCheckGreaterThan",(Y,X)=>{L0.init(Y,X);let J=a6[typeof X.value];Y._zod.onattach.push((Q)=>{let $=Q._zod.bag,G=(X.inclusive?$.minimum:$.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(X.value>G)if(X.inclusive)$.minimum=X.value;else $.exclusiveMinimum=X.value}),Y._zod.check=(Q)=>{if(X.inclusive?Q.value>=X.value:Q.value>X.value)return;Q.issues.push({origin:J,code:"too_small",minimum:X.value,input:Q.value,inclusive:X.inclusive,inst:Y,continue:!X.abort})}}),t6=q("$ZodCheckMultipleOf",(Y,X)=>{L0.init(Y,X),Y._zod.onattach.push((J)=>{var Q;(Q=J._zod.bag).multipleOf??(Q.multipleOf=X.value)}),Y._zod.check=(J)=>{if(typeof J.value!==typeof X.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof J.value==="bigint"?J.value%X.value===BigInt(0):y8(J.value,X.value)===0)return;J.issues.push({origin:typeof J.value,code:"not_multiple_of",divisor:X.value,input:J.value,inst:Y,continue:!X.abort})}}),e6=q("$ZodCheckNumberFormat",(Y,X)=>{L0.init(Y,X),X.format=X.format||"float64";let J=X.format?.includes("int"),Q=J?"int":"number",[$,G]=u8[X.format];Y._zod.onattach.push((W)=>{let K=W._zod.bag;if(K.format=X.format,K.minimum=$,K.maximum=G,J)K.pattern=d6}),Y._zod.check=(W)=>{let K=W.value;if(J){if(!Number.isInteger(K)){W.issues.push({expected:Q,format:X.format,code:"invalid_type",continue:!1,input:K,inst:Y});return}if(!Number.isSafeInteger(K)){if(K>0)W.issues.push({input:K,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:Q,continue:!X.abort});else W.issues.push({input:K,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:Q,continue:!X.abort});return}}if(K<$)W.issues.push({origin:"number",input:K,code:"too_small",minimum:$,inclusive:!0,inst:Y,continue:!X.abort});if(K>G)W.issues.push({origin:"number",input:K,code:"too_big",maximum:G,inst:Y})}});var YQ=q("$ZodCheckMaxLength",(Y,X)=>{var J;L0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!d1($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(X.maximum<$)Q._zod.bag.maximum=X.maximum}),Y._zod.check=(Q)=>{let $=Q.value;if($.length<=X.maximum)return;let W=n1($);Q.issues.push({origin:W,code:"too_big",maximum:X.maximum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),XQ=q("$ZodCheckMinLength",(Y,X)=>{var J;L0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!d1($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(X.minimum>$)Q._zod.bag.minimum=X.minimum}),Y._zod.check=(Q)=>{let $=Q.value;if($.length>=X.minimum)return;let W=n1($);Q.issues.push({origin:W,code:"too_small",minimum:X.minimum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),JQ=q("$ZodCheckLengthEquals",(Y,X)=>{var J;L0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!d1($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.minimum=X.length,$.maximum=X.length,$.length=X.length}),Y._zod.check=(Q)=>{let $=Q.value,G=$.length;if(G===X.length)return;let W=n1($),K=G>X.length;Q.issues.push({origin:W,...K?{code:"too_big",maximum:X.length}:{code:"too_small",minimum:X.length},inclusive:!0,exact:!0,input:Q.value,inst:Y,continue:!X.abort})}}),s1=q("$ZodCheckStringFormat",(Y,X)=>{var J,Q;if(L0.init(Y,X),Y._zod.onattach.push(($)=>{let G=$._zod.bag;if(G.format=X.format,X.pattern)G.patterns??(G.patterns=new Set),G.patterns.add(X.pattern)}),X.pattern)(J=Y._zod).check??(J.check=($)=>{if(X.pattern.lastIndex=0,X.pattern.test($.value))return;$.issues.push({origin:"string",code:"invalid_format",format:X.format,input:$.value,...X.pattern?{pattern:X.pattern.toString()}:{},inst:Y,continue:!X.abort})});else(Q=Y._zod).check??(Q.check=()=>{})}),QQ=q("$ZodCheckRegex",(Y,X)=>{s1.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})}}),$Q=q("$ZodCheckLowerCase",(Y,X)=>{X.pattern??(X.pattern=r6),s1.init(Y,X)}),GQ=q("$ZodCheckUpperCase",(Y,X)=>{X.pattern??(X.pattern=s6),s1.init(Y,X)}),WQ=q("$ZodCheckIncludes",(Y,X)=>{L0.init(Y,X);let J=i0(X.includes),Q=new RegExp(typeof X.position==="number"?`^.{${X.position}}${J}`:J);X.pattern=Q,Y._zod.onattach.push(($)=>{let G=$._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(Q)}),Y._zod.check=($)=>{if($.value.includes(X.includes,X.position))return;$.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:X.includes,input:$.value,inst:Y,continue:!X.abort})}}),zQ=q("$ZodCheckStartsWith",(Y,X)=>{L0.init(Y,X);let J=new RegExp(`^${i0(X.prefix)}.*`);X.pattern??(X.pattern=J),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(J)}),Y._zod.check=(Q)=>{if(Q.value.startsWith(X.prefix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:X.prefix,input:Q.value,inst:Y,continue:!X.abort})}}),KQ=q("$ZodCheckEndsWith",(Y,X)=>{L0.init(Y,X);let J=new RegExp(`.*${i0(X.suffix)}$`);X.pattern??(X.pattern=J),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(J)}),Y._zod.check=(Q)=>{if(Q.value.endsWith(X.suffix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:X.suffix,input:Q.value,inst:Y,continue:!X.abort})}});var UQ=q("$ZodCheckOverwrite",(Y,X)=>{L0.init(Y,X),Y._zod.check=(J)=>{J.value=X.tx(J.value)}});class o8{constructor(Y=[]){if(this.content=[],this.indent=0,this)this.args=Y}indented(Y){this.indent+=1,Y(this),this.indent-=1}write(Y){if(typeof Y==="function"){Y(this,{execution:"sync"}),Y(this,{execution:"async"});return}let J=Y.split(`
164
+ `}}function k2(Y){return Y.type==="response.output_item.done"&&C(Y.item)&&Y.item.type==="web_search_call"&&typeof Y.item.id==="string"}function b2(Y){return C(Y)&&Y.type==="function_call"&&Y.name==="web_search"&&typeof Y.call_id==="string"&&Y.call_id.startsWith(vY)}function x2(Y,X){return C(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 v2(Y){return C(Y)&&Y.type==="item_reference"&&typeof Y.id==="string"&&Y.id.startsWith(vY)}function n8(Y,X,J){let Q=h2(X),$=C(Q?.action)?Q.action:g2(J?.arguments);return{type:"web_search_call",status:"completed",...$?{action:$}:{}}}function h2(Y){if(C(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return C(X)?X:void 0}catch{return}}function g2(Y){if(C(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return C(X)?X:void 0}catch{return}}import{readFile as y2}from"node:fs/promises";import{homedir as f2}from"node:os";import{join as BJ}from"node:path";var m2="https://models.dev/api.json",c2="OPENCODE_OPENAI_AUTH_MODELS_CACHE",u2="OPENCODE_MODELS_PATH",p2="OPENCODE_DISABLE_MODELS_FETCH",l2=1e4,d2=300000;function W1(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function ZJ(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=ZJ(Y.cache_read),$=ZJ(Y.cache_write);if(Q===null||$===null)return null;return{input:X,output:J,cache:{read:Q,write:$}}}function i2(Y){let X=W1(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 L=W1(U);if(!L)continue;let H=W1(L.tier),N=H?.size;if(H?.type!=="context")continue;if(typeof N!=="number"||!Number.isFinite(N)||N<=0)continue;let O=r8(L);if(!O)continue;W.push({...O,tier:{type:"context",size:N}})}if(W.length>0)Q.tiers=W}let $=W1(X.context_over_200k),G=$?r8($):null;if(G)Q.experimentalOver200K=G;return Q}function KJ(Y){let X=W1(Y),J=W1(X?.openai),Q=W1(J?.models);if(!Q)return null;let $={};for(let[G,W]of Object.entries(Q)){let U=W1(W),L=i2(U?.cost);if(L)$[G]=L}return Object.keys($).length>0?$:null}function n2(){let Y=process.env[c2]?.trim();if(Y)return Y;let X=process.env[u2]?.trim();if(X)return X;let J=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||BJ(f2(),".cache");return BJ(J,"opencode","models.json")}function o2(){let Y=process.env[p2]?.toLowerCase();return Y==="true"||Y==="1"}async function r2(){try{let Y=KJ(JSON.parse(await y2(n2(),"utf8")));if(Y)return Y}catch{}if(o2())return null;try{let Y=await fetch(m2,{signal:AbortSignal.timeout(l2)});if(!Y.ok)return null;return KJ(await Y.json())}catch{return null}}var g1;function OJ(){let Y=Date.now();if(g1&&g1.expiresAt>Y)return g1.promise;let X={expiresAt:Y+d2,promise:r2()};return g1=X,X.promise.then((J)=>{if(J===null&&g1===X)g1=void 0}),X.promise}function y1(Y){return typeof Y==="object"&&Y!==null}function s2(Y){if(Array.isArray(Y))return Y;if(y1(Y)&&Array.isArray(Y.data))return Y.data;return[]}function a2(Y){if(!y1(Y)||!y1(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function qJ(Y){if(!y1(Y)||!y1(Y.info))return null;let X=Y.info,J=y1(X.model)?X.model:void 0,Q=typeof X.agent==="string"?X.agent:void 0,$=typeof J?.providerID==="string"?J.providerID:typeof X.providerID==="string"?X.providerID:void 0,G=typeof J?.modelID==="string"?J.modelID:typeof X.modelID==="string"?X.modelID:void 0,W=typeof J?.variant==="string"?J.variant:typeof X.variant==="string"?X.variant:void 0;if(!Q&&(!$||!G)&&!W)return null;let U={};if(Q)U.agent=Q;if($&&G)U.model={providerID:$,modelID:G};if(W)U.variant=W;return U}function FJ(Y,X){return{agent:Y.agent??X.agent,model:Y.model??X.model,variant:Y.variant??X.variant}}function jJ(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function DJ(Y,X){if(!Y||!X)return null;let J=Y;if(typeof J.session?.messages!=="function")return null;let Q=[];try{Q=s2(await Promise.resolve(J.session.messages({path:{id:X},query:{limit:100}})))}catch{return null}if(Q.length===0)return null;let $={};for(let G=Q.length-1;G>=0;G--){if(a2(Q[G])!=="assistant")continue;let W=qJ(Q[G]);if(!W)continue;if($=FJ($,W),jJ($))return $}for(let G=Q.length-1;G>=0;G--){let W=qJ(Q[G]);if(!W)continue;if($=FJ($,W),jJ($))return $}if(!$.agent&&!$.model&&!$.variant)return null;return $}var z1=[],t2=1,s8=0,PJ=new Map;function a8(Y,X){if(z1.push({id:t2++,type:"open-dialog",payload:Y,sessionId:X}),z1.length>100)z1=z1.slice(z1.length-100)}function MJ(Y=0,X){let J=Date.now();if(s8=J,X!==void 0)PJ.set(X,J);let Q=($)=>X===void 0||$.sessionId===void 0||$.sessionId===X;if(Y>0)z1=z1.filter(($)=>{if($.id>Y)return!0;if(X===void 0)return!1;return $.sessionId!==X});return z1.filter(($)=>$.id>Y&&Q($))}function wJ(Y){let X=Date.now();if(Y!==void 0){let J=PJ.get(Y)??0;return J>0&&X-J<3000}return s8>0&&X-s8<3000}import{randomBytes as e2,timingSafeEqual as Yz}from"node:crypto";import{unlink as Xz}from"node:fs/promises";import{createServer as Jz}from"node:http";import{join as Qz}from"node:path";var EJ=L0("rpc");function $z(Y){return new Promise((X,J)=>{let Q=[],$=0;Y.on("data",(G)=>{if($+=G.length,$>1e6){Y.destroy(),J(Error("body too large"));return}Q.push(G)}),Y.on("end",()=>X(Buffer.concat(Q).toString("utf8"))),Y.on("error",J)})}function Gz(Y,X){if(!Y?.startsWith("Bearer "))return!1;let J=Buffer.from(Y.slice(7)),Q=Buffer.from(X);return J.length===Q.length&&Yz(J,Q)}async function RJ(Y){let X=e2(32).toString("hex"),J=Y.timeoutMs??90000,Q=Y.receiptTimeoutMs??2000,$=Jz((U,L)=>{U.setTimeout(J,()=>{U.socket.destroy()}),G(U,L)});$.requestTimeout=Q,$.headersTimeout=Q;async function G(U,L){let H=(N,O)=>{if(L.headersSent||L.writableEnded||L.destroyed)return;L.writeHead(N,{"content-type":"application/json"}),L.end(JSON.stringify(O))};try{let N=U.url??"";if(U.method==="GET"&&N==="/health")return H(200,{ok:!0});if(U.method!=="POST"||!N.startsWith("/rpc/"))return H(404,{error:"not found"});if(!Gz(U.headers.authorization,X))return H(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 H(200,{messages:K})}if(O==="apply"){let K=await Y.apply(V);return H(200,K)}return H(404,{error:"unknown method"})}catch(N){H(500,{error:N instanceof Error?N.message:String(N)})}}let W=await new Promise((U,L)=>{$.on("error",L),$.listen(0,"127.0.0.1",()=>{let H=$.address();if(H&&typeof H==="object")U(H.port);else L(Error("no port"))})});if($.unref(),Y.sweepRoot)try{await TJ(Y.sweepRoot,Y.dir)}catch(U){EJ.warn("rpc state sweep failed",{pid:process.pid,error:U instanceof Error?U.message:String(U)})}try{await AJ(Y.dir,{port:W,token:X,pid:process.pid},{secureDir:Y.secureDir}),EJ.debug("rpc server pid",{pid:process.pid,rpcPort:W})}catch(U){throw await new Promise((L)=>$.close(()=>L())),U}return{port:W,token:X,async stop(){await new Promise((U)=>$.close(()=>U())),await Xz(Qz(Y.dir,`port-${process.pid}.json`)).catch(()=>{})}}}function s0(Y){return JSON.stringify(t8(Y))??"undefined"}function t8(Y){if(Array.isArray(Y))return Y.map(t8);if(!C(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((X)=>[X,t8(Y[X])]))}function P1(){let Y=crypto.getRandomValues(new Uint8Array(16)),X=Date.now();Y[0]=X/1099511627776&255,Y[1]=X/4294967296&255,Y[2]=X/16777216&255,Y[3]=X/65536&255,Y[4]=X/256&255,Y[5]=X&255,Y[6]=(Y[6]??0)&15|112,Y[8]=(Y[8]??0)&63|128;let J=Array.from(Y,(Q)=>Q.toString(16).padStart(2,"0")).join("");return`${J.slice(0,8)}-${J.slice(8,12)}-${J.slice(12,16)}-${J.slice(16,20)}-${J.slice(20)}`}var Z1={};X9(Z1,{withoutInternalHeaders:()=>FW,sanitizeHttpFallbackBody:()=>v8,orderCodexBody:()=>qY,hasWebSocketResponsesLiteMetadata:()=>x8,createWebSocketFetch:()=>NB,applyTurnId:()=>ZW,advanceTurn:()=>a9,TITLE_HEADER:()=>s9,QUOTA_ACCOUNT_HEADER:()=>H8,OpenAIWebSocketPool:()=>Z1,CODEX_BODY_KEY_ORDER:()=>NW});import{createHash as zB}from"node:crypto";var $6="vercel.ai.error",Wz=Symbol.for($6),CJ,_J,f=class Y extends(_J=Error,CJ=Wz,_J){constructor({name:X,message:J,cause:Q}){super(J);this[CJ]=!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}},G6="AI_APICallError",W6=`vercel.ai.error.${G6}`,zz=Symbol.for(W6),IJ,SJ,t1=class extends(SJ=f,IJ=zz,SJ){constructor({message:Y,url:X,requestBodyValues:J,statusCode:Q,responseHeaders:$,responseBody:G,cause:W,isRetryable:U=Q!=null&&(Q===408||Q===409||Q===429||Q>=500),data:L}){super({name:G6,message:Y,cause:W});this[IJ]=!0,this.url=X,this.requestBodyValues=J,this.statusCode=Q,this.responseHeaders=$,this.responseBody=G,this.isRetryable=U,this.data=L}static isInstance(Y){return f.hasMarker(Y,W6)}},z6="AI_EmptyResponseBodyError",U6=`vercel.ai.error.${z6}`,Uz=Symbol.for(U6),kJ,bJ,Hz=class extends(bJ=f,kJ=Uz,bJ){constructor({message:Y="Empty response body"}={}){super({name:z6,message:Y});this[kJ]=!0}static isInstance(Y){return f.hasMarker(Y,U6)}};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 H6="AI_InvalidArgumentError",L6=`vercel.ai.error.${H6}`,Lz=Symbol.for(L6),xJ,vJ,V6=class extends(vJ=f,xJ=Lz,vJ){constructor({message:Y,cause:X,argument:J}){super({name:H6,message:Y,cause:X});this[xJ]=!0,this.argument=J}static isInstance(Y){return f.hasMarker(Y,L6)}},N6="AI_InvalidPromptError",B6=`vercel.ai.error.${N6}`,Vz=Symbol.for(B6),hJ,gJ,Nz=class extends(gJ=f,hJ=Vz,gJ){constructor({prompt:Y,message:X,cause:J}){super({name:N6,message:`Invalid prompt: ${X}`,cause:J});this[hJ]=!0,this.prompt=Y}static isInstance(Y){return f.hasMarker(Y,B6)}},Z6="AI_InvalidResponseDataError",K6=`vercel.ai.error.${Z6}`,Bz=Symbol.for(K6),yJ,fJ,Zz=class extends(fJ=f,yJ=Bz,fJ){constructor({data:Y,message:X=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:Z6,message:X});this[yJ]=!0,this.data=Y}static isInstance(Y){return f.hasMarker(Y,K6)}},O6="AI_JSONParseError",q6=`vercel.ai.error.${O6}`,Kz=Symbol.for(q6),mJ,cJ,hY=class extends(cJ=f,mJ=Kz,cJ){constructor({text:Y,cause:X}){super({name:O6,message:`JSON parsing failed: Text: ${Y}.
165
+ Error message: ${e8(X)}`,cause:X});this[mJ]=!0,this.text=Y}static isInstance(Y){return f.hasMarker(Y,q6)}},F6="AI_LoadAPIKeyError",j6=`vercel.ai.error.${F6}`,Oz=Symbol.for(j6),uJ,pJ,qz=class extends(pJ=f,uJ=Oz,pJ){constructor({message:Y}){super({name:F6,message:Y});this[uJ]=!0}static isInstance(Y){return f.hasMarker(Y,j6)}},D6="AI_LoadSettingError",P6=`vercel.ai.error.${D6}`,Fz=Symbol.for(P6),lJ,dJ,jz=class extends(dJ=f,lJ=Fz,dJ){constructor({message:Y}){super({name:D6,message:Y});this[lJ]=!0}static isInstance(Y){return f.hasMarker(Y,P6)}},M6="AI_NoContentGeneratedError",w6=`vercel.ai.error.${M6}`,Dz=Symbol.for(w6),iJ,nJ,Pz=class extends(nJ=f,iJ=Dz,nJ){constructor({message:Y="No content generated."}={}){super({name:M6,message:Y});this[iJ]=!0}static isInstance(Y){return f.hasMarker(Y,w6)}},E6="AI_NoSuchModelError",A6=`vercel.ai.error.${E6}`,Mz=Symbol.for(A6),oJ,rJ,wz=class extends(rJ=f,oJ=Mz,rJ){constructor({errorName:Y=E6,modelId:X,modelType:J,message:Q=`No such ${J}: ${X}`}){super({name:Y,message:Q});this[oJ]=!0,this.modelId=X,this.modelType=J}static isInstance(Y){return f.hasMarker(Y,A6)}},T6="AI_NoSuchProviderReferenceError",R6=`vercel.ai.error.${T6}`,Ez=Symbol.for(R6),sJ,aJ,Az=class extends(aJ=f,sJ=Ez,aJ){constructor({provider:Y,reference:X,message:J=`No provider reference found for provider '${Y}'. Available providers: ${Object.keys(X).join(", ")}`}){super({name:T6,message:J});this[sJ]=!0,this.provider=Y,this.reference=X}static isInstance(Y){return f.hasMarker(Y,R6)}},C6="AI_TooManyEmbeddingValuesForCallError",_6=`vercel.ai.error.${C6}`,Tz=Symbol.for(_6),tJ,eJ,Rz=class extends(eJ=f,tJ=Tz,eJ){constructor(Y){super({name:C6,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[tJ]=!0,this.provider=Y.provider,this.modelId=Y.modelId,this.maxEmbeddingsPerCall=Y.maxEmbeddingsPerCall,this.values=Y.values}static isInstance(Y){return f.hasMarker(Y,_6)}},I6="AI_TypeValidationError",S6=`vercel.ai.error.${I6}`,Cz=Symbol.for(S6),Y6,X6,f0=class Y extends(X6=f,Y6=Cz,X6){constructor({value:X,cause:J,context:Q}){let $="Type validation failed";if(Q==null?void 0:Q.field)$+=` for ${Q.field}`;if((Q==null?void 0:Q.entityName)||(Q==null?void 0:Q.entityId)){$+=" (";let G=[];if(Q.entityName)G.push(Q.entityName);if(Q.entityId)G.push(`id: "${Q.entityId}"`);$+=G.join(", "),$+=")"}super({name:I6,message:`${$}: Value: ${JSON.stringify(X)}.
166
+ Error message: ${e8(J)}`,cause:J});this[Y6]=!0,this.value=X,this.context=Q}static isInstance(X){return f.hasMarker(X,S6)}static wrap({value:X,cause:J,context:Q}){var $,G,W;if(Y.isInstance(J)&&J.value===X&&(($=J.context)==null?void 0:$.field)===(Q==null?void 0:Q.field)&&((G=J.context)==null?void 0:G.entityName)===(Q==null?void 0:Q.entityName)&&((W=J.context)==null?void 0:W.entityId)===(Q==null?void 0:Q.entityId))return J;return new Y({value:X,cause:J,context:Q})}},k6="AI_UnsupportedFunctionalityError",b6=`vercel.ai.error.${k6}`,_z=Symbol.for(b6),J6,Q6,Iz=class extends(Q6=f,J6=_z,Q6){constructor({functionality:Y,message:X=`'${Y}' functionality not supported.`}){super({name:k6,message:X});this[J6]=!0,this.functionality=Y}static isInstance(Y){return f.hasMarker(Y,b6)}};var CK=Object.freeze({status:"aborted"});function F(Y,X,J){function Q(U,L){var H;Object.defineProperty(U,"_zod",{value:U._zod??{},enumerable:!1}),(H=U._zod).traits??(H.traits=new Set),U._zod.traits.add(Y),X(U,L);for(let N in W.prototype)if(!(N in U))Object.defineProperty(U,N,{value:W.prototype[N].bind(U)});U._zod.constr=W,U._zod.def=L}let $=J?.Parent??Object;class G extends ${}Object.defineProperty(G,"name",{value:Y});function W(U){var L;let H=J?.Parent?new G:this;Q(H,U),(L=H._zod).deferred??(L.deferred=[]);for(let N of H._zod.deferred)N();return H}return Object.defineProperty(W,"init",{value:Q}),Object.defineProperty(W,Symbol.hasInstance,{value:(U)=>{if(J?.Parent&&U instanceof J.Parent)return!0;return U?._zod?.traits?.has(Y)}}),Object.defineProperty(W,"name",{value:Y}),W}var _K=Symbol("zod_brand");class a0 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 m0(Y){if(Y)Object.assign(gY,Y);return gY}var u={};X9(u,{unwrapMessage:()=>YY,uint8ArrayToHex:()=>JU,uint8ArrayToBase64url:()=>YU,uint8ArrayToBase64:()=>c6,stringifyPrimitive:()=>g6,shallowClone:()=>v6,safeExtend:()=>oz,required:()=>az,randomString:()=>cz,propertyKeyTypes:()=>$9,promiseAllObject:()=>mz,primitiveTypes:()=>h6,prefixIssues:()=>e0,pick:()=>dz,partial:()=>sz,optionalKeys:()=>G9,omit:()=>iz,objectClone:()=>gz,numKeys:()=>uz,nullish:()=>JY,normalizeParams:()=>v,mergeDefs:()=>H1,merge:()=>rz,jsonStringifyReplacer:()=>f1,joinValues:()=>hz,issue:()=>c1,isPlainObject:()=>L1,isObject:()=>M1,hexToUint8Array:()=>XU,getSizableOrigin:()=>f6,getParsedType:()=>pz,getLengthableOrigin:()=>$Y,getEnumValues:()=>XY,getElementAtPath:()=>fz,floatSafeRemainder:()=>J9,finalizeIssue:()=>S0,extend:()=>nz,escapeRegex:()=>t0,esc:()=>yY,defineLazy:()=>l,createTransparentProxy:()=>lz,cloneDef:()=>yz,clone:()=>I0,cleanRegex:()=>QY,cleanEnum:()=>tz,captureStackTrace:()=>fY,cached:()=>m1,base64urlToUint8Array:()=>ez,base64ToUint8Array:()=>m6,assignProp:()=>U1,assertNotEqual:()=>kz,assertNever:()=>xz,assertIs:()=>bz,assertEqual:()=>Sz,assert:()=>vz,allowsEval:()=>Q9,aborted:()=>V1,NUMBER_FORMAT_RANGES:()=>W9,Class:()=>u6,BIGINT_FORMAT_RANGES:()=>y6});function Sz(Y){return Y}function kz(Y){return Y}function bz(Y){}function xz(Y){throw Error()}function vz(Y){}function XY(Y){let X=Object.values(Y).filter((Q)=>typeof Q==="number");return Object.entries(Y).filter(([Q,$])=>X.indexOf(+Q)===-1).map(([Q,$])=>$)}function hz(Y,X="|"){return Y.map((J)=>g6(J)).join(X)}function f1(Y,X){if(typeof X==="bigint")return X.toString();return X}function m1(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(),$=(Q.split(".")[1]||"").length;if($===0&&/\d?e-\d?/.test(Q)){let L=Q.match(/\d?e-(\d?)/);if(L?.[1])$=Number.parseInt(L[1])}let G=J>$?J:$,W=Number.parseInt(Y.toFixed(G).replace(".","")),U=Number.parseInt(X.toFixed(G).replace(".",""));return W%U/10**G}var x6=Symbol("evaluating");function l(Y,X,J){let Q=void 0;Object.defineProperty(Y,X,{get(){if(Q===x6)return;if(Q===void 0)Q=x6,Q=J();return Q},set($){Object.defineProperty(Y,X,{value:$})},configurable:!0})}function gz(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function U1(Y,X,J){Object.defineProperty(Y,X,{value:J,writable:!0,enumerable:!0,configurable:!0})}function H1(...Y){let X={};for(let J of Y){let Q=Object.getOwnPropertyDescriptors(J);Object.assign(X,Q)}return Object.defineProperties({},X)}function yz(Y){return H1(Y._zod.def)}function fz(Y,X){if(!X)return Y;return X.reduce((J,Q)=>J?.[Q],Y)}function mz(Y){let X=Object.keys(Y),J=X.map((Q)=>Y[Q]);return Promise.all(J).then((Q)=>{let $={};for(let G=0;G<X.length;G++)$[X[G]]=Q[G];return $})}function cz(Y=10){let J="";for(let Q=0;Q<Y;Q++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function yY(Y){return JSON.stringify(Y)}var fY="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function M1(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var Q9=m1(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function L1(Y){if(M1(Y)===!1)return!1;let X=Y.constructor;if(X===void 0)return!0;let J=X.prototype;if(M1(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function v6(Y){if(L1(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function uz(Y){let X=0;for(let J in Y)if(Object.prototype.hasOwnProperty.call(Y,J))X++;return X}var pz=(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}`)}},$9=new Set(["string","number","symbol"]),h6=new Set(["string","number","bigint","boolean","symbol","undefined"]);function t0(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function I0(Y,X,J){let Q=new Y._zod.constr(X??Y._zod.def);if(!X||J?.parent)Q._zod.parent=Y;return Q}function v(Y){let X=Y;if(!X)return{};if(typeof X==="string")return{error:()=>X};if(X?.message!==void 0){if(X?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");X.error=X.message}if(delete X.message,typeof X.error==="string")return{...X,error:()=>X.error};return X}function lz(Y){let X;return new Proxy({},{get(J,Q,$){return X??(X=Y()),Reflect.get(X,Q,$)},set(J,Q,$,G){return X??(X=Y()),Reflect.set(X,Q,$,G)},has(J,Q){return X??(X=Y()),Reflect.has(X,Q)},deleteProperty(J,Q){return X??(X=Y()),Reflect.deleteProperty(X,Q)},ownKeys(J){return X??(X=Y()),Reflect.ownKeys(X)},getOwnPropertyDescriptor(J,Q){return X??(X=Y()),Reflect.getOwnPropertyDescriptor(X,Q)},defineProperty(J,Q,$){return X??(X=Y()),Reflect.defineProperty(X,Q,$)}})}function g6(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function G9(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]},y6={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function dz(Y,X){let J=Y._zod.def,Q=H1(Y._zod.def,{get shape(){let $={};for(let G in X){if(!(G in J.shape))throw Error(`Unrecognized key: "${G}"`);if(!X[G])continue;$[G]=J.shape[G]}return U1(this,"shape",$),$},checks:[]});return I0(Y,Q)}function iz(Y,X){let J=Y._zod.def,Q=H1(Y._zod.def,{get shape(){let $={...Y._zod.def.shape};for(let G in X){if(!(G in J.shape))throw Error(`Unrecognized key: "${G}"`);if(!X[G])continue;delete $[G]}return U1(this,"shape",$),$},checks:[]});return I0(Y,Q)}function nz(Y,X){if(!L1(X))throw Error("Invalid input to extend: expected a plain object");let J=Y._zod.def.checks;if(J&&J.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let $=H1(Y._zod.def,{get shape(){let G={...Y._zod.def.shape,...X};return U1(this,"shape",G),G},checks:[]});return I0(Y,$)}function oz(Y,X){if(!L1(X))throw Error("Invalid input to safeExtend: expected a plain object");let J={...Y._zod.def,get shape(){let Q={...Y._zod.def.shape,...X};return U1(this,"shape",Q),Q},checks:Y._zod.def.checks};return I0(Y,J)}function rz(Y,X){let J=H1(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape,...X._zod.def.shape};return U1(this,"shape",Q),Q},get catchall(){return X._zod.def.catchall},checks:[]});return I0(Y,J)}function sz(Y,X,J){let Q=H1(X._zod.def,{get shape(){let $=X._zod.def.shape,G={...$};if(J)for(let W in J){if(!(W in $))throw Error(`Unrecognized key: "${W}"`);if(!J[W])continue;G[W]=Y?new Y({type:"optional",innerType:$[W]}):$[W]}else for(let W in $)G[W]=Y?new Y({type:"optional",innerType:$[W]}):$[W];return U1(this,"shape",G),G},checks:[]});return I0(X,Q)}function az(Y,X,J){let Q=H1(X._zod.def,{get shape(){let $=X._zod.def.shape,G={...$};if(J)for(let W in J){if(!(W in G))throw Error(`Unrecognized key: "${W}"`);if(!J[W])continue;G[W]=new Y({type:"nonoptional",innerType:$[W]})}else for(let W in $)G[W]=new Y({type:"nonoptional",innerType:$[W]});return U1(this,"shape",G),G},checks:[]});return I0(X,Q)}function V1(Y,X=0){if(Y.aborted===!0)return!0;for(let J=X;J<Y.issues.length;J++)if(Y.issues[J]?.continue!==!0)return!0;return!1}function e0(Y,X){return X.map((J)=>{var Q;return(Q=J).path??(Q.path=[]),J.path.unshift(Y),J})}function YY(Y){return typeof Y==="string"?Y:Y?.message}function S0(Y,X,J){let Q={...Y,path:Y.path??[]};if(!Y.message){let $=YY(Y.inst?._zod.def?.error?.(Y))??YY(X?.error?.(Y))??YY(J.customError?.(Y))??YY(J.localeError?.(Y))??"Invalid input";Q.message=$}if(delete Q.inst,delete Q.continue,!X?.reportInput)delete Q.input;return Q}function f6(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function $Y(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function c1(...Y){let[X,J,Q]=Y;if(typeof X==="string")return{message:X,code:"custom",input:J,inst:Q};return{...X}}function tz(Y){return Object.entries(Y).filter(([X,J])=>{return Number.isNaN(Number.parseInt(X,10))}).map((X)=>X[1])}function m6(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 c6(Y){let X="";for(let J=0;J<Y.length;J++)X+=String.fromCharCode(Y[J]);return btoa(X)}function ez(Y){let X=Y.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-X.length%4)%4);return m6(X+J)}function YU(Y){return c6(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function XU(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 JU(Y){return Array.from(Y).map((X)=>X.toString(16).padStart(2,"0")).join("")}class u6{constructor(...Y){}}var p6=(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,f1,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},mY=F("$ZodError",p6),z9=F("$ZodError",p6,{Parent:Error});function l6(Y,X=(J)=>J.message){let J={},Q=[];for(let $ of Y.issues)if($.path.length>0)J[$.path[0]]=J[$.path[0]]||[],J[$.path[0]].push(X($));else Q.push(X($));return{formErrors:Q,fieldErrors:J}}function d6(Y,X){let J=X||function(G){return G.message},Q={_errors:[]},$=(G)=>{for(let W of G.issues)if(W.code==="invalid_union"&&W.errors.length)W.errors.map((U)=>$({issues:U}));else if(W.code==="invalid_key")$({issues:W.issues});else if(W.code==="invalid_element")$({issues:W.issues});else if(W.path.length===0)Q._errors.push(J(W));else{let U=Q,L=0;while(L<W.path.length){let H=W.path[L];if(L!==W.path.length-1)U[H]=U[H]||{_errors:[]};else U[H]=U[H]||{_errors:[]},U[H]._errors.push(J(W));U=U[H],L++}}};return $(Y),Q}var cY=(Y)=>(X,J,Q,$)=>{let G=Q?Object.assign(Q,{async:!1}):{async:!1},W=X._zod.run({value:J,issues:[]},G);if(W instanceof Promise)throw new a0;if(W.issues.length){let U=new($?.Err??Y)(W.issues.map((L)=>S0(L,G,m0())));throw fY(U,$?.callee),U}return W.value};var uY=(Y)=>async(X,J,Q,$)=>{let G=Q?Object.assign(Q,{async:!0}):{async:!0},W=X._zod.run({value:J,issues:[]},G);if(W instanceof Promise)W=await W;if(W.issues.length){let U=new($?.Err??Y)(W.issues.map((L)=>S0(L,G,m0())));throw fY(U,$?.callee),U}return W.value};var GY=(Y)=>(X,J,Q)=>{let $=Q?{...Q,async:!1}:{async:!1},G=X._zod.run({value:J,issues:[]},$);if(G instanceof Promise)throw new a0;return G.issues.length?{success:!1,error:new(Y??mY)(G.issues.map((W)=>S0(W,$,m0())))}:{success:!0,data:G.value}},i6=GY(z9),WY=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{async:!0}):{async:!0},G=X._zod.run({value:J,issues:[]},$);if(G instanceof Promise)G=await G;return G.issues.length?{success:!1,error:new Y(G.issues.map((W)=>S0(W,$,m0())))}:{success:!0,data:G.value}},n6=WY(z9),o6=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return cY(Y)(X,J,$)};var r6=(Y)=>(X,J,Q)=>{return cY(Y)(X,J,Q)};var s6=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return uY(Y)(X,J,$)};var a6=(Y)=>async(X,J,Q)=>{return uY(Y)(X,J,Q)};var t6=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return GY(Y)(X,J,$)};var e6=(Y)=>(X,J,Q)=>{return GY(Y)(X,J,Q)};var YQ=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return WY(Y)(X,J,$)};var XQ=(Y)=>async(X,J,Q)=>{return WY(Y)(X,J,Q)};var JQ=/^[cC][^\s-]{8,}$/,QQ=/^[0-9a-z]+$/,$Q=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,GQ=/^[0-9a-vA-V]{20}$/,WQ=/^[A-Za-z0-9]{27}$/,zQ=/^[a-zA-Z0-9_-]{21}$/,UQ=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var HQ=/^([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 LQ=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function VQ(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var NQ=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,BQ=/^(([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}|:))$/,ZQ=/^((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])$/,KQ=/^(([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])$/,OQ=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,H9=/^[A-Za-z0-9_-]*$/,qQ=/^(?=.{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 FQ=/^\+(?:[0-9]){6,14}[0-9]$/,jQ="(?:(?:\\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])))",DQ=new RegExp(`^${jQ}$`);function PQ(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 MQ(Y){return new RegExp(`^${PQ(Y)}$`)}function wQ(Y){let X=PQ({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(`^${jQ}T(?:${Q})$`)}var EQ=(Y)=>{let X=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${X}$`)};var AQ=/^-?\d+$/,TQ=/^-?\d+(?:\.\d+)?/,RQ=/^(?:true|false)$/i,CQ=/^null$/i;var _Q=/^[^A-Z]*$/,IQ=/^[^a-z]*$/;var V0=F("$ZodCheck",(Y,X)=>{var J;Y._zod??(Y._zod={}),Y._zod.def=X,(J=Y._zod).onattach??(J.onattach=[])}),SQ={number:"number",bigint:"bigint",object:"date"},L9=F("$ZodCheckLessThan",(Y,X)=>{V0.init(Y,X);let J=SQ[typeof X.value];Y._zod.onattach.push((Q)=>{let $=Q._zod.bag,G=(X.inclusive?$.maximum:$.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(X.value<G)if(X.inclusive)$.maximum=X.value;else $.exclusiveMaximum=X.value}),Y._zod.check=(Q)=>{if(X.inclusive?Q.value<=X.value:Q.value<X.value)return;Q.issues.push({origin:J,code:"too_big",maximum:X.value,input:Q.value,inclusive:X.inclusive,inst:Y,continue:!X.abort})}}),V9=F("$ZodCheckGreaterThan",(Y,X)=>{V0.init(Y,X);let J=SQ[typeof X.value];Y._zod.onattach.push((Q)=>{let $=Q._zod.bag,G=(X.inclusive?$.minimum:$.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(X.value>G)if(X.inclusive)$.minimum=X.value;else $.exclusiveMinimum=X.value}),Y._zod.check=(Q)=>{if(X.inclusive?Q.value>=X.value:Q.value>X.value)return;Q.issues.push({origin:J,code:"too_small",minimum:X.value,input:Q.value,inclusive:X.inclusive,inst:Y,continue:!X.abort})}}),kQ=F("$ZodCheckMultipleOf",(Y,X)=>{V0.init(Y,X),Y._zod.onattach.push((J)=>{var Q;(Q=J._zod.bag).multipleOf??(Q.multipleOf=X.value)}),Y._zod.check=(J)=>{if(typeof J.value!==typeof X.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof J.value==="bigint"?J.value%X.value===BigInt(0):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})}}),bQ=F("$ZodCheckNumberFormat",(Y,X)=>{V0.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=$,U.maximum=G,J)U.pattern=AQ}),Y._zod.check=(W)=>{let U=W.value;if(J){if(!Number.isInteger(U)){W.issues.push({expected:Q,format:X.format,code:"invalid_type",continue:!1,input:U,inst:Y});return}if(!Number.isSafeInteger(U)){if(U>0)W.issues.push({input:U,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:Q,continue:!X.abort});else W.issues.push({input:U,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:Q,continue:!X.abort});return}}if(U<$)W.issues.push({origin:"number",input:U,code:"too_small",minimum:$,inclusive:!0,inst:Y,continue:!X.abort});if(U>G)W.issues.push({origin:"number",input:U,code:"too_big",maximum:G,inst:Y})}});var xQ=F("$ZodCheckMaxLength",(Y,X)=>{var J;V0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!JY($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(X.maximum<$)Q._zod.bag.maximum=X.maximum}),Y._zod.check=(Q)=>{let $=Q.value;if($.length<=X.maximum)return;let W=$Y($);Q.issues.push({origin:W,code:"too_big",maximum:X.maximum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),vQ=F("$ZodCheckMinLength",(Y,X)=>{var J;V0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!JY($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(X.minimum>$)Q._zod.bag.minimum=X.minimum}),Y._zod.check=(Q)=>{let $=Q.value;if($.length>=X.minimum)return;let W=$Y($);Q.issues.push({origin:W,code:"too_small",minimum:X.minimum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),hQ=F("$ZodCheckLengthEquals",(Y,X)=>{var J;V0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!JY($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.minimum=X.length,$.maximum=X.length,$.length=X.length}),Y._zod.check=(Q)=>{let $=Q.value,G=$.length;if(G===X.length)return;let W=$Y($),U=G>X.length;Q.issues.push({origin:W,...U?{code:"too_big",maximum:X.length}:{code:"too_small",minimum:X.length},inclusive:!0,exact:!0,input:Q.value,inst:Y,continue:!X.abort})}}),zY=F("$ZodCheckStringFormat",(Y,X)=>{var J,Q;if(V0.init(Y,X),Y._zod.onattach.push(($)=>{let G=$._zod.bag;if(G.format=X.format,X.pattern)G.patterns??(G.patterns=new Set),G.patterns.add(X.pattern)}),X.pattern)(J=Y._zod).check??(J.check=($)=>{if(X.pattern.lastIndex=0,X.pattern.test($.value))return;$.issues.push({origin:"string",code:"invalid_format",format:X.format,input:$.value,...X.pattern?{pattern:X.pattern.toString()}:{},inst:Y,continue:!X.abort})});else(Q=Y._zod).check??(Q.check=()=>{})}),gQ=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})}}),yQ=F("$ZodCheckLowerCase",(Y,X)=>{X.pattern??(X.pattern=_Q),zY.init(Y,X)}),fQ=F("$ZodCheckUpperCase",(Y,X)=>{X.pattern??(X.pattern=IQ),zY.init(Y,X)}),mQ=F("$ZodCheckIncludes",(Y,X)=>{V0.init(Y,X);let J=t0(X.includes),Q=new RegExp(typeof X.position==="number"?`^.{${X.position}}${J}`:J);X.pattern=Q,Y._zod.onattach.push(($)=>{let G=$._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(Q)}),Y._zod.check=($)=>{if($.value.includes(X.includes,X.position))return;$.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:X.includes,input:$.value,inst:Y,continue:!X.abort})}}),cQ=F("$ZodCheckStartsWith",(Y,X)=>{V0.init(Y,X);let J=new RegExp(`^${t0(X.prefix)}.*`);X.pattern??(X.pattern=J),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(J)}),Y._zod.check=(Q)=>{if(Q.value.startsWith(X.prefix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:X.prefix,input:Q.value,inst:Y,continue:!X.abort})}}),uQ=F("$ZodCheckEndsWith",(Y,X)=>{V0.init(Y,X);let J=new RegExp(`.*${t0(X.suffix)}$`);X.pattern??(X.pattern=J),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(J)}),Y._zod.check=(Q)=>{if(Q.value.endsWith(X.suffix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:X.suffix,input:Q.value,inst:Y,continue:!X.abort})}});var pQ=F("$ZodCheckOverwrite",(Y,X)=>{V0.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(`
117
167
  `).filter((G)=>G),Q=Math.min(...J.map((G)=>G.length-G.trimStart().length)),$=J.map((G)=>G.slice(Q)).map((G)=>" ".repeat(this.indent*2)+G);for(let G of $)this.content.push(G)}compile(){let Y=Function,X=this?.args,Q=[...(this?.content??[""]).map(($)=>` ${$}`)];return new Y(...X,Q.join(`
118
- `))}}var LQ={major:4,minor:1,patch:8};var n=q("$ZodType",(Y,X)=>{var J;Y??(Y={}),Y._zod.def=X,Y._zod.bag=Y._zod.bag||{},Y._zod.version=LQ;let Q=[...Y._zod.def.checks??[]];if(Y._zod.traits.has("$ZodCheck"))Q.unshift(Y);for(let $ of Q)for(let G of $._zod.onattach)G(Y);if(Q.length===0)(J=Y._zod).deferred??(J.deferred=[]),Y._zod.deferred?.push(()=>{Y._zod.run=Y._zod.parse});else{let $=(W,K,U)=>{let H=$1(W),N;for(let O of K){if(O._zod.def.when){if(!O._zod.def.when(W))continue}else if(H)continue;let B=W.issues.length,L=O._zod.check(W);if(L instanceof Promise&&U?.async===!1)throw new d0;if(N||L instanceof Promise)N=(N??Promise.resolve()).then(async()=>{if(await L,W.issues.length===B)return;if(!H)H=$1(W,B)});else{if(W.issues.length===B)continue;if(!H)H=$1(W,B)}}if(N)return N.then(()=>{return W});return W},G=(W,K,U)=>{if($1(W))return W.aborted=!0,W;let H=$(K,Q,U);if(H instanceof Promise){if(U.async===!1)throw new d0;return H.then((N)=>Y._zod.parse(N,U))}return Y._zod.parse(H,U)};Y._zod.run=(W,K)=>{if(K.skipChecks)return Y._zod.parse(W,K);if(K.direction==="backward"){let H=Y._zod.parse({value:W.value,issues:[]},{...K,skipChecks:!0});if(H instanceof Promise)return H.then((N)=>{return G(N,W,K)});return G(H,W,K)}let U=Y._zod.parse(W,K);if(U instanceof Promise){if(K.async===!1)throw new d0;return U.then((H)=>$(H,Q,K))}return $(U,Q,K)}}Y["~standard"]={validate:($)=>{try{let G=N6(Y,$);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return V6(Y,$).then((W)=>W.success?{value:W.data}:{issues:W.error?.issues})}},vendor:"zod",version:1}}),xY=q("$ZodString",(Y,X)=>{n.init(Y,X),Y._zod.pattern=[...Y?._zod.bag?.patterns??[]].pop()??l6(Y._zod.bag),Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=String(J.value)}catch($){}if(typeof J.value==="string")return J;return J.issues.push({expected:"string",code:"invalid_type",input:J.value,inst:Y}),J}}),r=q("$ZodStringFormat",(Y,X)=>{s1.init(Y,X),xY.init(Y,X)}),DQ=q("$ZodGUID",(Y,X)=>{X.pattern??(X.pattern=_6),r.init(Y,X)}),PQ=q("$ZodUUID",(Y,X)=>{if(X.version){let Q={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[X.version];if(Q===void 0)throw Error(`Invalid UUID version: "${X.version}"`);X.pattern??(X.pattern=l8(Q))}else X.pattern??(X.pattern=l8());r.init(Y,X)}),wQ=q("$ZodEmail",(Y,X)=>{X.pattern??(X.pattern=I6),r.init(Y,X)}),EQ=q("$ZodURL",(Y,X)=>{r.init(Y,X),Y._zod.check=(J)=>{try{let Q=J.value.trim(),$=new URL(Q);if(X.hostname){if(X.hostname.lastIndex=0,!X.hostname.test($.hostname))J.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:g6.source,input:J.value,inst:Y,continue:!X.abort})}if(X.protocol){if(X.protocol.lastIndex=0,!X.protocol.test($.protocol.endsWith(":")?$.protocol.slice(0,-1):$.protocol))J.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:X.protocol.source,input:J.value,inst:Y,continue:!X.abort})}if(X.normalize)J.value=$.href;else J.value=Q;return}catch(Q){J.issues.push({code:"invalid_format",format:"url",input:J.value,inst:Y,continue:!X.abort})}}}),MQ=q("$ZodEmoji",(Y,X)=>{X.pattern??(X.pattern=S6()),r.init(Y,X)}),AQ=q("$ZodNanoID",(Y,X)=>{X.pattern??(X.pattern=T6),r.init(Y,X)}),RQ=q("$ZodCUID",(Y,X)=>{X.pattern??(X.pattern=w6),r.init(Y,X)}),TQ=q("$ZodCUID2",(Y,X)=>{X.pattern??(X.pattern=E6),r.init(Y,X)}),CQ=q("$ZodULID",(Y,X)=>{X.pattern??(X.pattern=M6),r.init(Y,X)}),_Q=q("$ZodXID",(Y,X)=>{X.pattern??(X.pattern=A6),r.init(Y,X)}),IQ=q("$ZodKSUID",(Y,X)=>{X.pattern??(X.pattern=R6),r.init(Y,X)}),SQ=q("$ZodISODateTime",(Y,X)=>{X.pattern??(X.pattern=p6(X)),r.init(Y,X)}),kQ=q("$ZodISODate",(Y,X)=>{X.pattern??(X.pattern=m6),r.init(Y,X)}),bQ=q("$ZodISOTime",(Y,X)=>{X.pattern??(X.pattern=u6(X)),r.init(Y,X)}),xQ=q("$ZodISODuration",(Y,X)=>{X.pattern??(X.pattern=C6),r.init(Y,X)}),vQ=q("$ZodIPv4",(Y,X)=>{X.pattern??(X.pattern=k6),r.init(Y,X),Y._zod.onattach.push((J)=>{let Q=J._zod.bag;Q.format="ipv4"})}),hQ=q("$ZodIPv6",(Y,X)=>{X.pattern??(X.pattern=b6),r.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})}}}),gQ=q("$ZodCIDRv4",(Y,X)=>{X.pattern??(X.pattern=x6),r.init(Y,X)}),yQ=q("$ZodCIDRv6",(Y,X)=>{X.pattern??(X.pattern=v6),r.init(Y,X),Y._zod.check=(J)=>{let Q=J.value.split("/");try{if(Q.length!==2)throw Error();let[$,G]=Q;if(!G)throw Error();let W=Number(G);if(`${W}`!==G)throw Error();if(W<0||W>128)throw Error();new URL(`http://[${$}]`)}catch{J.issues.push({code:"invalid_format",format:"cidrv6",input:J.value,inst:Y,continue:!X.abort})}}});function fQ(Y){if(Y==="")return!0;if(Y.length%4!==0)return!1;try{return atob(Y),!0}catch{return!1}}var mQ=q("$ZodBase64",(Y,X)=>{X.pattern??(X.pattern=h6),r.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64"}),Y._zod.check=(J)=>{if(fQ(J.value))return;J.issues.push({code:"invalid_format",format:"base64",input:J.value,inst:Y,continue:!X.abort})}});function Xz(Y){if(!d8.test(Y))return!1;let X=Y.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),J=X.padEnd(Math.ceil(X.length/4)*4,"=");return fQ(J)}var cQ=q("$ZodBase64URL",(Y,X)=>{X.pattern??(X.pattern=d8),r.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64url"}),Y._zod.check=(J)=>{if(Xz(J.value))return;J.issues.push({code:"invalid_format",format:"base64url",input:J.value,inst:Y,continue:!X.abort})}}),uQ=q("$ZodE164",(Y,X)=>{X.pattern??(X.pattern=y6),r.init(Y,X)});function Jz(Y,X=null){try{let J=Y.split(".");if(J.length!==3)return!1;let[Q]=J;if(!Q)return!1;let $=JSON.parse(atob(Q));if("typ"in $&&$?.typ!=="JWT")return!1;if(!$.alg)return!1;if(X&&(!("alg"in $)||$.alg!==X))return!1;return!0}catch{return!1}}var pQ=q("$ZodJWT",(Y,X)=>{r.init(Y,X),Y._zod.check=(J)=>{if(Jz(J.value,X.alg))return;J.issues.push({code:"invalid_format",format:"jwt",input:J.value,inst:Y,continue:!X.abort})}});var s8=q("$ZodNumber",(Y,X)=>{n.init(Y,X),Y._zod.pattern=Y._zod.bag.pattern??i6,Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=Number(J.value)}catch(W){}let $=J.value;if(typeof $==="number"&&!Number.isNaN($)&&Number.isFinite($))return J;let G=typeof $==="number"?Number.isNaN($)?"NaN":!Number.isFinite($)?"Infinity":void 0:void 0;return J.issues.push({expected:"number",code:"invalid_type",input:$,inst:Y,...G?{received:G}:{}}),J}}),lQ=q("$ZodNumber",(Y,X)=>{e6.init(Y,X),s8.init(Y,X)}),dQ=q("$ZodBoolean",(Y,X)=>{n.init(Y,X),Y._zod.pattern=n6,Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=Boolean(J.value)}catch(G){}let $=J.value;if(typeof $==="boolean")return J;return J.issues.push({expected:"boolean",code:"invalid_type",input:$,inst:Y}),J}});var iQ=q("$ZodNull",(Y,X)=>{n.init(Y,X),Y._zod.pattern=o6,Y._zod.values=new Set([null]),Y._zod.parse=(J,Q)=>{let $=J.value;if($===null)return J;return J.issues.push({expected:"null",code:"invalid_type",input:$,inst:Y}),J}});var nQ=q("$ZodUnknown",(Y,X)=>{n.init(Y,X),Y._zod.parse=(J)=>J}),oQ=q("$ZodNever",(Y,X)=>{n.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(...n0(J,Y.issues));X.value[J]=Y.value}var rQ=q("$ZodArray",(Y,X)=>{n.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value;if(!Array.isArray($))return J.issues.push({expected:"array",code:"invalid_type",input:$,inst:Y}),J;J.value=Array($.length);let G=[];for(let W=0;W<$.length;W++){let K=$[W],U=X.element._zod.run({value:K,issues:[]},Q);if(U instanceof Promise)G.push(U.then((H)=>NQ(H,J,W)));else NQ(U,J,W)}if(G.length)return Promise.all(G).then(()=>J);return J}});function bY(Y,X,J,Q){if(Y.issues.length)X.issues.push(...n0(J,Y.issues));if(Y.value===void 0){if(J in Q)X.value[J]=void 0}else X.value[J]=Y.value}function sQ(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=c8(Y.shape);return{...Y,keys:X,keySet:new Set(X),numKeys:X.length,optionalKeys:new Set(J)}}function aQ(Y,X,J,Q,$,G){let W=[],K=$.keySet,U=$.catchall._zod,H=U.def.type;for(let N of Object.keys(X)){if(K.has(N))continue;if(H==="never"){W.push(N);continue}let O=U.run({value:X[N],issues:[]},Q);if(O instanceof Promise)Y.push(O.then((B)=>bY(B,J,N,X)));else bY(O,J,N,X)}if(W.length)J.issues.push({code:"unrecognized_keys",keys:W,input:X,inst:G});if(!Y.length)return J;return Promise.all(Y).then(()=>{return J})}var Qz=q("$ZodObject",(Y,X)=>{n.init(Y,X);let J=I1(()=>sQ(X));l(Y._zod,"propValues",()=>{let W=X.shape,K={};for(let U in W){let H=W[U]._zod;if(H.values){K[U]??(K[U]=new Set);for(let N of H.values)K[U].add(N)}}return K});let Q=B1,$=X.catchall,G;Y._zod.parse=(W,K)=>{G??(G=J.value);let U=W.value;if(!Q(U))return W.issues.push({expected:"object",code:"invalid_type",input:U,inst:Y}),W;W.value={};let H=[],N=G.shape;for(let O of G.keys){let L=N[O]._zod.run({value:U[O],issues:[]},K);if(L instanceof Promise)H.push(L.then((Z)=>bY(Z,W,O,U)));else bY(L,W,O,U)}if(!$)return H.length?Promise.all(H).then(()=>W):W;return aQ(H,U,W,K,J.value,Y)}}),tQ=q("$ZodObjectJIT",(Y,X)=>{Qz.init(Y,X);let J=Y._zod.parse,Q=I1(()=>sQ(X)),$=(B)=>{let L=new o8(["shape","payload","ctx"]),Z=Q.value,j=(b)=>{let _=RY(b);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};L.write("const input = payload.value;");let P=Object.create(null),S=0;for(let b of Z.keys)P[b]=`key_${S++}`;L.write("const newResult = {};");for(let b of Z.keys){let _=P[b],u=RY(b);L.write(`const ${_} = ${j(b)};`),L.write(`
119
- if (${_}.issues.length) {
120
- payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
168
+ `))}}var dQ={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=dQ;let Q=[...Y._zod.def.checks??[]];if(Y._zod.traits.has("$ZodCheck"))Q.unshift(Y);for(let $ of Q)for(let G of $._zod.onattach)G(Y);if(Q.length===0)(J=Y._zod).deferred??(J.deferred=[]),Y._zod.deferred?.push(()=>{Y._zod.run=Y._zod.parse});else{let $=(W,U,L)=>{let H=V1(W),N;for(let O of U){if(O._zod.def.when){if(!O._zod.def.when(W))continue}else if(H)continue;let Z=W.issues.length,V=O._zod.check(W);if(V instanceof Promise&&L?.async===!1)throw new a0;if(N||V instanceof Promise)N=(N??Promise.resolve()).then(async()=>{if(await V,W.issues.length===Z)return;if(!H)H=V1(W,Z)});else{if(W.issues.length===Z)continue;if(!H)H=V1(W,Z)}}if(N)return N.then(()=>{return W});return W},G=(W,U,L)=>{if(V1(W))return W.aborted=!0,W;let H=$(U,Q,L);if(H instanceof Promise){if(L.async===!1)throw new a0;return H.then((N)=>Y._zod.parse(N,L))}return Y._zod.parse(H,L)};Y._zod.run=(W,U)=>{if(U.skipChecks)return Y._zod.parse(W,U);if(U.direction==="backward"){let H=Y._zod.parse({value:W.value,issues:[]},{...U,skipChecks:!0});if(H instanceof Promise)return H.then((N)=>{return G(N,W,U)});return G(H,W,U)}let L=Y._zod.parse(W,U);if(L instanceof Promise){if(U.async===!1)throw new a0;return L.then((H)=>$(H,Q,U))}return $(L,Q,U)}}Y["~standard"]={validate:($)=>{try{let G=i6(Y,$);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return n6(Y,$).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()??EQ(Y._zod.bag),Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=String(J.value)}catch($){}if(typeof J.value==="string")return J;return J.issues.push({expected:"string",code:"invalid_type",input:J.value,inst:Y}),J}}),s=F("$ZodStringFormat",(Y,X)=>{zY.init(Y,X),iY.init(Y,X)}),Y7=F("$ZodGUID",(Y,X)=>{X.pattern??(X.pattern=HQ),s.init(Y,X)}),X7=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)}),J7=F("$ZodEmail",(Y,X)=>{X.pattern??(X.pattern=LQ),s.init(Y,X)}),Q7=F("$ZodURL",(Y,X)=>{s.init(Y,X),Y._zod.check=(J)=>{try{let Q=J.value.trim(),$=new URL(Q);if(X.hostname){if(X.hostname.lastIndex=0,!X.hostname.test($.hostname))J.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:qQ.source,input:J.value,inst:Y,continue:!X.abort})}if(X.protocol){if(X.protocol.lastIndex=0,!X.protocol.test($.protocol.endsWith(":")?$.protocol.slice(0,-1):$.protocol))J.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:X.protocol.source,input:J.value,inst:Y,continue:!X.abort})}if(X.normalize)J.value=$.href;else J.value=Q;return}catch(Q){J.issues.push({code:"invalid_format",format:"url",input:J.value,inst:Y,continue:!X.abort})}}}),$7=F("$ZodEmoji",(Y,X)=>{X.pattern??(X.pattern=VQ()),s.init(Y,X)}),G7=F("$ZodNanoID",(Y,X)=>{X.pattern??(X.pattern=zQ),s.init(Y,X)}),W7=F("$ZodCUID",(Y,X)=>{X.pattern??(X.pattern=JQ),s.init(Y,X)}),z7=F("$ZodCUID2",(Y,X)=>{X.pattern??(X.pattern=QQ),s.init(Y,X)}),U7=F("$ZodULID",(Y,X)=>{X.pattern??(X.pattern=$Q),s.init(Y,X)}),H7=F("$ZodXID",(Y,X)=>{X.pattern??(X.pattern=GQ),s.init(Y,X)}),L7=F("$ZodKSUID",(Y,X)=>{X.pattern??(X.pattern=WQ),s.init(Y,X)}),V7=F("$ZodISODateTime",(Y,X)=>{X.pattern??(X.pattern=wQ(X)),s.init(Y,X)}),N7=F("$ZodISODate",(Y,X)=>{X.pattern??(X.pattern=DQ),s.init(Y,X)}),B7=F("$ZodISOTime",(Y,X)=>{X.pattern??(X.pattern=MQ(X)),s.init(Y,X)}),Z7=F("$ZodISODuration",(Y,X)=>{X.pattern??(X.pattern=UQ),s.init(Y,X)}),K7=F("$ZodIPv4",(Y,X)=>{X.pattern??(X.pattern=NQ),s.init(Y,X),Y._zod.onattach.push((J)=>{let Q=J._zod.bag;Q.format="ipv4"})}),O7=F("$ZodIPv6",(Y,X)=>{X.pattern??(X.pattern=BQ),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})}}}),q7=F("$ZodCIDRv4",(Y,X)=>{X.pattern??(X.pattern=ZQ),s.init(Y,X)}),F7=F("$ZodCIDRv6",(Y,X)=>{X.pattern??(X.pattern=KQ),s.init(Y,X),Y._zod.check=(J)=>{let Q=J.value.split("/");try{if(Q.length!==2)throw Error();let[$,G]=Q;if(!G)throw Error();let W=Number(G);if(`${W}`!==G)throw Error();if(W<0||W>128)throw Error();new URL(`http://[${$}]`)}catch{J.issues.push({code:"invalid_format",format:"cidrv6",input:J.value,inst:Y,continue:!X.abort})}}});function j7(Y){if(Y==="")return!0;if(Y.length%4!==0)return!1;try{return atob(Y),!0}catch{return!1}}var D7=F("$ZodBase64",(Y,X)=>{X.pattern??(X.pattern=OQ),s.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64"}),Y._zod.check=(J)=>{if(j7(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 j7(J)}var P7=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})}}),M7=F("$ZodE164",(Y,X)=>{X.pattern??(X.pattern=FQ),s.init(Y,X)});function GU(Y,X=null){try{let J=Y.split(".");if(J.length!==3)return!1;let[Q]=J;if(!Q)return!1;let $=JSON.parse(atob(Q));if("typ"in $&&$?.typ!=="JWT")return!1;if(!$.alg)return!1;if(X&&(!("alg"in $)||$.alg!==X))return!1;return!0}catch{return!1}}var w7=F("$ZodJWT",(Y,X)=>{s.init(Y,X),Y._zod.check=(J)=>{if(GU(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??TQ,Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=Number(J.value)}catch(W){}let $=J.value;if(typeof $==="number"&&!Number.isNaN($)&&Number.isFinite($))return J;let G=typeof $==="number"?Number.isNaN($)?"NaN":!Number.isFinite($)?"Infinity":void 0:void 0;return J.issues.push({expected:"number",code:"invalid_type",input:$,inst:Y,...G?{received:G}:{}}),J}}),E7=F("$ZodNumber",(Y,X)=>{bQ.init(Y,X),Z9.init(Y,X)}),A7=F("$ZodBoolean",(Y,X)=>{o.init(Y,X),Y._zod.pattern=RQ,Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=Boolean(J.value)}catch(G){}let $=J.value;if(typeof $==="boolean")return J;return J.issues.push({expected:"boolean",code:"invalid_type",input:$,inst:Y}),J}});var T7=F("$ZodNull",(Y,X)=>{o.init(Y,X),Y._zod.pattern=CQ,Y._zod.values=new Set([null]),Y._zod.parse=(J,Q)=>{let $=J.value;if($===null)return J;return J.issues.push({expected:"null",code:"invalid_type",input:$,inst:Y}),J}});var R7=F("$ZodUnknown",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J)=>J}),C7=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 iQ(Y,X,J){if(Y.issues.length)X.issues.push(...e0(J,Y.issues));X.value[J]=Y.value}var _7=F("$ZodArray",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value;if(!Array.isArray($))return J.issues.push({expected:"array",code:"invalid_type",input:$,inst:Y}),J;J.value=Array($.length);let G=[];for(let W=0;W<$.length;W++){let U=$[W],L=X.element._zod.run({value:U,issues:[]},Q);if(L instanceof Promise)G.push(L.then((H)=>iQ(H,J,W)));else iQ(L,J,W)}if(G.length)return Promise.all(G).then(()=>J);return J}});function dY(Y,X,J,Q){if(Y.issues.length)X.issues.push(...e0(J,Y.issues));if(Y.value===void 0){if(J in Q)X.value[J]=void 0}else X.value[J]=Y.value}function I7(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=G9(Y.shape);return{...Y,keys:X,keySet:new Set(X),numKeys:X.length,optionalKeys:new Set(J)}}function S7(Y,X,J,Q,$,G){let W=[],U=$.keySet,L=$.catchall._zod,H=L.def.type;for(let N of Object.keys(X)){if(U.has(N))continue;if(H==="never"){W.push(N);continue}let O=L.run({value:X[N],issues:[]},Q);if(O instanceof Promise)Y.push(O.then((Z)=>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:G});if(!Y.length)return J;return Promise.all(Y).then(()=>{return J})}var WU=F("$ZodObject",(Y,X)=>{o.init(Y,X);let J=m1(()=>I7(X));l(Y._zod,"propValues",()=>{let W=X.shape,U={};for(let L in W){let H=W[L]._zod;if(H.values){U[L]??(U[L]=new Set);for(let N of H.values)U[L].add(N)}}return U});let Q=M1,$=X.catchall,G;Y._zod.parse=(W,U)=>{G??(G=J.value);let L=W.value;if(!Q(L))return W.issues.push({expected:"object",code:"invalid_type",input:L,inst:Y}),W;W.value={};let H=[],N=G.shape;for(let O of G.keys){let V=N[O]._zod.run({value:L[O],issues:[]},U);if(V instanceof Promise)H.push(V.then((K)=>dY(K,W,O,L)));else dY(V,W,O,L)}if(!$)return H.length?Promise.all(H).then(()=>W):W;return S7(H,L,W,U,J.value,Y)}}),k7=F("$ZodObjectJIT",(Y,X)=>{WU.init(Y,X);let J=Y._zod.parse,Q=m1(()=>I7(X)),$=(Z)=>{let V=new N9(["shape","payload","ctx"]),K=Q.value,j=(x)=>{let R=yY(x);return`shape[${R}]._zod.run({ value: input[${R}], issues: [] }, ctx)`};V.write("const input = payload.value;");let M=Object.create(null),I=0;for(let x of K.keys)M[x]=`key_${I++}`;V.write("const newResult = {};");for(let x of K.keys){let R=M[x],p=yY(x);V.write(`const ${R} = ${j(x)};`),V.write(`
169
+ if (${R}.issues.length) {
170
+ payload.issues = payload.issues.concat(${R}.issues.map(iss => ({
121
171
  ...iss,
122
- path: iss.path ? [${u}, ...iss.path] : [${u}]
172
+ path: iss.path ? [${p}, ...iss.path] : [${p}]
123
173
  })));
124
174
  }
125
175
 
126
176
 
127
- if (${_}.value === undefined) {
128
- if (${u} in input) {
129
- newResult[${u}] = undefined;
177
+ if (${R}.value === undefined) {
178
+ if (${p} in input) {
179
+ newResult[${p}] = undefined;
130
180
  }
131
181
  } else {
132
- newResult[${u}] = ${_}.value;
182
+ newResult[${p}] = ${R}.value;
133
183
  }
134
184
 
135
- `)}L.write("payload.value = newResult;"),L.write("return payload;");let E=L.compile();return(b,_)=>E(B,b,_)},G,W=B1,K=!AY.jitless,H=K&&f8.value,N=X.catchall,O;Y._zod.parse=(B,L)=>{O??(O=Q.value);let Z=B.value;if(!W(Z))return B.issues.push({expected:"object",code:"invalid_type",input:Z,inst:Y}),B;if(K&&H&&L?.async===!1&&L.jitless!==!0){if(!G)G=$(X.shape);if(B=G(B,L),!N)return B;return aQ([],Z,B,L,O,Y)}return J(B,L)}});function VQ(Y,X,J,Q){for(let G of Y)if(G.issues.length===0)return X.value=G.value,X;let $=Y.filter((G)=>!$1(G));if($.length===1)return X.value=$[0].value,$[0];return X.issues.push({code:"invalid_union",input:X.value,inst:J,errors:Y.map((G)=>G.issues.map((W)=>_0(W,Q,h0())))}),X}var a8=q("$ZodUnion",(Y,X)=>{n.init(Y,X),l(Y._zod,"optin",()=>X.options.some(($)=>$._zod.optin==="optional")?"optional":void 0),l(Y._zod,"optout",()=>X.options.some(($)=>$._zod.optout==="optional")?"optional":void 0),l(Y._zod,"values",()=>{if(X.options.every(($)=>$._zod.values))return new Set(X.options.flatMap(($)=>Array.from($._zod.values)));return}),l(Y._zod,"pattern",()=>{if(X.options.every(($)=>$._zod.pattern)){let $=X.options.map((G)=>G._zod.pattern);return new RegExp(`^(${$.map((G)=>i1(G.source)).join("|")})$`)}return});let J=X.options.length===1,Q=X.options[0]._zod.run;Y._zod.parse=($,G)=>{if(J)return Q($,G);let W=!1,K=[];for(let U of X.options){let H=U._zod.run({value:$.value,issues:[]},G);if(H instanceof Promise)K.push(H),W=!0;else{if(H.issues.length===0)return H;K.push(H)}}if(!W)return VQ(K,$,Y,G);return Promise.all(K).then((U)=>{return VQ(U,$,Y,G)})}}),eQ=q("$ZodDiscriminatedUnion",(Y,X)=>{a8.init(Y,X);let J=Y._zod.parse;l(Y._zod,"propValues",()=>{let $={};for(let G of X.options){let W=G._zod.propValues;if(!W||Object.keys(W).length===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf(G)}"`);for(let[K,U]of Object.entries(W)){if(!$[K])$[K]=new Set;for(let H of U)$[K].add(H)}}return $});let Q=I1(()=>{let $=X.options,G=new Map;for(let W of $){let K=W._zod.propValues?.[X.discriminator];if(!K||K.size===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf(W)}"`);for(let U of K){if(G.has(U))throw Error(`Duplicate discriminator value "${String(U)}"`);G.set(U,W)}}return G});Y._zod.parse=($,G)=>{let W=$.value;if(!B1(W))return $.issues.push({code:"invalid_type",expected:"object",input:W,inst:Y}),$;let K=Q.value.get(W?.[X.discriminator]);if(K)return K._zod.run($,G);if(X.unionFallback)return J($,G);return $.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:X.discriminator,input:W,path:[X.discriminator],inst:Y}),$}}),Y7=q("$ZodIntersection",(Y,X)=>{n.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value,G=X.left._zod.run({value:$,issues:[]},Q),W=X.right._zod.run({value:$,issues:[]},Q);if(G instanceof Promise||W instanceof Promise)return Promise.all([G,W]).then(([U,H])=>{return BQ(J,U,H)});return BQ(J,G,W)}});function r8(Y,X){if(Y===X)return{valid:!0,data:Y};if(Y instanceof Date&&X instanceof Date&&+Y===+X)return{valid:!0,data:Y};if(Q1(Y)&&Q1(X)){let J=Object.keys(X),Q=Object.keys(Y).filter((G)=>J.indexOf(G)!==-1),$={...Y,...X};for(let G of Q){let W=r8(Y[G],X[G]);if(!W.valid)return{valid:!1,mergeErrorPath:[G,...W.mergeErrorPath]};$[G]=W.data}return{valid:!0,data:$}}if(Array.isArray(Y)&&Array.isArray(X)){if(Y.length!==X.length)return{valid:!1,mergeErrorPath:[]};let J=[];for(let Q=0;Q<Y.length;Q++){let $=Y[Q],G=X[Q],W=r8($,G);if(!W.valid)return{valid:!1,mergeErrorPath:[Q,...W.mergeErrorPath]};J.push(W.data)}return{valid:!0,data:J}}return{valid:!1,mergeErrorPath:[]}}function BQ(Y,X,J){if(X.issues.length)Y.issues.push(...X.issues);if(J.issues.length)Y.issues.push(...J.issues);if($1(Y))return Y;let Q=r8(X.value,J.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return Y.value=Q.data,Y}var X7=q("$ZodRecord",(Y,X)=>{n.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value;if(!Q1($))return J.issues.push({expected:"record",code:"invalid_type",input:$,inst:Y}),J;let G=[];if(X.keyType._zod.values){let W=X.keyType._zod.values;J.value={};for(let U of W)if(typeof U==="string"||typeof U==="number"||typeof U==="symbol"){let H=X.valueType._zod.run({value:$[U],issues:[]},Q);if(H instanceof Promise)G.push(H.then((N)=>{if(N.issues.length)J.issues.push(...n0(U,N.issues));J.value[U]=N.value}));else{if(H.issues.length)J.issues.push(...n0(U,H.issues));J.value[U]=H.value}}let K;for(let U in $)if(!W.has(U))K=K??[],K.push(U);if(K&&K.length>0)J.issues.push({code:"unrecognized_keys",input:$,inst:Y,keys:K})}else{J.value={};for(let W of Reflect.ownKeys($)){if(W==="__proto__")continue;let K=X.keyType._zod.run({value:W,issues:[]},Q);if(K instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(K.issues.length){J.issues.push({code:"invalid_key",origin:"record",issues:K.issues.map((H)=>_0(H,Q,h0())),input:W,path:[W],inst:Y}),J.value[K.value]=K.value;continue}let U=X.valueType._zod.run({value:$[W],issues:[]},Q);if(U instanceof Promise)G.push(U.then((H)=>{if(H.issues.length)J.issues.push(...n0(W,H.issues));J.value[K.value]=H.value}));else{if(U.issues.length)J.issues.push(...n0(W,U.issues));J.value[K.value]=U.value}}}if(G.length)return Promise.all(G).then(()=>J);return J}});var J7=q("$ZodEnum",(Y,X)=>{n.init(Y,X);let J=l1(X.entries),Q=new Set(J);Y._zod.values=Q,Y._zod.pattern=new RegExp(`^(${J.filter(($)=>m8.has(typeof $)).map(($)=>typeof $==="string"?i0($):$.toString()).join("|")})$`),Y._zod.parse=($,G)=>{let W=$.value;if(Q.has(W))return $;return $.issues.push({code:"invalid_value",values:J,input:W,inst:Y}),$}}),Q7=q("$ZodLiteral",(Y,X)=>{if(n.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"?i0(J):J?i0(J.toString()):String(J)).join("|")})$`),Y._zod.parse=(J,Q)=>{let $=J.value;if(Y._zod.values.has($))return J;return J.issues.push({code:"invalid_value",values:X.values,input:$,inst:Y}),J}});var $7=q("$ZodTransform",(Y,X)=>{n.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new u1(Y.constructor.name);let $=X.transform(J.value,J);if(Q.async)return($ instanceof Promise?$:Promise.resolve($)).then((W)=>{return J.value=W,J});if($ instanceof Promise)throw new d0;return J.value=$,J}});function ZQ(Y,X){if(Y.issues.length&&X===void 0)return{issues:[],value:void 0};return Y}var G7=q("$ZodOptional",(Y,X)=>{n.init(Y,X),Y._zod.optin="optional",Y._zod.optout="optional",l(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,void 0]):void 0}),l(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${i1(J.source)})?$`):void 0}),Y._zod.parse=(J,Q)=>{if(X.innerType._zod.optin==="optional"){let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>ZQ(G,J.value));return ZQ($,J.value)}if(J.value===void 0)return J;return X.innerType._zod.run(J,Q)}}),W7=q("$ZodNullable",(Y,X)=>{n.init(Y,X),l(Y._zod,"optin",()=>X.innerType._zod.optin),l(Y._zod,"optout",()=>X.innerType._zod.optout),l(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${i1(J.source)}|null)$`):void 0}),l(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,null]):void 0}),Y._zod.parse=(J,Q)=>{if(J.value===null)return J;return X.innerType._zod.run(J,Q)}}),z7=q("$ZodDefault",(Y,X)=>{n.init(Y,X),Y._zod.optin="optional",l(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);if(J.value===void 0)return J.value=X.defaultValue,J;let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>OQ(G,X));return OQ($,X)}});function OQ(Y,X){if(Y.value===void 0)Y.value=X.defaultValue;return Y}var K7=q("$ZodPrefault",(Y,X)=>{n.init(Y,X),Y._zod.optin="optional",l(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);if(J.value===void 0)J.value=X.defaultValue;return X.innerType._zod.run(J,Q)}}),U7=q("$ZodNonOptional",(Y,X)=>{n.init(Y,X),l(Y._zod,"values",()=>{let J=X.innerType._zod.values;return J?new Set([...J].filter((Q)=>Q!==void 0)):void 0}),Y._zod.parse=(J,Q)=>{let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>FQ(G,Y));return FQ($,Y)}});function FQ(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 H7=q("$ZodCatch",(Y,X)=>{n.init(Y,X),l(Y._zod,"optin",()=>X.innerType._zod.optin),l(Y._zod,"optout",()=>X.innerType._zod.optout),l(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>{if(J.value=G.value,G.issues.length)J.value=X.catchValue({...J,error:{issues:G.issues.map((W)=>_0(W,Q,h0()))},input:J.value}),J.issues=[];return J});if(J.value=$.value,$.issues.length)J.value=X.catchValue({...J,error:{issues:$.issues.map((G)=>_0(G,Q,h0()))},input:J.value}),J.issues=[];return J}});var L7=q("$ZodPipe",(Y,X)=>{n.init(Y,X),l(Y._zod,"values",()=>X.in._zod.values),l(Y._zod,"optin",()=>X.in._zod.optin),l(Y._zod,"optout",()=>X.out._zod.optout),l(Y._zod,"propValues",()=>X.in._zod.propValues),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward"){let G=X.out._zod.run(J,Q);if(G instanceof Promise)return G.then((W)=>kY(W,X.in,Q));return kY(G,X.in,Q)}let $=X.in._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>kY(G,X.out,Q));return kY($,X.out,Q)}});function kY(Y,X,J){if(Y.issues.length)return Y.aborted=!0,Y;return X._zod.run({value:Y.value,issues:Y.issues},J)}var N7=q("$ZodReadonly",(Y,X)=>{n.init(Y,X),l(Y._zod,"propValues",()=>X.innerType._zod.propValues),l(Y._zod,"values",()=>X.innerType._zod.values),l(Y._zod,"optin",()=>X.innerType._zod.optin),l(Y._zod,"optout",()=>X.innerType._zod.optout),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then(qQ);return qQ($)}});function qQ(Y){return Y.value=Object.freeze(Y.value),Y}var V7=q("$ZodLazy",(Y,X)=>{n.init(Y,X),l(Y._zod,"innerType",()=>X.getter()),l(Y._zod,"pattern",()=>Y._zod.innerType._zod.pattern),l(Y._zod,"propValues",()=>Y._zod.innerType._zod.propValues),l(Y._zod,"optin",()=>Y._zod.innerType._zod.optin??void 0),l(Y._zod,"optout",()=>Y._zod.innerType._zod.optout??void 0),Y._zod.parse=(J,Q)=>{return Y._zod.innerType._zod.run(J,Q)}}),B7=q("$ZodCustom",(Y,X)=>{L0.init(Y,X),n.init(Y,X),Y._zod.parse=(J,Q)=>{return J},Y._zod.check=(J)=>{let Q=J.value,$=X.fn(Q);if($ instanceof Promise)return $.then((G)=>jQ(G,J,Q,Y));jQ($,J,Q,Y);return}});function jQ(Y,X,J,Q){if(!Y){let $={code:"custom",input:J,inst:Q,path:[...Q._zod.def.path??[]],continue:!Q._zod.def.abort};if(Q._zod.def.params)$.params=Q._zod.def.params;X.issues.push(S1($))}}var xB=Symbol("ZodOutput"),vB=Symbol("ZodInput");class vY{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Y,...X){let J=X[0];if(this._map.set(Y,J),J&&typeof J==="object"&&"id"in J){if(this._idmap.has(J.id))throw Error(`ID ${J.id} already exists in the registry`);this._idmap.set(J.id,Y)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Y){let X=this._map.get(Y);if(X&&typeof X==="object"&&"id"in X)this._idmap.delete(X.id);return this._map.delete(Y),this}get(Y){let X=Y._zod.parent;if(X){let J={...this.get(X)??{}};delete J.id;let Q={...J,...this._map.get(Y)};return Object.keys(Q).length?Q:void 0}return this._map.get(Y)}has(Y){return this._map.has(Y)}}function $z(){return new vY}var Z1=$z();function Z7(Y,X){return new Y({type:"string",...v(X)})}function O7(Y,X){return new Y({type:"string",format:"email",check:"string_format",abort:!1,...v(X)})}function t8(Y,X){return new Y({type:"string",format:"guid",check:"string_format",abort:!1,...v(X)})}function F7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...v(X)})}function q7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...v(X)})}function j7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...v(X)})}function D7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...v(X)})}function P7(Y,X){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...v(X)})}function w7(Y,X){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...v(X)})}function E7(Y,X){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...v(X)})}function M7(Y,X){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...v(X)})}function A7(Y,X){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...v(X)})}function R7(Y,X){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...v(X)})}function T7(Y,X){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...v(X)})}function C7(Y,X){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...v(X)})}function _7(Y,X){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...v(X)})}function I7(Y,X){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...v(X)})}function S7(Y,X){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...v(X)})}function k7(Y,X){return new Y({type:"string",format:"cidrv6",check:"string_format",abort:!1,...v(X)})}function b7(Y,X){return new Y({type:"string",format:"base64",check:"string_format",abort:!1,...v(X)})}function x7(Y,X){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...v(X)})}function v7(Y,X){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...v(X)})}function h7(Y,X){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...v(X)})}function g7(Y,X){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...v(X)})}function y7(Y,X){return new Y({type:"string",format:"date",check:"string_format",...v(X)})}function f7(Y,X){return new Y({type:"string",format:"time",check:"string_format",precision:null,...v(X)})}function m7(Y,X){return new Y({type:"string",format:"duration",check:"string_format",...v(X)})}function c7(Y,X){return new Y({type:"number",checks:[],...v(X)})}function u7(Y,X){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...v(X)})}function p7(Y,X){return new Y({type:"boolean",...v(X)})}function l7(Y,X){return new Y({type:"null",...v(X)})}function d7(Y){return new Y({type:"unknown"})}function i7(Y,X){return new Y({type:"never",...v(X)})}function hY(Y,X){return new i8({check:"less_than",...v(X),value:Y,inclusive:!1})}function a1(Y,X){return new i8({check:"less_than",...v(X),value:Y,inclusive:!0})}function gY(Y,X){return new n8({check:"greater_than",...v(X),value:Y,inclusive:!1})}function t1(Y,X){return new n8({check:"greater_than",...v(X),value:Y,inclusive:!0})}function yY(Y,X){return new t6({check:"multiple_of",...v(X),value:Y})}function fY(Y,X){return new YQ({check:"max_length",...v(X),maximum:Y})}function k1(Y,X){return new XQ({check:"min_length",...v(X),minimum:Y})}function mY(Y,X){return new JQ({check:"length_equals",...v(X),length:Y})}function e8(Y,X){return new QQ({check:"string_format",format:"regex",...v(X),pattern:Y})}function Y9(Y){return new $Q({check:"string_format",format:"lowercase",...v(Y)})}function X9(Y){return new GQ({check:"string_format",format:"uppercase",...v(Y)})}function J9(Y,X){return new WQ({check:"string_format",format:"includes",...v(X),includes:Y})}function Q9(Y,X){return new zQ({check:"string_format",format:"starts_with",...v(X),prefix:Y})}function $9(Y,X){return new KQ({check:"string_format",format:"ends_with",...v(X),suffix:Y})}function O1(Y){return new UQ({check:"overwrite",tx:Y})}function G9(Y){return O1((X)=>X.normalize(Y))}function W9(){return O1((Y)=>Y.trim())}function z9(){return O1((Y)=>Y.toLowerCase())}function K9(){return O1((Y)=>Y.toUpperCase())}function n7(Y,X,J){return new Y({type:"array",element:X,...v(J)})}function o7(Y,X,J){let Q=v(J);return Q.abort??(Q.abort=!0),new Y({type:"custom",check:"custom",fn:X,...Q})}function r7(Y,X,J){return new Y({type:"custom",check:"custom",fn:X,...v(J)})}function s7(Y){let X=Gz((J)=>{return J.addIssue=(Q)=>{if(typeof Q==="string")J.issues.push(S1(Q,J.value,X._zod.def));else{let $=Q;if($.fatal)$.continue=!1;$.code??($.code="custom"),$.input??($.input=J.value),$.inst??($.inst=X),$.continue??($.continue=!X._zod.def.abort),J.issues.push(S1($))}},Y(J.value,J)});return X}function Gz(Y,X){let J=new L0({check:"custom",...v(X)});return J._zod.check=Y,J}class U9{constructor(Y){this.counter=0,this.metadataRegistry=Y?.metadata??Z1,this.target=Y?.target??"draft-2020-12",this.unrepresentable=Y?.unrepresentable??"throw",this.override=Y?.override??(()=>{}),this.io=Y?.io??"output",this.seen=new Map}process(Y,X={path:[],schemaPath:[]}){var J;let Q=Y._zod.def,$={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},G=this.seen.get(Y);if(G){if(G.count++,X.schemaPath.includes(Y))G.cycle=X.path;return G.schema}let W={schema:{},count:1,cycle:void 0,path:X.path};this.seen.set(Y,W);let K=Y._zod.toJSONSchema?.();if(K)W.schema=K;else{let N={...X,schemaPath:[...X.schemaPath,Y],path:X.path},O=Y._zod.parent;if(O)W.ref=O,this.process(O,N),this.seen.get(O).isParent=!0;else{let B=W.schema;switch(Q.type){case"string":{let L=B;L.type="string";let{minimum:Z,maximum:j,format:P,patterns:S,contentEncoding:E}=Y._zod.bag;if(typeof Z==="number")L.minLength=Z;if(typeof j==="number")L.maxLength=j;if(P){if(L.format=$[P]??P,L.format==="")delete L.format}if(E)L.contentEncoding=E;if(S&&S.size>0){let b=[...S];if(b.length===1)L.pattern=b[0].source;else if(b.length>1)W.schema.allOf=[...b.map((_)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:_.source}))]}break}case"number":{let L=B,{minimum:Z,maximum:j,format:P,multipleOf:S,exclusiveMaximum:E,exclusiveMinimum:b}=Y._zod.bag;if(typeof P==="string"&&P.includes("int"))L.type="integer";else L.type="number";if(typeof b==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")L.minimum=b,L.exclusiveMinimum=!0;else L.exclusiveMinimum=b;if(typeof Z==="number"){if(L.minimum=Z,typeof b==="number"&&this.target!=="draft-4")if(b>=Z)delete L.minimum;else delete L.exclusiveMinimum}if(typeof E==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")L.maximum=E,L.exclusiveMaximum=!0;else L.exclusiveMaximum=E;if(typeof j==="number"){if(L.maximum=j,typeof E==="number"&&this.target!=="draft-4")if(E<=j)delete L.maximum;else delete L.exclusiveMaximum}if(typeof S==="number")L.multipleOf=S;break}case"boolean":{let L=B;L.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema");break}case"null":{if(this.target==="openapi-3.0")B.type="string",B.nullable=!0,B.enum=[null];else B.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema");break}case"never":{B.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let L=B,{minimum:Z,maximum:j}=Y._zod.bag;if(typeof Z==="number")L.minItems=Z;if(typeof j==="number")L.maxItems=j;L.type="array",L.items=this.process(Q.element,{...N,path:[...N.path,"items"]});break}case"object":{let L=B;L.type="object",L.properties={};let Z=Q.shape;for(let S in Z)L.properties[S]=this.process(Z[S],{...N,path:[...N.path,"properties",S]});let j=new Set(Object.keys(Z)),P=new Set([...j].filter((S)=>{let E=Q.shape[S]._zod;if(this.io==="input")return E.optin===void 0;else return E.optout===void 0}));if(P.size>0)L.required=Array.from(P);if(Q.catchall?._zod.def.type==="never")L.additionalProperties=!1;else if(!Q.catchall){if(this.io==="output")L.additionalProperties=!1}else if(Q.catchall)L.additionalProperties=this.process(Q.catchall,{...N,path:[...N.path,"additionalProperties"]});break}case"union":{let L=B,Z=Q.options.map((j,P)=>this.process(j,{...N,path:[...N.path,"anyOf",P]}));L.anyOf=Z;break}case"intersection":{let L=B,Z=this.process(Q.left,{...N,path:[...N.path,"allOf",0]}),j=this.process(Q.right,{...N,path:[...N.path,"allOf",1]}),P=(E)=>("allOf"in E)&&Object.keys(E).length===1,S=[...P(Z)?Z.allOf:[Z],...P(j)?j.allOf:[j]];L.allOf=S;break}case"tuple":{let L=B;L.type="array";let Z=this.target==="draft-2020-12"?"prefixItems":"items",j=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",P=Q.items.map((_,u)=>this.process(_,{...N,path:[...N.path,Z,u]})),S=Q.rest?this.process(Q.rest,{...N,path:[...N.path,j,...this.target==="openapi-3.0"?[Q.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(L.prefixItems=P,S)L.items=S}else if(this.target==="openapi-3.0"){if(L.items={anyOf:P},S)L.items.anyOf.push(S);if(L.minItems=P.length,!S)L.maxItems=P.length}else if(L.items=P,S)L.additionalItems=S;let{minimum:E,maximum:b}=Y._zod.bag;if(typeof E==="number")L.minItems=E;if(typeof b==="number")L.maxItems=b;break}case"record":{let L=B;if(L.type="object",this.target==="draft-7"||this.target==="draft-2020-12")L.propertyNames=this.process(Q.keyType,{...N,path:[...N.path,"propertyNames"]});L.additionalProperties=this.process(Q.valueType,{...N,path:[...N.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let L=B,Z=l1(Q.entries);if(Z.every((j)=>typeof j==="number"))L.type="number";if(Z.every((j)=>typeof j==="string"))L.type="string";L.enum=Z;break}case"literal":{let L=B,Z=[];for(let j of Q.values)if(j===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof j==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else Z.push(Number(j));else Z.push(j);if(Z.length===0);else if(Z.length===1){let j=Z[0];if(L.type=j===null?"null":typeof j,this.target==="draft-4"||this.target==="openapi-3.0")L.enum=[j];else L.const=j}else{if(Z.every((j)=>typeof j==="number"))L.type="number";if(Z.every((j)=>typeof j==="string"))L.type="string";if(Z.every((j)=>typeof j==="boolean"))L.type="string";if(Z.every((j)=>j===null))L.type="null";L.enum=Z}break}case"file":{let L=B,Z={type:"string",format:"binary",contentEncoding:"binary"},{minimum:j,maximum:P,mime:S}=Y._zod.bag;if(j!==void 0)Z.minLength=j;if(P!==void 0)Z.maxLength=P;if(S)if(S.length===1)Z.contentMediaType=S[0],Object.assign(L,Z);else L.anyOf=S.map((E)=>{return{...Z,contentMediaType:E}});else Object.assign(L,Z);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let L=this.process(Q.innerType,N);if(this.target==="openapi-3.0")W.ref=Q.innerType,B.nullable=!0;else B.anyOf=[L,{type:"null"}];break}case"nonoptional":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"success":{let L=B;L.type="boolean";break}case"default":{this.process(Q.innerType,N),W.ref=Q.innerType,B.default=JSON.parse(JSON.stringify(Q.defaultValue));break}case"prefault":{if(this.process(Q.innerType,N),W.ref=Q.innerType,this.io==="input")B._prefault=JSON.parse(JSON.stringify(Q.defaultValue));break}case"catch":{this.process(Q.innerType,N),W.ref=Q.innerType;let L;try{L=Q.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}B.default=L;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let L=B,Z=Y._zod.pattern;if(!Z)throw Error("Pattern not found in template literal");L.type="string",L.pattern=Z.source;break}case"pipe":{let L=this.io==="input"?Q.in._zod.def.type==="transform"?Q.out:Q.in:Q.out;this.process(L,N),W.ref=L;break}case"readonly":{this.process(Q.innerType,N),W.ref=Q.innerType,B.readOnly=!0;break}case"promise":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"optional":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"lazy":{let L=Y._zod.innerType;this.process(L,N),W.ref=L;break}case"custom":{if(this.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema");break}case"function":{if(this.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema");break}default:}}}let U=this.metadataRegistry.get(Y);if(U)Object.assign(W.schema,U);if(this.io==="input"&&W0(Y))delete W.schema.examples,delete W.schema.default;if(this.io==="input"&&W.schema._prefault)(J=W.schema).default??(J.default=W.schema._prefault);return delete W.schema._prefault,this.seen.get(Y).schema}emit(Y,X){let J={cycles:X?.cycles??"ref",reused:X?.reused??"inline",external:X?.external??void 0},Q=this.seen.get(Y);if(!Q)throw Error("Unprocessed schema. This is a bug in Zod.");let $=(H)=>{let N=this.target==="draft-2020-12"?"$defs":"definitions";if(J.external){let Z=J.external.registry.get(H[0])?.id,j=J.external.uri??((S)=>S);if(Z)return{ref:j(Z)};let P=H[1].defId??H[1].schema.id??`schema${this.counter++}`;return H[1].defId=P,{defId:P,ref:`${j("__shared")}#/${N}/${P}`}}if(H[1]===Q)return{ref:"#"};let B=`${"#"}/${N}/`,L=H[1].schema.id??`__schema${this.counter++}`;return{defId:L,ref:B+L}},G=(H)=>{if(H[1].schema.$ref)return;let N=H[1],{ref:O,defId:B}=$(H);if(N.def={...N.schema},B)N.defId=B;let L=N.schema;for(let Z in L)delete L[Z];L.$ref=O};if(J.cycles==="throw")for(let H of this.seen.entries()){let N=H[1];if(N.cycle)throw Error(`Cycle detected: #/${N.cycle?.join("/")}/<root>
185
+ `)}V.write("payload.value = newResult;"),V.write("return payload;");let E=V.compile();return(x,R)=>E(Z,x,R)},G,W=M1,U=!gY.jitless,H=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&&H&&V?.async===!1&&V.jitless!==!0){if(!G)G=$(X.shape);if(Z=G(Z,V),!N)return Z;return S7([],K,Z,V,O,Y)}return J(Z,V)}});function nQ(Y,X,J,Q){for(let G of Y)if(G.issues.length===0)return X.value=G.value,X;let $=Y.filter((G)=>!V1(G));if($.length===1)return X.value=$[0].value,$[0];return X.issues.push({code:"invalid_union",input:X.value,inst:J,errors:Y.map((G)=>G.issues.map((W)=>S0(W,Q,m0())))}),X}var K9=F("$ZodUnion",(Y,X)=>{o.init(Y,X),l(Y._zod,"optin",()=>X.options.some(($)=>$._zod.optin==="optional")?"optional":void 0),l(Y._zod,"optout",()=>X.options.some(($)=>$._zod.optout==="optional")?"optional":void 0),l(Y._zod,"values",()=>{if(X.options.every(($)=>$._zod.values))return new Set(X.options.flatMap(($)=>Array.from($._zod.values)));return}),l(Y._zod,"pattern",()=>{if(X.options.every(($)=>$._zod.pattern)){let $=X.options.map((G)=>G._zod.pattern);return new RegExp(`^(${$.map((G)=>QY(G.source)).join("|")})$`)}return});let J=X.options.length===1,Q=X.options[0]._zod.run;Y._zod.parse=($,G)=>{if(J)return Q($,G);let W=!1,U=[];for(let L of X.options){let H=L._zod.run({value:$.value,issues:[]},G);if(H instanceof Promise)U.push(H),W=!0;else{if(H.issues.length===0)return H;U.push(H)}}if(!W)return nQ(U,$,Y,G);return Promise.all(U).then((L)=>{return nQ(L,$,Y,G)})}}),b7=F("$ZodDiscriminatedUnion",(Y,X)=>{K9.init(Y,X);let J=Y._zod.parse;l(Y._zod,"propValues",()=>{let $={};for(let G of X.options){let W=G._zod.propValues;if(!W||Object.keys(W).length===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf(G)}"`);for(let[U,L]of Object.entries(W)){if(!$[U])$[U]=new Set;for(let H of L)$[U].add(H)}}return $});let Q=m1(()=>{let $=X.options,G=new Map;for(let W of $){let U=W._zod.propValues?.[X.discriminator];if(!U||U.size===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf(W)}"`);for(let L of U){if(G.has(L))throw Error(`Duplicate discriminator value "${String(L)}"`);G.set(L,W)}}return G});Y._zod.parse=($,G)=>{let W=$.value;if(!M1(W))return $.issues.push({code:"invalid_type",expected:"object",input:W,inst:Y}),$;let U=Q.value.get(W?.[X.discriminator]);if(U)return U._zod.run($,G);if(X.unionFallback)return J($,G);return $.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:X.discriminator,input:W,path:[X.discriminator],inst:Y}),$}}),x7=F("$ZodIntersection",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value,G=X.left._zod.run({value:$,issues:[]},Q),W=X.right._zod.run({value:$,issues:[]},Q);if(G instanceof Promise||W instanceof Promise)return Promise.all([G,W]).then(([L,H])=>{return oQ(J,L,H)});return oQ(J,G,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(L1(Y)&&L1(X)){let J=Object.keys(X),Q=Object.keys(Y).filter((G)=>J.indexOf(G)!==-1),$={...Y,...X};for(let G of Q){let W=B9(Y[G],X[G]);if(!W.valid)return{valid:!1,mergeErrorPath:[G,...W.mergeErrorPath]};$[G]=W.data}return{valid:!0,data:$}}if(Array.isArray(Y)&&Array.isArray(X)){if(Y.length!==X.length)return{valid:!1,mergeErrorPath:[]};let J=[];for(let Q=0;Q<Y.length;Q++){let $=Y[Q],G=X[Q],W=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 oQ(Y,X,J){if(X.issues.length)Y.issues.push(...X.issues);if(J.issues.length)Y.issues.push(...J.issues);if(V1(Y))return Y;let Q=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 v7=F("$ZodRecord",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value;if(!L1($))return J.issues.push({expected:"record",code:"invalid_type",input:$,inst:Y}),J;let G=[];if(X.keyType._zod.values){let W=X.keyType._zod.values;J.value={};for(let L of W)if(typeof L==="string"||typeof L==="number"||typeof L==="symbol"){let H=X.valueType._zod.run({value:$[L],issues:[]},Q);if(H instanceof Promise)G.push(H.then((N)=>{if(N.issues.length)J.issues.push(...e0(L,N.issues));J.value[L]=N.value}));else{if(H.issues.length)J.issues.push(...e0(L,H.issues));J.value[L]=H.value}}let U;for(let L in $)if(!W.has(L))U=U??[],U.push(L);if(U&&U.length>0)J.issues.push({code:"unrecognized_keys",input:$,inst:Y,keys:U})}else{J.value={};for(let W of Reflect.ownKeys($)){if(W==="__proto__")continue;let U=X.keyType._zod.run({value:W,issues:[]},Q);if(U instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(U.issues.length){J.issues.push({code:"invalid_key",origin:"record",issues:U.issues.map((H)=>S0(H,Q,m0())),input:W,path:[W],inst:Y}),J.value[U.value]=U.value;continue}let L=X.valueType._zod.run({value:$[W],issues:[]},Q);if(L instanceof Promise)G.push(L.then((H)=>{if(H.issues.length)J.issues.push(...e0(W,H.issues));J.value[U.value]=H.value}));else{if(L.issues.length)J.issues.push(...e0(W,L.issues));J.value[U.value]=L.value}}}if(G.length)return Promise.all(G).then(()=>J);return J}});var h7=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(($)=>$9.has(typeof $)).map(($)=>typeof $==="string"?t0($):$.toString()).join("|")})$`),Y._zod.parse=($,G)=>{let W=$.value;if(Q.has(W))return $;return $.issues.push({code:"invalid_value",values:J,input:W,inst:Y}),$}}),g7=F("$ZodLiteral",(Y,X)=>{if(o.init(Y,X),X.values.length===0)throw Error("Cannot create literal schema with no valid values");Y._zod.values=new Set(X.values),Y._zod.pattern=new RegExp(`^(${X.values.map((J)=>typeof J==="string"?t0(J):J?t0(J.toString()):String(J)).join("|")})$`),Y._zod.parse=(J,Q)=>{let $=J.value;if(Y._zod.values.has($))return J;return J.issues.push({code:"invalid_value",values:X.values,input:$,inst:Y}),J}});var y7=F("$ZodTransform",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new e1(Y.constructor.name);let $=X.transform(J.value,J);if(Q.async)return($ instanceof Promise?$:Promise.resolve($)).then((W)=>{return J.value=W,J});if($ instanceof Promise)throw new a0;return J.value=$,J}});function rQ(Y,X){if(Y.issues.length&&X===void 0)return{issues:[],value:void 0};return Y}var f7=F("$ZodOptional",(Y,X)=>{o.init(Y,X),Y._zod.optin="optional",Y._zod.optout="optional",l(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,void 0]):void 0}),l(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${QY(J.source)})?$`):void 0}),Y._zod.parse=(J,Q)=>{if(X.innerType._zod.optin==="optional"){let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>rQ(G,J.value));return rQ($,J.value)}if(J.value===void 0)return J;return X.innerType._zod.run(J,Q)}}),m7=F("$ZodNullable",(Y,X)=>{o.init(Y,X),l(Y._zod,"optin",()=>X.innerType._zod.optin),l(Y._zod,"optout",()=>X.innerType._zod.optout),l(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${QY(J.source)}|null)$`):void 0}),l(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,null]):void 0}),Y._zod.parse=(J,Q)=>{if(J.value===null)return J;return X.innerType._zod.run(J,Q)}}),c7=F("$ZodDefault",(Y,X)=>{o.init(Y,X),Y._zod.optin="optional",l(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);if(J.value===void 0)return J.value=X.defaultValue,J;let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>sQ(G,X));return sQ($,X)}});function sQ(Y,X){if(Y.value===void 0)Y.value=X.defaultValue;return Y}var u7=F("$ZodPrefault",(Y,X)=>{o.init(Y,X),Y._zod.optin="optional",l(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);if(J.value===void 0)J.value=X.defaultValue;return X.innerType._zod.run(J,Q)}}),p7=F("$ZodNonOptional",(Y,X)=>{o.init(Y,X),l(Y._zod,"values",()=>{let J=X.innerType._zod.values;return J?new Set([...J].filter((Q)=>Q!==void 0)):void 0}),Y._zod.parse=(J,Q)=>{let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>aQ(G,Y));return aQ($,Y)}});function aQ(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 l7=F("$ZodCatch",(Y,X)=>{o.init(Y,X),l(Y._zod,"optin",()=>X.innerType._zod.optin),l(Y._zod,"optout",()=>X.innerType._zod.optout),l(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>{if(J.value=G.value,G.issues.length)J.value=X.catchValue({...J,error:{issues:G.issues.map((W)=>S0(W,Q,m0()))},input:J.value}),J.issues=[];return J});if(J.value=$.value,$.issues.length)J.value=X.catchValue({...J,error:{issues:$.issues.map((G)=>S0(G,Q,m0()))},input:J.value}),J.issues=[];return J}});var d7=F("$ZodPipe",(Y,X)=>{o.init(Y,X),l(Y._zod,"values",()=>X.in._zod.values),l(Y._zod,"optin",()=>X.in._zod.optin),l(Y._zod,"optout",()=>X.out._zod.optout),l(Y._zod,"propValues",()=>X.in._zod.propValues),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward"){let G=X.out._zod.run(J,Q);if(G instanceof Promise)return G.then((W)=>lY(W,X.in,Q));return lY(G,X.in,Q)}let $=X.in._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>lY(G,X.out,Q));return lY($,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 i7=F("$ZodReadonly",(Y,X)=>{o.init(Y,X),l(Y._zod,"propValues",()=>X.innerType._zod.propValues),l(Y._zod,"values",()=>X.innerType._zod.values),l(Y._zod,"optin",()=>X.innerType._zod.optin),l(Y._zod,"optout",()=>X.innerType._zod.optout),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then(tQ);return tQ($)}});function tQ(Y){return Y.value=Object.freeze(Y.value),Y}var n7=F("$ZodLazy",(Y,X)=>{o.init(Y,X),l(Y._zod,"innerType",()=>X.getter()),l(Y._zod,"pattern",()=>Y._zod.innerType._zod.pattern),l(Y._zod,"propValues",()=>Y._zod.innerType._zod.propValues),l(Y._zod,"optin",()=>Y._zod.innerType._zod.optin??void 0),l(Y._zod,"optout",()=>Y._zod.innerType._zod.optout??void 0),Y._zod.parse=(J,Q)=>{return Y._zod.innerType._zod.run(J,Q)}}),o7=F("$ZodCustom",(Y,X)=>{V0.init(Y,X),o.init(Y,X),Y._zod.parse=(J,Q)=>{return J},Y._zod.check=(J)=>{let Q=J.value,$=X.fn(Q);if($ instanceof Promise)return $.then((G)=>eQ(G,J,Q,Y));eQ($,J,Q,Y);return}});function eQ(Y,X,J,Q){if(!Y){let $={code:"custom",input:J,inst:Q,path:[...Q._zod.def.path??[]],continue:!Q._zod.def.abort};if(Q._zod.def.params)$.params=Q._zod.def.params;X.issues.push(c1($))}}var lK=Symbol("ZodOutput"),dK=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 zU(){return new nY}var w1=zU();function r7(Y,X){return new Y({type:"string",...v(X)})}function s7(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 a7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...v(X)})}function t7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...v(X)})}function e7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...v(X)})}function Y$(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...v(X)})}function X$(Y,X){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...v(X)})}function J$(Y,X){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...v(X)})}function Q$(Y,X){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...v(X)})}function $$(Y,X){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...v(X)})}function G$(Y,X){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...v(X)})}function W$(Y,X){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...v(X)})}function z$(Y,X){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...v(X)})}function U$(Y,X){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...v(X)})}function H$(Y,X){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...v(X)})}function L$(Y,X){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...v(X)})}function V$(Y,X){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...v(X)})}function N$(Y,X){return new Y({type:"string",format:"cidrv6",check:"string_format",abort:!1,...v(X)})}function B$(Y,X){return new Y({type:"string",format:"base64",check:"string_format",abort:!1,...v(X)})}function Z$(Y,X){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...v(X)})}function K$(Y,X){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...v(X)})}function O$(Y,X){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...v(X)})}function q$(Y,X){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...v(X)})}function F$(Y,X){return new Y({type:"string",format:"date",check:"string_format",...v(X)})}function j$(Y,X){return new Y({type:"string",format:"time",check:"string_format",precision:null,...v(X)})}function D$(Y,X){return new Y({type:"string",format:"duration",check:"string_format",...v(X)})}function P$(Y,X){return new Y({type:"number",checks:[],...v(X)})}function M$(Y,X){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...v(X)})}function w$(Y,X){return new Y({type:"boolean",...v(X)})}function E$(Y,X){return new Y({type:"null",...v(X)})}function A$(Y){return new Y({type:"unknown"})}function T$(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 kQ({check:"multiple_of",...v(X),value:Y})}function aY(Y,X){return new xQ({check:"max_length",...v(X),maximum:Y})}function u1(Y,X){return new vQ({check:"min_length",...v(X),minimum:Y})}function tY(Y,X){return new hQ({check:"length_equals",...v(X),length:Y})}function q9(Y,X){return new gQ({check:"string_format",format:"regex",...v(X),pattern:Y})}function F9(Y){return new yQ({check:"string_format",format:"lowercase",...v(Y)})}function j9(Y){return new fQ({check:"string_format",format:"uppercase",...v(Y)})}function D9(Y,X){return new mQ({check:"string_format",format:"includes",...v(X),includes:Y})}function P9(Y,X){return new cQ({check:"string_format",format:"starts_with",...v(X),prefix:Y})}function M9(Y,X){return new uQ({check:"string_format",format:"ends_with",...v(X),suffix:Y})}function E1(Y){return new pQ({check:"overwrite",tx:Y})}function w9(Y){return E1((X)=>X.normalize(Y))}function E9(){return E1((Y)=>Y.trim())}function A9(){return E1((Y)=>Y.toLowerCase())}function T9(){return E1((Y)=>Y.toUpperCase())}function R$(Y,X,J){return new Y({type:"array",element:X,...v(J)})}function C$(Y,X,J){let Q=v(J);return Q.abort??(Q.abort=!0),new Y({type:"custom",check:"custom",fn:X,...Q})}function _$(Y,X,J){return new Y({type:"custom",check:"custom",fn:X,...v(J)})}function I$(Y){let X=UU((J)=>{return J.addIssue=(Q)=>{if(typeof Q==="string")J.issues.push(c1(Q,J.value,X._zod.def));else{let $=Q;if($.fatal)$.continue=!1;$.code??($.code="custom"),$.input??($.input=J.value),$.inst??($.inst=X),$.continue??($.continue=!X._zod.def.abort),J.issues.push(c1($))}},Y(J.value,J)});return X}function UU(Y,X){let J=new V0({check:"custom",...v(X)});return J._zod.check=Y,J}class R9{constructor(Y){this.counter=0,this.metadataRegistry=Y?.metadata??w1,this.target=Y?.target??"draft-2020-12",this.unrepresentable=Y?.unrepresentable??"throw",this.override=Y?.override??(()=>{}),this.io=Y?.io??"output",this.seen=new Map}process(Y,X={path:[],schemaPath:[]}){var J;let Q=Y._zod.def,$={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},G=this.seen.get(Y);if(G){if(G.count++,X.schemaPath.includes(Y))G.cycle=X.path;return G.schema}let W={schema:{},count:1,cycle:void 0,path:X.path};this.seen.set(Y,W);let U=Y._zod.toJSONSchema?.();if(U)W.schema=U;else{let N={...X,schemaPath:[...X.schemaPath,Y],path:X.path},O=Y._zod.parent;if(O)W.ref=O,this.process(O,N),this.seen.get(O).isParent=!0;else{let Z=W.schema;switch(Q.type){case"string":{let V=Z;V.type="string";let{minimum:K,maximum:j,format:M,patterns:I,contentEncoding:E}=Y._zod.bag;if(typeof K==="number")V.minLength=K;if(typeof j==="number")V.maxLength=j;if(M){if(V.format=$[M]??M,V.format==="")delete V.format}if(E)V.contentEncoding=E;if(I&&I.size>0){let x=[...I];if(x.length===1)V.pattern=x[0].source;else if(x.length>1)W.schema.allOf=[...x.map((R)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:R.source}))]}break}case"number":{let V=Z,{minimum:K,maximum:j,format:M,multipleOf:I,exclusiveMaximum:E,exclusiveMinimum:x}=Y._zod.bag;if(typeof M==="string"&&M.includes("int"))V.type="integer";else V.type="number";if(typeof x==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")V.minimum=x,V.exclusiveMinimum=!0;else V.exclusiveMinimum=x;if(typeof K==="number"){if(V.minimum=K,typeof x==="number"&&this.target!=="draft-4")if(x>=K)delete V.minimum;else delete V.exclusiveMinimum}if(typeof E==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")V.maximum=E,V.exclusiveMaximum=!0;else V.exclusiveMaximum=E;if(typeof j==="number"){if(V.maximum=j,typeof E==="number"&&this.target!=="draft-4")if(E<=j)delete V.maximum;else delete V.exclusiveMaximum}if(typeof I==="number")V.multipleOf=I;break}case"boolean":{let V=Z;V.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema");break}case"null":{if(this.target==="openapi-3.0")Z.type="string",Z.nullable=!0,Z.enum=[null];else Z.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema");break}case"never":{Z.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let V=Z,{minimum:K,maximum:j}=Y._zod.bag;if(typeof K==="number")V.minItems=K;if(typeof j==="number")V.maxItems=j;V.type="array",V.items=this.process(Q.element,{...N,path:[...N.path,"items"]});break}case"object":{let V=Z;V.type="object",V.properties={};let K=Q.shape;for(let I in K)V.properties[I]=this.process(K[I],{...N,path:[...N.path,"properties",I]});let j=new Set(Object.keys(K)),M=new Set([...j].filter((I)=>{let E=Q.shape[I]._zod;if(this.io==="input")return E.optin===void 0;else return E.optout===void 0}));if(M.size>0)V.required=Array.from(M);if(Q.catchall?._zod.def.type==="never")V.additionalProperties=!1;else if(!Q.catchall){if(this.io==="output")V.additionalProperties=!1}else if(Q.catchall)V.additionalProperties=this.process(Q.catchall,{...N,path:[...N.path,"additionalProperties"]});break}case"union":{let V=Z,K=Q.options.map((j,M)=>this.process(j,{...N,path:[...N.path,"anyOf",M]}));V.anyOf=K;break}case"intersection":{let V=Z,K=this.process(Q.left,{...N,path:[...N.path,"allOf",0]}),j=this.process(Q.right,{...N,path:[...N.path,"allOf",1]}),M=(E)=>("allOf"in E)&&Object.keys(E).length===1,I=[...M(K)?K.allOf:[K],...M(j)?j.allOf:[j]];V.allOf=I;break}case"tuple":{let V=Z;V.type="array";let K=this.target==="draft-2020-12"?"prefixItems":"items",j=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",M=Q.items.map((R,p)=>this.process(R,{...N,path:[...N.path,K,p]})),I=Q.rest?this.process(Q.rest,{...N,path:[...N.path,j,...this.target==="openapi-3.0"?[Q.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(V.prefixItems=M,I)V.items=I}else if(this.target==="openapi-3.0"){if(V.items={anyOf:M},I)V.items.anyOf.push(I);if(V.minItems=M.length,!I)V.maxItems=M.length}else if(V.items=M,I)V.additionalItems=I;let{minimum:E,maximum:x}=Y._zod.bag;if(typeof E==="number")V.minItems=E;if(typeof x==="number")V.maxItems=x;break}case"record":{let V=Z;if(V.type="object",this.target==="draft-7"||this.target==="draft-2020-12")V.propertyNames=this.process(Q.keyType,{...N,path:[...N.path,"propertyNames"]});V.additionalProperties=this.process(Q.valueType,{...N,path:[...N.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let V=Z,K=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"&&z0(Y))delete W.schema.examples,delete W.schema.default;if(this.io==="input"&&W.schema._prefault)(J=W.schema).default??(J.default=W.schema._prefault);return delete W.schema._prefault,this.seen.get(Y).schema}emit(Y,X){let J={cycles:X?.cycles??"ref",reused:X?.reused??"inline",external:X?.external??void 0},Q=this.seen.get(Y);if(!Q)throw Error("Unprocessed schema. This is a bug in Zod.");let $=(H)=>{let N=this.target==="draft-2020-12"?"$defs":"definitions";if(J.external){let K=J.external.registry.get(H[0])?.id,j=J.external.uri??((I)=>I);if(K)return{ref:j(K)};let M=H[1].defId??H[1].schema.id??`schema${this.counter++}`;return H[1].defId=M,{defId:M,ref:`${j("__shared")}#/${N}/${M}`}}if(H[1]===Q)return{ref:"#"};let Z=`${"#"}/${N}/`,V=H[1].schema.id??`__schema${this.counter++}`;return{defId:V,ref:Z+V}},G=(H)=>{if(H[1].schema.$ref)return;let N=H[1],{ref:O,defId:Z}=$(H);if(N.def={...N.schema},Z)N.defId=Z;let V=N.schema;for(let K in V)delete V[K];V.$ref=O};if(J.cycles==="throw")for(let H of this.seen.entries()){let N=H[1];if(N.cycle)throw Error(`Cycle detected: #/${N.cycle?.join("/")}/<root>
136
186
 
137
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let H of this.seen.entries()){let N=H[1];if(Y===H[0]){G(H);continue}if(J.external){let B=J.external.registry.get(H[0])?.id;if(Y!==H[0]&&B){G(H);continue}}if(this.metadataRegistry.get(H[0])?.id){G(H);continue}if(N.cycle){G(H);continue}if(N.count>1){if(J.reused==="ref"){G(H);continue}}}let W=(H,N)=>{let O=this.seen.get(H),B=O.def??O.schema,L={...B};if(O.ref===null)return;let Z=O.ref;if(O.ref=null,Z){W(Z,N);let j=this.seen.get(Z).schema;if(j.$ref&&(N.target==="draft-7"||N.target==="draft-4"||N.target==="openapi-3.0"))B.allOf=B.allOf??[],B.allOf.push(j);else Object.assign(B,j),Object.assign(B,L)}if(!O.isParent)this.override({zodSchema:H,jsonSchema:B,path:O.path??[]})};for(let H of[...this.seen.entries()].reverse())W(H[0],{target:this.target});let K={};if(this.target==="draft-2020-12")K.$schema="https://json-schema.org/draft/2020-12/schema";else if(this.target==="draft-7")K.$schema="http://json-schema.org/draft-07/schema#";else if(this.target==="draft-4")K.$schema="http://json-schema.org/draft-04/schema#";else if(this.target==="openapi-3.0");else console.warn(`Invalid target: ${this.target}`);if(J.external?.uri){let H=J.external.registry.get(Y)?.id;if(!H)throw Error("Schema is missing an `id` property");K.$id=J.external.uri(H)}Object.assign(K,Q.def);let U=J.external?.defs??{};for(let H of this.seen.entries()){let N=H[1];if(N.def&&N.defId)U[N.defId]=N.def}if(J.external);else if(Object.keys(U).length>0)if(this.target==="draft-2020-12")K.$defs=U;else K.definitions=U;try{return JSON.parse(JSON.stringify(K))}catch(H){throw Error("Error converting schema to JSON.")}}}function a7(Y,X){if(Y instanceof vY){let Q=new U9(X),$={};for(let K of Y._idmap.entries()){let[U,H]=K;Q.process(H)}let G={},W={registry:Y,uri:X?.uri,defs:$};for(let K of Y._idmap.entries()){let[U,H]=K;G[U]=Q.emit(H,{...X,external:W})}if(Object.keys($).length>0){let K=Q.target==="draft-2020-12"?"$defs":"definitions";G.__shared={[K]:$}}return{schemas:G}}let J=new U9(X);return J.process(Y),J.emit(Y,X)}function W0(Y,X){let J=X??{seen:new Set};if(J.seen.has(Y))return!1;J.seen.add(Y);let $=Y._zod.def;switch($.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return W0($.element,J);case"object":{for(let G in $.shape)if(W0($.shape[G],J))return!0;return!1}case"union":{for(let G of $.options)if(W0(G,J))return!0;return!1}case"intersection":return W0($.left,J)||W0($.right,J);case"tuple":{for(let G of $.items)if(W0(G,J))return!0;if($.rest&&W0($.rest,J))return!0;return!1}case"record":return W0($.keyType,J)||W0($.valueType,J);case"map":return W0($.keyType,J)||W0($.valueType,J);case"set":return W0($.valueType,J);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return W0($.innerType,J);case"lazy":return W0($.getter(),J);case"default":return W0($.innerType,J);case"prefault":return W0($.innerType,J);case"custom":return!1;case"transform":return!0;case"pipe":return W0($.in,J)||W0($.out,J);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${$.type}`)}var Lz=q("ZodISODateTime",(Y,X)=>{SQ.init(Y,X),s.init(Y,X)});function t7(Y){return g7(Lz,Y)}var Nz=q("ZodISODate",(Y,X)=>{kQ.init(Y,X),s.init(Y,X)});function e7(Y){return y7(Nz,Y)}var Vz=q("ZodISOTime",(Y,X)=>{bQ.init(Y,X),s.init(Y,X)});function Y$(Y){return f7(Vz,Y)}var Bz=q("ZodISODuration",(Y,X)=>{xQ.init(Y,X),s.init(Y,X)});function X$(Y){return m7(Bz,Y)}var J$=(Y,X)=>{CY.init(Y,X),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(J)=>L6(Y,J)},flatten:{value:(J)=>H6(Y,J)},addIssue:{value:(J)=>{Y.issues.push(J),Y.message=JSON.stringify(Y.issues,_1,2)}},addIssues:{value:(J)=>{Y.issues.push(...J),Y.message=JSON.stringify(Y.issues,_1,2)}},isEmpty:{get(){return Y.issues.length===0}}})},LZ=q("ZodError",J$),w0=q("ZodError",J$,{Parent:Error});var Q$=_Y(w0),$$=IY(w0),G$=o1(w0),uY=r1(w0),W$=B6(w0),z$=Z6(w0),K$=O6(w0),U$=F6(w0),H$=q6(w0),L$=j6(w0),N$=D6(w0),V$=P6(w0);var a=q("ZodType",(Y,X)=>{return n.init(Y,X),Y.def=X,Y.type=X.type,Object.defineProperty(Y,"_def",{value:X}),Y.check=(...J)=>{return Y.clone({...X,checks:[...X.checks??[],...J.map((Q)=>typeof Q==="function"?{_zod:{check:Q,def:{check:"custom"},onattach:[]}}:Q)]})},Y.clone=(J,Q)=>C0(Y,J,Q),Y.brand=()=>Y,Y.register=(J,Q)=>{return J.add(Y,Q),Y},Y.parse=(J,Q)=>Q$(Y,J,Q,{callee:Y.parse}),Y.safeParse=(J,Q)=>G$(Y,J,Q),Y.parseAsync=async(J,Q)=>$$(Y,J,Q,{callee:Y.parseAsync}),Y.safeParseAsync=async(J,Q)=>uY(Y,J,Q),Y.spa=Y.safeParseAsync,Y.encode=(J,Q)=>W$(Y,J,Q),Y.decode=(J,Q)=>z$(Y,J,Q),Y.encodeAsync=async(J,Q)=>K$(Y,J,Q),Y.decodeAsync=async(J,Q)=>U$(Y,J,Q),Y.safeEncode=(J,Q)=>H$(Y,J,Q),Y.safeDecode=(J,Q)=>L$(Y,J,Q),Y.safeEncodeAsync=async(J,Q)=>N$(Y,J,Q),Y.safeDecodeAsync=async(J,Q)=>V$(Y,J,Q),Y.refine=(J,Q)=>Y.check(zK(J,Q)),Y.superRefine=(J)=>Y.check(KK(J)),Y.overwrite=(J)=>Y.check(O1(J)),Y.optional=()=>O$(Y),Y.nullable=()=>F$(Y),Y.nullish=()=>O$(F$(Y)),Y.nonoptional=(J)=>YK(Y,J),Y.array=()=>N9(Y),Y.or=(J)=>V9([Y,J]),Y.and=(J)=>lz(Y,J),Y.transform=(J)=>q$(Y,oz(J)),Y.default=(J)=>az(Y,J),Y.prefault=(J)=>ez(Y,J),Y.catch=(J)=>JK(Y,J),Y.pipe=(J)=>q$(Y,J),Y.readonly=()=>GK(Y),Y.describe=(J)=>{let Q=Y.clone();return Z1.add(Q,{description:J}),Q},Object.defineProperty(Y,"description",{get(){return Z1.get(Y)?.description},configurable:!0}),Y.meta=(...J)=>{if(J.length===0)return Z1.get(Y);let Q=Y.clone();return Z1.add(Q,J[0]),Q},Y.isOptional=()=>Y.safeParse(void 0).success,Y.isNullable=()=>Y.safeParse(null).success,Y}),j$=q("_ZodString",(Y,X)=>{xY.init(Y,X),a.init(Y,X);let J=Y._zod.bag;Y.format=J.format??null,Y.minLength=J.minimum??null,Y.maxLength=J.maximum??null,Y.regex=(...Q)=>Y.check(e8(...Q)),Y.includes=(...Q)=>Y.check(J9(...Q)),Y.startsWith=(...Q)=>Y.check(Q9(...Q)),Y.endsWith=(...Q)=>Y.check($9(...Q)),Y.min=(...Q)=>Y.check(k1(...Q)),Y.max=(...Q)=>Y.check(fY(...Q)),Y.length=(...Q)=>Y.check(mY(...Q)),Y.nonempty=(...Q)=>Y.check(k1(1,...Q)),Y.lowercase=(Q)=>Y.check(Y9(Q)),Y.uppercase=(Q)=>Y.check(X9(Q)),Y.trim=()=>Y.check(W9()),Y.normalize=(...Q)=>Y.check(G9(...Q)),Y.toLowerCase=()=>Y.check(z9()),Y.toUpperCase=()=>Y.check(K9())}),qz=q("ZodString",(Y,X)=>{xY.init(Y,X),j$.init(Y,X),Y.email=(J)=>Y.check(O7(jz,J)),Y.url=(J)=>Y.check(P7(Dz,J)),Y.jwt=(J)=>Y.check(h7(vz,J)),Y.emoji=(J)=>Y.check(w7(Pz,J)),Y.guid=(J)=>Y.check(t8(B$,J)),Y.uuid=(J)=>Y.check(F7(pY,J)),Y.uuidv4=(J)=>Y.check(q7(pY,J)),Y.uuidv6=(J)=>Y.check(j7(pY,J)),Y.uuidv7=(J)=>Y.check(D7(pY,J)),Y.nanoid=(J)=>Y.check(E7(wz,J)),Y.guid=(J)=>Y.check(t8(B$,J)),Y.cuid=(J)=>Y.check(M7(Ez,J)),Y.cuid2=(J)=>Y.check(A7(Mz,J)),Y.ulid=(J)=>Y.check(R7(Az,J)),Y.base64=(J)=>Y.check(b7(kz,J)),Y.base64url=(J)=>Y.check(x7(bz,J)),Y.xid=(J)=>Y.check(T7(Rz,J)),Y.ksuid=(J)=>Y.check(C7(Tz,J)),Y.ipv4=(J)=>Y.check(_7(Cz,J)),Y.ipv6=(J)=>Y.check(I7(_z,J)),Y.cidrv4=(J)=>Y.check(S7(Iz,J)),Y.cidrv6=(J)=>Y.check(k7(Sz,J)),Y.e164=(J)=>Y.check(v7(xz,J)),Y.datetime=(J)=>Y.check(t7(J)),Y.date=(J)=>Y.check(e7(J)),Y.time=(J)=>Y.check(Y$(J)),Y.duration=(J)=>Y.check(X$(J))});function D$(Y){return Z7(qz,Y)}var s=q("ZodStringFormat",(Y,X)=>{r.init(Y,X),j$.init(Y,X)}),jz=q("ZodEmail",(Y,X)=>{wQ.init(Y,X),s.init(Y,X)});var B$=q("ZodGUID",(Y,X)=>{DQ.init(Y,X),s.init(Y,X)});var pY=q("ZodUUID",(Y,X)=>{PQ.init(Y,X),s.init(Y,X)});var Dz=q("ZodURL",(Y,X)=>{EQ.init(Y,X),s.init(Y,X)});var Pz=q("ZodEmoji",(Y,X)=>{MQ.init(Y,X),s.init(Y,X)});var wz=q("ZodNanoID",(Y,X)=>{AQ.init(Y,X),s.init(Y,X)});var Ez=q("ZodCUID",(Y,X)=>{RQ.init(Y,X),s.init(Y,X)});var Mz=q("ZodCUID2",(Y,X)=>{TQ.init(Y,X),s.init(Y,X)});var Az=q("ZodULID",(Y,X)=>{CQ.init(Y,X),s.init(Y,X)});var Rz=q("ZodXID",(Y,X)=>{_Q.init(Y,X),s.init(Y,X)});var Tz=q("ZodKSUID",(Y,X)=>{IQ.init(Y,X),s.init(Y,X)});var Cz=q("ZodIPv4",(Y,X)=>{vQ.init(Y,X),s.init(Y,X)});var _z=q("ZodIPv6",(Y,X)=>{hQ.init(Y,X),s.init(Y,X)});var Iz=q("ZodCIDRv4",(Y,X)=>{gQ.init(Y,X),s.init(Y,X)});var Sz=q("ZodCIDRv6",(Y,X)=>{yQ.init(Y,X),s.init(Y,X)});var kz=q("ZodBase64",(Y,X)=>{mQ.init(Y,X),s.init(Y,X)});var bz=q("ZodBase64URL",(Y,X)=>{cQ.init(Y,X),s.init(Y,X)});var xz=q("ZodE164",(Y,X)=>{uQ.init(Y,X),s.init(Y,X)});var vz=q("ZodJWT",(Y,X)=>{pQ.init(Y,X),s.init(Y,X)});var P$=q("ZodNumber",(Y,X)=>{s8.init(Y,X),a.init(Y,X),Y.gt=(Q,$)=>Y.check(gY(Q,$)),Y.gte=(Q,$)=>Y.check(t1(Q,$)),Y.min=(Q,$)=>Y.check(t1(Q,$)),Y.lt=(Q,$)=>Y.check(hY(Q,$)),Y.lte=(Q,$)=>Y.check(a1(Q,$)),Y.max=(Q,$)=>Y.check(a1(Q,$)),Y.int=(Q)=>Y.check(Z$(Q)),Y.safe=(Q)=>Y.check(Z$(Q)),Y.positive=(Q)=>Y.check(gY(0,Q)),Y.nonnegative=(Q)=>Y.check(t1(0,Q)),Y.negative=(Q)=>Y.check(hY(0,Q)),Y.nonpositive=(Q)=>Y.check(a1(0,Q)),Y.multipleOf=(Q,$)=>Y.check(yY(Q,$)),Y.step=(Q,$)=>Y.check(yY(Q,$)),Y.finite=()=>Y;let J=Y._zod.bag;Y.minValue=Math.max(J.minimum??Number.NEGATIVE_INFINITY,J.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Y.maxValue=Math.min(J.maximum??Number.POSITIVE_INFINITY,J.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Y.isInt=(J.format??"").includes("int")||Number.isSafeInteger(J.multipleOf??0.5),Y.isFinite=!0,Y.format=J.format??null});function w$(Y){return c7(P$,Y)}var hz=q("ZodNumberFormat",(Y,X)=>{lQ.init(Y,X),P$.init(Y,X)});function Z$(Y){return u7(hz,Y)}var gz=q("ZodBoolean",(Y,X)=>{dQ.init(Y,X),a.init(Y,X)});function E$(Y){return p7(gz,Y)}var yz=q("ZodNull",(Y,X)=>{iQ.init(Y,X),a.init(Y,X)});function M$(Y){return l7(yz,Y)}var fz=q("ZodUnknown",(Y,X)=>{nQ.init(Y,X),a.init(Y,X)});function e1(){return d7(fz)}var mz=q("ZodNever",(Y,X)=>{oQ.init(Y,X),a.init(Y,X)});function L9(Y){return i7(mz,Y)}var cz=q("ZodArray",(Y,X)=>{rQ.init(Y,X),a.init(Y,X),Y.element=X.element,Y.min=(J,Q)=>Y.check(k1(J,Q)),Y.nonempty=(J)=>Y.check(k1(1,J)),Y.max=(J,Q)=>Y.check(fY(J,Q)),Y.length=(J,Q)=>Y.check(mY(J,Q)),Y.unwrap=()=>Y.element});function N9(Y,X){return n7(cz,Y,X)}var A$=q("ZodObject",(Y,X)=>{tQ.init(Y,X),a.init(Y,X),c.defineLazy(Y,"shape",()=>X.shape),Y.keyof=()=>B9(Object.keys(Y._zod.def.shape)),Y.catchall=(J)=>Y.clone({...Y._zod.def,catchall:J}),Y.passthrough=()=>Y.clone({...Y._zod.def,catchall:e1()}),Y.loose=()=>Y.clone({...Y._zod.def,catchall:e1()}),Y.strict=()=>Y.clone({...Y._zod.def,catchall:L9()}),Y.strip=()=>Y.clone({...Y._zod.def,catchall:void 0}),Y.extend=(J)=>{return c.extend(Y,J)},Y.safeExtend=(J)=>{return c.safeExtend(Y,J)},Y.merge=(J)=>c.merge(Y,J),Y.pick=(J)=>c.pick(Y,J),Y.omit=(J)=>c.omit(Y,J),Y.partial=(...J)=>c.partial(k$,Y,J[0]),Y.required=(...J)=>c.required(b$,Y,J[0])});function R$(Y,X){let J={type:"object",get shape(){return c.assignProp(this,"shape",Y?c.objectClone(Y):{}),this.shape},...c.normalizeParams(X)};return new A$(J)}function T$(Y,X){return new A$({type:"object",get shape(){return c.assignProp(this,"shape",c.objectClone(Y)),this.shape},catchall:e1(),...c.normalizeParams(X)})}var C$=q("ZodUnion",(Y,X)=>{a8.init(Y,X),a.init(Y,X),Y.options=X.options});function V9(Y,X){return new C$({type:"union",options:Y,...c.normalizeParams(X)})}var uz=q("ZodDiscriminatedUnion",(Y,X)=>{C$.init(Y,X),eQ.init(Y,X)});function _$(Y,X,J){return new uz({type:"union",options:X,discriminator:Y,...c.normalizeParams(J)})}var pz=q("ZodIntersection",(Y,X)=>{Y7.init(Y,X),a.init(Y,X)});function lz(Y,X){return new pz({type:"intersection",left:Y,right:X})}var dz=q("ZodRecord",(Y,X)=>{X7.init(Y,X),a.init(Y,X),Y.keyType=X.keyType,Y.valueType=X.valueType});function I$(Y,X,J){return new dz({type:"record",keyType:Y,valueType:X,...c.normalizeParams(J)})}var H9=q("ZodEnum",(Y,X)=>{J7.init(Y,X),a.init(Y,X),Y.enum=X.entries,Y.options=Object.values(X.entries);let J=new Set(Object.keys(X.entries));Y.extract=(Q,$)=>{let G={};for(let W of Q)if(J.has(W))G[W]=X.entries[W];else throw Error(`Key ${W} not found in enum`);return new H9({...X,checks:[],...c.normalizeParams($),entries:G})},Y.exclude=(Q,$)=>{let G={...X.entries};for(let W of Q)if(J.has(W))delete G[W];else throw Error(`Key ${W} not found in enum`);return new H9({...X,checks:[],...c.normalizeParams($),entries:G})}});function B9(Y,X){let J=Array.isArray(Y)?Object.fromEntries(Y.map((Q)=>[Q,Q])):Y;return new H9({type:"enum",entries:J,...c.normalizeParams(X)})}var iz=q("ZodLiteral",(Y,X)=>{Q7.init(Y,X),a.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 S$(Y,X){return new iz({type:"literal",values:Array.isArray(Y)?Y:[Y],...c.normalizeParams(X)})}var nz=q("ZodTransform",(Y,X)=>{$7.init(Y,X),a.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new u1(Y.constructor.name);J.addIssue=(G)=>{if(typeof G==="string")J.issues.push(c.issue(G,J.value,X));else{let W=G;if(W.fatal)W.continue=!1;W.code??(W.code="custom"),W.input??(W.input=J.value),W.inst??(W.inst=Y),J.issues.push(c.issue(W))}};let $=X.transform(J.value,J);if($ instanceof Promise)return $.then((G)=>{return J.value=G,J});return J.value=$,J}});function oz(Y){return new nz({type:"transform",transform:Y})}var k$=q("ZodOptional",(Y,X)=>{G7.init(Y,X),a.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function O$(Y){return new k$({type:"optional",innerType:Y})}var rz=q("ZodNullable",(Y,X)=>{W7.init(Y,X),a.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function F$(Y){return new rz({type:"nullable",innerType:Y})}var sz=q("ZodDefault",(Y,X)=>{z7.init(Y,X),a.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function az(Y,X){return new sz({type:"default",innerType:Y,get defaultValue(){return typeof X==="function"?X():c.shallowClone(X)}})}var tz=q("ZodPrefault",(Y,X)=>{K7.init(Y,X),a.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function ez(Y,X){return new tz({type:"prefault",innerType:Y,get defaultValue(){return typeof X==="function"?X():c.shallowClone(X)}})}var b$=q("ZodNonOptional",(Y,X)=>{U7.init(Y,X),a.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function YK(Y,X){return new b$({type:"nonoptional",innerType:Y,...c.normalizeParams(X)})}var XK=q("ZodCatch",(Y,X)=>{H7.init(Y,X),a.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function JK(Y,X){return new XK({type:"catch",innerType:Y,catchValue:typeof X==="function"?X:()=>X})}var QK=q("ZodPipe",(Y,X)=>{L7.init(Y,X),a.init(Y,X),Y.in=X.in,Y.out=X.out});function q$(Y,X){return new QK({type:"pipe",in:Y,out:X})}var $K=q("ZodReadonly",(Y,X)=>{N7.init(Y,X),a.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function GK(Y){return new $K({type:"readonly",innerType:Y})}var WK=q("ZodLazy",(Y,X)=>{V7.init(Y,X),a.init(Y,X),Y.unwrap=()=>Y._zod.def.getter()});function x$(Y){return new WK({type:"lazy",getter:Y})}var Z9=q("ZodCustom",(Y,X)=>{B7.init(Y,X),a.init(Y,X)});function v$(Y,X){return o7(Z9,Y??(()=>!0),X)}function zK(Y,X={}){return r7(Z9,Y,X)}function KK(Y){return s7(Y)}function h$(Y,X={error:`Input not instance of ${Y.name}`}){let J=new Z9({type:"custom",check:"custom",fn:(Q)=>Q instanceof Y,abort:!0,...c.normalizeParams(X)});return J._zod.bag.Class=Y,J}var UK=[{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]}],tZ=[...UK,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];var HK=12,LK=131072,eZ=LK+HK;async function lY(Y){var X;try{await((X=Y.body)==null?void 0:X.cancel())}catch(J){}}var i$="AI_DownloadError",n$=`vercel.ai.error.${i$}`,NK=Symbol.for(n$),g$,y$,O0=class extends(y$=f,g$=NK,y$){constructor({url:Y,statusCode:X,statusText:J,cause:Q,message:$=Q==null?`Failed to download ${Y}: ${X} ${J}`:`Failed to download ${Y}: ${Q}`}){super({name:i$,message:$,cause:Q});this[g$]=!0,this.url=Y,this.statusCode=X,this.statusText=J}static isInstance(Y){return f.hasMarker(Y,n$)}};function VK(Y=globalThis){return Y.window!=null}function f$(Y,X){try{return new URL(Y).origin===new URL(X).origin}catch(J){return!1}}function BK(Y){let X;try{X=new URL(Y)}catch(Q){throw new O0({url:Y,message:`Invalid URL: ${Y}`})}if(X.protocol==="data:")return;if(X.protocol!=="http:"&&X.protocol!=="https:")throw new O0({url:Y,message:`URL scheme must be http, https, or data, got ${X.protocol}`});let J=X.hostname.toLowerCase().replace(/\.+$/,"");if(!J)throw new O0({url:Y,message:"URL must have a hostname"});if(J==="localhost"||J.endsWith(".local")||J.endsWith(".localhost"))throw new O0({url:Y,message:`URL with hostname ${J} is not allowed`});if(J.startsWith("[")&&J.endsWith("]")){let Q=J.slice(1,-1);if(o$(Q))throw new O0({url:Y,message:`URL with IPv6 address ${J} is not allowed`});return}if(P9(J)){if(w9(J))throw new O0({url:Y,message:`URL with IP address ${J} is not allowed`});return}}function ZK({address:Y,family:X,hostname:J}){if(X===4?!P9(Y)||w9(Y):X===6?o$(Y):!0)throw new O0({url:J,message:`Hostname ${J} resolved to disallowed IP address ${Y}`})}function P9(Y){let X=Y.split(".");if(X.length!==4)return!1;return X.every((J)=>{let Q=Number(J);return Number.isInteger(Q)&&Q>=0&&Q<=255&&String(Q)===J})}function w9(Y){let X=Y.split(".").map(Number),[J,Q,$]=X;if(J===0)return!0;if(J===10)return!0;if(J===100&&Q>=64&&Q<=127)return!0;if(J===127)return!0;if(J===169&&Q===254)return!0;if(J===172&&Q>=16&&Q<=31)return!0;if(J===192&&Q===0&&$===0)return!0;if(J===192&&Q===0&&$===2)return!0;if(J===192&&Q===168)return!0;if(J===198&&(Q===18||Q===19))return!0;if(J===198&&Q===51&&$===100)return!0;if(J===203&&Q===0&&$===113)return!0;if(J>=224)return!0;return!1}function OK(Y){let X=Y.toLowerCase(),J=X.indexOf("%");if(J!==-1)X=X.slice(0,J);let Q=X.split("::");if(Q.length>2)return null;let $=(W)=>{if(W==="")return[];let K=[],U=W.split(":");for(let H=0;H<U.length;H++){let N=U[H];if(N.includes(".")){if(H!==U.length-1||!P9(N))return null;let[O,B,L,Z]=N.split(".").map(Number);K.push(O<<8|B,L<<8|Z);continue}if(!/^[0-9a-f]{1,4}$/.test(N))return null;K.push(parseInt(N,16))}return K},G=$(Q[0]);if(G===null)return null;if(Q.length===2){let W=$(Q[1]);if(W===null)return null;let K=8-G.length-W.length;if(K<0)return null;return[...G,...Array(K).fill(0),...W]}return G.length===8?G:null}function o$(Y){let X=OK(Y);if(X===null)return!0;let J=($)=>X.slice(0,$).every((G)=>G===0);if(J(7)&&(X[7]===0||X[7]===1))return!0;if((X[0]&65024)===64512)return!0;if((X[0]&65472)===65152)return!0;if((X[0]&65472)===65216)return!0;if((X[0]&65280)===65280)return!0;if(X[0]===8193&&X[1]===3512)return!0;if(X[0]===16383&&(X[1]&61440)===0)return!0;if(J(6)||J(5)&&X[5]===65535||J(4)&&X[4]===65535&&X[5]===0||X[0]===100&&X[1]===65435&&X[2]===0&&X[3]===0&&X[4]===0&&X[5]===0||X[0]===100&&X[1]===65435&&X[2]===1){let $=X[6]>>8&255,G=X[6]&255,W=X[7]>>8&255,K=X[7]&255;return w9(`${$}.${G}.${W}.${K}`)}return!1}function FK(Y){return(X,J,Q)=>{Y(X,{...J,all:!0},($,G)=>{if($){Q($);return}try{let[W]=G;if(W==null)throw Error(`Hostname ${X} did not resolve to an address`);for(let{address:K,family:U}of G)ZK({address:K,family:U,hostname:X});if(J.all===!0)Q(null,G);else Q(null,W.address,W.family)}catch(W){Q(W instanceof Error?W:Error(String(W)))}})}}var O9,r$=globalThis.fetch,qK=PK(r$);function jK(){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 DK(){if(!jK()||!qK||globalThis.fetch!==r$)return globalThis.fetch;return O9!=null?O9:O9=Promise.resolve().then(wK)}function PK(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 wK(){let{createRequire:Y}=m$("node:module"),{lookup:X}=m$("node:dns"),{Agent:J,fetch:Q}=Y(s$())("undici"),$=new J({connect:{lookup:FK(X)}});return(G,W)=>Q(G,{...W,dispatcher:$})}function m$(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)=>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 EK=["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 MK(Y){let X=new Headers(Y);for(let J of EK)X.delete(J);return X}var AK=10,RK=new Set([301,302,303,307,308]);async function a$({url:Y,headers:X,abortSignal:J,maxRedirects:Q=AK,fetch:$,trustedOrigin:G}){let W=X===void 0?void 0:MK(X),K=(H)=>{let N={signal:J,redirect:H};if(W!==void 0)N.headers=new Headers(W);return N},U=Y;for(let H=0;H<=Q;H++){let N=G!==void 0&&f$(U,G);if(!N)BK(U);let O=$!=null?$:N?globalThis.fetch:await DK(),B=await O(U,K("manual"));if(B.type==="opaqueredirect"){if(!VK())throw new O0({url:Y,message:`Redirect from ${U} could not be validated and was blocked`});return await O(U,K("follow"))}let L=B.headers.get("location");if(RK.has(B.status)&&L){await lY(B);let Z=new URL(L,U).toString();if(W!==void 0&&!f$(Z,U)){let j=W.get("user-agent");W=new Headers(j==null?void 0:{"user-agent":j})}U=Z;continue}return B}throw new O0({url:Y,message:`Too many redirects (max ${Q})`})}var E9=2147483648;async function t$({response:Y,url:X,maxBytes:J=E9}){let Q=Y.headers.get("content-length");if(Q!=null){let N=parseInt(Q,10);if(!isNaN(N)&&N>J)throw await lY(Y),new O0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes (Content-Length: ${N}).`})}let $=Y.body;if($==null)return new Uint8Array(0);let G=$.getReader(),W=[],K=0;try{while(!0){let{done:N,value:O}=await G.read();if(N)break;if(K+=O.length,K>J)throw new O0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes.`});W.push(O)}}finally{try{await G.cancel()}finally{G.releaseLock()}}let U=new Uint8Array(K),H=0;for(let N of W)U.set(N,H),H+=N.length;return U}var Q0=({prefix:Y,size:X=16,alphabet:J="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:Q="-"}={})=>{let $=()=>{let G=J.length,W=Array(X);for(let K=0;K<X;K++)W[K]=J[Math.random()*G|0];return W.join("")};if(Y==null)return $;if(J.includes(Q))throw new SJ({argument:"separator",message:`The separator "${Q}" must not be part of the alphabet "${J}".`});return()=>`${Y}${Q}${$()}`},JO=Q0();function e$(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 TK(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 b1(Y,...X){let J=new Headers(TK(Y)),Q=J.get("user-agent")||"";return J.set("user-agent",[Q,...X].filter(Boolean).join(" ")),Object.fromEntries(J.entries())}function YG(Y){var X,J;return(J=(X=globalThis.Buffer)==null?void 0:X.isBuffer(Y))!=null?J:!1}var CK=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,_K=/"(?: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 c$(Y){let X=JSON.parse(Y);if(X===null||typeof X!=="object")return X;if(CK.test(Y)===!1&&_K.test(Y)===!1)return X;return IK(X)}function IK(Y){let X=[Y];while(X.length){let J=X;X=[];for(let Q of J){if(Object.prototype.hasOwnProperty.call(Q,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(Q,"constructor")&&Q.constructor!==null&&typeof Q.constructor==="object"&&Object.prototype.hasOwnProperty.call(Q.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let $ in Q){let G=Q[$];if(G&&typeof G==="object")X.push(G)}}}return Y}function SK(Y){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(J){return c$(Y)}try{return c$(Y)}finally{Error.stackTraceLimit=X}}function M9(Y){if(Y.type==="object"||Array.isArray(Y.type)&&Y.type.includes("object")){Y.additionalProperties=!1;let{properties:J}=Y;if(J!=null)for(let Q of Object.keys(J))J[Q]=F1(J[Q])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(F1):F1(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(F1);if(Y.allOf!=null)Y.allOf=Y.allOf.map(F1);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(F1);let{definitions:X}=Y;if(X!=null)for(let J of Object.keys(X))X[J]=F1(X[J]);return Y}function F1(Y){if(typeof Y==="boolean")return Y;return M9(Y)}var kK=Symbol("Let zodToJsonSchema decide on which parser to use"),u$={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"},bK=(Y)=>typeof Y==="string"?{...u$,name:Y}:{...u$,...Y};function E0(){return{}}function xK(Y,X){var J,Q,$;let G={type:"array"};if(((J=Y.type)==null?void 0:J._def)&&(($=(Q=Y.type)==null?void 0:Q._def)==null?void 0:$.typeName)!=="ZodAny")G.items=i(Y.type._def,{...X,currentPath:[...X.currentPath,"items"]});if(Y.minLength)G.minItems=Y.minLength.value;if(Y.maxLength)G.maxItems=Y.maxLength.value;if(Y.exactLength)G.minItems=Y.exactLength.value,G.maxItems=Y.exactLength.value;return G}function vK(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 hK(){return{type:"boolean"}}function XG(Y,X){return i(Y.type._def,X)}var gK=(Y,X)=>{return i(Y.innerType._def,X)};function JG(Y,X,J){let Q=J!=null?J:X.dateStrategy;if(Array.isArray(Q))return{anyOf:Q.map(($)=>JG(Y,X,$))};switch(Q){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return yK(Y)}}var yK=(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 fK(Y,X){return{...i(Y.innerType._def,X),default:Y.defaultValue()}}function mK(Y,X){return X.effectStrategy==="input"?i(Y.schema._def,X):E0()}function cK(Y){return{type:"string",enum:Array.from(Y.values)}}var uK=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function pK(Y,X){let J=[i(Y.left._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),i(Y.right._def,{...X,currentPath:[...X.currentPath,"allOf","1"]})].filter(($)=>!!$),Q=[];return J.forEach(($)=>{if(uK($))Q.push(...$.allOf);else{let G=$;if("additionalProperties"in $&&$.additionalProperties===!1){let{additionalProperties:W,...K}=$;G=K}Q.push(G)}}),Q.length?{allOf:Q}:void 0}function lK(Y){let X=typeof Y.value;if(X!=="bigint"&&X!=="number"&&X!=="boolean"&&X!=="string")return{type:Array.isArray(Y.value)?"array":"object"};return{type:X==="bigint"?"integer":X,const:Y.value}}var F9=void 0,I0={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(F9===void 0)F9=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return F9},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function QG(Y,X){let J={type:"string"};if(Y.checks)for(let Q of Y.checks)switch(Q.kind){case"min":J.minLength=typeof J.minLength==="number"?Math.max(J.minLength,Q.value):Q.value;break;case"max":J.maxLength=typeof J.maxLength==="number"?Math.min(J.maxLength,Q.value):Q.value;break;case"email":switch(X.emailStrategy){case"format:email":S0(J,"email",Q.message,X);break;case"format:idn-email":S0(J,"idn-email",Q.message,X);break;case"pattern:zod":Z0(J,I0.email,Q.message,X);break}break;case"url":S0(J,"uri",Q.message,X);break;case"uuid":S0(J,"uuid",Q.message,X);break;case"regex":Z0(J,Q.regex,Q.message,X);break;case"cuid":Z0(J,I0.cuid,Q.message,X);break;case"cuid2":Z0(J,I0.cuid2,Q.message,X);break;case"startsWith":Z0(J,RegExp(`^${q9(Q.value,X)}`),Q.message,X);break;case"endsWith":Z0(J,RegExp(`${q9(Q.value,X)}$`),Q.message,X);break;case"datetime":S0(J,"date-time",Q.message,X);break;case"date":S0(J,"date",Q.message,X);break;case"time":S0(J,"time",Q.message,X);break;case"duration":S0(J,"duration",Q.message,X);break;case"length":J.minLength=typeof J.minLength==="number"?Math.max(J.minLength,Q.value):Q.value,J.maxLength=typeof J.maxLength==="number"?Math.min(J.maxLength,Q.value):Q.value;break;case"includes":{Z0(J,RegExp(q9(Q.value,X)),Q.message,X);break}case"ip":{if(Q.version!=="v6")S0(J,"ipv4",Q.message,X);if(Q.version!=="v4")S0(J,"ipv6",Q.message,X);break}case"base64url":Z0(J,I0.base64url,Q.message,X);break;case"jwt":Z0(J,I0.jwt,Q.message,X);break;case"cidr":{if(Q.version!=="v6")Z0(J,I0.ipv4Cidr,Q.message,X);if(Q.version!=="v4")Z0(J,I0.ipv6Cidr,Q.message,X);break}case"emoji":Z0(J,I0.emoji(),Q.message,X);break;case"ulid":{Z0(J,I0.ulid,Q.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{S0(J,"binary",Q.message,X);break}case"contentEncoding:base64":{J.contentEncoding="base64";break}case"pattern:zod":{Z0(J,I0.base64,Q.message,X);break}}break}case"nanoid":Z0(J,I0.nanoid,Q.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return J}function q9(Y,X){return X.patternStrategy==="escape"?iK(Y):Y}var dK=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function iK(Y){let X="";for(let J=0;J<Y.length;J++){if(!dK.has(Y[J]))X+="\\";X+=Y[J]}return X}function S0(Y,X,J,Q){var $;if(Y.format||(($=Y.anyOf)==null?void 0:$.some((G)=>G.format))){if(!Y.anyOf)Y.anyOf=[];if(Y.format)Y.anyOf.push({format:Y.format}),delete Y.format;Y.anyOf.push({format:X,...J&&Q.errorMessages&&{errorMessage:{format:J}}})}else Y.format=X}function Z0(Y,X,J,Q){var $;if(Y.pattern||(($=Y.allOf)==null?void 0:$.some((G)=>G.pattern))){if(!Y.allOf)Y.allOf=[];if(Y.pattern)Y.allOf.push({pattern:Y.pattern}),delete Y.pattern;Y.allOf.push({pattern:p$(X,Q),...J&&Q.errorMessages&&{errorMessage:{pattern:J}}})}else Y.pattern=p$(X,Q)}function p$(Y,X){var J;if(!X.applyRegexFlags||!Y.flags)return Y.source;let Q={i:Y.flags.includes("i"),m:Y.flags.includes("m"),s:Y.flags.includes("s")},$=Q.i?Y.source.toLowerCase():Y.source,G="",W=!1,K=!1,U=!1;for(let H=0;H<$.length;H++){if(W){G+=$[H],W=!1;continue}if(Q.i){if(K){if($[H].match(/[a-z]/)){if(U)G+=$[H],G+=`${$[H-2]}-${$[H]}`.toUpperCase(),U=!1;else if($[H+1]==="-"&&((J=$[H+2])==null?void 0:J.match(/[a-z]/)))G+=$[H],U=!0;else G+=`${$[H]}${$[H].toUpperCase()}`;continue}}else if($[H].match(/[a-z]/)){G+=`[${$[H]}${$[H].toUpperCase()}]`;continue}}if(Q.m){if($[H]==="^"){G+=`(^|(?<=[\r
187
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let H of this.seen.entries()){let N=H[1];if(Y===H[0]){G(H);continue}if(J.external){let Z=J.external.registry.get(H[0])?.id;if(Y!==H[0]&&Z){G(H);continue}}if(this.metadataRegistry.get(H[0])?.id){G(H);continue}if(N.cycle){G(H);continue}if(N.count>1){if(J.reused==="ref"){G(H);continue}}}let W=(H,N)=>{let O=this.seen.get(H),Z=O.def??O.schema,V={...Z};if(O.ref===null)return;let K=O.ref;if(O.ref=null,K){W(K,N);let j=this.seen.get(K).schema;if(j.$ref&&(N.target==="draft-7"||N.target==="draft-4"||N.target==="openapi-3.0"))Z.allOf=Z.allOf??[],Z.allOf.push(j);else Object.assign(Z,j),Object.assign(Z,V)}if(!O.isParent)this.override({zodSchema:H,jsonSchema:Z,path:O.path??[]})};for(let H of[...this.seen.entries()].reverse())W(H[0],{target:this.target});let U={};if(this.target==="draft-2020-12")U.$schema="https://json-schema.org/draft/2020-12/schema";else if(this.target==="draft-7")U.$schema="http://json-schema.org/draft-07/schema#";else if(this.target==="draft-4")U.$schema="http://json-schema.org/draft-04/schema#";else if(this.target==="openapi-3.0");else console.warn(`Invalid target: ${this.target}`);if(J.external?.uri){let H=J.external.registry.get(Y)?.id;if(!H)throw Error("Schema is missing an `id` property");U.$id=J.external.uri(H)}Object.assign(U,Q.def);let L=J.external?.defs??{};for(let H of this.seen.entries()){let N=H[1];if(N.def&&N.defId)L[N.defId]=N.def}if(J.external);else if(Object.keys(L).length>0)if(this.target==="draft-2020-12")U.$defs=L;else U.definitions=L;try{return JSON.parse(JSON.stringify(U))}catch(H){throw Error("Error converting schema to JSON.")}}}function S$(Y,X){if(Y instanceof nY){let Q=new R9(X),$={};for(let U of Y._idmap.entries()){let[L,H]=U;Q.process(H)}let G={},W={registry:Y,uri:X?.uri,defs:$};for(let U of Y._idmap.entries()){let[L,H]=U;G[L]=Q.emit(H,{...X,external:W})}if(Object.keys($).length>0){let U=Q.target==="draft-2020-12"?"$defs":"definitions";G.__shared={[U]:$}}return{schemas:G}}let J=new R9(X);return J.process(Y),J.emit(Y,X)}function z0(Y,X){let J=X??{seen:new Set};if(J.seen.has(Y))return!1;J.seen.add(Y);let $=Y._zod.def;switch($.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return z0($.element,J);case"object":{for(let G in $.shape)if(z0($.shape[G],J))return!0;return!1}case"union":{for(let G of $.options)if(z0(G,J))return!0;return!1}case"intersection":return z0($.left,J)||z0($.right,J);case"tuple":{for(let G of $.items)if(z0(G,J))return!0;if($.rest&&z0($.rest,J))return!0;return!1}case"record":return z0($.keyType,J)||z0($.valueType,J);case"map":return z0($.keyType,J)||z0($.valueType,J);case"set":return z0($.valueType,J);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return z0($.innerType,J);case"lazy":return z0($.getter(),J);case"default":return z0($.innerType,J);case"prefault":return z0($.innerType,J);case"custom":return!1;case"transform":return!0;case"pipe":return z0($.in,J)||z0($.out,J);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${$.type}`)}var ZU=F("ZodISODateTime",(Y,X)=>{V7.init(Y,X),a.init(Y,X)});function k$(Y){return q$(ZU,Y)}var KU=F("ZodISODate",(Y,X)=>{N7.init(Y,X),a.init(Y,X)});function b$(Y){return F$(KU,Y)}var OU=F("ZodISOTime",(Y,X)=>{B7.init(Y,X),a.init(Y,X)});function x$(Y){return j$(OU,Y)}var qU=F("ZodISODuration",(Y,X)=>{Z7.init(Y,X),a.init(Y,X)});function v$(Y){return D$(qU,Y)}var h$=(Y,X)=>{mY.init(Y,X),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(J)=>d6(Y,J)},flatten:{value:(J)=>l6(Y,J)},addIssue:{value:(J)=>{Y.issues.push(J),Y.message=JSON.stringify(Y.issues,f1,2)}},addIssues:{value:(J)=>{Y.issues.push(...J),Y.message=JSON.stringify(Y.issues,f1,2)}},isEmpty:{get(){return Y.issues.length===0}}})},PO=F("ZodError",h$),E0=F("ZodError",h$,{Parent:Error});var g$=cY(E0),y$=uY(E0),f$=GY(E0),Y8=WY(E0),m$=o6(E0),c$=r6(E0),u$=s6(E0),p$=a6(E0),l$=t6(E0),d$=e6(E0),i$=YQ(E0),n$=XQ(E0);var t=F("ZodType",(Y,X)=>{return o.init(Y,X),Y.def=X,Y.type=X.type,Object.defineProperty(Y,"_def",{value:X}),Y.check=(...J)=>{return Y.clone({...X,checks:[...X.checks??[],...J.map((Q)=>typeof Q==="function"?{_zod:{check:Q,def:{check:"custom"},onattach:[]}}:Q)]})},Y.clone=(J,Q)=>I0(Y,J,Q),Y.brand=()=>Y,Y.register=(J,Q)=>{return J.add(Y,Q),Y},Y.parse=(J,Q)=>g$(Y,J,Q,{callee:Y.parse}),Y.safeParse=(J,Q)=>f$(Y,J,Q),Y.parseAsync=async(J,Q)=>y$(Y,J,Q,{callee:Y.parseAsync}),Y.safeParseAsync=async(J,Q)=>Y8(Y,J,Q),Y.spa=Y.safeParseAsync,Y.encode=(J,Q)=>m$(Y,J,Q),Y.decode=(J,Q)=>c$(Y,J,Q),Y.encodeAsync=async(J,Q)=>u$(Y,J,Q),Y.decodeAsync=async(J,Q)=>p$(Y,J,Q),Y.safeEncode=(J,Q)=>l$(Y,J,Q),Y.safeDecode=(J,Q)=>d$(Y,J,Q),Y.safeEncodeAsync=async(J,Q)=>i$(Y,J,Q),Y.safeDecodeAsync=async(J,Q)=>n$(Y,J,Q),Y.refine=(J,Q)=>Y.check(LH(J,Q)),Y.superRefine=(J)=>Y.check(VH(J)),Y.overwrite=(J)=>Y.check(E1(J)),Y.optional=()=>s$(Y),Y.nullable=()=>a$(Y),Y.nullish=()=>s$(a$(Y)),Y.nonoptional=(J)=>QH(Y,J),Y.array=()=>I9(Y),Y.or=(J)=>S9([Y,J]),Y.and=(J)=>nU(Y,J),Y.transform=(J)=>t$(Y,aU(J)),Y.default=(J)=>YH(Y,J),Y.prefault=(J)=>JH(Y,J),Y.catch=(J)=>GH(Y,J),Y.pipe=(J)=>t$(Y,J),Y.readonly=()=>UH(Y),Y.describe=(J)=>{let Q=Y.clone();return w1.add(Q,{description:J}),Q},Object.defineProperty(Y,"description",{get(){return w1.get(Y)?.description},configurable:!0}),Y.meta=(...J)=>{if(J.length===0)return w1.get(Y);let Q=Y.clone();return w1.add(Q,J[0]),Q},Y.isOptional=()=>Y.safeParse(void 0).success,Y.isNullable=()=>Y.safeParse(null).success,Y}),e$=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(u1(...Q)),Y.max=(...Q)=>Y.check(aY(...Q)),Y.length=(...Q)=>Y.check(tY(...Q)),Y.nonempty=(...Q)=>Y.check(u1(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())}),PU=F("ZodString",(Y,X)=>{iY.init(Y,X),e$.init(Y,X),Y.email=(J)=>Y.check(s7(MU,J)),Y.url=(J)=>Y.check(X$(wU,J)),Y.jwt=(J)=>Y.check(O$(yU,J)),Y.emoji=(J)=>Y.check(J$(EU,J)),Y.guid=(J)=>Y.check(O9(o$,J)),Y.uuid=(J)=>Y.check(a7(X8,J)),Y.uuidv4=(J)=>Y.check(t7(X8,J)),Y.uuidv6=(J)=>Y.check(e7(X8,J)),Y.uuidv7=(J)=>Y.check(Y$(X8,J)),Y.nanoid=(J)=>Y.check(Q$(AU,J)),Y.guid=(J)=>Y.check(O9(o$,J)),Y.cuid=(J)=>Y.check($$(TU,J)),Y.cuid2=(J)=>Y.check(G$(RU,J)),Y.ulid=(J)=>Y.check(W$(CU,J)),Y.base64=(J)=>Y.check(B$(vU,J)),Y.base64url=(J)=>Y.check(Z$(hU,J)),Y.xid=(J)=>Y.check(z$(_U,J)),Y.ksuid=(J)=>Y.check(U$(IU,J)),Y.ipv4=(J)=>Y.check(H$(SU,J)),Y.ipv6=(J)=>Y.check(L$(kU,J)),Y.cidrv4=(J)=>Y.check(V$(bU,J)),Y.cidrv6=(J)=>Y.check(N$(xU,J)),Y.e164=(J)=>Y.check(K$(gU,J)),Y.datetime=(J)=>Y.check(k$(J)),Y.date=(J)=>Y.check(b$(J)),Y.time=(J)=>Y.check(x$(J)),Y.duration=(J)=>Y.check(v$(J))});function YG(Y){return r7(PU,Y)}var a=F("ZodStringFormat",(Y,X)=>{s.init(Y,X),e$.init(Y,X)}),MU=F("ZodEmail",(Y,X)=>{J7.init(Y,X),a.init(Y,X)});var o$=F("ZodGUID",(Y,X)=>{Y7.init(Y,X),a.init(Y,X)});var X8=F("ZodUUID",(Y,X)=>{X7.init(Y,X),a.init(Y,X)});var wU=F("ZodURL",(Y,X)=>{Q7.init(Y,X),a.init(Y,X)});var EU=F("ZodEmoji",(Y,X)=>{$7.init(Y,X),a.init(Y,X)});var AU=F("ZodNanoID",(Y,X)=>{G7.init(Y,X),a.init(Y,X)});var TU=F("ZodCUID",(Y,X)=>{W7.init(Y,X),a.init(Y,X)});var RU=F("ZodCUID2",(Y,X)=>{z7.init(Y,X),a.init(Y,X)});var CU=F("ZodULID",(Y,X)=>{U7.init(Y,X),a.init(Y,X)});var _U=F("ZodXID",(Y,X)=>{H7.init(Y,X),a.init(Y,X)});var IU=F("ZodKSUID",(Y,X)=>{L7.init(Y,X),a.init(Y,X)});var SU=F("ZodIPv4",(Y,X)=>{K7.init(Y,X),a.init(Y,X)});var kU=F("ZodIPv6",(Y,X)=>{O7.init(Y,X),a.init(Y,X)});var bU=F("ZodCIDRv4",(Y,X)=>{q7.init(Y,X),a.init(Y,X)});var xU=F("ZodCIDRv6",(Y,X)=>{F7.init(Y,X),a.init(Y,X)});var vU=F("ZodBase64",(Y,X)=>{D7.init(Y,X),a.init(Y,X)});var hU=F("ZodBase64URL",(Y,X)=>{P7.init(Y,X),a.init(Y,X)});var gU=F("ZodE164",(Y,X)=>{M7.init(Y,X),a.init(Y,X)});var yU=F("ZodJWT",(Y,X)=>{w7.init(Y,X),a.init(Y,X)});var XG=F("ZodNumber",(Y,X)=>{Z9.init(Y,X),t.init(Y,X),Y.gt=(Q,$)=>Y.check(rY(Q,$)),Y.gte=(Q,$)=>Y.check(HY(Q,$)),Y.min=(Q,$)=>Y.check(HY(Q,$)),Y.lt=(Q,$)=>Y.check(oY(Q,$)),Y.lte=(Q,$)=>Y.check(UY(Q,$)),Y.max=(Q,$)=>Y.check(UY(Q,$)),Y.int=(Q)=>Y.check(r$(Q)),Y.safe=(Q)=>Y.check(r$(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,$)=>Y.check(sY(Q,$)),Y.step=(Q,$)=>Y.check(sY(Q,$)),Y.finite=()=>Y;let J=Y._zod.bag;Y.minValue=Math.max(J.minimum??Number.NEGATIVE_INFINITY,J.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Y.maxValue=Math.min(J.maximum??Number.POSITIVE_INFINITY,J.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Y.isInt=(J.format??"").includes("int")||Number.isSafeInteger(J.multipleOf??0.5),Y.isFinite=!0,Y.format=J.format??null});function JG(Y){return P$(XG,Y)}var fU=F("ZodNumberFormat",(Y,X)=>{E7.init(Y,X),XG.init(Y,X)});function r$(Y){return M$(fU,Y)}var mU=F("ZodBoolean",(Y,X)=>{A7.init(Y,X),t.init(Y,X)});function QG(Y){return w$(mU,Y)}var cU=F("ZodNull",(Y,X)=>{T7.init(Y,X),t.init(Y,X)});function $G(Y){return E$(cU,Y)}var uU=F("ZodUnknown",(Y,X)=>{R7.init(Y,X),t.init(Y,X)});function LY(){return A$(uU)}var pU=F("ZodNever",(Y,X)=>{C7.init(Y,X),t.init(Y,X)});function _9(Y){return T$(pU,Y)}var lU=F("ZodArray",(Y,X)=>{_7.init(Y,X),t.init(Y,X),Y.element=X.element,Y.min=(J,Q)=>Y.check(u1(J,Q)),Y.nonempty=(J)=>Y.check(u1(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 R$(lU,Y,X)}var GG=F("ZodObject",(Y,X)=>{k7.init(Y,X),t.init(Y,X),u.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 u.extend(Y,J)},Y.safeExtend=(J)=>{return u.safeExtend(Y,J)},Y.merge=(J)=>u.merge(Y,J),Y.pick=(J)=>u.pick(Y,J),Y.omit=(J)=>u.omit(Y,J),Y.partial=(...J)=>u.partial(NG,Y,J[0]),Y.required=(...J)=>u.required(BG,Y,J[0])});function WG(Y,X){let J={type:"object",get shape(){return u.assignProp(this,"shape",Y?u.objectClone(Y):{}),this.shape},...u.normalizeParams(X)};return new GG(J)}function zG(Y,X){return new GG({type:"object",get shape(){return u.assignProp(this,"shape",u.objectClone(Y)),this.shape},catchall:LY(),...u.normalizeParams(X)})}var UG=F("ZodUnion",(Y,X)=>{K9.init(Y,X),t.init(Y,X),Y.options=X.options});function S9(Y,X){return new UG({type:"union",options:Y,...u.normalizeParams(X)})}var dU=F("ZodDiscriminatedUnion",(Y,X)=>{UG.init(Y,X),b7.init(Y,X)});function HG(Y,X,J){return new dU({type:"union",options:X,discriminator:Y,...u.normalizeParams(J)})}var iU=F("ZodIntersection",(Y,X)=>{x7.init(Y,X),t.init(Y,X)});function nU(Y,X){return new iU({type:"intersection",left:Y,right:X})}var oU=F("ZodRecord",(Y,X)=>{v7.init(Y,X),t.init(Y,X),Y.keyType=X.keyType,Y.valueType=X.valueType});function LG(Y,X,J){return new oU({type:"record",keyType:Y,valueType:X,...u.normalizeParams(J)})}var C9=F("ZodEnum",(Y,X)=>{h7.init(Y,X),t.init(Y,X),Y.enum=X.entries,Y.options=Object.values(X.entries);let J=new Set(Object.keys(X.entries));Y.extract=(Q,$)=>{let G={};for(let W of Q)if(J.has(W))G[W]=X.entries[W];else throw Error(`Key ${W} not found in enum`);return new C9({...X,checks:[],...u.normalizeParams($),entries:G})},Y.exclude=(Q,$)=>{let G={...X.entries};for(let W of Q)if(J.has(W))delete G[W];else throw Error(`Key ${W} not found in enum`);return new C9({...X,checks:[],...u.normalizeParams($),entries:G})}});function k9(Y,X){let J=Array.isArray(Y)?Object.fromEntries(Y.map((Q)=>[Q,Q])):Y;return new C9({type:"enum",entries:J,...u.normalizeParams(X)})}var rU=F("ZodLiteral",(Y,X)=>{g7.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 VG(Y,X){return new rU({type:"literal",values:Array.isArray(Y)?Y:[Y],...u.normalizeParams(X)})}var sU=F("ZodTransform",(Y,X)=>{y7.init(Y,X),t.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new e1(Y.constructor.name);J.addIssue=(G)=>{if(typeof G==="string")J.issues.push(u.issue(G,J.value,X));else{let W=G;if(W.fatal)W.continue=!1;W.code??(W.code="custom"),W.input??(W.input=J.value),W.inst??(W.inst=Y),J.issues.push(u.issue(W))}};let $=X.transform(J.value,J);if($ instanceof Promise)return $.then((G)=>{return J.value=G,J});return J.value=$,J}});function aU(Y){return new sU({type:"transform",transform:Y})}var NG=F("ZodOptional",(Y,X)=>{f7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function s$(Y){return new NG({type:"optional",innerType:Y})}var tU=F("ZodNullable",(Y,X)=>{m7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function a$(Y){return new tU({type:"nullable",innerType:Y})}var eU=F("ZodDefault",(Y,X)=>{c7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function YH(Y,X){return new eU({type:"default",innerType:Y,get defaultValue(){return typeof X==="function"?X():u.shallowClone(X)}})}var XH=F("ZodPrefault",(Y,X)=>{u7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function JH(Y,X){return new XH({type:"prefault",innerType:Y,get defaultValue(){return typeof X==="function"?X():u.shallowClone(X)}})}var BG=F("ZodNonOptional",(Y,X)=>{p7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function QH(Y,X){return new BG({type:"nonoptional",innerType:Y,...u.normalizeParams(X)})}var $H=F("ZodCatch",(Y,X)=>{l7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function GH(Y,X){return new $H({type:"catch",innerType:Y,catchValue:typeof X==="function"?X:()=>X})}var WH=F("ZodPipe",(Y,X)=>{d7.init(Y,X),t.init(Y,X),Y.in=X.in,Y.out=X.out});function t$(Y,X){return new WH({type:"pipe",in:Y,out:X})}var zH=F("ZodReadonly",(Y,X)=>{i7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function UH(Y){return new zH({type:"readonly",innerType:Y})}var HH=F("ZodLazy",(Y,X)=>{n7.init(Y,X),t.init(Y,X),Y.unwrap=()=>Y._zod.def.getter()});function ZG(Y){return new HH({type:"lazy",getter:Y})}var b9=F("ZodCustom",(Y,X)=>{o7.init(Y,X),t.init(Y,X)});function KG(Y,X){return C$(b9,Y??(()=>!0),X)}function LH(Y,X={}){return _$(b9,Y,X)}function VH(Y){return I$(Y)}function OG(Y,X={error:`Input not instance of ${Y.name}`}){let J=new b9({type:"custom",check:"custom",fn:(Q)=>Q instanceof Y,abort:!0,...u.normalizeParams(X)});return J._zod.bag.Class=Y,J}var NH=[{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]}],U4=[...NH,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];var BH=12,ZH=131072,H4=ZH+BH;async function J8(Y){var X;try{await((X=Y.body)==null?void 0:X.cancel())}catch(J){}}var TG="AI_DownloadError",RG=`vercel.ai.error.${TG}`,KH=Symbol.for(RG),qG,FG,O0=class extends(FG=f,qG=KH,FG){constructor({url:Y,statusCode:X,statusText:J,cause:Q,message:$=Q==null?`Failed to download ${Y}: ${X} ${J}`:`Failed to download ${Y}: ${Q}`}){super({name:TG,message:$,cause:Q});this[qG]=!0,this.url=Y,this.statusCode=X,this.statusText=J}static isInstance(Y){return f.hasMarker(Y,RG)}};function OH(Y=globalThis){return Y.window!=null}function jG(Y,X){try{return new URL(Y).origin===new URL(X).origin}catch(J){return!1}}function qH(Y){let X;try{X=new URL(Y)}catch(Q){throw new O0({url:Y,message:`Invalid URL: ${Y}`})}if(X.protocol==="data:")return;if(X.protocol!=="http:"&&X.protocol!=="https:")throw new O0({url:Y,message:`URL scheme must be http, https, or data, got ${X.protocol}`});let J=X.hostname.toLowerCase().replace(/\.+$/,"");if(!J)throw new O0({url:Y,message:"URL must have a hostname"});if(J==="localhost"||J.endsWith(".local")||J.endsWith(".localhost"))throw new O0({url:Y,message:`URL with hostname ${J} is not allowed`});if(J.startsWith("[")&&J.endsWith("]")){let Q=J.slice(1,-1);if(CG(Q))throw new O0({url:Y,message:`URL with IPv6 address ${J} is not allowed`});return}if(f9(J)){if(m9(J))throw new O0({url:Y,message:`URL with IP address ${J} is not allowed`});return}}function FH({address:Y,family:X,hostname:J}){if(X===4?!f9(Y)||m9(Y):X===6?CG(Y):!0)throw new O0({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,$]=X;if(J===0)return!0;if(J===10)return!0;if(J===100&&Q>=64&&Q<=127)return!0;if(J===127)return!0;if(J===169&&Q===254)return!0;if(J===172&&Q>=16&&Q<=31)return!0;if(J===192&&Q===0&&$===0)return!0;if(J===192&&Q===0&&$===2)return!0;if(J===192&&Q===168)return!0;if(J===198&&(Q===18||Q===19))return!0;if(J===198&&Q===51&&$===100)return!0;if(J===203&&Q===0&&$===113)return!0;if(J>=224)return!0;return!1}function jH(Y){let X=Y.toLowerCase(),J=X.indexOf("%");if(J!==-1)X=X.slice(0,J);let Q=X.split("::");if(Q.length>2)return null;let $=(W)=>{if(W==="")return[];let U=[],L=W.split(":");for(let H=0;H<L.length;H++){let N=L[H];if(N.includes(".")){if(H!==L.length-1||!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(G===null)return null;if(Q.length===2){let W=$(Q[1]);if(W===null)return null;let U=8-G.length-W.length;if(U<0)return null;return[...G,...Array(U).fill(0),...W]}return G.length===8?G:null}function CG(Y){let X=jH(Y);if(X===null)return!0;let J=($)=>X.slice(0,$).every((G)=>G===0);if(J(7)&&(X[7]===0||X[7]===1))return!0;if((X[0]&65024)===64512)return!0;if((X[0]&65472)===65152)return!0;if((X[0]&65472)===65216)return!0;if((X[0]&65280)===65280)return!0;if(X[0]===8193&&X[1]===3512)return!0;if(X[0]===16383&&(X[1]&61440)===0)return!0;if(J(6)||J(5)&&X[5]===65535||J(4)&&X[4]===65535&&X[5]===0||X[0]===100&&X[1]===65435&&X[2]===0&&X[3]===0&&X[4]===0&&X[5]===0||X[0]===100&&X[1]===65435&&X[2]===1){let $=X[6]>>8&255,G=X[6]&255,W=X[7]>>8&255,U=X[7]&255;return m9(`${$}.${G}.${W}.${U}`)}return!1}function DH(Y){return(X,J,Q)=>{Y(X,{...J,all:!0},($,G)=>{if($){Q($);return}try{let[W]=G;if(W==null)throw Error(`Hostname ${X} did not resolve to an address`);for(let{address:U,family:L}of G)FH({address:U,family:L,hostname:X});if(J.all===!0)Q(null,G);else Q(null,W.address,W.family)}catch(W){Q(W instanceof Error?W:Error(String(W)))}})}}var x9,_G=globalThis.fetch,PH=EH(_G);function MH(){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 wH(){if(!MH()||!PH||globalThis.fetch!==_G)return globalThis.fetch;return x9!=null?x9:x9=Promise.resolve().then(AH)}function EH(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 AH(){let{createRequire:Y}=DG("node:module"),{lookup:X}=DG("node:dns"),{Agent:J,fetch:Q}=Y(IG())("undici"),$=new J({connect:{lookup:DH(X)}});return(G,W)=>Q(G,{...W,dispatcher:$})}function DG(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 IG(){let Y=Error.prepareStackTrace;try{Error.prepareStackTrace=($,G)=>G;let X=Error("Capture current module path");Error.captureStackTrace(X,IG);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 TH=["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 RH(Y){let X=new Headers(Y);for(let J of TH)X.delete(J);return X}var CH=10,_H=new Set([301,302,303,307,308]);async function SG({url:Y,headers:X,abortSignal:J,maxRedirects:Q=CH,fetch:$,trustedOrigin:G}){let W=X===void 0?void 0:RH(X),U=(H)=>{let N={signal:J,redirect:H};if(W!==void 0)N.headers=new Headers(W);return N},L=Y;for(let H=0;H<=Q;H++){let N=G!==void 0&&jG(L,G);if(!N)qH(L);let O=$!=null?$:N?globalThis.fetch:await wH(),Z=await O(L,U("manual"));if(Z.type==="opaqueredirect"){if(!OH())throw new O0({url:Y,message:`Redirect from ${L} could not be validated and was blocked`});return await O(L,U("follow"))}let V=Z.headers.get("location");if(_H.has(Z.status)&&V){await J8(Z);let K=new URL(V,L).toString();if(W!==void 0&&!jG(K,L)){let j=W.get("user-agent");W=new Headers(j==null?void 0:{"user-agent":j})}L=K;continue}return Z}throw new O0({url:Y,message:`Too many redirects (max ${Q})`})}var c9=2147483648;async function kG({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 O0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes (Content-Length: ${N}).`})}let $=Y.body;if($==null)return new Uint8Array(0);let G=$.getReader(),W=[],U=0;try{while(!0){let{done:N,value:O}=await G.read();if(N)break;if(U+=O.length,U>J)throw new O0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes.`});W.push(O)}}finally{try{await G.cancel()}finally{G.releaseLock()}}let L=new Uint8Array(U),H=0;for(let N of W)L.set(N,H),H+=N.length;return L}var G0=({prefix:Y,size:X=16,alphabet:J="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:Q="-"}={})=>{let $=()=>{let G=J.length,W=Array(X);for(let U=0;U<X;U++)W[U]=J[Math.random()*G|0];return W.join("")};if(Y==null)return $;if(J.includes(Q))throw new V6({argument:"separator",message:`The separator "${Q}" must not be part of the alphabet "${J}".`});return()=>`${Y}${Q}${$()}`},N4=G0();function bG(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 IH(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 p1(Y,...X){let J=new Headers(IH(Y)),Q=J.get("user-agent")||"";return J.set("user-agent",[Q,...X].filter(Boolean).join(" ")),Object.fromEntries(J.entries())}function xG(Y){var X,J;return(J=(X=globalThis.Buffer)==null?void 0:X.isBuffer(Y))!=null?J:!1}var SH=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,kH=/"(?: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 PG(Y){let X=JSON.parse(Y);if(X===null||typeof X!=="object")return X;if(SH.test(Y)===!1&&kH.test(Y)===!1)return X;return bH(X)}function bH(Y){let X=[Y];while(X.length){let J=X;X=[];for(let Q of J){if(Object.prototype.hasOwnProperty.call(Q,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(Q,"constructor")&&Q.constructor!==null&&typeof Q.constructor==="object"&&Object.prototype.hasOwnProperty.call(Q.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let $ in Q){let G=Q[$];if(G&&typeof G==="object")X.push(G)}}}return Y}function xH(Y){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(J){return PG(Y)}try{return PG(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]=A1(J[Q])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(A1):A1(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(A1);if(Y.allOf!=null)Y.allOf=Y.allOf.map(A1);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(A1);let{definitions:X}=Y;if(X!=null)for(let J of Object.keys(X))X[J]=A1(X[J]);return Y}function A1(Y){if(typeof Y==="boolean")return Y;return u9(Y)}var vH=Symbol("Let zodToJsonSchema decide on which parser to use"),MG={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"},hH=(Y)=>typeof Y==="string"?{...MG,name:Y}:{...MG,...Y};function A0(){return{}}function gH(Y,X){var J,Q,$;let G={type:"array"};if(((J=Y.type)==null?void 0:J._def)&&(($=(Q=Y.type)==null?void 0:Q._def)==null?void 0:$.typeName)!=="ZodAny")G.items=n(Y.type._def,{...X,currentPath:[...X.currentPath,"items"]});if(Y.minLength)G.minItems=Y.minLength.value;if(Y.maxLength)G.maxItems=Y.maxLength.value;if(Y.exactLength)G.minItems=Y.exactLength.value,G.maxItems=Y.exactLength.value;return G}function yH(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 fH(){return{type:"boolean"}}function vG(Y,X){return n(Y.type._def,X)}var mH=(Y,X)=>{return n(Y.innerType._def,X)};function hG(Y,X,J){let Q=J!=null?J:X.dateStrategy;if(Array.isArray(Q))return{anyOf:Q.map(($)=>hG(Y,X,$))};switch(Q){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return cH(Y)}}var cH=(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 uH(Y,X){return{...n(Y.innerType._def,X),default:Y.defaultValue()}}function pH(Y,X){return X.effectStrategy==="input"?n(Y.schema._def,X):A0()}function lH(Y){return{type:"string",enum:Array.from(Y.values)}}var dH=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function iH(Y,X){let J=[n(Y.left._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),n(Y.right._def,{...X,currentPath:[...X.currentPath,"allOf","1"]})].filter(($)=>!!$),Q=[];return J.forEach(($)=>{if(dH($))Q.push(...$.allOf);else{let G=$;if("additionalProperties"in $&&$.additionalProperties===!1){let{additionalProperties:W,...U}=$;G=U}Q.push(G)}}),Q.length?{allOf:Q}:void 0}function nH(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,k0={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(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 gG(Y,X){let J={type:"string"};if(Y.checks)for(let Q of Y.checks)switch(Q.kind){case"min":J.minLength=typeof J.minLength==="number"?Math.max(J.minLength,Q.value):Q.value;break;case"max":J.maxLength=typeof J.maxLength==="number"?Math.min(J.maxLength,Q.value):Q.value;break;case"email":switch(X.emailStrategy){case"format:email":b0(J,"email",Q.message,X);break;case"format:idn-email":b0(J,"idn-email",Q.message,X);break;case"pattern:zod":K0(J,k0.email,Q.message,X);break}break;case"url":b0(J,"uri",Q.message,X);break;case"uuid":b0(J,"uuid",Q.message,X);break;case"regex":K0(J,Q.regex,Q.message,X);break;case"cuid":K0(J,k0.cuid,Q.message,X);break;case"cuid2":K0(J,k0.cuid2,Q.message,X);break;case"startsWith":K0(J,RegExp(`^${h9(Q.value,X)}`),Q.message,X);break;case"endsWith":K0(J,RegExp(`${h9(Q.value,X)}$`),Q.message,X);break;case"datetime":b0(J,"date-time",Q.message,X);break;case"date":b0(J,"date",Q.message,X);break;case"time":b0(J,"time",Q.message,X);break;case"duration":b0(J,"duration",Q.message,X);break;case"length":J.minLength=typeof J.minLength==="number"?Math.max(J.minLength,Q.value):Q.value,J.maxLength=typeof J.maxLength==="number"?Math.min(J.maxLength,Q.value):Q.value;break;case"includes":{K0(J,RegExp(h9(Q.value,X)),Q.message,X);break}case"ip":{if(Q.version!=="v6")b0(J,"ipv4",Q.message,X);if(Q.version!=="v4")b0(J,"ipv6",Q.message,X);break}case"base64url":K0(J,k0.base64url,Q.message,X);break;case"jwt":K0(J,k0.jwt,Q.message,X);break;case"cidr":{if(Q.version!=="v6")K0(J,k0.ipv4Cidr,Q.message,X);if(Q.version!=="v4")K0(J,k0.ipv6Cidr,Q.message,X);break}case"emoji":K0(J,k0.emoji(),Q.message,X);break;case"ulid":{K0(J,k0.ulid,Q.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{b0(J,"binary",Q.message,X);break}case"contentEncoding:base64":{J.contentEncoding="base64";break}case"pattern:zod":{K0(J,k0.base64,Q.message,X);break}}break}case"nanoid":K0(J,k0.nanoid,Q.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return J}function h9(Y,X){return X.patternStrategy==="escape"?rH(Y):Y}var oH=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function rH(Y){let X="";for(let J=0;J<Y.length;J++){if(!oH.has(Y[J]))X+="\\";X+=Y[J]}return X}function b0(Y,X,J,Q){var $;if(Y.format||(($=Y.anyOf)==null?void 0:$.some((G)=>G.format))){if(!Y.anyOf)Y.anyOf=[];if(Y.format)Y.anyOf.push({format:Y.format}),delete Y.format;Y.anyOf.push({format:X,...J&&Q.errorMessages&&{errorMessage:{format:J}}})}else Y.format=X}function K0(Y,X,J,Q){var $;if(Y.pattern||(($=Y.allOf)==null?void 0:$.some((G)=>G.pattern))){if(!Y.allOf)Y.allOf=[];if(Y.pattern)Y.allOf.push({pattern:Y.pattern}),delete Y.pattern;Y.allOf.push({pattern:wG(X,Q),...J&&Q.errorMessages&&{errorMessage:{pattern:J}}})}else Y.pattern=wG(X,Q)}function wG(Y,X){var J;if(!X.applyRegexFlags||!Y.flags)return Y.source;let Q={i:Y.flags.includes("i"),m:Y.flags.includes("m"),s:Y.flags.includes("s")},$=Q.i?Y.source.toLowerCase():Y.source,G="",W=!1,U=!1,L=!1;for(let H=0;H<$.length;H++){if(W){G+=$[H],W=!1;continue}if(Q.i){if(U){if($[H].match(/[a-z]/)){if(L)G+=$[H],G+=`${$[H-2]}-${$[H]}`.toUpperCase(),L=!1;else if($[H+1]==="-"&&((J=$[H+2])==null?void 0:J.match(/[a-z]/)))G+=$[H],L=!0;else G+=`${$[H]}${$[H].toUpperCase()}`;continue}}else if($[H].match(/[a-z]/)){G+=`[${$[H]}${$[H].toUpperCase()}]`;continue}}if(Q.m){if($[H]==="^"){G+=`(^|(?<=[\r
138
188
  ]))`;continue}else if($[H]==="$"){G+=`($|(?=[\r
139
- ]))`;continue}}if(Q.s&&$[H]==="."){G+=K?`${$[H]}\r
189
+ ]))`;continue}}if(Q.s&&$[H]==="."){G+=U?`${$[H]}\r
140
190
  `:`[${$[H]}\r
141
- ]`;continue}if(G+=$[H],$[H]==="\\")W=!0;else if(K&&$[H]==="]")K=!1;else if(!K&&$[H]==="[")K=!0}try{new RegExp(G)}catch(H){return console.warn(`Could not convert regex pattern at ${X.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Y.source}return G}function $G(Y,X){var J,Q,$,G,W,K;let U={type:"object",additionalProperties:(J=i(Y.valueType._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]}))!=null?J:X.allowedAdditionalProperties};if(((Q=Y.keyType)==null?void 0:Q._def.typeName)==="ZodString"&&(($=Y.keyType._def.checks)==null?void 0:$.length)){let{type:H,...N}=QG(Y.keyType._def,X);return{...U,propertyNames:N}}else if(((G=Y.keyType)==null?void 0:G._def.typeName)==="ZodEnum")return{...U,propertyNames:{enum:Y.keyType._def.values}};else if(((W=Y.keyType)==null?void 0:W._def.typeName)==="ZodBranded"&&Y.keyType._def.type._def.typeName==="ZodString"&&((K=Y.keyType._def.type._def.checks)==null?void 0:K.length)){let{type:H,...N}=XG(Y.keyType._def,X);return{...U,propertyNames:N}}return U}function nK(Y,X){if(X.mapStrategy==="record")return $G(Y,X);let J=i(Y.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||E0(),Q=i(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||E0();return{type:"array",maxItems:125,items:{type:"array",items:[J,Q],minItems:2,maxItems:2}}}function oK(Y){let X=Y.values,Q=Object.keys(Y.values).filter((G)=>{return typeof X[X[G]]!=="number"}).map((G)=>X[G]),$=Array.from(new Set(Q.map((G)=>typeof G)));return{type:$.length===1?$[0]==="string"?"string":"number":["string","number"],enum:Q}}function rK(){return{not:E0()}}function sK(){return{type:"null"}}var j9={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function aK(Y,X){let J=Y.options instanceof Map?Array.from(Y.options.values()):Y.options;if(J.every((Q)=>(Q._def.typeName in j9)&&(!Q._def.checks||!Q._def.checks.length))){let Q=J.reduce(($,G)=>{let W=j9[G._def.typeName];return W&&!$.includes(W)?[...$,W]:$},[]);return{type:Q.length>1?Q:Q[0]}}else if(J.every((Q)=>Q._def.typeName==="ZodLiteral"&&!Q.description)){let Q=J.reduce(($,G)=>{let W=typeof G._def.value;switch(W){case"string":case"number":case"boolean":return[...$,W];case"bigint":return[...$,"integer"];case"object":if(G._def.value===null)return[...$,"null"];case"symbol":case"undefined":case"function":default:return $}},[]);if(Q.length===J.length){let $=Q.filter((G,W,K)=>K.indexOf(G)===W);return{type:$.length>1?$:$[0],enum:J.reduce((G,W)=>{return G.includes(W._def.value)?G:[...G,W._def.value]},[])}}}else if(J.every((Q)=>Q._def.typeName==="ZodEnum"))return{type:"string",enum:J.reduce((Q,$)=>[...Q,...$._def.values.filter((G)=>!Q.includes(G))],[])};return tK(Y,X)}var tK=(Y,X)=>{let J=(Y.options instanceof Map?Array.from(Y.options.values()):Y.options).map((Q,$)=>i(Q._def,{...X,currentPath:[...X.currentPath,"anyOf",`${$}`]})).filter((Q)=>!!Q&&(!X.strictUnions||typeof Q==="object"&&Object.keys(Q).length>0));return J.length?{anyOf:J}:void 0};function eK(Y,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Y.innerType._def.typeName)&&(!Y.innerType._def.checks||!Y.innerType._def.checks.length))return{type:[j9[Y.innerType._def.typeName],"null"]};let J=i(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return J&&{anyOf:[J,{type:"null"}]}}function YU(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 XU(Y,X){let J={type:"object",properties:{}},Q=[],$=Y.shape();for(let W in $){let K=$[W];if(K===void 0||K._def===void 0)continue;let U=QU(K),H=i(K._def,{...X,currentPath:[...X.currentPath,"properties",W],propertyPath:[...X.currentPath,"properties",W]});if(H===void 0)continue;if(J.properties[W]=H,!U)Q.push(W)}if(Q.length)J.required=Q;let G=JU(Y,X);if(G!==void 0)J.additionalProperties=G;return J}function JU(Y,X){if(Y.catchall._def.typeName!=="ZodNever")return i(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 QU(Y){try{return Y.isOptional()}catch(X){return!0}}var $U=(Y,X)=>{var J;if(X.currentPath.toString()===((J=X.propertyPath)==null?void 0:J.toString()))return i(Y.innerType._def,X);let Q=i(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return Q?{anyOf:[{not:E0()},Q]}:E0()},GU=(Y,X)=>{if(X.pipeStrategy==="input")return i(Y.in._def,X);else if(X.pipeStrategy==="output")return i(Y.out._def,X);let J=i(Y.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),Q=i(Y.out._def,{...X,currentPath:[...X.currentPath,"allOf",J?"1":"0"]});return{allOf:[J,Q].filter(($)=>$!==void 0)}};function WU(Y,X){return i(Y.type._def,X)}function zU(Y,X){let Q={type:"array",uniqueItems:!0,items:i(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 KU(Y,X){if(Y.rest)return{type:"array",minItems:Y.items.length,items:Y.items.map((J,Q)=>i(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[]),additionalItems:i(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)=>i(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[])}}function UU(){return{not:E0()}}function HU(){return E0()}var LU=(Y,X)=>{return i(Y.innerType._def,X)},NU=(Y,X,J)=>{switch(X){case"ZodString":return QG(Y,J);case"ZodNumber":return YU(Y);case"ZodObject":return XU(Y,J);case"ZodBigInt":return vK(Y);case"ZodBoolean":return hK();case"ZodDate":return JG(Y,J);case"ZodUndefined":return UU();case"ZodNull":return sK();case"ZodArray":return xK(Y,J);case"ZodUnion":case"ZodDiscriminatedUnion":return aK(Y,J);case"ZodIntersection":return pK(Y,J);case"ZodTuple":return KU(Y,J);case"ZodRecord":return $G(Y,J);case"ZodLiteral":return lK(Y);case"ZodEnum":return cK(Y);case"ZodNativeEnum":return oK(Y);case"ZodNullable":return eK(Y,J);case"ZodOptional":return $U(Y,J);case"ZodMap":return nK(Y,J);case"ZodSet":return zU(Y,J);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return WU(Y,J);case"ZodNaN":case"ZodNever":return rK();case"ZodEffects":return mK(Y,J);case"ZodAny":return E0();case"ZodUnknown":return HU();case"ZodDefault":return fK(Y,J);case"ZodBranded":return XG(Y,J);case"ZodReadonly":return LU(Y,J);case"ZodCatch":return gK(Y,J);case"ZodPipeline":return GU(Y,J);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Q)=>{return})(X)}},VU=(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 i(Y,X,J=!1){var Q;let $=X.seen.get(Y);if(X.override){let U=(Q=X.override)==null?void 0:Q.call(X,Y,X,$,J);if(U!==kK)return U}if($&&!J){let U=BU($,X);if(U!==void 0)return U}let G={def:Y,path:X.currentPath,jsonSchema:void 0};X.seen.set(Y,G);let W=NU(Y,Y.typeName,X),K=typeof W==="function"?i(W(),X):W;if(K)ZU(Y,X,K);if(X.postProcess){let U=X.postProcess(K,Y,X);return G.jsonSchema=K,U}return G.jsonSchema=K,K}var BU=(Y,X)=>{switch(X.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:VU(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`),E0();return X.$refStrategy==="seen"?E0():void 0}}},ZU=(Y,X,J)=>{if(Y.description)J.description=Y.description;return J},OU=(Y)=>{let X=bK(Y),J=X.name!==void 0?[...X.basePath,X.definitionPath,X.name]:X.basePath;return{...X,currentPath:J,propertyPath:void 0,seen:new Map(Object.entries(X.definitions).map(([Q,$])=>[$._def,{def:$._def,path:[...X.basePath,X.definitionPath,Q],jsonSchema:void 0}]))}},FU=(Y,X)=>{var J;let Q=OU(X),$=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((H,[N,O])=>{var B;return{...H,[N]:(B=i(O._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,N]},!0))!=null?B:E0()}},{}):void 0,G=typeof X==="string"?X:(X==null?void 0:X.nameStrategy)==="title"?void 0:X==null?void 0:X.name,W=(J=i(Y._def,G===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,G]},!1))!=null?J:E0(),K=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if(K!==void 0)W.title=K;let U=G===void 0?$?{...W,[Q.definitionPath]:$}:W:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,G].join("/"),[Q.definitionPath]:{...$,[G]:W}};return U.$schema="http://json-schema.org/draft-07/schema#",U},D9=Symbol.for("vercel.ai.schema");function dY(Y){let X;return()=>{if(X==null)X=Y();return X}}function iY(Y,{validate:X}={}){return{[D9]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:X}}function qU(Y){return typeof Y==="object"&&Y!==null&&D9 in Y&&Y[D9]===!0&&"jsonSchema"in Y&&"validate"in Y}function nY(Y){return Y==null?iY({type:"object",properties:{},additionalProperties:!1}):qU(Y)?Y:("~standard"in Y)?Y["~standard"].vendor==="zod"?YY(Y):jU(Y):Y()}function jU(Y){return iY(()=>{if(!DU(Y))throw Error(`Standard schema vendor '${Y["~standard"].vendor}' does not support JSON Schema conversion.`);return M9(Y["~standard"].jsonSchema.input({target:"draft-07"}))},{validate:async(X)=>{let J=await Y["~standard"].validate(X);return"value"in J?{success:!0,value:J.value}:{success:!1,error:new v0({value:X,cause:J.issues})}}})}function DU(Y){return Y["~standard"].jsonSchema!=null}function PU(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return iY(()=>FU(Y,{$refStrategy:Q?"root":"none"}),{validate:async($)=>{let G=await Y.safeParseAsync($);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function wU(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return iY(()=>M9(a7(Y,{target:"draft-7",io:"input",reused:Q?"ref":"inline"})),{validate:async($)=>{let G=await uY(Y,$);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function EU(Y){return"_zod"in Y}function YY(Y,X){if(EU(Y))return wU(Y,X);else return PU(Y,X)}async function XY({value:Y,schema:X,context:J}){let Q=nY(X);try{if(Q.validate==null)return{success:!0,value:Y,rawValue:Y};let $=await Q.validate(Y);if($.success)return{success:!0,value:$.value,rawValue:Y};return{success:!1,error:v0.wrap({value:Y,cause:$.error,context:J}),rawValue:Y}}catch($){return{success:!1,error:v0.wrap({value:Y,cause:$,context:J}),rawValue:Y}}}async function G1({text:Y,schema:X}){try{let J=SK(Y);if(X==null)return{success:!0,value:J,rawValue:J};return await XY({value:J,schema:X})}catch(J){return{success:!1,error:MY.isInstance(J)?J:new MY({text:Y,cause:J}),rawValue:void 0}}}async function A9(Y){if(typeof Y==="function")Y=Y();return Promise.resolve(Y)}var GG="AI_SerializationError",WG=`vercel.ai.error.${GG}`,MU=Symbol.for(WG),l$,d$,UO=class extends(d$=f,l$=MU,d$){constructor({message:Y="Failed to serialize value.",cause:X}={}){super({name:GG,message:Y,cause:X});this[l$]=!0}static isInstance(Y){return f.hasMarker(Y,WG)}};var TU=Object.defineProperty,CU=(Y,X)=>{for(var J in X)TU(Y,J,{get:X[J],enumerable:!0})},_U="AI_InvalidArgumentError",IU=`vercel.ai.error.${_U}`,SU=Symbol.for(IU),kU;kU=SU;var bU="AI_InvalidStreamPartError",xU=`vercel.ai.error.${bU}`,vU=Symbol.for(xU),hU;hU=vU;var gU="AI_InvalidToolApprovalError",yU=`vercel.ai.error.${gU}`,fU=Symbol.for(yU),mU;mU=fU;var cU="AI_InvalidToolApprovalSignatureError",uU=`vercel.ai.error.${cU}`,pU=Symbol.for(uU),lU;lU=pU;var dU="AI_InvalidToolInputError",iU=`vercel.ai.error.${dU}`,nU=Symbol.for(iU),oU;oU=nU;var rU="AI_ToolCallNotFoundForApprovalError",sU=`vercel.ai.error.${rU}`,aU=Symbol.for(sU),tU;tU=aU;var eU="AI_MissingToolResultsError",YH=`vercel.ai.error.${eU}`,XH=Symbol.for(YH),JH;JH=XH;var QH="AI_NoImageGeneratedError",$H=`vercel.ai.error.${QH}`,GH=Symbol.for($H),WH;WH=GH;var zG="AI_NoObjectGeneratedError",KG=`vercel.ai.error.${zG}`,zH=Symbol.for(KG),UG,W1=class extends f{constructor({message:Y="No object generated.",cause:X,text:J,response:Q,usage:$,finishReason:G}){super({name:zG,message:Y,cause:X});this[UG]=!0,this.text=J,this.response=Q,this.usage=$,this.finishReason=G}static isInstance(Y){return f.hasMarker(Y,KG)}};UG=zH;var KH="AI_NoOutputGeneratedError",UH=`vercel.ai.error.${KH}`,HH=Symbol.for(UH),LH;LH=HH;var NH="AI_NoSpeechGeneratedError",VH=`vercel.ai.error.${NH}`,BH=Symbol.for(VH),ZH;ZH=BH;var OH="AI_NoTranscriptGeneratedError",FH=`vercel.ai.error.${OH}`,qH=Symbol.for(FH),jH;jH=qH;var DH="AI_NoTranslationGeneratedError",PH=`vercel.ai.error.${DH}`,wH=Symbol.for(PH),EH;EH=wH;var MH="AI_NoVideoGeneratedError",AH=`vercel.ai.error.${MH}`,RH=Symbol.for(AH),TH;TH=RH;var CH="AI_NoSuchToolError",_H=`vercel.ai.error.${CH}`,IH=Symbol.for(_H),SH;SH=IH;var kH="AI_ToolCallRepairError",bH=`vercel.ai.error.${kH}`,xH=Symbol.for(bH),vH;vH=xH;var hH="AI_UIMessageStreamError",gH=`vercel.ai.error.${hH}`,yH=Symbol.for(gH),fH;fH=yH;var mH="AI_InvalidDataContentError",cH=`vercel.ai.error.${mH}`,uH=Symbol.for(cH),pH;pH=uH;var lH="AI_InvalidMessageRoleError",dH=`vercel.ai.error.${lH}`,iH=Symbol.for(dH),nH;nH=iH;var oH="AI_MessageConversionError",rH=`vercel.ai.error.${oH}`,sH=Symbol.for(rH),aH;aH=sH;var tH="AI_RetryError",eH=`vercel.ai.error.${tH}`,YL=Symbol.for(eH),XL;XL=YL;var JL="7.0.59",QL=async({url:Y,maxBytes:X,abortSignal:J})=>{var Q;let $=Y.toString();try{let G=b1({},`ai-sdk/${JL}`,e$()),W=await a$({url:$,headers:G,abortSignal:J});if(!W.ok)throw await lY(W),new O0({url:$,statusCode:W.status,statusText:W.statusText});return{data:await t$({response:W,url:$,maxBytes:X!=null?X:E9}),mediaType:(Q=W.headers.get("content-type"))!=null?Q:void 0}}catch(G){if(O0.isInstance(G))throw G;throw new O0({url:$,cause:G})}};var z={array:N9,boolean:E$,custom:v$,discriminatedUnion:_$,enum:B9,instanceof:h$,lazy:x$,literal:S$,looseObject:T$,never:L9,null:M$,number:w$,object:R$,record:I$,string:D$,union:V9,unknown:e1},q1=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),q1.optional()),z.array(q1)])),A=z.record(z.string(),z.record(z.string(),q1.optional())),QY=z.union([z.string(),z.instanceof(Uint8Array),z.instanceof(ArrayBuffer),z.custom(YG,{message:"Must be a Buffer"})]),R9=z.record(z.string(),z.string()),HG=z.object({type:z.literal("text"),text:z.string(),providerOptions:A.optional()}),$L=z.object({type:z.literal("image"),image:z.union([QY,z.instanceof(URL),R9]),mediaType:z.string().optional(),providerOptions:A.optional()}),LG=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:QY}),z.object({type:z.literal("url"),url:z.instanceof(URL)}),z.object({type:z.literal("reference"),reference:R9}),z.object({type:z.literal("text"),text:z.string()})]),GL=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:QY}),z.object({type:z.literal("url"),url:z.instanceof(URL)})]),NG=z.object({type:z.literal("file"),data:z.union([LG,QY,z.instanceof(URL),R9]),filename:z.string().optional(),mediaType:z.string(),providerOptions:A.optional()}),WL=z.object({type:z.literal("reasoning"),text:z.string(),providerOptions:A.optional()}),zL=z.object({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerOptions:A.optional()}),KL=z.object({type:z.literal("reasoning-file"),data:z.union([GL,QY,z.instanceof(URL)]),mediaType:z.string(),providerOptions:A.optional()}),UL=z.object({type:z.literal("tool-call"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerOptions:A.optional(),providerExecuted:z.boolean().optional()}),HL=z.discriminatedUnion("type",[z.object({type:z.literal("text"),value:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("json"),value:q1,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:q1,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:LG,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()})]))})]),VG=z.object({type:z.literal("tool-result"),toolCallId:z.string(),toolName:z.string(),output:HL,providerOptions:A.optional()}),LL=z.object({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string()}),NL=z.object({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional()}),VL=z.object({role:z.literal("system"),content:z.string(),providerOptions:A.optional()}),BL=z.object({role:z.literal("user"),content:z.union([z.string(),z.array(z.union([HG,$L,NG]))]),providerOptions:A.optional()}),ZL=z.object({role:z.literal("assistant"),content:z.union([z.string(),z.array(z.union([HG,zL,NG,WL,KL,UL,VG,LL]))]),providerOptions:A.optional()}),OL=z.object({role:z.literal("tool"),content:z.array(z.union([VG,NL])),providerOptions:A.optional()}),EO=z.union([VL,BL,ZL,OL]);var FL={};CU(FL,{array:()=>PL,choice:()=>wL,json:()=>EL,object:()=>DL,text:()=>jL});function qL(Y){let X=["ROOT"],J=-1,Q=null,$=0;function G(N){return N>="0"&&N<="9"||N>="A"&&N<="F"||N>="a"&&N<="f"}function W(N,O,B){switch(N){case'"':{J=O,X.pop(),X.push(B),X.push("INSIDE_STRING");break}case"f":case"t":case"n":{J=O,Q=O,X.pop(),X.push(B),X.push("INSIDE_LITERAL");break}case"-":{X.pop(),X.push(B),X.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=O,X.pop(),X.push(B),X.push("INSIDE_NUMBER");break}case"{":{J=O,X.pop(),X.push(B),X.push("INSIDE_OBJECT_START");break}case"[":{J=O,X.pop(),X.push(B),X.push("INSIDE_ARRAY_START");break}}}function K(N,O){switch(N){case",":{X.pop(),X.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{J=O,X.pop();break}}}function U(N,O){switch(N){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=O,X.pop();break}}}for(let N=0;N<Y.length;N++){let O=Y[N];switch(X[X.length-1]){case"ROOT":W(O,N,"FINISH");break;case"INSIDE_OBJECT_START":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}case"}":{J=N,X.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(O){case":":{X.pop(),X.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{W(O,N,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{K(O,N);break}case"INSIDE_STRING":{switch(O){case'"':{X.pop(),J=N;break}case"\\":{X.push("INSIDE_STRING_ESCAPE");break}default:J=N}break}case"INSIDE_ARRAY_START":{switch(O){case"]":{J=N,X.pop();break}default:{J=N,W(O,N,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(O){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=N,X.pop();break}default:{J=N;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{W(O,N,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{if(X.pop(),O==="u")$=0,X.push("INSIDE_STRING_UNICODE_ESCAPE");else J=N;break}case"INSIDE_STRING_UNICODE_ESCAPE":{if(G(O)){if($++,$===4)X.pop(),J=N}break}case"INSIDE_NUMBER":{switch(O){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=N;break}case"e":case"E":case"-":case".":break;case",":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")U(O,N);if(X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(O,N);break}case"}":{if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(O,N);break}case"]":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")U(O,N);break}default:{X.pop();break}}break}case"INSIDE_LITERAL":{let L=Y.substring(Q,N+1);if(!"false".startsWith(L)&&!"true".startsWith(L)&&!"null".startsWith(L)){if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(O,N);else if(X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")U(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 B=Y.substring(Q,Y.length);if("true".startsWith(B))H+="true".slice(B.length);else if("false".startsWith(B))H+="false".slice(B.length);else if("null".startsWith(B))H+="null".slice(B.length)}}return H}async function oY(Y){if(Y===void 0)return{value:void 0,state:"undefined-input"};let X=await G1({text:Y});if(X.success)return{value:X.value,state:"successful-parse"};if(X=await G1({text:qL(Y)}),X.success)return{value:X.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var jL=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:Y}){return Y},async parsePartialOutput({text:Y}){return{partial:Y}},createElementStreamTransform(){return}}),DL=({schema:Y,name:X,description:J})=>{let Q=nY(Y);return{name:"object",responseFormat:A9(Q.jsonSchema).then(($)=>({type:"json",schema:$,...X!=null&&{name:X},...J!=null&&{description:J}})),async parseCompleteOutput({text:$},G){let W=await G1({text:$});if(!W.success)throw new W1({message:"No object generated: could not parse the response.",cause:W.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let K=await XY({value:W.value,schema:Q});if(!K.success)throw new W1({message:"No object generated: response did not match schema.",cause:K.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});return K.value},async parsePartialOutput({text:$}){let G=await oY($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:G.value}}},createElementStreamTransform(){return}}},PL=({element:Y,name:X,description:J})=>{let Q=nY(Y);return{name:"array",responseFormat:A9(Q.jsonSchema).then(($)=>{let{$schema:G,...W}=$;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:W}},required:["elements"],additionalProperties:!1},...X!=null&&{name:X},...J!=null&&{description:J}}}),async parseCompleteOutput({text:$},G){let W=await G1({text:$});if(!W.success)throw new W1({message:"No object generated: could not parse the response.",cause:W.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let K=W.value;if(K==null||typeof K!=="object"||!("elements"in K)||!Array.isArray(K.elements))throw new W1({message:"No object generated: response did not match schema.",cause:new v0({value:K,cause:"response must be an object with an elements array"}),text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let U=[];for(let H of K.elements){let N=await XY({value:H,schema:Q});if(!N.success)throw new W1({message:"No object generated: response did not match schema.",cause:N.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});U.push(N.value)}return U},async parsePartialOutput({text:$}){let G=await oY($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let W=G.value;if(W==null||typeof W!=="object"||!("elements"in W)||!Array.isArray(W.elements))return;let K=G.state==="repaired-parse"&&W.elements.length>0?W.elements.slice(0,-1):W.elements,U=[];for(let H of K){let N=await XY({value:H,schema:Q});if(N.success)U.push(N.value)}return{partial:U}}}},createElementStreamTransform(){let $=0;return new TransformStream({transform({partialOutput:G},W){if(G!=null)for(;$<G.length;$++)W.enqueue(G[$])}})}}},wL=({options:Y,name:X,description:J})=>{return{name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:Y}},required:["result"],additionalProperties:!1},...X!=null&&{name:X},...J!=null&&{description:J}}),async parseCompleteOutput({text:Q},$){let G=await G1({text:Q});if(!G.success)throw new W1({message:"No object generated: could not parse the response.",cause:G.error,text:Q,response:$.response,usage:$.usage,finishReason:$.finishReason});let W=G.value;if(W==null||typeof W!=="object"||!("result"in W)||typeof W.result!=="string"||!Y.includes(W.result))throw new W1({message:"No object generated: response did not match schema.",cause:new v0({value:W,cause:"response must be an object that contains a choice value."}),text:Q,response:$.response,usage:$.usage,finishReason:$.finishReason});return W.result},async parsePartialOutput({text:Q}){let $=await oY(Q);switch($.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let G=$.value;if(G==null||typeof G!=="object"||!("result"in G)||typeof G.result!=="string")return;let W=Y.filter((K)=>K.startsWith(G.result));if($.state==="successful-parse")return W.includes(G.result)?{partial:G.result}:void 0;else return W.length===1?{partial:W[0]}:void 0}}},createElementStreamTransform(){return}}},EL=({name:Y,description:X}={})=>{return{name:"json",responseFormat:Promise.resolve({type:"json",...Y!=null&&{name:Y},...X!=null&&{description:X}}),async parseCompleteOutput({text:J},Q){let $=await G1({text:J});if(!$.success)throw new W1({message:"No object generated: could not parse the response.",cause:$.error,text:J,response:Q.response,usage:Q.usage,finishReason:Q.finishReason});return $.value},async parsePartialOutput({text:J}){let Q=await oY(J);switch(Q.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return Q.value===void 0?void 0:{partial:Q.value}}},createElementStreamTransform(){return}}};var TO=Q0({prefix:"aitxt",size:24}),CO=Q0({prefix:"call",size:24});var IO=class extends TransformStream{constructor(){super({transform(Y,X){X.enqueue(`data: ${JSON.stringify(Y)}
191
+ ]`;continue}if(G+=$[H],$[H]==="\\")W=!0;else if(U&&$[H]==="]")U=!1;else if(!U&&$[H]==="[")U=!0}try{new RegExp(G)}catch(H){return console.warn(`Could not convert regex pattern at ${X.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Y.source}return G}function yG(Y,X){var J,Q,$,G,W,U;let L={type:"object",additionalProperties:(J=n(Y.valueType._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]}))!=null?J:X.allowedAdditionalProperties};if(((Q=Y.keyType)==null?void 0:Q._def.typeName)==="ZodString"&&(($=Y.keyType._def.checks)==null?void 0:$.length)){let{type:H,...N}=gG(Y.keyType._def,X);return{...L,propertyNames:N}}else if(((G=Y.keyType)==null?void 0:G._def.typeName)==="ZodEnum")return{...L,propertyNames:{enum:Y.keyType._def.values}};else if(((W=Y.keyType)==null?void 0:W._def.typeName)==="ZodBranded"&&Y.keyType._def.type._def.typeName==="ZodString"&&((U=Y.keyType._def.type._def.checks)==null?void 0:U.length)){let{type:H,...N}=vG(Y.keyType._def,X);return{...L,propertyNames:N}}return L}function sH(Y,X){if(X.mapStrategy==="record")return yG(Y,X);let J=n(Y.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||A0(),Q=n(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||A0();return{type:"array",maxItems:125,items:{type:"array",items:[J,Q],minItems:2,maxItems:2}}}function aH(Y){let X=Y.values,Q=Object.keys(Y.values).filter((G)=>{return typeof X[X[G]]!=="number"}).map((G)=>X[G]),$=Array.from(new Set(Q.map((G)=>typeof G)));return{type:$.length===1?$[0]==="string"?"string":"number":["string","number"],enum:Q}}function tH(){return{not:A0()}}function eH(){return{type:"null"}}var g9={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function YL(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[G._def.typeName];return W&&!$.includes(W)?[...$,W]:$},[]);return{type:Q.length>1?Q:Q[0]}}else if(J.every((Q)=>Q._def.typeName==="ZodLiteral"&&!Q.description)){let Q=J.reduce(($,G)=>{let W=typeof G._def.value;switch(W){case"string":case"number":case"boolean":return[...$,W];case"bigint":return[...$,"integer"];case"object":if(G._def.value===null)return[...$,"null"];case"symbol":case"undefined":case"function":default:return $}},[]);if(Q.length===J.length){let $=Q.filter((G,W,U)=>U.indexOf(G)===W);return{type:$.length>1?$:$[0],enum:J.reduce((G,W)=>{return G.includes(W._def.value)?G:[...G,W._def.value]},[])}}}else if(J.every((Q)=>Q._def.typeName==="ZodEnum"))return{type:"string",enum:J.reduce((Q,$)=>[...Q,...$._def.values.filter((G)=>!Q.includes(G))],[])};return XL(Y,X)}var XL=(Y,X)=>{let J=(Y.options instanceof Map?Array.from(Y.options.values()):Y.options).map((Q,$)=>n(Q._def,{...X,currentPath:[...X.currentPath,"anyOf",`${$}`]})).filter((Q)=>!!Q&&(!X.strictUnions||typeof Q==="object"&&Object.keys(Q).length>0));return J.length?{anyOf:J}:void 0};function JL(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 QL(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=[],$=Y.shape();for(let W in $){let U=$[W];if(U===void 0||U._def===void 0)continue;let L=WL(U),H=n(U._def,{...X,currentPath:[...X.currentPath,"properties",W],propertyPath:[...X.currentPath,"properties",W]});if(H===void 0)continue;if(J.properties[W]=H,!L)Q.push(W)}if(Q.length)J.required=Q;let G=GL(Y,X);if(G!==void 0)J.additionalProperties=G;return J}function GL(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 WL(Y){try{return Y.isOptional()}catch(X){return!0}}var zL=(Y,X)=>{var J;if(X.currentPath.toString()===((J=X.propertyPath)==null?void 0:J.toString()))return n(Y.innerType._def,X);let Q=n(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return Q?{anyOf:[{not:A0()},Q]}:A0()},UL=(Y,X)=>{if(X.pipeStrategy==="input")return n(Y.in._def,X);else if(X.pipeStrategy==="output")return n(Y.out._def,X);let J=n(Y.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),Q=n(Y.out._def,{...X,currentPath:[...X.currentPath,"allOf",J?"1":"0"]});return{allOf:[J,Q].filter(($)=>$!==void 0)}};function HL(Y,X){return n(Y.type._def,X)}function LL(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 VL(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 NL(){return{not:A0()}}function BL(){return A0()}var ZL=(Y,X)=>{return n(Y.innerType._def,X)},KL=(Y,X,J)=>{switch(X){case"ZodString":return gG(Y,J);case"ZodNumber":return QL(Y);case"ZodObject":return $L(Y,J);case"ZodBigInt":return yH(Y);case"ZodBoolean":return fH();case"ZodDate":return hG(Y,J);case"ZodUndefined":return NL();case"ZodNull":return eH();case"ZodArray":return gH(Y,J);case"ZodUnion":case"ZodDiscriminatedUnion":return YL(Y,J);case"ZodIntersection":return iH(Y,J);case"ZodTuple":return VL(Y,J);case"ZodRecord":return yG(Y,J);case"ZodLiteral":return nH(Y);case"ZodEnum":return lH(Y);case"ZodNativeEnum":return aH(Y);case"ZodNullable":return JL(Y,J);case"ZodOptional":return zL(Y,J);case"ZodMap":return sH(Y,J);case"ZodSet":return LL(Y,J);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return HL(Y,J);case"ZodNaN":case"ZodNever":return tH();case"ZodEffects":return pH(Y,J);case"ZodAny":return A0();case"ZodUnknown":return BL();case"ZodDefault":return uH(Y,J);case"ZodBranded":return vG(Y,J);case"ZodReadonly":return ZL(Y,J);case"ZodCatch":return mH(Y,J);case"ZodPipeline":return UL(Y,J);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Q)=>{return})(X)}},OL=(Y,X)=>{let J=0;for(;J<Y.length&&J<X.length;J++)if(Y[J]!==X[J])break;return[(Y.length-J).toString(),...X.slice(J)].join("/")};function n(Y,X,J=!1){var Q;let $=X.seen.get(Y);if(X.override){let L=(Q=X.override)==null?void 0:Q.call(X,Y,X,$,J);if(L!==vH)return L}if($&&!J){let L=qL($,X);if(L!==void 0)return L}let G={def:Y,path:X.currentPath,jsonSchema:void 0};X.seen.set(Y,G);let W=KL(Y,Y.typeName,X),U=typeof W==="function"?n(W(),X):W;if(U)FL(Y,X,U);if(X.postProcess){let L=X.postProcess(U,Y,X);return G.jsonSchema=U,L}return G.jsonSchema=U,U}var qL=(Y,X)=>{switch(X.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:OL(X.currentPath,Y.path)};case"none":case"seen":{if(Y.path.length<X.currentPath.length&&Y.path.every((J,Q)=>X.currentPath[Q]===J))return console.warn(`Recursive reference detected at ${X.currentPath.join("/")}! Defaulting to any`),A0();return X.$refStrategy==="seen"?A0():void 0}}},FL=(Y,X,J)=>{if(Y.description)J.description=Y.description;return J},jL=(Y)=>{let X=hH(Y),J=X.name!==void 0?[...X.basePath,X.definitionPath,X.name]:X.basePath;return{...X,currentPath:J,propertyPath:void 0,seen:new Map(Object.entries(X.definitions).map(([Q,$])=>[$._def,{def:$._def,path:[...X.basePath,X.definitionPath,Q],jsonSchema:void 0}]))}},DL=(Y,X)=>{var J;let Q=jL(X),$=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((H,[N,O])=>{var Z;return{...H,[N]:(Z=n(O._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,N]},!0))!=null?Z:A0()}},{}):void 0,G=typeof X==="string"?X:(X==null?void 0:X.nameStrategy)==="title"?void 0:X==null?void 0:X.name,W=(J=n(Y._def,G===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,G]},!1))!=null?J:A0(),U=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if(U!==void 0)W.title=U;let L=G===void 0?$?{...W,[Q.definitionPath]:$}:W:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,G].join("/"),[Q.definitionPath]:{...$,[G]:W}};return L.$schema="http://json-schema.org/draft-07/schema#",L},y9=Symbol.for("vercel.ai.schema");function Q8(Y){let X;return()=>{if(X==null)X=Y();return X}}function $8(Y,{validate:X}={}){return{[y9]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:X}}function PL(Y){return typeof Y==="object"&&Y!==null&&y9 in Y&&Y[y9]===!0&&"jsonSchema"in Y&&"validate"in Y}function G8(Y){return Y==null?$8({type:"object",properties:{},additionalProperties:!1}):PL(Y)?Y:("~standard"in Y)?Y["~standard"].vendor==="zod"?VY(Y):ML(Y):Y()}function ML(Y){return $8(()=>{if(!wL(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 f0({value:X,cause:J.issues})}}})}function wL(Y){return Y["~standard"].jsonSchema!=null}function EL(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return $8(()=>DL(Y,{$refStrategy:Q?"root":"none"}),{validate:async($)=>{let G=await Y.safeParseAsync($);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function AL(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return $8(()=>u9(S$(Y,{target:"draft-7",io:"input",reused:Q?"ref":"inline"})),{validate:async($)=>{let G=await Y8(Y,$);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function TL(Y){return"_zod"in Y}function VY(Y,X){if(TL(Y))return AL(Y,X);else return EL(Y,X)}async function NY({value:Y,schema:X,context:J}){let Q=G8(X);try{if(Q.validate==null)return{success:!0,value:Y,rawValue:Y};let $=await Q.validate(Y);if($.success)return{success:!0,value:$.value,rawValue:Y};return{success:!1,error:f0.wrap({value:Y,cause:$.error,context:J}),rawValue:Y}}catch($){return{success:!1,error:f0.wrap({value:Y,cause:$,context:J}),rawValue:Y}}}async function N1({text:Y,schema:X}){try{let J=xH(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 fG="AI_SerializationError",mG=`vercel.ai.error.${fG}`,RL=Symbol.for(mG),EG,AG,j4=class extends(AG=f,EG=RL,AG){constructor({message:Y="Failed to serialize value.",cause:X}={}){super({name:fG,message:Y,cause:X});this[EG]=!0}static isInstance(Y){return f.hasMarker(Y,mG)}};var IL=Object.defineProperty,SL=(Y,X)=>{for(var J in X)IL(Y,J,{get:X[J],enumerable:!0})},kL="AI_InvalidArgumentError",bL=`vercel.ai.error.${kL}`,xL=Symbol.for(bL),vL;vL=xL;var hL="AI_InvalidStreamPartError",gL=`vercel.ai.error.${hL}`,yL=Symbol.for(gL),fL;fL=yL;var mL="AI_InvalidToolApprovalError",cL=`vercel.ai.error.${mL}`,uL=Symbol.for(cL),pL;pL=uL;var lL="AI_InvalidToolApprovalSignatureError",dL=`vercel.ai.error.${lL}`,iL=Symbol.for(dL),nL;nL=iL;var oL="AI_InvalidToolInputError",rL=`vercel.ai.error.${oL}`,sL=Symbol.for(rL),aL;aL=sL;var tL="AI_ToolCallNotFoundForApprovalError",eL=`vercel.ai.error.${tL}`,YV=Symbol.for(eL),XV;XV=YV;var JV="AI_MissingToolResultsError",QV=`vercel.ai.error.${JV}`,$V=Symbol.for(QV),GV;GV=$V;var WV="AI_NoImageGeneratedError",zV=`vercel.ai.error.${WV}`,UV=Symbol.for(zV),HV;HV=UV;var cG="AI_NoObjectGeneratedError",uG=`vercel.ai.error.${cG}`,LV=Symbol.for(uG),pG,B1=class extends f{constructor({message:Y="No object generated.",cause:X,text:J,response:Q,usage:$,finishReason:G}){super({name:cG,message:Y,cause:X});this[pG]=!0,this.text=J,this.response=Q,this.usage=$,this.finishReason=G}static isInstance(Y){return f.hasMarker(Y,uG)}};pG=LV;var VV="AI_NoOutputGeneratedError",NV=`vercel.ai.error.${VV}`,BV=Symbol.for(NV),ZV;ZV=BV;var KV="AI_NoSpeechGeneratedError",OV=`vercel.ai.error.${KV}`,qV=Symbol.for(OV),FV;FV=qV;var jV="AI_NoTranscriptGeneratedError",DV=`vercel.ai.error.${jV}`,PV=Symbol.for(DV),MV;MV=PV;var wV="AI_NoTranslationGeneratedError",EV=`vercel.ai.error.${wV}`,AV=Symbol.for(EV),TV;TV=AV;var RV="AI_NoVideoGeneratedError",CV=`vercel.ai.error.${RV}`,_V=Symbol.for(CV),IV;IV=_V;var SV="AI_NoSuchToolError",kV=`vercel.ai.error.${SV}`,bV=Symbol.for(kV),xV;xV=bV;var vV="AI_ToolCallRepairError",hV=`vercel.ai.error.${vV}`,gV=Symbol.for(hV),yV;yV=gV;var fV="AI_UIMessageStreamError",mV=`vercel.ai.error.${fV}`,cV=Symbol.for(mV),uV;uV=cV;var pV="AI_InvalidDataContentError",lV=`vercel.ai.error.${pV}`,dV=Symbol.for(lV),iV;iV=dV;var nV="AI_InvalidMessageRoleError",oV=`vercel.ai.error.${nV}`,rV=Symbol.for(oV),sV;sV=rV;var aV="AI_MessageConversionError",tV=`vercel.ai.error.${aV}`,eV=Symbol.for(tV),YN;YN=eV;var XN="AI_RetryError",JN=`vercel.ai.error.${XN}`,QN=Symbol.for(JN),$N;$N=QN;var GN="7.0.59",WN=async({url:Y,maxBytes:X,abortSignal:J})=>{var Q;let $=Y.toString();try{let G=p1({},`ai-sdk/${GN}`,bG()),W=await SG({url:$,headers:G,abortSignal:J});if(!W.ok)throw await J8(W),new O0({url:$,statusCode:W.status,statusText:W.statusText});return{data:await kG({response:W,url:$,maxBytes:X!=null?X:c9}),mediaType:(Q=W.headers.get("content-type"))!=null?Q:void 0}}catch(G){if(O0.isInstance(G))throw G;throw new O0({url:$,cause:G})}};var z={array:I9,boolean:QG,custom:KG,discriminatedUnion:HG,enum:k9,instanceof:OG,lazy:ZG,literal:VG,looseObject:zG,never:_9,null:$G,number:JG,object:WG,record:LG,string:YG,union:S9,unknown:LY},T1=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),T1.optional()),z.array(T1)])),A=z.record(z.string(),z.record(z.string(),T1.optional())),ZY=z.union([z.string(),z.instanceof(Uint8Array),z.instanceof(ArrayBuffer),z.custom(xG,{message:"Must be a Buffer"})]),l9=z.record(z.string(),z.string()),lG=z.object({type:z.literal("text"),text:z.string(),providerOptions:A.optional()}),zN=z.object({type:z.literal("image"),image:z.union([ZY,z.instanceof(URL),l9]),mediaType:z.string().optional(),providerOptions:A.optional()}),dG=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()})]),UN=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:ZY}),z.object({type:z.literal("url"),url:z.instanceof(URL)})]),iG=z.object({type:z.literal("file"),data:z.union([dG,ZY,z.instanceof(URL),l9]),filename:z.string().optional(),mediaType:z.string(),providerOptions:A.optional()}),HN=z.object({type:z.literal("reasoning"),text:z.string(),providerOptions:A.optional()}),LN=z.object({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerOptions:A.optional()}),VN=z.object({type:z.literal("reasoning-file"),data:z.union([UN,ZY,z.instanceof(URL)]),mediaType:z.string(),providerOptions:A.optional()}),NN=z.object({type:z.literal("tool-call"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerOptions:A.optional(),providerExecuted:z.boolean().optional()}),BN=z.discriminatedUnion("type",[z.object({type:z.literal("text"),value:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("json"),value:T1,providerOptions:A.optional()}),z.object({type:z.literal("execution-denied"),reason:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("error-text"),value:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("error-json"),value:T1,providerOptions:A.optional()}),z.object({type:z.literal("content"),value:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("file"),data:dG,mediaType:z.string(),filename:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("file-data"),data:z.string(),mediaType:z.string(),filename:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("file-url"),url:z.string(),mediaType:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:A.optional()}),z.object({type:z.literal("file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:A.optional()}),z.object({type:z.literal("image-data"),data:z.string(),mediaType:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("image-url"),url:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("image-file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:A.optional()}),z.object({type:z.literal("image-file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:A.optional()}),z.object({type:z.literal("custom"),providerOptions:A.optional()})]))})]),nG=z.object({type:z.literal("tool-result"),toolCallId:z.string(),toolName:z.string(),output:BN,providerOptions:A.optional()}),ZN=z.object({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string()}),KN=z.object({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional()}),ON=z.object({role:z.literal("system"),content:z.string(),providerOptions:A.optional()}),qN=z.object({role:z.literal("user"),content:z.union([z.string(),z.array(z.union([lG,zN,iG]))]),providerOptions:A.optional()}),FN=z.object({role:z.literal("assistant"),content:z.union([z.string(),z.array(z.union([lG,LN,iG,HN,VN,NN,nG,ZN]))]),providerOptions:A.optional()}),jN=z.object({role:z.literal("tool"),content:z.array(z.union([nG,KN])),providerOptions:A.optional()}),b4=z.union([ON,qN,FN,jN]);var DN={};SL(DN,{array:()=>EN,choice:()=>AN,json:()=>TN,object:()=>wN,text:()=>MN});function PN(Y){let X=["ROOT"],J=-1,Q=null,$=0;function G(N){return N>="0"&&N<="9"||N>="A"&&N<="F"||N>="a"&&N<="f"}function W(N,O,Z){switch(N){case'"':{J=O,X.pop(),X.push(Z),X.push("INSIDE_STRING");break}case"f":case"t":case"n":{J=O,Q=O,X.pop(),X.push(Z),X.push("INSIDE_LITERAL");break}case"-":{X.pop(),X.push(Z),X.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=O,X.pop(),X.push(Z),X.push("INSIDE_NUMBER");break}case"{":{J=O,X.pop(),X.push(Z),X.push("INSIDE_OBJECT_START");break}case"[":{J=O,X.pop(),X.push(Z),X.push("INSIDE_ARRAY_START");break}}}function U(N,O){switch(N){case",":{X.pop(),X.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{J=O,X.pop();break}}}function L(N,O){switch(N){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=O,X.pop();break}}}for(let N=0;N<Y.length;N++){let O=Y[N];switch(X[X.length-1]){case"ROOT":W(O,N,"FINISH");break;case"INSIDE_OBJECT_START":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}case"}":{J=N,X.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(O){case":":{X.pop(),X.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{W(O,N,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{U(O,N);break}case"INSIDE_STRING":{switch(O){case'"':{X.pop(),J=N;break}case"\\":{X.push("INSIDE_STRING_ESCAPE");break}default:J=N}break}case"INSIDE_ARRAY_START":{switch(O){case"]":{J=N,X.pop();break}default:{J=N,W(O,N,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(O){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=N,X.pop();break}default:{J=N;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{W(O,N,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{if(X.pop(),O==="u")$=0,X.push("INSIDE_STRING_UNICODE_ESCAPE");else J=N;break}case"INSIDE_STRING_UNICODE_ESCAPE":{if(G(O)){if($++,$===4)X.pop(),J=N}break}case"INSIDE_NUMBER":{switch(O){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=N;break}case"e":case"E":case"-":case".":break;case",":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")L(O,N);if(X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")U(O,N);break}case"}":{if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")U(O,N);break}case"]":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")L(O,N);break}default:{X.pop();break}}break}case"INSIDE_LITERAL":{let V=Y.substring(Q,N+1);if(!"false".startsWith(V)&&!"true".startsWith(V)&&!"null".startsWith(V)){if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")U(O,N);else if(X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")L(O,N)}else J=N;break}}}let H=Y.slice(0,J+1);for(let N=X.length-1;N>=0;N--)switch(X[N]){case"INSIDE_STRING":{H+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{H+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{H+="]";break}case"INSIDE_LITERAL":{let Z=Y.substring(Q,Y.length);if("true".startsWith(Z))H+="true".slice(Z.length);else if("false".startsWith(Z))H+="false".slice(Z.length);else if("null".startsWith(Z))H+="null".slice(Z.length)}}return H}async function W8(Y){if(Y===void 0)return{value:void 0,state:"undefined-input"};let X=await N1({text:Y});if(X.success)return{value:X.value,state:"successful-parse"};if(X=await N1({text:PN(Y)}),X.success)return{value:X.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var MN=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:Y}){return Y},async parsePartialOutput({text:Y}){return{partial:Y}},createElementStreamTransform(){return}}),wN=({schema:Y,name:X,description:J})=>{let Q=G8(Y);return{name:"object",responseFormat:p9(Q.jsonSchema).then(($)=>({type:"json",schema:$,...X!=null&&{name:X},...J!=null&&{description:J}})),async parseCompleteOutput({text:$},G){let W=await N1({text:$});if(!W.success)throw new B1({message:"No object generated: could not parse the response.",cause:W.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let U=await NY({value:W.value,schema:Q});if(!U.success)throw new B1({message:"No object generated: response did not match schema.",cause:U.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});return U.value},async parsePartialOutput({text:$}){let G=await W8($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:G.value}}},createElementStreamTransform(){return}}},EN=({element:Y,name:X,description:J})=>{let Q=G8(Y);return{name:"array",responseFormat:p9(Q.jsonSchema).then(($)=>{let{$schema:G,...W}=$;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:W}},required:["elements"],additionalProperties:!1},...X!=null&&{name:X},...J!=null&&{description:J}}}),async parseCompleteOutput({text:$},G){let W=await N1({text:$});if(!W.success)throw new B1({message:"No object generated: could not parse the response.",cause:W.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let U=W.value;if(U==null||typeof U!=="object"||!("elements"in U)||!Array.isArray(U.elements))throw new B1({message:"No object generated: response did not match schema.",cause:new f0({value:U,cause:"response must be an object with an elements array"}),text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let L=[];for(let H of U.elements){let N=await NY({value:H,schema:Q});if(!N.success)throw new B1({message:"No object generated: response did not match schema.",cause:N.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});L.push(N.value)}return L},async parsePartialOutput({text:$}){let G=await W8($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let W=G.value;if(W==null||typeof W!=="object"||!("elements"in W)||!Array.isArray(W.elements))return;let U=G.state==="repaired-parse"&&W.elements.length>0?W.elements.slice(0,-1):W.elements,L=[];for(let H of U){let N=await NY({value:H,schema:Q});if(N.success)L.push(N.value)}return{partial:L}}}},createElementStreamTransform(){let $=0;return new TransformStream({transform({partialOutput:G},W){if(G!=null)for(;$<G.length;$++)W.enqueue(G[$])}})}}},AN=({options:Y,name:X,description:J})=>{return{name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:Y}},required:["result"],additionalProperties:!1},...X!=null&&{name:X},...J!=null&&{description:J}}),async parseCompleteOutput({text:Q},$){let G=await N1({text:Q});if(!G.success)throw new B1({message:"No object generated: could not parse the response.",cause:G.error,text:Q,response:$.response,usage:$.usage,finishReason:$.finishReason});let W=G.value;if(W==null||typeof W!=="object"||!("result"in W)||typeof W.result!=="string"||!Y.includes(W.result))throw new B1({message:"No object generated: response did not match schema.",cause:new f0({value:W,cause:"response must be an object that contains a choice value."}),text:Q,response:$.response,usage:$.usage,finishReason:$.finishReason});return W.result},async parsePartialOutput({text:Q}){let $=await W8(Q);switch($.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let G=$.value;if(G==null||typeof G!=="object"||!("result"in G)||typeof G.result!=="string")return;let W=Y.filter((U)=>U.startsWith(G.result));if($.state==="successful-parse")return W.includes(G.result)?{partial:G.result}:void 0;else return W.length===1?{partial:W[0]}:void 0}}},createElementStreamTransform(){return}}},TN=({name:Y,description:X}={})=>{return{name:"json",responseFormat:Promise.resolve({type:"json",...Y!=null&&{name:Y},...X!=null&&{description:X}}),async parseCompleteOutput({text:J},Q){let $=await N1({text:J});if(!$.success)throw new B1({message:"No object generated: could not parse the response.",cause:$.error,text:J,response:Q.response,usage:Q.usage,finishReason:Q.finishReason});return $.value},async parsePartialOutput({text:J}){let Q=await 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 g4=G0({prefix:"aitxt",size:24}),y4=G0({prefix:"call",size:24});var m4=class extends TransformStream{constructor(){super({transform(Y,X){X.enqueue(`data: ${JSON.stringify(Y)}
142
192
 
143
193
  `)},flush(Y){Y.enqueue(`data: [DONE]
144
194
 
145
- `)}})}};var JY=z.record(z.string(),q1.optional()),kO=dY(()=>YY(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:JY.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:JY.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:JY.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:JY.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:JY.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 xO=Q0({prefix:"aitxt",size:24}),vO=Q0({prefix:"call",size:24});var hO=Q0({prefix:"aitxt",size:24}),gO=Q0({prefix:"call",size:24});var q0=z.record(z.string(),q1.optional()),ML=z.record(z.string(),z.string()),fO=dY(()=>YY(z.array(z.object({id:z.string(),role:z.enum(["system","user","assistant"]),metadata:z.unknown().optional(),parts:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:A.optional()}),z.object({type:z.literal("reasoning"),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:A.optional()}),z.object({type:z.literal("custom"),kind:z.string(),providerMetadata:A.optional()}),z.object({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:A.optional()}),z.object({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:A.optional()}),z.object({type:z.literal("file"),mediaType:z.string(),filename:z.string().optional(),url:z.string(),providerReference:ML.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:q0.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:q0.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:q0.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:q0.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:q0.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:q0.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:q0.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:q0.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:q0.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:q0.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:q0.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:q0.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:q0.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:q0.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 cO=Q0({prefix:"call",size:24});var pO=Q0({prefix:"call",size:24});var dO=Q0({prefix:"aiobj",size:24});function BG(Y){return({url:X,abortSignal:J})=>QL({url:X,maxBytes:Y==null?void 0:Y.maxBytes,abortSignal:J})}var nO=Q0({prefix:"aiobj",size:24});var oO=BG();var AL="AI_NoSuchProviderError",RL=`vercel.ai.error.${AL}`,TL=Symbol.for(RL),CL;CL=TL;var sO=Q0({prefix:"call",size:24});var aO=BG();class R0 extends c1{name="ProviderResponseStreamError";constructor(Y,X){super({message:Y,url:"",requestBodyValues:void 0,cause:X?.cause,isRetryable:!0})}}var j0={};g8(j0,{toWebSocketUrl:()=>iL,streamResponsesWebSocket:()=>sL,parseRateLimitSignal:()=>GY,normalizeHeaders:()=>nL,isUpgradeFailure:()=>oL,isAbortError:()=>I9,connectResponsesWebSocket:()=>rL,PROTOCOL_HEADER:()=>wG,OpenAIWebSocket:()=>j0});function $Y(Y){let X=Number(Y.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(X)?X:void 0}function rY(Y,X,J=!1){let $=Buffer.from(Y.slice(0,X)).toString("latin1").split(`\r
146
- `),G=$[0]??"",W=$Y(G);if(W===void 0||W===101)return;let K=Object.fromEntries($.slice(1).flatMap((L)=>{let Z=L.indexOf(":");return Z===-1?[]:[[L.slice(0,Z).trim().toLowerCase(),L.slice(Z+1).trim()]]})),U=Y.slice(X+4),H=K["content-length"],N=Number(H);if(!J&&(H===void 0||Number.isFinite(N)&&U.length<N))return;let O=Buffer.from(U).toString("utf8"),B=(()=>{try{let L=JSON.parse(O);return I(L)?L:void 0}catch{return}})();return{message:`WS upgrade failed: ${G}`,status:W,status_code:W,headers:K,body:O,...I(B?.error)?{error:B.error}:{}}}var _L="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",ZG=["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 T9{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];writeQueue=[];constructor(Y,X,J){this.url=Y,this.sessionID=J?.sessionID,this.connect(Y,X)}addEventListener(Y,X,J){this.listeners[Y]?.add(X)}removeEventListener(Y,X){this.listeners[Y]?.delete(X)}emit(Y,X){for(let J of[...this.listeners[Y]??[]])try{J(X)}catch{}}async connect(Y,X){let J=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),Q=J.hostname,$=J.port?Number(J.port):J.protocol==="https:"?443:80,G=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),K=Buffer.from(W).toString("base64"),U=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(K+_L));this.expectedAccept=Buffer.from(new Uint8Array(U)).toString("base64");let H={};for(let[B,L]of Object.entries(X))H[B.toLowerCase()]=L;let N=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${K}`];for(let B of ZG)if(H[B]!==void 0)N.push(`${IL(B)}: ${H[B]}`);for(let[B,L]of Object.entries(X))if(!ZG.includes(B.toLowerCase())&&B.toLowerCase()!=="content-length")N.push(`${B}: ${L}`);let O=`${N.join(`\r
195
+ `)}})}};var BY=z.record(z.string(),T1.optional()),u4=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 l4=G0({prefix:"aitxt",size:24}),d4=G0({prefix:"call",size:24});var i4=G0({prefix:"aitxt",size:24}),n4=G0({prefix:"call",size:24});var j0=z.record(z.string(),T1.optional()),RN=z.record(z.string(),z.string()),r4=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"),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:RN.optional(),providerMetadata:A.optional()}),z.object({type:z.literal("reasoning-file"),mediaType:z.string(),url:z.string(),providerMetadata:A.optional()}),z.object({type:z.literal("step-start")}),z.object({type:z.string().startsWith("data-"),id:z.string().optional(),data:z.unknown()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("input-streaming"),input:z.unknown().optional(),providerExecuted:z.boolean().optional(),callProviderMetadata:A.optional(),output:z.never().optional(),errorText:z.never().optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("input-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),reason:z.never().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.boolean(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("output-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("output-error"),input:z.unknown().optional(),rawInput:z.unknown().optional(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.string(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("output-denied"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("input-streaming"),providerExecuted:z.boolean().optional(),callProviderMetadata:A.optional(),input:z.unknown().optional(),output:z.never().optional(),errorText:z.never().optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("input-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),reason:z.never().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.boolean(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("output-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("output-error"),providerExecuted:z.boolean().optional(),input:z.unknown().optional(),rawInput:z.unknown().optional(),output:z.never().optional(),errorText:z.string(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("output-denied"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})})]))}).superRefine((Y,X)=>{if(Y.role!=="assistant"&&Y.parts.length===0)X.addIssue({origin:"array",code:"too_small",minimum:1,inclusive:!0,input:Y.parts,path:["parts"],message:"Message must contain at least one part"})})).nonempty("Messages array must not be empty")));var a4=G0({prefix:"call",size:24});var e4=G0({prefix:"call",size:24});var Xq=G0({prefix:"aiobj",size:24});function oG(Y){return({url:X,abortSignal:J})=>WN({url:X,maxBytes:Y==null?void 0:Y.maxBytes,abortSignal:J})}var Qq=G0({prefix:"aiobj",size:24});var $q=oG();var CN="AI_NoSuchProviderError",_N=`vercel.ai.error.${CN}`,IN=Symbol.for(_N),SN;SN=IN;var Wq=G0({prefix:"call",size:24});var zq=oG();class R0 extends t1{name="ProviderResponseStreamError";constructor(Y,X){super({message:Y,url:"",requestBodyValues:void 0,cause:X?.cause,isRetryable:!0})}}var D0={};X9(D0,{toWebSocketUrl:()=>rN,streamResponsesWebSocket:()=>eN,parseRateLimitSignal:()=>OY,normalizeHeaders:()=>sN,isUpgradeFailure:()=>aN,isAbortError:()=>o9,connectResponsesWebSocket:()=>tN,PROTOCOL_HEADER:()=>JW,OpenAIWebSocket:()=>D0});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 $=Buffer.from(Y.slice(0,X)).toString("latin1").split(`\r
196
+ `),G=$[0]??"",W=KY(G);if(W===void 0||W===101)return;let U=Object.fromEntries($.slice(1).flatMap((V)=>{let K=V.indexOf(":");return K===-1?[]:[[V.slice(0,K).trim().toLowerCase(),V.slice(K+1).trim()]]})),L=Y.slice(X+4),H=U["content-length"],N=Number(H);if(!J&&(H===void 0||Number.isFinite(N)&&L.length<N))return;let O=Buffer.from(L).toString("utf8"),Z=(()=>{try{let V=JSON.parse(O);return C(V)?V:void 0}catch{return}})();return{message:`WS upgrade failed: ${G}`,status:W,status_code:W,headers:U,body:O,...C(Z?.error)?{error:Z.error}:{}}}var kN="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",rG=["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,$=J.port?Number(J.port):J.protocol==="https:"?443:80,G=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),U=Buffer.from(W).toString("base64"),L=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(U+kN));this.expectedAccept=Buffer.from(new Uint8Array(L)).toString("base64");let H={};for(let[Z,V]of Object.entries(X))H[Z.toLowerCase()]=V;let N=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${U}`];for(let Z of rG)if(H[Z]!==void 0)N.push(`${bN(Z)}: ${H[Z]}`);for(let[Z,V]of Object.entries(X))if(!rG.includes(Z.toLowerCase())&&Z.toLowerCase()!=="content-length")N.push(`${Z}: ${V}`);let O=`${N.join(`\r
147
197
  `)}\r
148
198
  \r
149
- `;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let B=globalThis.Bun?.connect;if(!B)throw Error("Bun.connect is not available");this.socket=await B({hostname:Q,port:$,tls:J.protocol==="https:"?{serverName:Q}:void 0,socket:{open:(L)=>{this.socket=L,this.enqueueWrite(new TextEncoder().encode(O))},data:(L,Z)=>this.onData(Z),drain:()=>this.flushWrites(),error:(L,Z)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let j=Z instanceof Error?Z.message:String(Z);this.log("socket_error",{message:j}),this.emit("error",{message:j})},close:()=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close"),this.emit("close",{code:1006,reason:"socket closed"})}}})}catch(B){this.readyState=3;let L=B instanceof Error?B.message:String(B);this.log("connect_exception",{message:L}),this.emit("error",{message:L})}}onData(Y){if(this.rxBuffer=SL(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:$,tls:J.protocol==="https:"});let Z=globalThis.Bun?.connect;if(!Z)throw Error("Bun.connect is not available");this.socket=await Z({hostname:Q,port:$,tls:J.protocol==="https:"?{serverName:Q}:void 0,socket:{open:(V)=>{this.socket=V,this.enqueueWrite(new TextEncoder().encode(O))},data:(V,K)=>this.onData(K),drain:()=>this.flushWrites(),error:(V,K)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let j=K instanceof Error?K.message:String(K);this.log("socket_error",{message:j}),this.emit("error",{message:j})},close:()=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close"),this.emit("close",{code:1006,reason:"socket closed"})}}})}catch(Z){this.readyState=3;let V=Z instanceof Error?Z.message:String(Z);this.log("connect_exception",{message:V}),this.emit("error",{message:V})}}onData(Y){if(this.rxBuffer=xN(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
150
200
  \r
151
201
  `);if(J===-1)return;let Q=X.slice(0,J),$=Q.split(`\r
152
- `)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=$Y($);if(W!==101){if(W===void 0){this.readyState=3;try{this.socket?.end()}catch{}this.log("upgrade_failed",{statusLine:$}),this.emit("error",{message:`WS upgrade failed: ${$}`});return}if(!this.emitRejectedUpgrade())return;try{this.socket?.end()}catch{}return}if(!G||G[1]!==this.expectedAccept){this.readyState=3;try{this.socket?.end()}catch{}this.log("accept_mismatch",{statusLine:$}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(J+4),this.log("open",{statusLine:$}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let X=Buffer.from(this.rxBuffer).indexOf(`\r
202
+ `)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=KY($);if(W!==101){if(W===void 0){this.readyState=3;try{this.socket?.end()}catch{}this.log("upgrade_failed",{statusLine:$}),this.emit("error",{message:`WS upgrade failed: ${$}`});return}if(!this.emitRejectedUpgrade())return;try{this.socket?.end()}catch{}return}if(!G||G[1]!==this.expectedAccept){this.readyState=3;try{this.socket?.end()}catch{}this.log("accept_mismatch",{statusLine:$}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(J+4),this.log("open",{statusLine:$}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let X=Buffer.from(this.rxBuffer).indexOf(`\r
153
203
  \r
154
- `);if(X===-1)return!1;let J=rY(this.rxBuffer,X,Y);if(!J)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:J.status,partial:Y}),this.emit("error",J),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let X=Y[0],J=Y[1],Q=(X&128)!==0,$=X&15,G=(J&128)!==0,W=J&127,K=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],K=4}else if(W===127){if(Y.length<10)return;W=0;for(let H=0;H<8;H++)W=W*256+Y[2+H];K=10}if(G)K+=4;if(Y.length<K+W)return;let U=Y.slice(K,K+W);this.rxBuffer=Y.slice(K+W),this.handleFrame(Q,$,U)}}handleFrame(Y,X,J){if(X===9){this.writeFrame(10,J);return}if(X===10)return;if(X===8){let $=1005,G="";if(J.length>=2)$=J[0]<<8|J[1],G=Buffer.from(J.slice(2)).toString("utf-8");this.readyState=3;try{this.socket?.end()}catch{}this.log("close_frame",{code:$,reason:G}),this.emit("close",{code:$,reason:G});return}if(X===1||X===2)this.fragOpcode=X,this.fragChunks=[J];else if(X===0)this.fragChunks.push(J);if(!Y)return;let Q=kL(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let $=Buffer.from(Q).toString("utf-8");this.emit("message",{data:$})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),$;if(J<126)$=[128|Y,128|J];else if(J<65536)$=[128|Y,254,J>>8&255,J&255];else{$=[128|Y,255];for(let K=7;K>=0;K--)$.push(J/2**(8*K)&255)}let G=new Uint8Array(J);for(let K=0;K<J;K++)G[K]=X[K]^Q[K%4];let W=new Uint8Array($.length+4+J);W.set($,0),W.set(Q,$.length),W.set(G,$.length+4);try{this.enqueueWrite(W)}catch{}}enqueueWrite(Y){this.writeQueue.push(Y),this.flushWrites()}flushWrites(){let Y=this.socket;if(!Y)return;while(this.writeQueue.length>0){let X=this.writeQueue[0],J=Y.write(X);if(J<X.length){this.writeQueue[0]=X.slice(J),this.log("write_backpressure",{written:J,remaining:X.length-J});return}this.writeQueue.shift()}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return p0({component:"raw-ws-bun",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function IL(Y){return Y}function SL(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function kL(Y){let X=0;for(let $ of Y)X+=$.length;let J=new Uint8Array(X),Q=0;for(let $ of Y)J.set($,Q),Q+=$.length;return J}import{connect as bL}from"node:net";import{connect as xL}from"node:tls";var vL="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",OG=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class C9{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];constructor(Y,X,J){this.url=Y,this.sessionID=J?.sessionID,this.connect(Y,X)}addEventListener(Y,X,J){this.listeners[Y]?.add(X)}removeEventListener(Y,X){this.listeners[Y]?.delete(X)}emit(Y,X){for(let J of[...this.listeners[Y]??[]])try{J(X)}catch{}}async connect(Y,X){let J=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),Q=J.hostname,$=J.port?Number(J.port):J.protocol==="https:"?443:80,G=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),K=Buffer.from(W).toString("base64"),U=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(K+vL));this.expectedAccept=Buffer.from(new Uint8Array(U)).toString("base64");let H={};for(let[B,L]of Object.entries(X))H[B.toLowerCase()]=L;let N=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${K}`];for(let B of OG)if(H[B]!==void 0)N.push(`${hL(B)}: ${H[B]}`);for(let[B,L]of Object.entries(X))if(!OG.includes(B.toLowerCase())&&B.toLowerCase()!=="content-length")N.push(`${B}: ${L}`);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,$=X&15,G=(J&128)!==0,W=J&127,U=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],U=4}else if(W===127){if(Y.length<10)return;W=0;for(let H=0;H<8;H++)W=W*256+Y[2+H];U=10}if(G)U+=4;if(Y.length<U+W)return;let L=Y.slice(U,U+W);this.rxBuffer=Y.slice(U+W),this.handleFrame(Q,$,L)}}handleFrame(Y,X,J){if(X===9){this.writeFrame(10,J);return}if(X===10)return;if(X===8){let $=1005,G="";if(J.length>=2)$=J[0]<<8|J[1],G=Buffer.from(J.slice(2)).toString("utf-8");this.readyState=3;try{this.socket?.end()}catch{}this.log("close_frame",{code:$,reason:G}),this.emit("close",{code:$,reason:G});return}if(X===1||X===2)this.fragOpcode=X,this.fragChunks=[J];else if(X===0)this.fragChunks.push(J);if(!Y)return;let Q=vN(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let $=Buffer.from(Q).toString("utf-8");this.emit("message",{data:$})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),$;if(J<126)$=[128|Y,128|J];else if(J<65536)$=[128|Y,254,J>>8&255,J&255];else{$=[128|Y,255];for(let U=7;U>=0;U--)$.push(J/2**(8*U)&255)}let G=new Uint8Array(J);for(let U=0;U<J;U++)G[U]=X[U]^Q[U%4];let W=new Uint8Array($.length+4+J);W.set($,0),W.set(Q,$.length),W.set(G,$.length+4);try{this.enqueueWrite(W)}catch{}}enqueueWrite(Y){this.writeQueue.push(Y),this.flushWrites()}flushWrites(){let Y=this.socket;if(!Y)return;while(this.writeQueue.length>0){let X=this.writeQueue[0],J=Y.write(X);if(J<X.length){this.writeQueue[0]=X.slice(J),this.log("write_backpressure",{written:J,remaining:X.length-J});return}this.writeQueue.shift()}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return r0({component:"raw-ws-bun",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function bN(Y){return Y}function xN(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function vN(Y){let X=0;for(let $ of Y)X+=$.length;let J=new Uint8Array(X),Q=0;for(let $ of Y)J.set($,Q),Q+=$.length;return J}import{connect as hN}from"node:net";import{connect as gN}from"node:tls";var yN="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",sG=["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,$=J.port?Number(J.port):J.protocol==="https:"?443:80,G=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),U=Buffer.from(W).toString("base64"),L=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(U+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 ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${U}`];for(let Z of sG)if(H[Z]!==void 0)N.push(`${fN(Z)}: ${H[Z]}`);for(let[Z,V]of Object.entries(X))if(!sG.includes(Z.toLowerCase())&&Z.toLowerCase()!=="content-length")N.push(`${Z}: ${V}`);let O=`${N.join(`\r
155
205
  `)}\r
156
206
  \r
157
- `;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let B=()=>{this.socket?.write(O)},L=J.protocol==="https:"?xL({host:Q,port:$,servername:Q},B):bL({host:Q,port:$},B);this.socket=L,L.on("data",(Z)=>{this.onData(typeof Z==="string"?Buffer.from(Z,"binary"):Z)}),L.on("error",(Z)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let j=Z instanceof Error?Z.message:String(Z);this.log("socket_error",{message:j}),this.emit("error",{message:j})}),L.on("close",(Z)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close",{hadError:Z}),this.emit("close",{code:1006,reason:"socket closed"})})}catch(B){this.readyState=3,this.log("connect_exception",{message:B instanceof Error?B.message:String(B)}),this.emit("error",{message:B instanceof Error?B.message:String(B)})}}onData(Y){if(this.rxBuffer=gL(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:$,tls:J.protocol==="https:"});let Z=()=>{this.socket?.write(O)},V=J.protocol==="https:"?gN({host:Q,port:$,servername:Q},Z):hN({host:Q,port:$},Z);this.socket=V,V.on("data",(K)=>{this.onData(typeof K==="string"?Buffer.from(K,"binary"):K)}),V.on("error",(K)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let j=K instanceof Error?K.message:String(K);this.log("socket_error",{message:j}),this.emit("error",{message:j})}),V.on("close",(K)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close",{hadError:K}),this.emit("close",{code:1006,reason:"socket closed"})})}catch(Z){this.readyState=3,this.log("connect_exception",{message:Z instanceof Error?Z.message:String(Z)}),this.emit("error",{message:Z instanceof Error?Z.message:String(Z)})}}onData(Y){if(this.rxBuffer=mN(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
158
208
  \r
159
209
  `);if(J===-1)return;let Q=X.slice(0,J),$=Q.split(`\r
160
- `)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=$Y($);if(W!==101){if(W===void 0){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:$}),this.emit("error",{message:`WS upgrade failed: ${$}`});return}if(!this.emitRejectedUpgrade())return;this.socket?.destroy?.();return}if(!G||G[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:$}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(J+4),this.log("open",{statusLine:$}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let X=Buffer.from(this.rxBuffer).indexOf(`\r
210
+ `)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=KY($);if(W!==101){if(W===void 0){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:$}),this.emit("error",{message:`WS upgrade failed: ${$}`});return}if(!this.emitRejectedUpgrade())return;this.socket?.destroy?.();return}if(!G||G[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:$}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(J+4),this.log("open",{statusLine:$}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let X=Buffer.from(this.rxBuffer).indexOf(`\r
161
211
  \r
162
- `);if(X===-1)return!1;let J=rY(this.rxBuffer,X,Y);if(!J)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:J.status,partial:Y}),this.emit("error",J),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let X=Y[0],J=Y[1],Q=(X&128)!==0,$=X&15,G=(J&128)!==0,W=J&127,K=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],K=4}else if(W===127){if(Y.length<10)return;W=0;for(let H=0;H<8;H++)W=W*256+Y[2+H];K=10}if(G)K+=4;if(Y.length<K+W)return;let U=Y.slice(K,K+W);this.rxBuffer=Y.slice(K+W),this.handleFrame(Q,$,U)}}handleFrame(Y,X,J){if(X===9){this.writeFrame(10,J);return}if(X===10)return;if(X===8){let $=1005,G="";if(J.length>=2)$=J[0]<<8|J[1],G=Buffer.from(J.slice(2)).toString("utf-8");this.readyState=3;try{this.socket?.end()}catch{}this.emit("close",{code:$,reason:G});return}if(X===1||X===2)this.fragOpcode=X,this.fragChunks=[J];else if(X===0)this.fragChunks.push(J);if(!Y)return;let Q=yL(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let $=Buffer.from(Q).toString("utf-8");this.emit("message",{data:$})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),$;if(J<126)$=[128|Y,128|J];else if(J<65536)$=[128|Y,254,J>>8&255,J&255];else{$=[128|Y,255];for(let K=7;K>=0;K--)$.push(J/2**(8*K)&255)}let G=new Uint8Array(J);for(let K=0;K<J;K++)G[K]=X[K]^Q[K%4];let W=new Uint8Array($.length+4+J);W.set($,0),W.set(Q,$.length),W.set(G,$.length+4);try{this.socket?.write(W)}catch{}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return p0({component:"raw-ws-node",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function hL(Y){return Y}function gL(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function yL(Y){let X=0;for(let $ of Y)X+=$.length;let J=new Uint8Array(X),Q=0;for(let $ of Y)J.set($,Q),Q+=$.length;return J}function fL(){return typeof globalThis.Bun?.connect==="function"}var FG=fL()?T9:C9;function sY(Y){return process.env[Y]??process.env[Y.toLowerCase()]}function mL(Y){let X=sY("NO_PROXY");if(!X)return!1;let J=Y.hostname.toLowerCase(),Q=X.split(",").map(($)=>$.trim().toLowerCase()).filter(Boolean);for(let $ of Q){if($==="*")return!0;if($.startsWith(".")){if(J===$.slice(1)||J.endsWith($))return!0}else if(J===$||J.endsWith(`.${$}`))return!0}return!1}function cL(Y){let X=new URL(Y);if(mL(X))return;if(X.protocol==="http:")return sY("HTTP_PROXY");if(X.protocol==="https:")return sY("HTTPS_PROXY")??sY("HTTP_PROXY");return}var qG={getProxyForUrl:cL};var uL=H0("quota"),wG="responses_websockets=2026-02-06",jG=["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"],pL=new Set([t0,"x-opencode-title"]);function lL(Y){let X=new Map;for(let Q of Object.keys(Y))X.set(Q.toLowerCase(),Q);let J={};for(let Q of jG){let $=X.get(Q),G=$===void 0?void 0:Y[$];if($!==void 0&&G!==void 0)J[$]=G}for(let[Q,$]of Object.entries(Y))if(!jG.includes(Q.toLowerCase()))J[Q]=$;return J}function dL(Y){let X={};for(let[J,Q]of Object.entries(Y)){if(pL.has(J.toLowerCase()))continue;X[J]=Q}return X}function iL(Y){return Y.replace(/^http/,"ws")}function nL(Y){let X={};if(!Y)return X;if(Y instanceof Headers)return Y.forEach((J,Q)=>{X[Q.toLowerCase()]=J}),X;if(Array.isArray(Y)){for(let[J,Q]of Y)X[J.toLowerCase()]=Q;return X}for(let[J,Q]of Object.entries(Y))if(Q!=null)X[J.toLowerCase()]=String(Q);return X}function I9(Y){return Y instanceof DOMException&&Y.name==="AbortError"}var EG=new WeakSet;function oL(Y){return typeof Y==="object"&&Y!==null&&EG.has(Y)}function DG(Y,X){let J=Error(Y,X===void 0?void 0:{cause:X});return EG.add(J),J}function rL(Y){return new Promise((X,J)=>{if(Y.signal?.aborted){J(_9(Y.signal));return}let Q={...Y.headers,"openai-beta":Y.headers["openai-beta"]??wG},$=Q[t0]??Q["session-id"];delete Q["content-length"],Q=lL(dL(Q));let G=typeof Bun>"u"?void 0:qG.getProxyForUrl(Y.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),W=!0,K=Y.rawWebSocket?new FG(Y.url,Q,{sessionID:$}):new globalThis.WebSocket(Y.url,{headers:Q,...G?{proxy:G}:{},perMessageDeflate:W}),U=Y.timeout?setTimeout(()=>{H(),K.close(),J(Error("WebSocket connect timed out"))},Y.timeout):void 0;function H(){if(U)clearTimeout(U);K.removeEventListener("open",N),K.removeEventListener("error",O),K.removeEventListener("close",B),Y.signal?.removeEventListener("abort",L)}function N(){H(),X(K)}function O(Z){H(),J(DG(a0(Z),Z))}function B(Z){H(),J(DG(AG("WebSocket closed before open",Z.code,Z.reason)))}function L(){H(),K.close(),J(_9(Y.signal))}K.addEventListener("open",N,{once:!0}),K.addEventListener("error",O,{once:!0}),K.addEventListener("close",B,{once:!0}),Y.signal?.addEventListener("abort",L,{once:!0})})}function sL(Y){let X=new TextEncoder,J=Y.socket,Q,$=()=>{},G=!1,W=!1,K,U=new Set;function H(){if(K)clearTimeout(K);$(),Y.signal?.removeEventListener("abort",S)}function N(_=J){_.close()}function O(){H(),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,$=X&15,G=(J&128)!==0,W=J&127,U=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],U=4}else if(W===127){if(Y.length<10)return;W=0;for(let H=0;H<8;H++)W=W*256+Y[2+H];U=10}if(G)U+=4;if(Y.length<U+W)return;let L=Y.slice(U,U+W);this.rxBuffer=Y.slice(U+W),this.handleFrame(Q,$,L)}}handleFrame(Y,X,J){if(X===9){this.writeFrame(10,J);return}if(X===10)return;if(X===8){let $=1005,G="";if(J.length>=2)$=J[0]<<8|J[1],G=Buffer.from(J.slice(2)).toString("utf-8");this.readyState=3;try{this.socket?.end()}catch{}this.emit("close",{code:$,reason:G});return}if(X===1||X===2)this.fragOpcode=X,this.fragChunks=[J];else if(X===0)this.fragChunks.push(J);if(!Y)return;let Q=cN(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let $=Buffer.from(Q).toString("utf-8");this.emit("message",{data:$})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),$;if(J<126)$=[128|Y,128|J];else if(J<65536)$=[128|Y,254,J>>8&255,J&255];else{$=[128|Y,255];for(let U=7;U>=0;U--)$.push(J/2**(8*U)&255)}let G=new Uint8Array(J);for(let U=0;U<J;U++)G[U]=X[U]^Q[U%4];let W=new Uint8Array($.length+4+J);W.set($,0),W.set(Q,$.length),W.set(G,$.length+4);try{this.socket?.write(W)}catch{}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return r0({component:"raw-ws-node",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function 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 $ of Y)X+=$.length;let J=new Uint8Array(X),Q=0;for(let $ of Y)J.set($,Q),Q+=$.length;return J}function uN(){return typeof globalThis.Bun?.connect==="function"}var aG=uN()?d9:i9;function U8(Y){return process.env[Y]??process.env[Y.toLowerCase()]}function pN(Y){let X=U8("NO_PROXY");if(!X)return!1;let J=Y.hostname.toLowerCase(),Q=X.split(",").map(($)=>$.trim().toLowerCase()).filter(Boolean);for(let $ of Q){if($==="*")return!0;if($.startsWith(".")){if(J===$.slice(1)||J.endsWith($))return!0}else if(J===$||J.endsWith(`.${$}`))return!0}return!1}function lN(Y){let X=new URL(Y);if(pN(X))return;if(X.protocol==="http:")return U8("HTTP_PROXY");if(X.protocol==="https:")return U8("HTTPS_PROXY")??U8("HTTP_PROXY");return}var tG={getProxyForUrl:lN};var dN=L0("quota"),JW="responses_websockets=2026-02-06",eG=["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"],iN=new Set([G1,"x-opencode-title"]);function nN(Y){let X=new Map;for(let Q of Object.keys(Y))X.set(Q.toLowerCase(),Q);let J={};for(let Q of eG){let $=X.get(Q),G=$===void 0?void 0:Y[$];if($!==void 0&&G!==void 0)J[$]=G}for(let[Q,$]of Object.entries(Y))if(!eG.includes(Q.toLowerCase()))J[Q]=$;return J}function oN(Y){let X={};for(let[J,Q]of Object.entries(Y)){if(iN.has(J.toLowerCase()))continue;X[J]=Q}return X}function rN(Y){return Y.replace(/^http/,"ws")}function sN(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 QW=new WeakSet;function aN(Y){return typeof Y==="object"&&Y!==null&&QW.has(Y)}function YW(Y,X){let J=Error(Y,X===void 0?void 0:{cause:X});return QW.add(J),J}function tN(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"]??JW},$=Q[G1]??Q["session-id"];delete Q["content-length"],Q=nN(oN(Q));let G=typeof Bun>"u"?void 0:tG.getProxyForUrl(Y.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),W=!0,U=Y.rawWebSocket?new aG(Y.url,Q,{sessionID:$}):new globalThis.WebSocket(Y.url,{headers:Q,...G?{proxy:G}:{},perMessageDeflate:W}),L=Y.timeout?setTimeout(()=>{H(),U.close(),J(Error("WebSocket connect timed out"))},Y.timeout):void 0;function H(){if(L)clearTimeout(L);U.removeEventListener("open",N),U.removeEventListener("error",O),U.removeEventListener("close",Z),Y.signal?.removeEventListener("abort",V)}function N(){H(),X(U)}function O(K){H(),J(YW($1(K),K))}function Z(K){H(),J(YW(GW("WebSocket closed before open",K.code,K.reason)))}function V(){H(),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 eN(Y){let X=new TextEncoder,J=Y.socket,Q,$=()=>{},G=!1,W=!1,U,L=new Set;function H(){if(U)clearTimeout(U);$(),Y.signal?.removeEventListener("abort",I)}function N(R=J){R.close()}function O(){H(),Q?.enqueue(X.encode(`data: [DONE]
163
213
 
164
- `)),Q?.close()}function B(_){if(G)return;G=!0,H(),Y.onConnectionInvalid?.(_),Q?.error(_)}function L(_){if(G)return;if(!Y.idleTimeout)return;if(K)clearTimeout(K);K=setTimeout(()=>B(new R0(_)),Y.idleTimeout)}async function Z(_){if(G)return;if(typeof _.data!=="string"){B(new R0("Unexpected binary WebSocket frame"));return}let u=_.data,m=(()=>{try{let p=JSON.parse(u);return typeof p==="object"&&p!==null?p:void 0}catch{return}})();if(m?.type==="codex.rate_limits"){uL.debug("codex.rate_limits frame received",{pid:process.pid}),L("idle timeout waiting for websocket");let p=PG(m);Y.onQuota?.(p);return}let d=!W?GY(m):void 0;if(d&&m){G=!0,H(),Y.onRateLimitReached?.(d.window,d.resetAt),Y.onTerminal?.(m),Y.onFirstEvent?.(),Q?.error(new R0(`OpenAI account rate limit reached at admission (${d.window})`));return}if(m?.type==="error"&&Y.onRetryableTerminal){if($(),K)clearTimeout(K);K=void 0;try{let p=await Y.onRetryableTerminal(m);if(G){if(p)N(p);return}if(p){b(p);return}}catch(p){B(new R0(p instanceof Error?p.message:String(p),{cause:p}));return}}let y=XN(m,u);if(y&&m){if(!W)Y.onFirstEvent?.(y);G=!0,H(),Y.onTerminal?.(m),Q?.error(new c1({message:y.message,url:J.url,requestBodyValues:Y.body,statusCode:y.status,responseHeaders:y.headers,responseBody:y.body}));return}if(I(m)&&m.type==="response.failed"){let p=I(m.response)?m.response.failed:void 0,r0=I(p)?p.rate_limit_reached_type:void 0;if(typeof r0==="string"){if(G=!0,H(),Y.onRateLimitReached?.(r0),Y.onTerminal?.(m),!W)Y.onFirstEvent?.(),Q?.error(new R0(`OpenAI account rate limit reached mid-stream (${r0})`));else O();return}}if(m)aL(m,Y.sessionID),eL(m,U);let e=m?I8(m):m;if(!e){if(!W)Y.onFirstEvent?.();L("idle timeout waiting for websocket");return}let g0=e===m?u:JSON.stringify(e);if(!W)Y.onFirstEvent?.();if(Q?.enqueue(X.encode(`${g0.split(/\r?\n/).map((p)=>`data: ${p}`).join(`
214
+ `)),Q?.close()}function Z(R){if(G)return;G=!0,H(),Y.onConnectionInvalid?.(R),Q?.error(R)}function V(R){if(G)return;if(!Y.idleTimeout)return;if(U)clearTimeout(U);U=setTimeout(()=>Z(new R0(R)),Y.idleTimeout)}async function K(R){if(G)return;if(typeof R.data!=="string"){Z(new R0("Unexpected binary WebSocket frame"));return}let p=R.data,m=(()=>{try{let c=JSON.parse(p);return typeof c==="object"&&c!==null?c:void 0}catch{return}})();if(m?.type==="codex.rate_limits"){dN.debug("codex.rate_limits frame received",{pid:process.pid}),V("idle timeout waiting for websocket");let c=XW(m);Y.onQuota?.(c);return}let d=!W?OY(m):void 0;if(d&&m){G=!0,H(),Y.onRateLimitReached?.(d.window,d.resetAt),Y.onTerminal?.(m),Y.onFirstEvent?.(),Q?.error(new R0(`OpenAI account rate limit reached at admission (${d.window})`));return}if(m?.type==="error"&&Y.onRetryableTerminal){if($(),U)clearTimeout(U);U=void 0;try{let c=await Y.onRetryableTerminal(m);if(G){if(c)N(c);return}if(c){x(c);return}}catch(c){Z(new R0(c instanceof Error?c.message:String(c),{cause:c}));return}}let y=$B(m,p);if(y&&m){if(!W)Y.onFirstEvent?.(y);G=!0,H(),Y.onTerminal?.(m),Q?.error(new t1({message:y.message,url:J.url,requestBodyValues:Y.body,statusCode:y.status,responseHeaders:y.headers,responseBody:y.body}));return}if(C(m)&&m.type==="response.failed"){let c=C(m.response)?m.response.failed:void 0,X1=C(c)?c.rate_limit_reached_type:void 0;if(typeof X1==="string"){if(G=!0,H(),Y.onRateLimitReached?.(X1),Y.onTerminal?.(m),!W)Y.onFirstEvent?.(),Q?.error(new R0(`OpenAI account rate limit reached mid-stream (${X1})`));else O();return}}if(m)YB(m,Y.sessionID),JB(m,L);let Y0=m?o8(m):m;if(!Y0){if(!W)Y.onFirstEvent?.();V("idle timeout waiting for websocket");return}let p0=Y0===m?p:JSON.stringify(Y0);if(!W)Y.onFirstEvent?.();if(Q?.enqueue(X.encode(`${p0.split(/\r?\n/).map((c)=>`data: ${c}`).join(`
165
215
  `)}
166
216
 
167
- `)),W=!0,L("idle timeout waiting for websocket"),!e)return;if(e.type==="response.completed"||e.type==="response.done"){G=!0,YN(e,U),Y.onComplete?.(e,U),Y.onTerminal?.(e),O();return}if(e.type==="response.failed"||e.type==="response.incomplete"||e.type==="error")G=!0,Y.onTerminal?.(e),O()}function j(_){B(new R0(a0(_),{cause:_}))}function P(_){if(G)return;B(new R0(AG("WebSocket closed before response.completed",_.code,_.reason)))}function S(){let _=_9(Y.signal);if(G)return;G=!0,H(),N(),Y.onAbort?.(_),Q?.error(_)}function E(_){if(G)return;G=!0,H(),N(),Y.onAbort?.(JN(_))}function b(_){$(),J=_,J.addEventListener("message",Z),J.addEventListener("error",j,{once:!0}),J.addEventListener("close",P,{once:!0}),$=()=>{J.removeEventListener("message",Z),J.removeEventListener("error",j),J.removeEventListener("close",P)};let{background:u,...m}=Y.body;L("idle timeout sending websocket request");try{J.send(JSON.stringify({type:"response.create",...m})),L("idle timeout waiting for websocket")}catch(d){if(G)return;B(new R0(d instanceof Error?d.message:String(d),{cause:d}))}}return new Response(new ReadableStream({start(_){if(Q=_,Y.signal?.addEventListener("abort",S,{once:!0}),Y.signal?.aborted){S();return}b(J)},cancel(_){E(_)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function aL(Y,X){if(!tL(Y))return;await p0({component:"ws",event:"provider_native_web_search_event",sessionID:X,serverEventType:Y.type,itemType:I(Y.item)?Y.item.type:void 0,serverEvent:Y})}function tL(Y){if(typeof Y.type==="string"&&(Y.type.startsWith("response.web_search_call.")||Y.type.startsWith("response.web_search_preview_call.")))return!0;if(I(Y.item)&&typeof Y.item.type==="string")return Y.item.type==="web_search_call"||Y.item.type==="web_search_preview_call";return!1}function eL(Y,X){if(Y.type!=="response.output_item.done")return;if(!I(Y.item))return;MG(Y.item,X)}function YN(Y,X){let J=Y.response;if(!I(J)||!Array.isArray(J.output))return;for(let Q of J.output)if(I(Q))MG(Q,X)}function MG(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 XN(Y,X){if(Y?.type!=="error")return;let J=Y.status??Y.status_code;if(typeof J!=="number"||J>=200&&J<300)return;return{status:J,headers:I(Y.headers)?Object.fromEntries(Object.entries(Y.headers).flatMap(([Q,$])=>typeof $==="string"||typeof $==="number"||typeof $==="boolean"?[[Q,String($)]]:[])):void 0,body:X,message:I(Y.error)&&typeof Y.error.message==="string"?Y.error.message:`${J}`}}function GY(Y){if(typeof Y==="string")try{return GY(JSON.parse(Y))}catch{return}if(!I(Y))return;let X=GY(Y.cause);if(X)return X;let J=GY(Y.body);if(J)return J;let Q=I(Y.error)?Y.error:Y,$=typeof Q.type==="string"?Q.type:void 0,G=Y.status??Y.status_code;if($!=="usage_limit_reached"&&G!==429)return;let{resets_at:W,resets_in_seconds:K}=Q,U=typeof W==="number"&&Number.isFinite(W)&&W>0?W*1000:typeof K==="number"&&Number.isFinite(K)&&K>0?Date.now()+K*1000:void 0;return{window:$??"primary",resetAt:U}}function JN(Y){if(I9(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function _9(Y){let X=Y?.reason;if(I9(X))return X;if(QN(X))return X;return new DOMException(X instanceof Error?X.message:"Aborted","AbortError")}function QN(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function AG(Y,X,J){let Q=[`code ${X}`];if(X===1009)Q.push("message too big");if(J.length>0)Q.push(J.toString());return`${Y} (${Q.join(": ")})`}var k9="x-opencode-title",aY="x-openai-auth-quota-account",S9=new Set([k9,t0,aY,"x-opencode-session"]),GN=15000,WN=300000,zN=3300000,RG="websocket_connection_limit_reached";function KN(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 $N("sha256").update(Q).digest("hex").slice(0,12)}function UN(Y){let X=Y?.httpFetch??globalThis.fetch,J=new Map,Q=Y?.connectTimeout??GN,$=Y?.idleTimeout??WN,G=Y?.maxConnectionAge??zN,W=Y?.streamRetries??5,K=Y?.firstEventGraceMs??250,U=Y?.rawWebSocket??!1,H=Y?.onQuota,N=Y?.onRateLimitReached,O=setInterval(()=>j(),Math.min($,60000));if(typeof O==="object"&&"unref"in O&&typeof O.unref==="function")O.unref();function B(E,b,_){if(!b||!_)return _;b9(E,TG(b));let u=new Headers(_.headers),m=u.get("x-codex-turn-metadata");if(!m)return _;let d=vG(m,E.turnID,E.turnStartedAt);if(!d)return _;return u.set("x-codex-turn-metadata",d),{..._,headers:u}}async function L(E,b){let _=E instanceof URL?E.toString():typeof E==="string"?E:E.url,u=j0.normalizeHeaders(b?.headers),m=yG(b),d=wY(m);if(b?.method!=="POST"||!new URL(_).pathname.endsWith("/responses"))return X(E,d);let y=(()=>{try{if(typeof b?.body!=="string")return;let o=JSON.parse(b.body);return typeof o==="object"&&o!==null?o:void 0}catch{return}})();if(!y?.stream)return X(E,d);if(u[k9]==="true")return X(E,d);let e=u[t0]??u["x-session-affinity"]??u["session-id"],g0=e;if(!e)return X(E,d);let p=j0.normalizeHeaders(m?.headers),r0=KN(p),v1=`${e}:${r0}:conversation`,h1=typeof u[aY]==="string"?u[aY]:void 0,D1=N?(o,V0)=>N(o,h1,V0):void 0,h=J.get(v1)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};if(J.set(v1,h),h.fallback)return X(E,B(h,y,d));if(h.busy)return X(E,B(h,y,d));h.busy=!0,h.lastUsedAt=Date.now();try{let o=TG(y),V0=j0.normalizeHeaders(m?.headers),J8=typeof V0.authorization==="string"&&V0.authorization.startsWith("Bearer ")?V0.authorization.slice(7):"",P1=typeof V0["chatgpt-account-id"]==="string"?V0["chatgpt-account-id"]:void 0,BY=H?(Y0)=>H(Y0,J8,h1,P1):void 0,K1=!h.socket&&!h.continuation?FN(V0):V0;if(h.socket=await NN(h,Y?.url??_,K1,Q,G,U,b?.signal),PN(h,o))await VN(h,o,$,{signal:b?.signal??void 0,sessionID:g0,url:Y?.url??_,headers:m?.headers,onRateLimitReached:D1});let s0=()=>{},y0=()=>{},U1=new Promise((Y0,A0)=>{s0=Y0,y0=A0}),Q8=DN(h,o),f0=WY(xG(h,Q8,o)),F0=typeof f0.previous_response_id==="string";await R1({sessionID:g0,transport:"websocket",phase:"main",bodyText:JSON.stringify(f0),url:Y?.url??_,method:m?.method,headers:m?.headers});let m0=j0.streamResponsesWebSocket({socket:h.socket,body:f0,sessionID:g0??void 0,idleTimeout:$,signal:b?.signal??void 0,onQuota:BY,onRateLimitReached:D1,onFirstEvent:(Y0)=>s0(Y0??!0),onComplete:(Y0,A0)=>{let w1=IG(Y0);p0({component:"ws-pool",event:"main_completed",sessionID:g0,responseID:_G(Y0),usage:w1}),bG(h,o,Y0,A0,F0)},onTerminal:(Y0)=>{if(h.busy=!1,h.lastUsedAt=Date.now(),h.streamFailures=0,Y0.type!=="response.completed"&&Y0.type!=="response.done")h.continuation=void 0,o0(h)},onConnectionInvalid:()=>{if(h.busy=!1,h.lastUsedAt=Date.now(),!h.fallback)Z(h);h.continuation=void 0,o0(h),s0(!1)},onAbort:(Y0)=>{h.busy=!1,h.lastUsedAt=Date.now(),h.streamFailures=0,h.continuation=void 0,o0(h),y0(Y0)},onRetryableTerminal:async(Y0)=>{let A0=CG(Y0);if(!A0)return;throw h.fallback=!0,A0}}),k0=await HN(U1,K);if(k0!==!1){if(k0===!0||k0.status<200||k0.status>599)return m0;return new Response(k0.body,{status:k0.status,headers:{"content-type":"application/json",...k0.headers}})}if(!h.fallback)return m0;return X(E,B(h,y,d))}catch(o){if(h.busy=!1,h.lastUsedAt=Date.now(),j0.isAbortError(o))throw h.streamFailures=0,h.continuation=void 0,o0(h),o;let V0=j0.parseRateLimitSignal(o);if(V0)D1?.(V0.window,V0.resetAt);if(j0.isUpgradeFailure(o)&&!U)h.fallback=!0;if(Z(h),h.continuation=void 0,o0(h),h.fallback)return X(E,B(h,y,d));return LN(new R0(o instanceof Error?o.message:String(o),{cause:o}))}}function Z(E){if(E.streamFailures++,E.streamFailures>W)E.fallback=!0}function j(){let E=Date.now();for(let[b,_]of J){if(_.busy)continue;if(E-_.lastUsedAt<$)continue;o0(_),J.delete(b)}}function P(){clearInterval(O);for(let E of J.values())o0(E);J.clear()}function S(E){let b=`${E}:`;for(let[_,u]of J){if(!_.startsWith(b))continue;o0(u),J.delete(_)}}return Object.assign(L,{close:P,remove:S})}function CG(Y){if(Y.type!=="error"||!I(Y.error)||Y.error.code!==RG)return;return Error(typeof Y.error.message==="string"?Y.error.message:RG)}async function HN(Y,X){if(X<=0)return!1;return new Promise((J,Q)=>{let $=setTimeout(()=>J(!1),X);Y.then((G)=>{clearTimeout($),J(G)},(G)=>{clearTimeout($),Q(G)})})}function LN(Y){return new Response(new ReadableStream({start(X){X.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function NN(Y,X,J,Q,$,G,W){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<$)return Y.socket;o0(Y);let K=await j0.connectResponsesWebSocket({url:j0.toWebSocketUrl(X),headers:J,timeout:Q,rawWebSocket:G,signal:W??void 0});return Y.connectedAt=Date.now(),K}function o0(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function VN(Y,X,J,Q){if(!Y.socket||!Array.isArray(X.input)||X.input.length===0)return;let $=ZN(X);await R1({sessionID:Q.sessionID,transport:"websocket",phase:"prewarm",bodyText:JSON.stringify($),url:Q.url,method:"POST",headers:Q.headers});let G=j0.streamResponsesWebSocket({socket:Y.socket,body:$,sessionID:Q.sessionID,idleTimeout:J,signal:Q.signal,onRateLimitReached:Q.onRateLimitReached,onComplete:(W,K)=>{p0({component:"ws-pool",event:"prewarm_completed",sessionID:Q.sessionID,responseID:_G(W),usage:IG(W)}),bG(Y,$,W,K,!1)},onTerminal:(W)=>{if(W.type!=="response.completed"&&W.type!=="response.done")Y.continuation=void 0},onConnectionInvalid:()=>{Y.continuation=void 0},onAbort:()=>{Y.continuation=void 0},onRetryableTerminal:async(W)=>{let K=CG(W);if(!K)return;throw Y.fallback=!0,K}});await BN(G)}function _G(Y){let X=Y.response;if(!I(X))return;return typeof X.id==="string"?X.id:void 0}function IG(Y){let X=Y.response;if(!I(X))return;return I(X.usage)?X.usage:void 0}async function BN(Y){let X=Y.body?.getReader();if(!X)return;while(!0)if((await X.read()).done)return}function ZN(Y){return WY({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:ON(Y.client_metadata)})}function SG(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 ON(Y){if(!I(Y))return Y;if(typeof Y["x-codex-turn-metadata"]!=="string")return Y;try{let X=JSON.parse(Y["x-codex-turn-metadata"]);if(!I(X))return Y;return{...Y,"x-codex-turn-metadata":SG(X),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function FN(Y){let X=Y["x-codex-turn-metadata"];if(!X)return Y;try{let J=JSON.parse(X);if(!I(J))return Y;return{...Y,"x-codex-turn-metadata":SG(J)}}catch{return Y}}var kG=["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 TG(Y){let X={...Y};if(Array.isArray(Y.input))X.input=Y.input.map(qN);return X}function WY(Y){let X={};for(let J of kG)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 qN(Y){if(!I(Y))return Y;if(typeof Y.type==="string")return Y;if(typeof Y.role!=="string")return Y;if(!("content"in Y))return Y;return{...Y,type:"message"}}function bG(Y,X,J,Q,$){let G=J.response,W=I(G)&&typeof G.id==="string"?G.id:void 0;if(!W||!Array.isArray(X.input)){Y.continuation=void 0;return}let K=$?new Set(Y.continuation?.finalizedCallIds):new Set;for(let U of Q)K.add(U);Y.continuation={responseID:W,input:X.input,signature:x9(X),finalizedCallIds:K}}function b9(Y,X,J=X){let Q=Array.isArray(X.input)?X.input:[],$=Array.isArray(J.input)?J.input:Q,G=x9(J),W=Y.turnInput&&Y.turnSignature===G?jN(Y.turnInput,$):void 0,K=W===void 0?Q:$.slice(W);if(K.length>0&&K.some(hG)||!Y.turnID)Y.turnID=V1(),Y.turnStartedAt=Date.now();Y.turnInput=$.slice(),Y.turnSignature=G}function xG(Y,X,J=X){b9(Y,X,J);let Q=X.client_metadata;if(!I(Q)||typeof Q["x-codex-turn-metadata"]!=="string")return X;let $=vG(Q["x-codex-turn-metadata"],Y.turnID,Y.turnStartedAt);if(!$)return X;return{...X,client_metadata:{...Q,"x-codex-turn-metadata":$}}}function vG(Y,X,J){let Q;try{Q=JSON.parse(Y)}catch{return}if(!I(Q))return;return JSON.stringify({session_id:Q.session_id,thread_id:Q.thread_id,thread_source:Q.thread_source,turn_id:X,sandbox:Q.sandbox,turn_started_at_unix_ms:J,request_kind:"turn",window_id:Q.window_id})}function jN(Y,X){if(Y.length>X.length)return;for(let J=0;J<Y.length;J++)if(l0(Y[J])!==l0(X[J]))return;return Y.length}function DN(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!J||!Y.continuation)return X;if(Y.continuation.signature!==x9(X))return Y.continuation=void 0,X;if(!gG(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),$=wN(Q,Y.continuation.finalizedCallIds);if($.length===0)return X;return{...X,previous_response_id:Y.continuation.responseID,input:$}}function PN(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!Y.continuation)return!0;if(!J)return!1;if(!gG(Y.continuation.input,J))return!0;return J.slice(Y.continuation.input.length).some(hG)}function hG(Y){if(!I(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function wN(Y,X){return Y.filter((J)=>{if(!I(J))return!0;if(typeof J.type==="string"&&J.type.endsWith("_output"))return!0;if(J.type==="function_call_output"||J.type==="custom_tool_call_output")return!0;if(J.type==="function_call"||J.type==="custom_tool_call"){let Q=typeof J.call_id==="string"?J.call_id:typeof J.id==="string"?J.id:void 0;return Q?!X.has(Q):!0}if(J.type==="message")return J.role!=="assistant";if(typeof J.role==="string")return J.role!=="assistant";return!1})}function x9(Y){return l0(EN(Object.fromEntries(Object.entries(Y).filter(([X])=>X!=="input"&&X!=="stream"&&X!=="background"&&X!=="previous_response_id"&&X!=="generate"))))}function EN(Y){if(!I(Y.client_metadata))return Y;let X=Object.fromEntries(Object.entries(Y.client_metadata).filter(([J])=>J!=="x-codex-turn-metadata"&&J!=="x-codex-ws-stream-request-start-ms"));return{...Y,client_metadata:X}}function gG(Y,X){if(Y.length>=X.length)return!1;for(let J=0;J<Y.length;J++)if(l0(Y[J])!==l0(X[J]))return!1;return!0}function yG(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let X=new Headers(Y.headers);for(let J of S9)X.delete(J);return{...Y,headers:X}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((X)=>!S9.has(X[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([X])=>!S9.has(X.toLowerCase())))}}var IN=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),SN=new Set(["gpt-5.6"]),kN=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),bN="opencode-oauth-dummy-key",xN="terminal_resize_reflow",y9="0.144.0",vN=`codex_exec/${y9} (Debian 12.0.0; aarch64) unknown (codex_exec; ${y9})`,hN="seccomp",gN="main-refresh",yN=120000,fN=90000,mN=4000,fG=50,mG=3,cN=25,uN=60000,pN="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",cG=!1,uG=H0("models"),pG=!1,lG=!1;class m9 extends Error{code="OPENAI_AUTH_PERSIST_FAILED";constructor(Y){super("OpenAI OAuth token refreshed but could not be persisted; re-login required",{cause:Y});this.name="AuthPersistError"}}function h9(Y){return Y instanceof m9}function dG(){throw Error(pN)}function lN(Y){return Math.floor(Math.random()*Y)}function dN(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 iN(Y,X,J){let Q=Y.get(X);if(Q)return Q;let $=V1(),G={threadID:$,turnID:V1(),windowID:`${$}:0`};return Y.set(X,G),J?.(),G}function AW(){return _N(jY(),"openai-auth-sessions.json")}function nN(){let Y=new Map;try{let X=JSON.parse(AN(AW(),"utf8"));if(!I(X.sessions))return Y;for(let[J,Q]of Object.entries(X.sessions)){if(!I(Q)||typeof Q.threadID!=="string")continue;Y.set(J,{threadID:Q.threadID,turnID:V1(),windowID:`${Q.threadID}:0`})}}catch{}return Y}function oN(Y){let X=AW(),J=`${X}.tmp-${process.pid}`;try{MN(jY(),{recursive:!0});let Q={version:1,sessions:Object.fromEntries([...Y.entries()].map(([$,G])=>[$,{threadID:G.threadID}]))};CN(J,`${JSON.stringify(Q,null,2)}
168
- `,"utf8"),RN(J,X)}catch{}}function iG(Y,X){return I(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===X}function rN(Y,X){if(Y.length>X.length)return!1;for(let J=0;J<Y.length;J++)if(l0(Y[J])!==l0(X[J]))return!1;return!0}function sN(Y,X){if(!Y.input)return X.length>0;if(!rN(Y.input,X))return!0;return X.slice(Y.input.length).some((Q)=>iG(Q,"user")||iG(Q,"developer"))}function aN(Y,X){let J=Array.isArray(X?.input)?X.input:void 0;if(J&&(sN(Y,J)||!Y.turnID))Y.turnID=V1(),Y.turnStartedAt=Date.now();else if(!Y.turnStartedAt)Y.turnStartedAt=Date.now();if(J)Y.input=J}function tN(Y){if(!Y.metadata)return{init:Y.init};let X=dN(Y.init?.body);if(!Y.websocket)aN(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:hN,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",xN),Y.headers.set("x-codex-turn-metadata",J),Y.headers.set("user-agent",vN),Y.headers.set("version",y9),Y.dumpSessionID)Y.headers.set(t0,Y.dumpSessionID);let Q=X;if(!Q)return{init:Y.init};let $=Y.responsesLite&&typeof Q.model==="string"&&kN.has(Q.model);if($&&!Y.websocket)Y.headers.set("x-openai-internal-codex-responses-lite","true");if(Q.prompt_cache_key=Y.metadata.threadID,Q.parallel_tool_calls??=!0,Array.isArray(Q.tools))Q.tools=Q.tools.map(GV);if(QV(Q),$V(Q),kX(Q),XV(Q),$)JV(Q);let G={...typeof Q.client_metadata==="object"&&Q.client_metadata!==null?Q.client_metadata:{},"x-codex-installation-id":Y.installationID,"x-codex-window-id":Y.metadata.windowID};if(Y.websocket){if(G["x-codex-turn-metadata"]=J,G["x-codex-ws-stream-request-start-ms"]=String(Date.now()),$)G.ws_request_header_x_openai_internal_codex_responses_lite="true"}return Q.client_metadata=G,Y.headers.delete("content-length"),Y.headers.delete("Content-Length"),{init:{...Y.init,body:JSON.stringify(WY(Q))}}}function eN(Y,X){return Y.find((J)=>J.enabled!==!1&&j1(J)&&(J.id===X||J.accountId===X))}function nG(Y,X){if(Y.resetCreditsAvailable!==void 0||X?.resetCreditsAvailable===void 0)return Y;return{...Y,resetCreditsAvailable:X.resetCreditsAvailable}}function tY(Y,X){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:X}}function RW(Y,X,J=Date.now(),Q=X.mainAccountId){let $=Y.getMain(),G=$?.quota;return{main:{quota:G?{...G,checkedAt:$.checkedAt,primary:tY(G.primary,$.checkedAt),secondary:tY(G.secondary,$.checkedAt)}:null,...typeof Q==="string"?{mainAccountId:Q}:{},killed:!1,...G?.resetCreditsAvailable!==void 0?{resetCredits:G.resetCreditsAvailable}:{}},fallbacks:X.accounts.filter((W)=>W.enabled).map((W)=>{let K=Y.getFallback(W.id),U=K?.quota;return{id:W.id,label:W.label,accountId:K?.accountId??W.accountId,quota:U?{...U,checkedAt:K.checkedAt,primary:tY(U.primary,K.checkedAt),secondary:tY(U.secondary,K.checkedAt)}:null,killed:!1,enabled:!0,...U?.resetCreditsAvailable!==void 0?{resetCredits:U.resetCreditsAvailable}:{}}}),route:X.routing?.mode??"main-first",lastUpdated:J}}function N4(Y,X,J,Q=Date.now()){return{...RW(Y,X,Q),activeId:J}}function oG(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 YV(Y,X){if(!(Y instanceof Request))return X;let J=new Request(Y,X),Q=J.method.toUpperCase(),$=Q==="GET"||Q==="HEAD"||J.body===null?void 0:await J.text();return{method:J.method,headers:new Headers(J.headers),body:$,signal:J.signal,cache:J.cache,credentials:J.credentials,integrity:J.integrity,keepalive:J.keepalive,mode:J.mode,redirect:J.redirect,referrer:J.referrer,referrerPolicy:J.referrerPolicy}}function rG(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}function XV(Y){if(!P0().webSearch)return;if(!Array.isArray(Y.tools)||Y.tools.length===0)return;if(Y.tools.some((X)=>I(X)&&X.type==="web_search"))return;Y.tools=[...Y.tools,{type:"web_search",external_web_access:!1,search_content_types:["text","image"]}]}function f9(Y){if(Array.isArray(Y)){for(let X of Y)f9(X);return}if(!I(Y))return;if(Y.type==="input_image")delete Y.detail;for(let X of Object.values(Y))f9(X)}function JV(Y){let X=I(Y.reasoning)?{...Y.reasoning}:{};X.context="all_turns",Y.reasoning=X,Y.parallel_tool_calls=!1;let J=Array.isArray(Y.input)?Y.input:[];f9(J);let $=[{type:"additional_tools",role:"developer",tools:Array.isArray(Y.tools)?Y.tools.filter((G)=>!(I(G)&&G.type==="web_search")):[]}];if(typeof Y.instructions==="string"&&Y.instructions.length>0)$.push({type:"message",role:"developer",content:[{type:"input_text",text:Y.instructions}]});Y.input=[...$,...J],delete Y.tools,delete Y.instructions}function QV(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(I(X)&&X.type==="function"&&X.name==="web_search"))}function $V(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(I(X)&&X.type==="function"&&X.name==="websearch_web_search_exa"))}function GV(Y){if(!I(Y))return Y;if(Y.type!=="function")return Y;let X=I(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:U,...H}=Y.parameters;return H})():Y.parameters,{type:J,name:Q,description:$,strict:G,parameters:W,...K}=Y;return{type:J,name:Q,description:$,strict:G??!1,parameters:X,...K}}async function WV(Y,X={}){let J=X.codexApiEndpoint??P0().codexApiEndpoint,Q=crypto.randomUUID(),$=nN(),G=()=>oN($),W=!1,K=[],U=null,H=null,N,O=new Z8;async function B(L,Z){let j=Y.client.session;if(typeof j?.promptAsync==="function"){let P=await mX(Y.client,L),S={noReply:!0,parts:[{type:"text",text:Z,ignored:!0}]};if(P?.agent)S.agent=P.agent;if(P?.model)S.model=P.model;if(P?.variant)S.variant=P.variant;await j.promptAsync({path:{id:L},body:S});return}}return{async dispose(){O.stop();for(let L of K)L.close();if(K.length=0,H){await H.stop().catch(()=>{});let L=globalThis;if(L.__openaiAuthRpcServer===H)L.__openaiAuthRpcServer=void 0;H=null}},async event(L){if(L.event.type!=="session.deleted")return;let Z=L.event.properties.info,j=$.get(Z.id);if(j)U?.cacheKeepManager?.remove(j.threadID);if($.delete(Z.id))G();if(N){let P=(await M0(K0()))?.accounts;await PW(Z.id,P,N)}for(let P of K)P.remove(Z.id)},provider:{id:"openai",async models(L,Z){if(Z.auth?.type!=="oauth")return L.models;let j=await M0(K0()),P=!j||LW(j),S=P?null:await hX();if(!P&&S&&!pG)pG=!0,uG.debug("restoring OAuth model costs from models.dev catalog");if(!P&&!S&&!lG)lG=!0,uG.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(L.models).filter(([,E])=>{if(E.options.reasoningMode==="pro")return!1;if(IN.has(E.api.id))return!0;if(SN.has(E.api.id))return!1;let _=E.api.id.match(/^gpt-(\d+\.\d+)/)?.[1];return _?parseFloat(_)>5.4:!1}).map(([E,b])=>[E,{...b,cost:P?{input:0,output:0,cache:{read:0,write:0}}:S?.[b.api.id]??S?.[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:IX},auth:{provider:"openai",async loader(L){let Z=await L();if(Z.type!=="oauth")return{};await VW({type:"oauth",access:Z.access??"",refresh:Z.refresh??"",expires:Z.expires??0},K0());let j=await M0(K0()).catch((V)=>{let F=K0();throw Error(`OpenAI auth store at ${F} is corrupt or unreadable: ${V instanceof Error?V.message:String(V)}. Fix or remove it to continue.`,{cause:V})}),P;async function S(){let V=K0();try{let F=TN(V);if(P?.path===V&&P.mtimeMs===F.mtimeMs&&P.size===F.size)return P.storage;let D=await M0(V);return P={path:V,mtimeMs:F.mtimeMs,size:F.size,storage:D},D}catch{return P=void 0,M0(V)}}function E(){P=void 0}if(j&&Z.access){let V=eY({id_token:"",access_token:Z.access,refresh_token:Z.refresh??""});if(V&&V!==j.mainAccountId)await J0((F)=>{return F.mainAccountId=V,F},K0()),j.mainAccountId=V,E()}let b=j?.logging?.level;if(b&&typeof b==="string")DY(b);let _=H0("transport"),u=H0("quota"),m=H0("refresh"),d=H0("accounts");_.info("codex auth loader ready",{codexApiEndpoint:J,transport:P0().rawWebSocket?"raw-websocket":P0().webSockets?"websocket":"http",webSearch:P0().webSearch});let y=new HW({storage:j,fetchQuotaFn:void 0}),e,g0=0,p=new BW({refreshFn:(V)=>x1({refreshToken:V.refreshToken,fetchImpl:V.fetchImpl,now:V.now}),quotaManager:y,onFallbackStorageChanged:E});if(j&&j.accounts.length>0)p.startBackgroundRefresh();let r0=H0("cachekeep"),v1=j?.cachekeep?.enabled===!0,h1=j?.cachekeep?.subagents===!0,D1=j?.cachekeep?.sustain===!0,h=ZX(j),o;async function V0(V){await new Promise((F)=>setTimeout(F,V))}async function J8(V){let F;for(let D=1;D<=mG;D++)try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:V.refresh,access:V.access,expires:V.expires}});return}catch(R){if(F=R,D<mG)await V0(cN*D)}throw new m9(F)}async function P1(V){await J0((F)=>{return F.refresh=F.refresh??{},V(F),F},K0()),E()}async function BY(V){let F=Date.now()+mN;while(Date.now()<F){await new Promise((k)=>setTimeout(k,fG+lN(fG)));let D=await L();if(D.type!=="oauth"||!D.access)continue;if((D.access!==V.access||D.refresh!==V.refresh||(D.expires??0)>(V.expires??0)+60000)&&(!D.expires||D.expires>Date.now()))return m.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:D.expires?D.expires-Date.now():void 0}),{access:D.access,refresh:D.refresh??V.refresh??"",expires:D.expires??0}}return null}async function K1(){if(!o)o=(async()=>{let V=await L();if(V.type!=="oauth")throw Error("not oauth");if(!V.refresh)throw Error("Token refresh failed: missing refresh token");let F=sG(V.refresh),D=await M0(K0()),R=D?.refresh?.mainLastRefreshError;if(R&&tG(R,V.refresh,Date.now()))throw Error(eG(R,Date.now()));if(D?.refresh?.mainRefreshLeaseUntil&&D.refresh.mainRefreshLeaseUntil>Date.now()&&D.refresh.mainRefreshLeaseTokenHash===F){let M=await BY(V);if(M)return M;throw Error("Codex OAuth refresh is already in progress")}let k=await PY({name:gN,ttlMs:yN,path:K0(),renew:!0});if(!k){let M=await BY(V);if(M)return M;throw Error("Codex OAuth refresh is already in progress")}let T=crypto.randomUUID(),C=F;try{await P1((g)=>{g.refresh=g.refresh??{},g.refresh.mainRefreshLeaseId=T,g.refresh.mainRefreshLeaseUntil=Date.now()+fN,g.refresh.mainRefreshLeaseTokenHash=F});let M=await M0(K0());if(M?.refresh?.mainRefreshLeaseId!==T||M.refresh.mainRefreshLeaseTokenHash!==F)throw Error("Codex OAuth refresh is already in progress");let w=await x1({refreshToken:V.refresh,fetchImpl:fetch,now:Date.now});return await J8(w),await P1((g)=>{if(g.refresh=g.refresh??{},g.refresh.mainLastRefreshError=void 0,g.refresh.mainRefreshLeaseId===T)g.refresh.mainRefreshLeaseId=void 0,g.refresh.mainRefreshLeaseUntil=void 0,g.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),C=void 0,w}catch(M){if(V.refresh&&!h9(M))await P1((w)=>{w.refresh=w.refresh??{},w.refresh.mainLastRefreshError=aG({error:M,now:Date.now(),refreshToken:V.refresh??"",previous:w.refresh.mainLastRefreshError})}).catch(()=>{});throw M}finally{if(C)await P1((M)=>{if(M.refresh?.mainRefreshLeaseId===T&&M.refresh.mainRefreshLeaseTokenHash===C)M.refresh.mainRefreshLeaseId=void 0,M.refresh.mainRefreshLeaseUntil=void 0,M.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await k.release().catch(()=>{})}})().finally(()=>{o=void 0});return o}let s0=globalThis;s0.__openaiAuthCacheKeepManager?.stop();let y0=new D8({fetchImpl:fetch,getMainToken:async()=>{let V=await L();if(V.type!=="oauth")throw Error("not oauth");if(!V.access||(V.expires??0)<Date.now())try{return(await K1()).access}catch(F){if(h9(F))throw F;if(V.access)return V.access;throw Error("main token refresh failed")}return V.access},refreshFallback:async(V)=>{let F=await S(),D=F?eN(F.accounts,V):void 0;if(!D)throw Error(`fallback account ${V} not found`);let R=await p.refreshAccount(D,F??{version:1,accounts:[D]});if(!R.access)throw Error(`no access token for ${V}`);return R.access},codexResponsesUrl:J,logger:r0,now:Date.now,getWindow:()=>h,getSustain:()=>D1});s0.__openaiAuthCacheKeepManager=y0;async function U1(V,F,D,R,k=!1){if(Object.keys(V).length===0&&!k)return;let T=Date.now(),C=V,M={quota:C,refreshAfter:T+300000,checkedAt:T},w;if(D&&D!=="main"){let x=F?NY(F):null,X0=x?VY(x):void 0,B0=y.peekFallbackForPolicy(D)?.quota,b0=nG(C,B0);M={...M,quota:b0},y.setFallback(D,M,F,k,X0)}else{if(w=R,!w&&F){let B0=NY(F);w=B0?VY(B0):void 0}if(w&&e&&w!==e){u.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:w,currentMainIdentity:e});return}let x=y.peekMainForPolicy(w)?.quota,X0=nG(C,x);M={...M,quota:X0},y.setMain(F,M,w,k)}u.debug("quota pushed",{pid:process.pid,accountId:D??"main",snapshot:M.quota});let g=await S();await m0(y,g,D&&D!=="main"?g?.mainAccountId:w)}function Q8(V,F,D){let R=V==="main"?y.peekMainForPolicy()?.quota:y.peekFallbackForPolicy(V)?.quota;return UW(R,F,Date.now(),uN,D)}let f0=X.experimentalWebSockets?z1.createWebSocketFetch({httpFetch:fetch,rawWebSocket:P0().rawWebSocket,onQuota:(V,F,D,R)=>{U1(V,F,D,!D||D==="main"?R:void 0,!0)},onRateLimitReached:(V,F,D)=>{if(!F)u.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:V});let R=F??"main",k=Q8(R,V,D);y.markRateLimited(R,k),u.debug("mid-stream rate limit mark",{pid:process.pid,accountId:R,window:V})}}):void 0;if(f0)K.push(f0),W=!0;let F0=ZW();N=F0;async function m0(V,F,D=F?.mainAccountId){if(!F)return;await jW(RW(V,F,Date.now(),D),F0)}async function k0(V,F,D,R,k){let T={activeId:D,route:R,updatedAt:Date.now()};if(V){if(await X8({sessionId:V,...T},k,F0),F&&F!==V){if(R==="sticky-balanced"){let C=(await N1(F0)).stickyAssignments?.[LY(F)]?.accountId,M=k===void 0||C==="main"||k.some((w)=>w.enabled!==!1&&w.id===C);if(!C||!M)return;await X8({sessionId:F,activeId:C,route:R,updatedAt:Date.now()},k,F0);return}await X8({sessionId:F,...T},k,F0)}return}await DW(T,F0)}U={accountStoragePath:K0(),quotaManager:y,loadAccounts:M0,client:Y.client,cacheKeepManager:y0,setCacheKeepEnabled:(V)=>{v1=V},setCacheKeepSubagents:(V)=>{h1=V},setCacheKeepSustain:(V)=>{D1=V},setCacheKeepWindow:(V)=>{h=V},clearStickyRouting:(V)=>EW(V,F0),getStickyRouting:async(V)=>qW(await N1(F0),V),refreshSidebar:async()=>{let V=await M0(K0());await m0(y,V)},refreshAllQuota:async()=>f1({getAuth:L,codexRefreshFn:x1,refreshMainWithLease:K1,fallbackManager:p,quotaManager:y,loadAccounts:M0,writeSidebarState:m0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:K0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:j1,whamFn:Y8})};let Y0=null;if(Y.directory){let V=await MW(Y.directory),F=globalThis;if(F.__openaiAuthRpcServer)await F.__openaiAuthRpcServer.stop().catch(()=>{}),F.__openaiAuthRpcServer=void 0;try{Y0=await nX({dir:V.dir,secureDir:V.secureDir,sweepRoot:V.sweepRoot,drain:uX,apply:async(D)=>{let R={...U,sessionId:D.sessionId},k=await B8(D.command,D.arguments,R);return{text:k.text,knobs:k.knobs}}}),F.__openaiAuthRpcServer=Y0,H=Y0}catch{}}async function A0(V,F,D,R,k="main"){let T=oG(V,F);if(T.delete("x-api-key"),T.delete("api-key"),T.set("authorization",`Bearer ${D}`),R)T.set("ChatGPT-Account-Id",R);T.set(z1.QUOTA_ACCOUNT_HEADER,k);let C=rG(T),M=C?iN($,C,G):void 0,w=V instanceof URL?V:new URL(typeof V==="string"?V:V.url),g=w.pathname.includes("/v1/responses")||w.pathname.includes("/chat/completions")?new URL(J):w,X0=tN({init:{...F,headers:T},headers:T,metadata:M,installationID:Q,websocket:Boolean(f0&&w.pathname.endsWith("/responses")),responsesLite:X.responsesLite??!1,dumpSessionID:C}).init,B0=v1,b0=new Headers(X0?.headers),$0=BX({enabled:B0,includeSubagents:h1,headers:b0,body:X0?.body});if(B0)r0.trace("cachekeep headers",{pid:process.pid,hasParent:b0.has("x-parent-session-id"),sessionKey:$0?.sessionKey,captured:Boolean($0),affinity:b0.get("x-session-affinity"),opencodeSession:b0.get("x-opencode-session"),sessionId:b0.get("session-id")});if(f0&&w.pathname.endsWith("/responses")){if(_.debug("WS transport",{pid:process.pid,pathname:w.pathname,accountId:k}),$0)y0.track($0.sessionKey,$0.bodyText,k,R,$0.replayHeaders,$0.isSubagent);return f0(g,X0)}let N0=z1.withoutInternalHeaders(X0);if(typeof N0?.body!=="string")return fetch(g,N0);if($0)y0.track($0.sessionKey,$0.bodyText,k,R,$0.replayHeaders,$0.isSubagent);_.debug("HTTP transport",{pid:process.pid,pathname:w.pathname,accountId:k});try{let T0=await fetch(g,N0);return await R1({sessionID:C,transport:"http",phase:"http",bodyText:N0.body,accountId:k,url:g.toString(),method:N0.method,headers:N0.headers,status:T0.status}),SX(T0)}catch(T0){throw await R1({sessionID:C,transport:"http",phase:"http",bodyText:N0.body,accountId:k,url:g.toString(),method:N0.method,headers:N0.headers,error:T0 instanceof Error?T0.message:String(T0)}),T0}}function w1(V,F){if((F?.method??(V instanceof Request?V.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof F?.body!=="string")return!1;try{let R=V instanceof URL?V.toString():typeof V==="string"?V:V.url;return new URL(R).pathname.endsWith("/responses")}catch{return!1}}function TW(V){return y.peekMainForPolicy(V)?.quota}function c9(V,F){for(let D of[V?.primary?.checkedAt,V?.secondary?.checkedAt,V?.checkedAt,F])if(typeof D==="number"&&Number.isFinite(D))return D;return}function g1(V,F,D,R,k){let T=c9(V,F),C=c9(D),M=R===k&&D!=null&&(V===void 0||C!==void 0&&(T===void 0||C>T));return{quota:M?D:V,quotaCheckedAt:M?C:T,source:M?"file":"memory"}}function u9(V,F,D,R,k){let T=V?.quota,C=g1(T,V?.checkedAt,F,R,k),M=C.source,w=C.quota;if(!FW(w,D))return{exhausted:!1};let g=OW(w,D);if(!g)return{exhausted:!1};return{exhausted:!0,source:M,...g}}function p9(V,F){u.debug("admission skip: exhausted account",{accountId:V,source:F.source,resetsAt:F.resetsAt})}function CW(V,F="killswitch",D){let R=Date.now(),k=y.getMain()?.quota,T=(V?.accounts??[]).filter((x)=>x.enabled!==!1&&j1(x)).map((x)=>({accountId:x.id,quota:y.getFallback(x.id)?.quota})),C=NW(k,T,R,V);if(F==="quota-exhausted"&&D!==void 0)C=Math.max(1,Math.ceil((D-R)/1000));else if(F==="mid-stream-rate-limit"&&D!==void 0){let x=Math.max(1,Math.ceil((D-R)/1000));C=Math.min(C,x)}let M=Math.floor(C/60),w=C%60,g=F==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${M}m ${w}s.`:F==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${M}m ${w}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${M}m ${w}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(C)}})}function l9(V){let F=V?.resetCreditsAvailable;return typeof F==="number"&&Number.isFinite(F)?F:void 0}async function _W(V){let F=UY(V.storage),D=Date.now(),R=y.peekMainForPolicy(V.mainAccountIdentity),k=g1(R?.quota,R?.checkedAt,V.sidebarState.main.quota,V.sidebarState.main.mainAccountId,V.mainAccountIdentity),T=F?HY(R?.quota,V.storage,void 0,D):void 0,C=[{accountId:"main",wireAccountId:V.mainAccountIdentity,access:V.primaryAccess,keepwarmAccountKey:"main",quota:k.quota,quotaCheckedAt:k.quotaCheckedAt,reservePercent:g9(V.storage),configuredOrder:0,resetCreditsApplicable:l9(k.quota),killswitchPasses:T}],M=await p.getUsableFallbackAccounts(V.storage);for(let w of M){if(!w.access)continue;let g=V.sidebarState.fallbacks.find((b0)=>b0.id===w.id),x=y.peekFallbackForPolicy(w.id,w.accountId),X0=g1(x?.quota,x?.checkedAt,g?.quota,g?.accountId,w.accountId),B0=F?HY(x?.quota,V.storage,w.id,D):void 0;C.push({accountId:w.id,wireAccountId:w.accountId,access:w.access,keepwarmAccountKey:w.id,fallback:w,quota:X0.quota,quotaCheckedAt:X0.quotaCheckedAt,reservePercent:g9(V.storage,w.id),configuredOrder:C.length,resetCreditsApplicable:l9(X0.quota),killswitchPasses:B0})}return C}function d9(V,F,D,R,k){let T=UY(k)?V.killswitchPasses:void 0;if(V.accountId==="main"){let g=y.peekMainForPolicy(V.wireAccountId),x=g1(g?.quota,g?.checkedAt,F.main.quota,F.main.mainAccountId,V.wireAccountId);return E8({quota:x.quota,quotaCheckedAt:x.quotaCheckedAt,status:D,now:R,killswitchPasses:T})}let C=F.fallbacks.find((g)=>g.id===V.accountId),M=y.peekFallbackForPolicy(V.accountId,V.wireAccountId),w=g1(M?.quota,M?.checkedAt,C?.quota,C?.accountId,V.wireAccountId);return E8({quota:w.quota,quotaCheckedAt:w.quotaCheckedAt,status:D,now:R,killswitchPasses:T})}function IW(V){return V.accountId==="main"?"main":V.keepwarmAccountKey}function i9(V){return y.isRateLimited(IW(V))}async function $8(V){let F=V.candidates.filter((M)=>!i9(M)),D=new Map(F.map((M)=>[M.accountId,M])),R=Object.fromEntries(F.map((M)=>[M.accountId,M.quotaCheckedAt])),k=new Set(V.excludeAccountIds),T,C=await wW({sessionId:V.sessionId,requestBytes:V.requestBytes,now:V.now,validPinnedAccountIds:[...D.keys()],excludeAccountIds:V.excludeAccountIds,quotaCheckedAtByAccount:R,choose:(M)=>{let w=F.filter((x)=>!k.has(x.accountId));if(w.length===0)return;let g=wX({candidates:w,pendingBytes:M,requestBytes:V.requestBytes,now:V.now,onEmptyWeightedSet:()=>{d.debug("sticky routing: no fresh weighted candidates; using configured order")}});if(!g)return;return T={accountId:g.accountId,source:g.source,pendingBytes:M.get(g.accountId)??0},g}},F0);if(T&&C?.accountId===T.accountId)d.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:LY(V.sessionId),accountId:T.accountId,source:T.source,requestBytes:V.requestBytes,pendingBytes:T.pendingBytes});return C?D.get(C.accountId):void 0}async function SW(V,F){let D=await p.getUsableFallbackAccounts(V),R=[];for(let x of D)if(x.access)R.push({access:x.access,accountId:x.accountId,keepwarmAccountKey:x.id,quotaAccountId:x.id,fallback:x});let k=R.filter((x)=>!y.isRateLimited(x.quotaAccountId)),T=UY(V)?k.filter((x)=>HY(y.peekFallbackForPolicy(x.quotaAccountId,x.accountId)?.quota,V,x.quotaAccountId,Date.now())):k,C=new Map(F.fallbacks.map((x)=>[x.id,{quota:x.quota,accountId:x.accountId}])),M=[],w=[],g=Date.now();for(let x of T){let X0=C.get(x.quotaAccountId),B0=u9(y.peekFallbackForPolicy(x.quotaAccountId,x.accountId),X0?.quota,g,X0?.accountId,x.accountId);if(B0.exhausted)w.push({candidate:x,decision:B0});else M.push(x)}return{current:T,retained:M,skipped:w}}function n9(V,F){if(V.retained.length===0&&!F)return V.current;for(let{candidate:D,decision:R}of V.skipped)p9(D.quotaAccountId,R);return V.retained}async function o9(V,F){try{let D=M1(V.headers);await U1(D,F.access,F.quotaAccountId,void 0,zY(V.headers))}catch{}}async function kW(V,F,D,R){for(let k of R){let T;try{T=await A0(V,F,k.access,k.accountId,k.keepwarmAccountKey)}catch(C){if(C instanceof DOMException&&C.name==="AbortError")throw C;if(F?.signal?.aborted)throw C;throw d.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:k.quotaAccountId}),C}if(!KY(T.status,D))return await p.markUsed(k.fallback),{response:T,accessToken:k.access,quotaAccountId:k.quotaAccountId,activeId:k.keepwarmAccountKey};await o9(T,k),T.body?.cancel().catch(()=>{})}return}async function bW(V,F,D,R,k){if(!w1(V,F))return{response:D};if(!k.length)return{response:D};let T=D,C;for(let M of k){let w;try{w=await A0(V,F,M.access,M.accountId,M.keepwarmAccountKey)}catch(g){if(g instanceof DOMException&&g.name==="AbortError")throw g;if(F?.signal?.aborted)throw g;return d.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:M.quotaAccountId}),{response:T,...C}}if(T.body?.cancel().catch(()=>{}),T=w,C={accessToken:M.access,accountId:M.quotaAccountId},!KY(w.status,R))return await p.markUsed(M.fallback),{response:w,...C};await o9(w,M)}return{response:T,...C}}if(!cG){if(cG=!0,j){let V=[];for(let F of j.accounts)if(j1(F))V.push(F);y.seedFallbacksFromAccounts(V)}m0(y,j).catch(()=>{}),f1({getAuth:L,codexRefreshFn:x1,refreshMainWithLease:K1,fallbackManager:p,quotaManager:y,loadAccounts:M0,writeSidebarState:m0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:K0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:j1,whamFn:Y8,respectBackoff:!0}).catch((V)=>u.warn("boot quota seed failed",{pid:process.pid,error:a0(V)}))}return O.start(async()=>{let F=(await UX({getAuth:L,codexRefreshFn:x1,refreshMainWithLease:K1,fallbackManager:p,quotaManager:y,loadAccounts:M0,writeSidebarState:(D,R)=>O.isStopped()?Promise.resolve():m0(D,R),client:Y.client,fetchImpl:fetch,now:Date.now,configPath:K0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:j1,whamFn:Y8,readSidebarState:()=>N1(F0)})).filter((D)=>!D.ok);if(F.length>0)u.warn("background quota refresh completed with failures",{pid:process.pid,failures:F})},(V)=>{u.warn("background quota refresh failed",{pid:process.pid,error:V instanceof Error?V.message:String(V)})}),{apiKey:bN,async fetch(V,F){let D=oG(V,F),R=rG(D),k=D.get("x-parent-session-id")?.trim()||void 0,T=await S(),C=await L(),M=++g0;if(C.type!=="oauth")return fetch(V,F);F=await YV(V,F);let w=C.access??"";if(!C.access||(C.expires??0)<Date.now()){m.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(C.access),expiresInMs:C.expires?C.expires-Date.now():void 0});try{let t=await K1();C.access=t.access,C.refresh=t.refresh,C.expires=t.expires}catch(t){if(h9(t))throw t}}w=C.access??"";let x=C.accountId??(w?VY(NY(w)??{}):void 0);if(M===g0)e=x;let X0=T?.routing?.mode??"main-first",B0,$0=await(()=>{return B0??=N1(F0),B0})();if(X0==="sticky-balanced"&&R&&w1(V,F)&&typeof F?.body==="string"){let t=Buffer.byteLength(F.body,"utf8"),U0=await _W({storage:T,sidebarState:$0,primaryAccess:w,mainAccountIdentity:x}),z0=await $8({sessionId:R,requestBytes:t,candidates:U0,now:Date.now()});if(z0){let XX=i9(z0)?{action:"migrate",reason:"exhausted"}:d9(z0,$0,void 0,Date.now(),T);if(XX.action==="migrate"){let D0=await $8({sessionId:R,requestBytes:t,candidates:U0,excludeAccountIds:[z0.accountId],now:Date.now()});if(D0)d.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:LY(R),fromAccountId:z0.accountId,toAccountId:D0.accountId,reason:XX.reason}),z0=D0}let x0=await A0(V,F,z0.access,z0.wireAccountId,z0.keepwarmAccountKey),JX=async(D0,H1)=>{try{let xW=M1(D0.headers);await U1(xW,H1.access,H1.accountId==="main"?void 0:H1.accountId,H1.accountId==="main"?H1.wireAccountId:void 0,zY(D0.headers))}catch{}};await JX(x0,z0);let QX=d9(z0,$0,x0.status,Date.now(),T);if((x0.status===401||x0.status===403||x0.status===429)&&QX.action==="migrate"){let D0=await $8({sessionId:R,requestBytes:t,candidates:U0,excludeAccountIds:[z0.accountId],now:Date.now()});if(D0){d.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:LY(R),fromAccountId:z0.accountId,toAccountId:D0.accountId,reason:QX.reason});let H1=x0;x0=await A0(V,F,D0.access,D0.wireAccountId,D0.keepwarmAccountKey),H1.body?.cancel().catch(()=>{}),z0=D0,await JX(x0,z0)}}if(z0.fallback&&!KY(x0.status,T))await p.markUsed(z0.fallback);return await k0(R,k,z0.accountId,X0,T?.accounts).catch(()=>{}),x0}}let N0=u9(y.peekMainForPolicy(x),$0.main.quota,Date.now(),$0.main.mainAccountId,x),T0=UY(T)&&!HY(TW(x),T,void 0,Date.now()),ZY=y.isRateLimited("main"),r9,G8=()=>{return r9??=SW(T,$0),r9},c0,E1,s9=!1,OY;if(X0==="fallback-first"&&w1(V,F)){s9=!0;let t=await G8();OY=n9(t,!T0&&!ZY&&!N0.exhausted);let U0=await kW(V,F,T,OY);if(U0)c0=U0.response,E1={accessToken:U0.accessToken,accountId:U0.quotaAccountId,activeId:U0.activeId}}if(!c0){let t=N0.exhausted&&w1(V,F)&&(await G8()).retained.length>0;if(T0||ZY||t){let U0=T0?"killswitch":ZY?"mid-stream-rate-limit":"quota-exhausted";if(U0==="quota-exhausted"&&N0.exhausted)p9("main",N0);d.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:U0}),c0=CW(T,U0,U0==="quota-exhausted"&&N0.exhausted?N0.resetAtMs:ZY?y.rateLimitedUntil("main"):void 0)}else c0=await A0(V,F,w,x,"main")}let a9=Boolean(E1),y1=c0,t9=E1?.accessToken??w,e9=E1?.accountId,YX=E1?.activeId??"main";if(!E1&&!s9&&KY(c0.status,T)){d.debug("reactive fallback triggered",{pid:process.pid,status:c0.status}),OY??=n9(await G8(),!1);let t=await bW(V,F,c0,T,OY),U0=t.response;if(U0!==c0){if(a9=!0,y1=U0,t9=t.accessToken??w,e9=t.accountId,t.accountId)YX=t.accountId}}try{let t=M1(y1.headers);if(a9)await U1(t,t9,e9,void 0,zY(y1.headers));else await U1(t,w,void 0,x,zY(y1.headers))}catch{}return await k0(R,k,YX,X0,T?.accounts).catch(()=>{}),y1},async dispose(){if(O.stop(),y0.stop(),s0.__openaiAuthCacheKeepManager===y0)s0.__openaiAuthCacheKeepManager=void 0;if(p.stopBackgroundRefresh(),H){await H.stop().catch(()=>{});let V=globalThis;if(V.__openaiAuthRpcServer===H)V.__openaiAuthRpcServer=void 0;H=null}}}},methods:[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:async()=>{let{redirectUri:L}=await GW(),Z=await JW(),j=XW(crypto.getRandomValues(new Uint8Array(32)).buffer),P=QW(L,Z,j),S=WW(Z,j);return{url:P,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let E=await S,b=eY(E);return{type:"success",refresh:E.refresh_token,access:E.access_token,expires:Date.now()+(E.expires_in??3600)*1000,accountId:b}}finally{$W(j)}}}}},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:async()=>{let{deviceData:L,url:Z,instructions:j}=await zW();return{url:Z,instructions:j,method:"auto",async callback(){try{let P=await KW(L);return{type:"success",refresh:P.refresh_token,access:P.access_token,expires:Date.now()+(P.expires_in??3600)*1000,accountId:eY(P)}}catch{return{type:"failed"}}}}}},{label:"Manually enter API Key",type:"api"}]},"chat.headers":async(L,Z)=>{if(L.model.providerID!=="openai")return;if(Z.headers.originator="opencode",Z.headers["User-Agent"]=`${YW} (${v9.platform()} ${v9.release()}; ${v9.arch()})`,Z.headers["session-id"]=L.sessionID,W&&L.agent==="title")Z.headers[z1.TITLE_HEADER]="true"},"chat.params":async(L,Z)=>{if(L.model.providerID!=="openai")return;Z.maxOutputTokens=void 0},config:async(L)=>{L.command={...L.command??{},[z8]:{template:z8,description:"Show current OpenAI Codex OAuth quota usage for all accounts."},[K8]:{template:K8,description:"Manage OpenAI accounts — add, switch, remove, or reorder."},[U8]:{template:U8,description:"Show or change OpenAI account routing between main-first, fallback-first, and sticky-balanced."},[H8]:{template:H8,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."},[L8]:{template:L8,description:"Show or toggle OpenAI Codex request dump capture for debugging."},[N8]:{template:N8,description:"Show or change the plugin log level (error, warn, info, debug, trace)."},[V8]:{template:V8,description:"Keep Codex prompt cache alive during idle by shadow-replaying the last request."}}},"command.execute.before":async(L)=>{if(!KX.includes(L.command))return;if(!U)await B(L.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),dG();let Z=L.command,j={...U,sessionId:L.sessionID,notify:(S)=>{b8(S,L.sessionID)}},P=await B8(Z,L.arguments,j);if(pX(L.sessionID))b8(P,L.sessionID);else await B(L.sessionID,P.text);dG()}}}var zV=async(Y)=>{let X=P0();return WV(Y,{codexApiEndpoint:X.codexApiEndpoint,experimentalWebSockets:X.webSockets,responsesLite:X.responsesLite})},V4={id:"cortexkit-openai-auth",server:zV};export{rG as resolveSidebarSessionId,NY as parseJwtClaims,nG as mergePushedQuotaMetadata,eN as findCachekeepFallbackAccount,VY as extractAccountIdFromClaims,V4 as default,N4 as buildSidebarState,RW as buildSidebarMachineState,zV as OpenAIAuthPlugin,yN as MAIN_REFRESH_LOCK_TTL_MS,fN as MAIN_REFRESH_LEASE_TTL_MS,WV as CodexAuthPlugin,m9 as AuthPersistError};
217
+ `)),W=!0,V("idle timeout waiting for websocket"),!Y0)return;if(Y0.type==="response.completed"||Y0.type==="response.done"){G=!0,QB(Y0,L),Y.onComplete?.(Y0,L),Y.onTerminal?.(Y0),O();return}if(Y0.type==="response.failed"||Y0.type==="response.incomplete"||Y0.type==="error")G=!0,Y.onTerminal?.(Y0),O()}function j(R){Z(new R0($1(R),{cause:R}))}function M(R){if(G)return;Z(new R0(GW("WebSocket closed before response.completed",R.code,R.reason)))}function I(){let R=n9(Y.signal);if(G)return;G=!0,H(),N(),Y.onAbort?.(R),Q?.error(R)}function E(R){if(G)return;G=!0,H(),N(),Y.onAbort?.(GB(R))}function x(R){$(),J=R,J.addEventListener("message",K),J.addEventListener("error",j,{once:!0}),J.addEventListener("close",M,{once:!0}),$=()=>{J.removeEventListener("message",K),J.removeEventListener("error",j),J.removeEventListener("close",M)};let{background:p,...m}=Y.body;V("idle timeout sending websocket request");try{J.send(JSON.stringify({type:"response.create",...m})),V("idle timeout waiting for websocket")}catch(d){if(G)return;Z(new R0(d instanceof Error?d.message:String(d),{cause:d}))}}return new Response(new ReadableStream({start(R){if(Q=R,Y.signal?.addEventListener("abort",I,{once:!0}),Y.signal?.aborted){I();return}x(J)},cancel(R){E(R)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function YB(Y,X){if(!XB(Y))return;await r0({component:"ws",event:"provider_native_web_search_event",sessionID:X,serverEventType:Y.type,itemType:C(Y.item)?Y.item.type:void 0,serverEvent:Y})}function XB(Y){if(typeof Y.type==="string"&&(Y.type.startsWith("response.web_search_call.")||Y.type.startsWith("response.web_search_preview_call.")))return!0;if(C(Y.item)&&typeof Y.item.type==="string")return Y.item.type==="web_search_call"||Y.item.type==="web_search_preview_call";return!1}function JB(Y,X){if(Y.type!=="response.output_item.done")return;if(!C(Y.item))return;$W(Y.item,X)}function QB(Y,X){let J=Y.response;if(!C(J)||!Array.isArray(J.output))return;for(let Q of J.output)if(C(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:C(Y.headers)?Object.fromEntries(Object.entries(Y.headers).flatMap(([Q,$])=>typeof $==="string"||typeof $==="number"||typeof $==="boolean"?[[Q,String($)]]:[])):void 0,body:X,message:C(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(!C(Y))return;let X=OY(Y.cause);if(X)return X;let J=OY(Y.body);if(J)return J;let Q=C(Y.error)?Y.error:Y,$=typeof Q.type==="string"?Q.type:void 0,G=Y.status??Y.status_code;if($!=="usage_limit_reached"&&G!==429)return;let{resets_at:W,resets_in_seconds:U}=Q,L=typeof W==="number"&&Number.isFinite(W)&&W>0?W*1000:typeof U==="number"&&Number.isFinite(U)&&U>0?Date.now()+U*1000:void 0;return{window:$??"primary",resetAt:L}}function GB(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(WB(X))return X;return new DOMException(X instanceof Error?X.message:"Aborted","AbortError")}function WB(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function GW(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,G1,H8,"x-opencode-session"]),UB=15000,HB=300000,LB=3300000,WW="websocket_connection_limit_reached";function VB(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 zB("sha256").update(Q).digest("hex").slice(0,12)}function NB(Y){let X=Y?.httpFetch??globalThis.fetch,J=new Map,Q=Y?.connectTimeout??UB,$=Y?.idleTimeout??HB,G=Y?.maxConnectionAge??LB,W=Y?.streamRetries??5,U=Y?.firstEventGraceMs??250,L=Y?.rawWebSocket??!1,H=Y?.onQuota,N=Y?.onRateLimitReached,O=setInterval(()=>j(),Math.min($,60000));if(typeof O==="object"&&"unref"in O&&typeof O.unref==="function")O.unref();function Z(E,x,R){if(!x||!R)return R;a9(E,zW(x));let p=new Headers(R.headers),m=p.get("x-codex-turn-metadata");if(!m)return R;let d=KW(m,E.turnID,E.turnStartedAt);if(!d)return R;return p.set("x-codex-turn-metadata",d),{...R,headers:p}}async function V(E,x){let R=E instanceof URL?E.toString():typeof E==="string"?E:E.url,p=D0.normalizeHeaders(x?.headers),m=FW(x),d=xY(m);if(x?.method!=="POST"||!new URL(R).pathname.endsWith("/responses"))return X(E,d);let y=(()=>{try{if(typeof x?.body!=="string")return;let r=JSON.parse(x.body);return typeof r==="object"&&r!==null?r:void 0}catch{return}})();if(!y?.stream)return X(E,d);if(p[s9]==="true")return X(E,d);let Y0=p[G1]??p["x-session-affinity"]??p["session-id"],p0=Y0;if(!Y0)return X(E,d);let c=D0.normalizeHeaders(m?.headers),X1=VB(c),i1=`${Y0}:${X1}:conversation`,n1=typeof p[H8]==="string"?p[H8]:void 0,C1=N?(r,B0)=>N(r,n1,B0):void 0,h=J.get(i1)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};if(J.set(i1,h),h.fallback)return X(E,Z(h,y,d));if(h.busy)return X(E,Z(h,y,d));h.busy=!0,h.lastUsedAt=Date.now();try{let r=zW(y),B0=D0.normalizeHeaders(m?.headers),B8=typeof B0.authorization==="string"&&B0.authorization.startsWith("Bearer ")?B0.authorization.slice(7):"",_1=typeof B0["chatgpt-account-id"]==="string"?B0["chatgpt-account-id"]:void 0,wY=H?(Q0)=>H(Q0,B8,n1,_1):void 0,l0=!h.socket&&!h.continuation?DB(B0):B0;if(h.socket=await KB(h,Y?.url??R,l0,Q,G,L,x?.signal),EB(h,r))await OB(h,r,$,{signal:x?.signal??void 0,sessionID:p0,url:Y?.url??R,headers:m?.headers,onRateLimitReached:C1});let J1=()=>{},d0=()=>{},K1=new Promise((Q0,T0)=>{J1=Q0,d0=T0}),Z8=wB(h,r),i0=qY(ZW(h,Z8,r)),F0=typeof i0.previous_response_id==="string";await h1({sessionID:p0,transport:"websocket",phase:"main",bodyText:JSON.stringify(i0),url:Y?.url??R,method:m?.method,headers:m?.headers});let x0=D0.streamResponsesWebSocket({socket:h.socket,body:i0,sessionID:p0??void 0,idleTimeout:$,signal:x?.signal??void 0,onQuota:wY,onRateLimitReached:C1,onFirstEvent:(Q0)=>J1(Q0??!0),onComplete:(Q0,T0)=>{let I1=LW(Q0);r0({component:"ws-pool",event:"main_completed",sessionID:p0,responseID:HW(Q0),usage:I1}),BW(h,r,Q0,T0,F0)},onTerminal:(Q0)=>{if(h.busy=!1,h.lastUsedAt=Date.now(),h.streamFailures=0,Q0.type!=="response.completed"&&Q0.type!=="response.done")h.continuation=void 0,Y1(h)},onConnectionInvalid:()=>{if(h.busy=!1,h.lastUsedAt=Date.now(),!h.fallback)K(h);h.continuation=void 0,Y1(h),J1(!1)},onAbort:(Q0)=>{h.busy=!1,h.lastUsedAt=Date.now(),h.streamFailures=0,h.continuation=void 0,Y1(h),d0(Q0)},onRetryableTerminal:async(Q0)=>{let T0=UW(Q0);if(!T0)return;throw h.fallback=!0,T0}}),v0=await BB(K1,U);if(v0!==!1){if(v0===!0||v0.status<200||v0.status>599)return x0;return new Response(v0.body,{status:v0.status,headers:{"content-type":"application/json",...v0.headers}})}if(!h.fallback)return x0;return X(E,Z(h,y,d))}catch(r){if(h.busy=!1,h.lastUsedAt=Date.now(),D0.isAbortError(r))throw h.streamFailures=0,h.continuation=void 0,Y1(h),r;let B0=D0.parseRateLimitSignal(r);if(B0)C1?.(B0.window,B0.resetAt);if(D0.isUpgradeFailure(r)&&!L)h.fallback=!0;if(K(h),h.continuation=void 0,Y1(h),h.fallback)return X(E,Z(h,y,d));return ZB(new R0(r instanceof Error?r.message:String(r),{cause:r}))}}function K(E){if(E.streamFailures++,E.streamFailures>W)E.fallback=!0}function j(){let E=Date.now();for(let[x,R]of J){if(R.busy)continue;if(E-R.lastUsedAt<$)continue;Y1(R),J.delete(x)}}function M(){clearInterval(O);for(let E of J.values())Y1(E);J.clear()}function I(E){let x=`${E}:`;for(let[R,p]of J){if(!R.startsWith(x))continue;Y1(p),J.delete(R)}}return Object.assign(V,{close:M,remove:I})}function UW(Y){if(Y.type!=="error"||!C(Y.error)||Y.error.code!==WW)return;return Error(typeof Y.error.message==="string"?Y.error.message:WW)}async function BB(Y,X){if(X<=0)return!1;return new Promise((J,Q)=>{let $=setTimeout(()=>J(!1),X);Y.then((G)=>{clearTimeout($),J(G)},(G)=>{clearTimeout($),Q(G)})})}function ZB(Y){return new Response(new ReadableStream({start(X){X.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function KB(Y,X,J,Q,$,G,W){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<$)return Y.socket;Y1(Y);let U=await D0.connectResponsesWebSocket({url:D0.toWebSocketUrl(X),headers:J,timeout:Q,rawWebSocket:G,signal:W??void 0});return Y.connectedAt=Date.now(),U}function Y1(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function OB(Y,X,J,Q){if(!Y.socket||!Array.isArray(X.input)||X.input.length===0)return;let $=FB(X);await h1({sessionID:Q.sessionID,transport:"websocket",phase:"prewarm",bodyText:JSON.stringify($),url:Q.url,method:"POST",headers:Q.headers});let G=D0.streamResponsesWebSocket({socket:Y.socket,body:$,sessionID:Q.sessionID,idleTimeout:J,signal:Q.signal,onRateLimitReached:Q.onRateLimitReached,onComplete:(W,U)=>{r0({component:"ws-pool",event:"prewarm_completed",sessionID:Q.sessionID,responseID:HW(W),usage:LW(W)}),BW(Y,$,W,U,!1)},onTerminal:(W)=>{if(W.type!=="response.completed"&&W.type!=="response.done")Y.continuation=void 0},onConnectionInvalid:()=>{Y.continuation=void 0},onAbort:()=>{Y.continuation=void 0},onRetryableTerminal:async(W)=>{let U=UW(W);if(!U)return;throw Y.fallback=!0,U}});await qB(G)}function HW(Y){let X=Y.response;if(!C(X))return;return typeof X.id==="string"?X.id:void 0}function LW(Y){let X=Y.response;if(!C(X))return;return C(X.usage)?X.usage:void 0}async function qB(Y){let X=Y.body?.getReader();if(!X)return;while(!0)if((await X.read()).done)return}function FB(Y){return qY({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:jB(Y.client_metadata)})}function VW(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 jB(Y){if(!C(Y))return Y;if(typeof Y["x-codex-turn-metadata"]!=="string")return Y;try{let X=JSON.parse(Y["x-codex-turn-metadata"]);if(!C(X))return Y;return{...Y,"x-codex-turn-metadata":VW(X),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function DB(Y){let X=Y["x-codex-turn-metadata"];if(!X)return Y;try{let J=JSON.parse(X);if(!C(J))return Y;return{...Y,"x-codex-turn-metadata":VW(J)}}catch{return Y}}var NW=["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 zW(Y){let X={...Y};if(Array.isArray(Y.input))X.input=Y.input.map(PB);return X}function qY(Y){let X={};for(let J of NW)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 PB(Y){if(!C(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 BW(Y,X,J,Q,$){let G=J.response,W=C(G)&&typeof G.id==="string"?G.id:void 0;if(!W||!Array.isArray(X.input)){Y.continuation=void 0;return}let U=$?new Set(Y.continuation?.finalizedCallIds):new Set;for(let L of Q)U.add(L);Y.continuation={responseID:W,input:X.input,signature:t9(X),finalizedCallIds:U}}function a9(Y,X,J=X){let Q=Array.isArray(X.input)?X.input:[],$=Array.isArray(J.input)?J.input:Q,G=t9(J),W=Y.turnInput&&Y.turnSignature===G?MB(Y.turnInput,$):void 0,U=W===void 0?Q:$.slice(W);if(U.length>0&&U.some(OW)||!Y.turnID)Y.turnID=P1(),Y.turnStartedAt=Date.now();Y.turnInput=$.slice(),Y.turnSignature=G}function ZW(Y,X,J=X){a9(Y,X,J);let Q=X.client_metadata;if(!C(Q)||typeof Q["x-codex-turn-metadata"]!=="string")return X;let $=KW(Q["x-codex-turn-metadata"],Y.turnID,Y.turnStartedAt);if(!$)return X;return{...X,client_metadata:{...Q,"x-codex-turn-metadata":$}}}function KW(Y,X,J){let Q;try{Q=JSON.parse(Y)}catch{return}if(!C(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 MB(Y,X){if(Y.length>X.length)return;for(let J=0;J<Y.length;J++)if(s0(Y[J])!==s0(X[J]))return;return Y.length}function wB(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(!qW(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),$=AB(Q,Y.continuation.finalizedCallIds);if($.length===0)return X;return{...X,previous_response_id:Y.continuation.responseID,input:$}}function EB(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!Y.continuation)return!0;if(!J)return!1;if(!qW(Y.continuation.input,J))return!0;return J.slice(Y.continuation.input.length).some(OW)}function OW(Y){if(!C(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function AB(Y,X){return Y.filter((J)=>{if(!C(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 s0(TB(Object.fromEntries(Object.entries(Y).filter(([X])=>X!=="input"&&X!=="stream"&&X!=="background"&&X!=="previous_response_id"&&X!=="generate"))))}function TB(Y){if(!C(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 qW(Y,X){if(Y.length>=X.length)return!1;for(let J=0;J<Y.length;J++)if(s0(Y[J])!==s0(X[J]))return!1;return!0}function FW(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 bB=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),xB=new Set(["gpt-5.6"]),vB=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),hB="opencode-oauth-dummy-key",gB="terminal_resize_reflow",JX="0.144.0",yB=`codex_exec/${JX} (Debian 12.0.0; aarch64) unknown (codex_exec; ${JX})`,fB="seccomp",mB="main-refresh",cB=120000,uB=90000,pB=4000,jW=50,DW=3,lB=25,dB=60000,iB="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",PW=!1,MW=L0("models"),wW=!1,EW=!1;class $X extends Error{code="OPENAI_AUTH_PERSIST_FAILED";constructor(Y){super("OpenAI OAuth token refreshed but could not be persisted; re-login required",{cause:Y});this.name="AuthPersistError"}}class c0 extends Error{code;constructor(Y,X){super(X);this.name="ResetTargetResolutionError",this.code=Y}}function AW(Y,X,J,Q){let $=(J?.refresh?.refreshBeforeExpiryMinutes??240)*60000;return!Y||!X||X-Q<=$}function nB(Y){return async(X)=>{if(X==="main"){let U=await Y.loadAccounts(Y.accountStoragePath),L=await Y.getAuth();if(L.type!=="oauth")throw new c0("non_oauth_account","Main OpenAI account is not authenticated with OAuth.");if(AW(L.access,L.expires,U,Y.now()))L={type:"oauth",...await Y.refreshMainWithLease()};if(!L.access)throw new c0("token_unavailable","Main OpenAI account has no usable access token.");let H=l1(L.access),N=H?d1(H):void 0,O=await Y.loadAccounts(Y.accountStoragePath);return{accountKey:X,label:"Main account",accessToken:L.access,chatgptAccountId:N??O?.mainAccountId}}let J=await Y.loadAccounts(Y.accountStoragePath),Q=J?.accounts.find((U)=>U.id===X);if(!J||!Q)throw new c0("unknown_account",`Fallback account ${X} was not found.`);if(Q.enabled===!1)throw new c0("disabled_account",`Fallback account ${X} is disabled.`);if(!u0(Q))throw new c0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);let $=Q;if(AW($.access,$.expires,J,Y.now()))$=await Y.refreshFallbackAccount($,J);if(!$.access)throw new c0("token_unavailable",`Fallback account ${X} has no usable access token.`);let G=await Y.loadAccounts(Y.accountStoragePath),W=G?.accounts.find((U)=>U.id===X);if(!G||!W)throw new c0("unknown_account",`Fallback account ${X} was not found.`);if(W.enabled===!1)throw new c0("disabled_account",`Fallback account ${X} is disabled.`);if(!u0(W))throw new c0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);return{accountKey:X,label:$.label??X,accessToken:$.access,chatgptAccountId:W.accountId}}}function oB(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function YX(Y){return Y instanceof $X}function TW(){throw Error(iB)}function rB(Y){return Math.floor(Math.random()*Y)}function sB(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 aB(Y,X,J){let Q=Y.get(X);if(Q)return Q;let $=P1(),G={threadID:$,turnID:P1(),windowID:`${$}:0`};return Y.set(X,G),J?.(),G}function W5(){return kB(CY(),"openai-auth-sessions.json")}function tB(){let Y=new Map;try{let X=JSON.parse(CB(W5(),"utf8"));if(!C(X.sessions))return Y;for(let[J,Q]of Object.entries(X.sessions)){if(!C(Q)||typeof Q.threadID!=="string")continue;Y.set(J,{threadID:Q.threadID,turnID:P1(),windowID:`${Q.threadID}:0`})}}catch{}return Y}function eB(Y){let X=W5(),J=`${X}.tmp-${process.pid}`;try{RB(CY(),{recursive:!0});let Q={version:1,sessions:Object.fromEntries([...Y.entries()].map(([$,G])=>[$,{threadID:G.threadID}]))};SB(J,`${JSON.stringify(Q,null,2)}
218
+ `,"utf8"),_B(J,X)}catch{}}function RW(Y,X){return C(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===X}function YZ(Y,X){if(Y.length>X.length)return!1;for(let J=0;J<Y.length;J++)if(s0(Y[J])!==s0(X[J]))return!1;return!0}function XZ(Y,X){if(!Y.input)return X.length>0;if(!YZ(Y.input,X))return!0;return X.slice(Y.input.length).some((Q)=>RW(Q,"user")||RW(Q,"developer"))}function JZ(Y,X){let J=Array.isArray(X?.input)?X.input:void 0;if(J&&(XZ(Y,J)||!Y.turnID))Y.turnID=P1(),Y.turnStartedAt=Date.now();else if(!Y.turnStartedAt)Y.turnStartedAt=Date.now();if(J)Y.input=J}function QZ(Y){if(!Y.metadata)return{init:Y.init};let X=sB(Y.init?.body);if(!Y.websocket)JZ(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:fB,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",gB),Y.headers.set("x-codex-turn-metadata",J),Y.headers.set("user-agent",yB),Y.headers.set("version",JX),Y.dumpSessionID)Y.headers.set(G1,Y.dumpSessionID);let Q=X;if(!Q)return{init:Y.init};let $=Y.responsesLite&&typeof Q.model==="string"&&vB.has(Q.model);if($&&!Y.websocket)Y.headers.set("x-openai-internal-codex-responses-lite","true");if(Q.prompt_cache_key=Y.metadata.threadID,Q.parallel_tool_calls??=!0,Array.isArray(Q.tools))Q.tools=Q.tools.map(LZ);if(UZ(Q),HZ(Q),NJ(Q),WZ(Q),$)zZ(Q);let G={...typeof Q.client_metadata==="object"&&Q.client_metadata!==null?Q.client_metadata:{},"x-codex-installation-id":Y.installationID,"x-codex-window-id":Y.metadata.windowID};if(Y.websocket){if(G["x-codex-turn-metadata"]=J,G["x-codex-ws-stream-request-start-ms"]=String(Date.now()),$)G.ws_request_header_x_openai_internal_codex_responses_lite="true"}return Q.client_metadata=G,Y.headers.delete("content-length"),Y.headers.delete("Content-Length"),{init:{...Y.init,body:JSON.stringify(qY(Q))}}}function $Z(Y,X){return Y.find((J)=>J.enabled!==!1&&u0(J)&&(J.id===X||J.accountId===X))}function CW(Y,X){if(!X)return Y;let J={...Y};for(let Q of["resetCreditsAvailable","resetCreditsApplicable"]){let $=X[Q];if(J[Q]===void 0&&$!==void 0)J[Q]=$}return J}function L8(Y,X){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:X}}function z5(Y,X,J=Date.now(),Q=X.mainAccountId){let $=Y.getMain(),G=$?.quota;return{main:{quota:G?{...G,checkedAt:$.checkedAt,primary:L8(G.primary,$.checkedAt),secondary:L8(G.secondary,$.checkedAt)}:null,...typeof Q==="string"?{mainAccountId:Q}:{},killed:!1,...G?.resetCreditsAvailable!==void 0?{resetCredits:G.resetCreditsAvailable}:{}},fallbacks:X.accounts.filter((W)=>W.enabled).map((W)=>{let U=Y.getFallback(W.id),L=U?.quota;return{id:W.id,label:W.label,accountId:U?.accountId??W.accountId,quota:L?{...L,checkedAt:U.checkedAt,primary:L8(L.primary,U.checkedAt),secondary:L8(L.secondary,U.checkedAt)}:null,killed:!1,enabled:!0,...L?.resetCreditsAvailable!==void 0?{resetCredits:L.resetCreditsAvailable}:{}}}),route:X.routing?.mode??"main-first",lastUpdated:J}}function MF(Y,X,J,Q=Date.now()){return{...z5(Y,X,Q),activeId:J}}function _W(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 GZ(Y,X){if(!(Y instanceof Request))return X;let J=new Request(Y,X),Q=J.method.toUpperCase(),$=Q==="GET"||Q==="HEAD"||J.body===null?void 0:await J.text();return{method:J.method,headers:new Headers(J.headers),body:$,signal:J.signal,cache:J.cache,credentials:J.credentials,integrity:J.integrity,keepalive:J.keepalive,mode:J.mode,redirect:J.redirect,referrer:J.referrer,referrerPolicy:J.referrerPolicy}}function IW(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}function WZ(Y){if(!M0().webSearch)return;if(!Array.isArray(Y.tools)||Y.tools.length===0)return;if(Y.tools.some((X)=>C(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(!C(Y))return;if(Y.type==="input_image")delete Y.detail;for(let X of Object.values(Y))QX(X)}function zZ(Y){let X=C(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 $=[{type:"additional_tools",role:"developer",tools:Array.isArray(Y.tools)?Y.tools.filter((G)=>!(C(G)&&G.type==="web_search")):[]}];if(typeof Y.instructions==="string"&&Y.instructions.length>0)$.push({type:"message",role:"developer",content:[{type:"input_text",text:Y.instructions}]});Y.input=[...$,...J],delete Y.tools,delete Y.instructions}function UZ(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(C(X)&&X.type==="function"&&X.name==="web_search"))}function HZ(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(C(X)&&X.type==="function"&&X.name==="websearch_web_search_exa"))}function LZ(Y){if(!C(Y))return Y;if(Y.type!=="function")return Y;let X=C(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:L,...H}=Y.parameters;return H})():Y.parameters,{type:J,name:Q,description:$,strict:G,parameters:W,...U}=Y;return{type:J,name:Q,description:$,strict:G??!1,parameters:X,...U}}async function VZ(Y,X={}){let J=X.codexApiEndpoint??M0().codexApiEndpoint,Q=crypto.randomUUID(),$=tB(),G=()=>eB($),W=!1,U=[],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 DJ(Y.client,V),I={noReply:!0,parts:[{type:"text",text:K,ignored:!0}]};if(M?.agent)I.agent=M.agent;if(M?.model)I.model=M.model;if(M?.variant)I.variant=M.variant;await j.promptAsync({path:{id:V},body:I});return}}return{async dispose(){O.stop();for(let V of U)V.close();if(U.length=0,H){await H.stop().catch(()=>{});let V=globalThis;if(V.__openaiAuthRpcServer===H)V.__openaiAuthRpcServer=void 0;H=null}},async event(V){if(V.event.type!=="session.deleted")return;let K=V.event.properties.info,j=$.get(K.id);if(j)L?.cacheKeepManager?.remove(j.threadID);if($.delete(K.id))G();if(N){let M=(await q0($0()))?.accounts;await J5(K.id,M,N)}for(let M of U)M.remove(K.id)},provider:{id:"openai",async models(V,K){if(K.auth?.type!=="oauth")return V.models;let j=await q0($0()),M=!j||iW(j),I=M?null:await OJ();if(!M&&I&&!wW)wW=!0,MW.debug("restoring OAuth model costs from models.dev catalog");if(!M&&!I&&!EW)EW=!0,MW.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(bB.has(E.api.id))return!0;if(xB.has(E.api.id))return!1;let R=E.api.id.match(/^gpt-(\d+\.\d+)/)?.[1];return R?parseFloat(R)>5.4:!1}).map(([E,x])=>[E,{...x,cost:M?{input:0,output:0,cache:{read:0,write:0}}:I?.[x.api.id]??I?.[E]??x.cost,limit:x.id.includes("gpt-5.5")?{context:400000,input:272000,output:128000}:x.id.includes("gpt-5.6")?{context:372000,input:244000,output:128000}:x.limit}]))}},tool:{web_search:LJ},auth:{provider:"openai",async loader(V){let K=await V();if(K.type!=="oauth")return{};await oW({type:"oauth",access:K.access??"",refresh:K.refresh??"",expires:K.expires??0},$0());let j=await q0($0()).catch((B)=>{let q=$0();throw Error(`OpenAI auth store at ${q} is corrupt or unreadable: ${B instanceof Error?B.message:String(B)}. Fix or remove it to continue.`,{cause:B})}),M;async function I(){let B=$0();try{let q=IB(B);if(M?.path===B&&M.mtimeMs===q.mtimeMs&&M.size===q.size)return M.storage;let D=await q0(B);return M={path:B,mtimeMs:q.mtimeMs,size:q.size,storage:D},D}catch{return M=void 0,q0(B)}}function E(){M=void 0}if(j&&K.access){let B=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 x=j?.logging?.level;if(x&&typeof x==="string")kY(x);let R=L0("transport"),p=L0("quota"),m=L0("refresh"),d=L0("accounts");R.info("codex auth loader ready",{codexApiEndpoint:J,transport:M0().rawWebSocket?"raw-websocket":M0().webSockets?"websocket":"http",webSearch:M0().webSearch});let y=new dW({storage:j,fetchQuotaFn:void 0}),Y0,p0=0,c=new rW({refreshFn:(B)=>R1({refreshToken:B.refreshToken,fetchImpl:B.fetchImpl,now:B.now}),quotaManager:y,onFallbackStorageChanged:E});if(j&&j.accounts.length>0)c.startBackgroundRefresh();let X1=L0("cachekeep"),i1=j?.cachekeep?.enabled===!0,n1=j?.cachekeep?.subagents===!0,C1=j?.cachekeep?.sustain===!0,h=rX(j),r;async function B0(B){await new Promise((q)=>setTimeout(q,B))}async function B8(B){let q;for(let D=1;D<=DW;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<DW)await B0(lB*D)}throw new $X(q)}async function _1(B){await J0((q)=>{return q.refresh=q.refresh??{},B(q),q},$0()),E()}async function wY(B){let q=Date.now()+pB;while(Date.now()<q){await new Promise((k)=>setTimeout(k,jW+rB(jW)));let D=await V();if(D.type!=="oauth"||!D.access)continue;if((D.access!==B.access||D.refresh!==B.refresh||(D.expires??0)>(B.expires??0)+60000)&&(!D.expires||D.expires>Date.now()))return m.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:D.expires?D.expires-Date.now():void 0}),{access:D.access,refresh:D.refresh??B.refresh??"",expires:D.expires??0}}return null}async function l0(){if(!r)r=(async()=>{let B=await V();if(B.type!=="oauth")throw Error("not oauth");if(!B.refresh)throw Error("Token refresh failed: missing refresh token");let q=SW(B.refresh),D=await q0($0()),T=D?.refresh?.mainLastRefreshError;if(T&&bW(T,B.refresh,Date.now()))throw Error(xW(T,Date.now()));if(D?.refresh?.mainRefreshLeaseUntil&&D.refresh.mainRefreshLeaseUntil>Date.now()&&D.refresh.mainRefreshLeaseTokenHash===q){let S=await wY(B);if(S)return S;throw Error("Codex OAuth refresh is already in progress")}let k=await bY({name:mB,ttlMs:cB,path:$0(),renew:!0});if(!k){let S=await wY(B);if(S)return S;throw Error("Codex OAuth refresh is already in progress")}let _=crypto.randomUUID(),w=q;try{await _1((g)=>{g.refresh=g.refresh??{},g.refresh.mainRefreshLeaseId=_,g.refresh.mainRefreshLeaseUntil=Date.now()+uB,g.refresh.mainRefreshLeaseTokenHash=q});let S=await q0($0());if(S?.refresh?.mainRefreshLeaseId!==_||S.refresh.mainRefreshLeaseTokenHash!==q)throw Error("Codex OAuth refresh is already in progress");let P=await R1({refreshToken:B.refresh,fetchImpl:fetch,now:Date.now});return await B8(P),await _1((g)=>{if(g.refresh=g.refresh??{},g.refresh.mainLastRefreshError=void 0,g.refresh.mainRefreshLeaseId===_)g.refresh.mainRefreshLeaseId=void 0,g.refresh.mainRefreshLeaseUntil=void 0,g.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),w=void 0,P}catch(S){if(B.refresh&&!YX(S))await _1((P)=>{P.refresh=P.refresh??{},P.refresh.mainLastRefreshError=kW({error:S,now:Date.now(),refreshToken:B.refresh??"",previous:P.refresh.mainLastRefreshError})}).catch(()=>{});throw S}finally{if(w)await _1((S)=>{if(S.refresh?.mainRefreshLeaseId===_&&S.refresh.mainRefreshLeaseTokenHash===w)S.refresh.mainRefreshLeaseId=void 0,S.refresh.mainRefreshLeaseUntil=void 0,S.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await k.release().catch(()=>{})}})().finally(()=>{r=void 0});return r}let J1=globalThis;J1.__openaiAuthCacheKeepManager?.stop();let d0=new 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 l0()).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 c.refreshAccount(D,q??{version:1,accounts:[D]});if(!T.access)throw Error(`no access token for ${B}`);return T.access},codexResponsesUrl:J,logger:X1,now:Date.now,getWindow:()=>h,getSustain:()=>C1});J1.__openaiAuthCacheKeepManager=d0;async function K1(B,q,D,T,k=!1){if(Object.keys(B).length===0&&!k)return;let _=Date.now(),w=B,S={quota:w,refreshAfter:_+300000,checkedAt:_},P;if(D&&D!=="main"){let b=q?l1(q):null,X0=b?d1(b):void 0,Z0=y.peekFallbackForPolicy(D)?.quota,h0=CW(w,Z0);S={...S,quota:h0},y.setFallback(D,S,q,k,X0)}else{if(P=T,!P&&q){let Z0=l1(q);P=Z0?d1(Z0):void 0}if(P&&Y0&&P!==Y0){p.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:P,currentMainIdentity:Y0});return}let b=y.peekMainForPolicy(P)?.quota,X0=CW(w,b);S={...S,quota:X0},y.setMain(q,S,P,k)}p.debug("quota pushed",{pid:process.pid,accountId:D??"main",snapshot:S.quota});let g=await I();await x0(y,g,D&&D!=="main"?g?.mainAccountId:P)}function Z8(B,q,D){let T=B==="main"?y.peekMainForPolicy()?.quota:y.peekFallbackForPolicy(B)?.quota;return lW(T,q,Date.now(),dB,D)}let i0=X.experimentalWebSockets?Z1.createWebSocketFetch({httpFetch:fetch,rawWebSocket:M0().rawWebSocket,onQuota:(B,q,D,T)=>{K1(B,q,D,!D||D==="main"?T:void 0,!0)},onRateLimitReached:(B,q,D)=>{if(!q)p.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:B});let T=q??"main",k=Z8(T,B,D);y.markRateLimited(T,k),p.debug("mid-stream rate limit mark",{pid:process.pid,accountId:T,window:B})}}):void 0;if(i0)U.push(i0),W=!0;let F0=sW();N=F0;async function x0(B,q,D=q?.mainAccountId){if(!q)return;await Y5(z5(B,q,Date.now(),D),F0)}async function v0(B,q,D,T,k){let _={activeId:D,route:T,updatedAt:Date.now()};if(B){if(await N8({sessionId:B,..._},k,F0),q&&q!==B){if(T==="sticky-balanced"){let w=(await D1(F0)).stickyAssignments?.[MY(q)]?.accountId,S=k===void 0||w==="main"||k.some((P)=>P.enabled!==!1&&P.id===w);if(!w||!S)return;await N8({sessionId:q,activeId:w,route:T,updatedAt:Date.now()},k,F0);return}await N8({sessionId:q,..._},k,F0)}return}await X5(_,F0)}L={accountStoragePath:$0(),quotaManager:y,loadAccounts:q0,client:Y.client,resolveResetTarget:nB({getAuth:V,refreshMainWithLease:l0,refreshFallbackAccount:(B,q)=>c.refreshAccount(B,q),loadAccounts:q0,accountStoragePath:$0(),now:Date.now}),...oB(),cacheKeepManager:d0,setCacheKeepEnabled:(B)=>{i1=B},setCacheKeepSubagents:(B)=>{n1=B},setCacheKeepSustain:(B)=>{C1=B},setCacheKeepWindow:(B)=>{h=B},clearStickyRouting:(B)=>$5(B,F0),getStickyRouting:async(B)=>eW(await D1(F0),B),refreshSidebar:async()=>{let B=await q0($0());await x0(y,B)},refreshAllQuota:async()=>b1({getAuth:V,codexRefreshFn:R1,refreshMainWithLease:l0,fallbackManager:c,quotaManager:y,loadAccounts:q0,writeSidebarState:x0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:$0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:u0,whamFn:Q1}),refreshResetTargetQuota:async(B)=>{return(await b1({getAuth:V,codexRefreshFn:R1,refreshMainWithLease:l0,fallbackManager:c,quotaManager:y,loadAccounts:q0,writeSidebarState:x0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:$0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:u0,whamFn:Q1,respectBackoff:!1},{accountKey:B})).find((D)=>D.account===B)??{account:B,ok:!1,error:"targeted quota refresh returned no result"}}};let Q0=null;if(Y.directory){let B=await G5(Y.directory),q=globalThis;if(q.__openaiAuthRpcServer)await q.__openaiAuthRpcServer.stop().catch(()=>{}),q.__openaiAuthRpcServer=void 0;try{Q0=await RJ({dir:B.dir,secureDir:B.secureDir,sweepRoot:B.sweepRoot,drain:MJ,apply:async(D)=>{let T={...L,sessionId:D.sessionId},k=await k8(D.command,D.arguments,T);return{text:k.text,knobs:k.knobs}}}),q.__openaiAuthRpcServer=Q0,H=Q0}catch{}}async function T0(B,q,D,T,k="main"){let _=_W(B,q);if(_.delete("x-api-key"),_.delete("api-key"),_.set("authorization",`Bearer ${D}`),T)_.set("ChatGPT-Account-Id",T);_.set(Z1.QUOTA_ACCOUNT_HEADER,k);let w=IW(_),S=w?aB($,w,G):void 0,P=B instanceof URL?B:new URL(typeof B==="string"?B:B.url),g=P.pathname.includes("/v1/responses")||P.pathname.includes("/chat/completions")?new URL(J):P,X0=QZ({init:{...q,headers:_},headers:_,metadata:S,installationID:Q,websocket:Boolean(i0&&P.pathname.endsWith("/responses")),responsesLite:X.responsesLite??!1,dumpSessionID:w}).init,Z0=i1,h0=new Headers(X0?.headers),W0=oX({enabled:Z0,includeSubagents:n1,headers:h0,body:X0?.body});if(Z0)X1.trace("cachekeep headers",{pid:process.pid,hasParent:h0.has("x-parent-session-id"),sessionKey:W0?.sessionKey,captured:Boolean(W0),affinity:h0.get("x-session-affinity"),opencodeSession:h0.get("x-opencode-session"),sessionId:h0.get("session-id")});if(i0&&P.pathname.endsWith("/responses")){if(R.debug("WS transport",{pid:process.pid,pathname:P.pathname,accountId:k}),W0)d0.track(W0.sessionKey,W0.bodyText,k,T,W0.replayHeaders,W0.isSubagent);return i0(g,X0)}let N0=Z1.withoutInternalHeaders(X0);if(typeof N0?.body!=="string")return fetch(g,N0);if(W0)d0.track(W0.sessionKey,W0.bodyText,k,T,W0.replayHeaders,W0.isSubagent);R.debug("HTTP transport",{pid:process.pid,pathname:P.pathname,accountId:k});try{let C0=await fetch(g,N0);return await h1({sessionID:w,transport:"http",phase:"http",bodyText:N0.body,accountId:k,url:g.toString(),method:N0.method,headers:N0.headers,status:C0.status}),VJ(C0)}catch(C0){throw await h1({sessionID:w,transport:"http",phase:"http",bodyText:N0.body,accountId:k,url:g.toString(),method:N0.method,headers:N0.headers,error:C0 instanceof Error?C0.message:String(C0)}),C0}}function I1(B,q){if((q?.method??(B instanceof Request?B.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof q?.body!=="string")return!1;try{let T=B instanceof URL?B.toString():typeof B==="string"?B:B.url;return new URL(T).pathname.endsWith("/responses")}catch{return!1}}function U5(B){return y.peekMainForPolicy(B)?.quota}function GX(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,k){let _=GX(B,q),w=GX(D),S=T===k&&D!=null&&(B===void 0||w!==void 0&&(_===void 0||w>_));return{quota:S?D:B,quotaCheckedAt:S?w:_,source:S?"file":"memory"}}function WX(B,q,D,T,k){let _=B?.quota,w=o1(_,B?.checkedAt,q,T,k),S=w.source,P=w.quota;if(!tW(P,D))return{exhausted:!1};let g=aW(P,D);if(!g)return{exhausted:!1};return{exhausted:!0,source:S,...g}}function zX(B,q){p.debug("admission skip: exhausted account",{accountId:B,source:q.source,resetsAt:q.resetsAt})}function H5(B,q="killswitch",D){let T=Date.now(),k=y.getMain()?.quota,_=(B?.accounts??[]).filter((b)=>b.enabled!==!1&&u0(b)).map((b)=>({accountId:b.id,quota:y.getFallback(b.id)?.quota})),w=nW(k,_,T,B);if(q==="quota-exhausted"&&D!==void 0)w=Math.max(1,Math.ceil((D-T)/1000));else if(q==="mid-stream-rate-limit"&&D!==void 0){let b=Math.max(1,Math.ceil((D-T)/1000));w=Math.min(w,b)}let S=Math.floor(w/60),P=w%60,g=q==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${S}m ${P}s.`:q==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${S}m ${P}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${S}m ${P}s.`;return new Response(JSON.stringify({error:{message:g,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(w)}})}function UX(B){let q=B?.resetCreditsAvailable;return typeof q==="number"&&Number.isFinite(q)?q:void 0}async function L5(B){let q=DY(B.storage),D=Date.now(),T=y.peekMainForPolicy(B.mainAccountIdentity),k=o1(T?.quota,T?.checkedAt,B.sidebarState.main.quota,B.sidebarState.main.mainAccountId,B.mainAccountIdentity),_=q?PY(T?.quota,B.storage,void 0,D):void 0,w=[{accountId:"main",wireAccountId:B.mainAccountIdentity,access:B.primaryAccess,keepwarmAccountKey:"main",quota:k.quota,quotaCheckedAt:k.quotaCheckedAt,reservePercent:XX(B.storage),configuredOrder:0,resetCreditsApplicable:UX(k.quota),killswitchPasses:_}],S=await c.getUsableFallbackAccounts(B.storage);for(let P of S){if(!P.access)continue;let g=B.sidebarState.fallbacks.find((h0)=>h0.id===P.id),b=y.peekFallbackForPolicy(P.id,P.accountId),X0=o1(b?.quota,b?.checkedAt,g?.quota,g?.accountId,P.accountId),Z0=q?PY(b?.quota,B.storage,P.id,D):void 0;w.push({accountId:P.id,wireAccountId:P.accountId,access:P.access,keepwarmAccountKey:P.id,fallback:P,quota:X0.quota,quotaCheckedAt:X0.quotaCheckedAt,reservePercent:XX(B.storage,P.id),configuredOrder:w.length,resetCreditsApplicable:UX(X0.quota),killswitchPasses:Z0})}return w}function HX(B,q,D,T,k){let _=DY(k)?B.killswitchPasses:void 0;if(B.accountId==="main"){let g=y.peekMainForPolicy(B.wireAccountId),b=o1(g?.quota,g?.checkedAt,q.main.quota,q.main.mainAccountId,B.wireAccountId);return c8({quota:b.quota,quotaCheckedAt:b.quotaCheckedAt,status:D,now:T,killswitchPasses:_})}let w=q.fallbacks.find((g)=>g.id===B.accountId),S=y.peekFallbackForPolicy(B.accountId,B.wireAccountId),P=o1(S?.quota,S?.checkedAt,w?.quota,w?.accountId,B.wireAccountId);return c8({quota:P.quota,quotaCheckedAt:P.quotaCheckedAt,status:D,now:T,killswitchPasses:_})}function V5(B){return B.accountId==="main"?"main":B.keepwarmAccountKey}function LX(B){return y.isRateLimited(V5(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])),k=Object.fromEntries(q.map((P)=>[P.accountId,P.wireAccountId])),_=new Set(B.excludeAccountIds),w,S=await Q5({sessionId:B.sessionId,requestBytes:B.requestBytes,now:B.now,validPinnedAccountIds:[...D.keys()],excludeAccountIds:B.excludeAccountIds,quotaCheckedAtByAccount:T,wireAccountIdByAccount:k,choose:(P)=>{let g=q.filter((X0)=>!_.has(X0.accountId));if(g.length===0)return;let b=JJ({candidates:g,pendingBytes:P,requestBytes:B.requestBytes,now:B.now,onEmptyWeightedSet:()=>{d.debug("sticky routing: no fresh weighted candidates; using configured order")}});if(!b)return;return w={accountId:b.accountId,source:b.source,pendingBytes:P.get(b.accountId)??0},b}},F0);if(w&&S?.accountId===w.accountId)d.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:MY(B.sessionId),accountId:w.accountId,source:w.source,requestBytes:B.requestBytes,pendingBytes:w.pendingBytes});return S?D.get(S.accountId):void 0}async function N5(B,q){let D=await c.getUsableFallbackAccounts(B),T=[];for(let b of D)if(b.access)T.push({access:b.access,accountId:b.accountId,keepwarmAccountKey:b.id,quotaAccountId:b.id,fallback:b});let k=T.filter((b)=>!y.isRateLimited(b.quotaAccountId)),_=DY(B)?k.filter((b)=>PY(y.peekFallbackForPolicy(b.quotaAccountId,b.accountId)?.quota,B,b.quotaAccountId,Date.now())):k,w=new Map(q.fallbacks.map((b)=>[b.id,{quota:b.quota,accountId:b.accountId}])),S=[],P=[],g=Date.now();for(let b of _){let X0=w.get(b.quotaAccountId),Z0=WX(y.peekFallbackForPolicy(b.quotaAccountId,b.accountId),X0?.quota,g,X0?.accountId,b.accountId);if(Z0.exhausted)P.push({candidate:b,decision:Z0});else S.push(b)}return{current:_,retained:S,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=x1(B.headers);await K1(D,q.access,q.quotaAccountId,void 0,FY(B.headers))}catch{}}async function B5(B,q,D,T){for(let k of T){let _;try{_=await T0(B,q,k.access,k.accountId,k.keepwarmAccountKey)}catch(w){if(w instanceof DOMException&&w.name==="AbortError")throw w;if(q?.signal?.aborted)throw w;throw d.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:k.quotaAccountId}),w}if(!jY(_.status,D))return await c.markUsed(k.fallback),{response:_,accessToken:k.access,quotaAccountId:k.quotaAccountId,activeId:k.keepwarmAccountKey};await NX(_,k),_.body?.cancel().catch(()=>{})}return}async function Z5(B,q,D,T,k){if(!I1(B,q))return{response:D};if(!k.length)return{response:D};let _=D,w;for(let S of k){let P;try{P=await T0(B,q,S.access,S.accountId,S.keepwarmAccountKey)}catch(g){if(g instanceof DOMException&&g.name==="AbortError")throw g;if(q?.signal?.aborted)throw g;return d.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:S.quotaAccountId}),{response:_,...w}}if(_.body?.cancel().catch(()=>{}),_=P,w={accessToken:S.access,accountId:S.quotaAccountId},!jY(P.status,T))return await c.markUsed(S.fallback),{response:P,...w};await NX(P,S)}return{response:_,...w}}if(!PW){if(PW=!0,j){let B=[];for(let q of j.accounts)if(u0(q))B.push(q);y.seedFallbacksFromAccounts(B)}x0(y,j).catch(()=>{}),b1({getAuth:V,codexRefreshFn:R1,refreshMainWithLease:l0,fallbackManager:c,quotaManager:y,loadAccounts:q0,writeSidebarState:x0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:$0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:u0,whamFn:Q1,respectBackoff:!0}).catch((B)=>p.warn("boot quota seed failed",{pid:process.pid,error:$1(B)}))}return O.start(async()=>{let q=(await pX({getAuth:V,codexRefreshFn:R1,refreshMainWithLease:l0,fallbackManager:c,quotaManager:y,loadAccounts:q0,writeSidebarState:(D,T)=>O.isStopped()?Promise.resolve():x0(D,T),client:Y.client,fetchImpl:fetch,now:Date.now,configPath:$0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:u0,whamFn:Q1,readSidebarState:()=>D1(F0)})).filter((D)=>!D.ok);if(q.length>0)p.warn("background quota refresh completed with failures",{pid:process.pid,failures:q})},(B)=>{p.warn("background quota refresh failed",{pid:process.pid,error:B instanceof Error?B.message:String(B)})}),{apiKey:hB,async fetch(B,q){let D=_W(B,q),T=IW(D),k=D.get("x-parent-session-id")?.trim()||void 0,_=await I(),w=await V(),S=++p0;if(w.type!=="oauth")return fetch(B,q);q=await GZ(B,q);let P=w.access??"";if(!w.access||(w.expires??0)<Date.now()){m.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(w.access),expiresInMs:w.expires?w.expires-Date.now():void 0});try{let e=await l0();w.access=e.access,w.refresh=e.refresh,w.expires=e.expires}catch(e){if(YX(e))throw e}}P=w.access??"";let b=w.accountId??(P?d1(l1(P)??{}):void 0);if(S===p0)Y0=b;let X0=_?.routing?.mode??"main-first",Z0,W0=await(()=>{return Z0??=D1(F0),Z0})();if(X0==="sticky-balanced"&&T&&I1(B,q)&&typeof q?.body==="string"){let e=Buffer.byteLength(q.body,"utf8"),H0=await L5({storage:_,sidebarState:W0,primaryAccess:P,mainAccountIdentity:b}),U0=await K8({sessionId:T,requestBytes:e,candidates:H0,now:Date.now()});if(U0){let jX=LX(U0)?{action:"migrate",reason:"exhausted"}:HX(U0,W0,void 0,Date.now(),_);if(jX.action==="migrate"){let P0=await K8({sessionId:T,requestBytes:e,candidates:H0,excludeAccountIds:[U0.accountId],now:Date.now()});if(P0)d.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:MY(T),fromAccountId:U0.accountId,toAccountId:P0.accountId,reason:jX.reason}),U0=P0}let g0=await T0(B,q,U0.access,U0.wireAccountId,U0.keepwarmAccountKey),DX=async(P0,O1)=>{try{let K5=x1(P0.headers);await K1(K5,O1.access,O1.accountId==="main"?void 0:O1.accountId,O1.accountId==="main"?O1.wireAccountId:void 0,FY(P0.headers))}catch{}};await DX(g0,U0);let PX=HX(U0,W0,g0.status,Date.now(),_);if((g0.status===401||g0.status===403||g0.status===429)&&PX.action==="migrate"){let P0=await K8({sessionId:T,requestBytes:e,candidates:H0,excludeAccountIds:[U0.accountId],now:Date.now()});if(P0){d.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:MY(T),fromAccountId:U0.accountId,toAccountId:P0.accountId,reason:PX.reason});let O1=g0;g0=await T0(B,q,P0.access,P0.wireAccountId,P0.keepwarmAccountKey),O1.body?.cancel().catch(()=>{}),U0=P0,await DX(g0,U0)}}if(U0.fallback&&!jY(g0.status,_))await c.markUsed(U0.fallback);return await v0(T,k,U0.accountId,X0,_?.accounts).catch(()=>{}),g0}}let N0=WX(y.peekMainForPolicy(b),W0.main.quota,Date.now(),W0.main.mainAccountId,b),C0=DY(_)&&!PY(U5(b),_,void 0,Date.now()),EY=y.isRateLimited("main"),BX,O8=()=>{return BX??=N5(_,W0),BX},n0,S1,ZX=!1,AY;if(X0==="fallback-first"&&I1(B,q)){ZX=!0;let e=await O8();AY=VX(e,!C0&&!EY&&!N0.exhausted);let H0=await B5(B,q,_,AY);if(H0)n0=H0.response,S1={accessToken:H0.accessToken,accountId:H0.quotaAccountId,activeId:H0.activeId}}if(!n0){let e=N0.exhausted&&I1(B,q)&&(await O8()).retained.length>0;if(C0||EY||e){let H0=C0?"killswitch":EY?"mid-stream-rate-limit":"quota-exhausted";if(H0==="quota-exhausted"&&N0.exhausted)zX("main",N0);d.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:H0}),n0=H5(_,H0,H0==="quota-exhausted"&&N0.exhausted?N0.resetAtMs:EY?y.rateLimitedUntil("main"):void 0)}else n0=await T0(B,q,P,b,"main")}let KX=Boolean(S1),r1=n0,OX=S1?.accessToken??P,qX=S1?.accountId,FX=S1?.activeId??"main";if(!S1&&!ZX&&jY(n0.status,_)){d.debug("reactive fallback triggered",{pid:process.pid,status:n0.status}),AY??=VX(await O8(),!1);let e=await Z5(B,q,n0,_,AY),H0=e.response;if(H0!==n0){if(KX=!0,r1=H0,OX=e.accessToken??P,qX=e.accountId,e.accountId)FX=e.accountId}}try{let e=x1(r1.headers);if(KX)await K1(e,OX,qX,void 0,FY(r1.headers));else await K1(e,P,void 0,b,FY(r1.headers))}catch{}return await v0(T,k,FX,X0,_?.accounts).catch(()=>{}),r1},async dispose(){if(O.stop(),d0.stop(),J1.__openaiAuthCacheKeepManager===d0)J1.__openaiAuthCacheKeepManager=void 0;if(c.stopBackgroundRefresh(),H){await H.stop().catch(()=>{});let B=globalThis;if(B.__openaiAuthRpcServer===H)B.__openaiAuthRpcServer=void 0;H=null}}}},methods:[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:async()=>{let{redirectUri:V}=await mW(),K=await gW(),j=hW(crypto.getRandomValues(new Uint8Array(32)).buffer),M=yW(V,K,j),I=cW(K,j);return{url:M,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let E=await I,x=V8(E);return{type:"success",refresh:E.refresh_token,access:E.access_token,expires:Date.now()+(E.expires_in??3600)*1000,accountId:x}}finally{fW(j)}}}}},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:async()=>{let{deviceData:V,url:K,instructions:j}=await uW();return{url:K,instructions:j,method:"auto",async callback(){try{let M=await pW(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"]=`${vW} (${e9.platform()} ${e9.release()}; ${e9.arch()})`,K.headers["session-id"]=V.sessionID,W&&V.agent==="title")K.headers[Z1.TITLE_HEADER]="true"},"chat.params":async(V,K)=>{if(V.model.providerID!=="openai")return;K.maxOutputTokens=void 0},config:async(V)=>{V.command={...V.command??{},[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."},[j1]:{template:j1,description:"Spend one reset credit on an exhausted Codex account."}}},"command.execute.before":async(V)=>{if(!cX.includes(V.command))return;if(!L)await Z(V.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),TW();let K=V.command,j={...L,sessionId:V.sessionID,notify:(I)=>{a8(I,V.sessionID)}},M=await k8(K,V.arguments,j);if(wJ(V.sessionID))a8(M,V.sessionID);else await Z(V.sessionID,M.text);TW()}}}var NZ=async(Y)=>{let X=M0();return VZ(Y,{codexApiEndpoint:X.codexApiEndpoint,experimentalWebSockets:X.webSockets,responsesLite:X.responsesLite})},wF={id:"cortexkit-openai-auth",server:NZ};export{IW as resolveSidebarSessionId,l1 as parseJwtClaims,CW as mergePushedQuotaMetadata,$Z as findCachekeepFallbackAccount,d1 as extractAccountIdFromClaims,wF as default,nB as createResetTargetResolver,MF as buildSidebarState,z5 as buildSidebarMachineState,oB as buildResetRedemptionDeps,c0 as ResetTargetResolutionError,NZ as OpenAIAuthPlugin,cB as MAIN_REFRESH_LOCK_TTL_MS,uB as MAIN_REFRESH_LEASE_TTL_MS,VZ as CodexAuthPlugin,$X as AuthPersistError};