@cortexkit/opencode-openai-auth 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +9 -5
  2. package/dist/{index-9jpc8yct.js → index-02h7g5f9.js} +1 -1
  3. package/dist/index-2xppkvkx.js +2 -0
  4. package/dist/index-3w4vmckx.js +2 -0
  5. package/dist/{index-zxqb5ydj.js → index-507jh8bv.js} +1 -1
  6. package/dist/{index-zg1x8sty.js → index-944gsj1s.js} +1 -1
  7. package/dist/index-nshbgkz1.js +198 -0
  8. package/dist/{index-87145jkw.js → index-xyg86jgt.js} +1 -1
  9. package/dist/index.d.ts +381 -35
  10. package/dist/index.js +66 -161
  11. package/dist/protocol-Cv9ZmU0p.d.ts +24 -0
  12. package/dist/quota-normalize-wap0rne8.js +1 -0
  13. package/dist/rpc/port-file.d.ts +11 -9
  14. package/dist/rpc/port-file.js +1 -1
  15. package/dist/rpc/protocol.d.ts +2 -21
  16. package/dist/rpc/rpc-client.d.ts +6 -4
  17. package/dist/rpc/rpc-client.js +1 -1
  18. package/dist/rpc/rpc-dir.d.ts +7 -5
  19. package/dist/rpc/rpc-dir.js +1 -1
  20. package/dist/sidebar-state.d.ts +84 -83
  21. package/dist/sidebar-state.js +1 -1
  22. package/dist/{token-bvp0y166.js → token-jdvpwk60.js} +1 -1
  23. package/dist/token-util-zzm7paz9.js +1 -0
  24. package/dist/tui-preferences.d.ts +27 -26
  25. package/dist/tui-preferences.js +1 -1
  26. package/dist/tui.d.ts +18 -17
  27. package/package.json +10 -17
  28. package/src/tui/entry.mjs +2 -2
  29. package/src/tui-compiled/{core/account-paths.ts → raw/core-account-paths.ts} +29 -18
  30. package/src/tui-compiled/raw/logger.ts +53 -0
  31. package/src/tui-compiled/{rpc/port-file.ts → raw/rpc-port-file.ts} +1 -1
  32. package/src/tui-compiled/raw/rpc-protocol.ts +12 -0
  33. package/src/{rpc/rpc-client.ts → tui-compiled/raw/rpc-rpc-client.ts} +2 -2
  34. package/src/{sidebar-state.ts → tui-compiled/raw/sidebar-state.ts} +2 -2
  35. package/src/{tui/command-dialogs.tsx → tui-compiled/raw/tui-command-dialogs.tsx} +5 -5
  36. package/src/{tui.tsx → tui-compiled/raw/tui.tsx} +11 -10
  37. package/src/{core/account-paths.ts → tui-compiled/runtime/core-account-paths.ts} +29 -18
  38. package/src/tui-compiled/runtime/logger.ts +53 -0
  39. package/src/{rpc/port-file.ts → tui-compiled/runtime/rpc-port-file.ts} +1 -1
  40. package/src/tui-compiled/runtime/rpc-protocol.ts +12 -0
  41. package/src/tui-compiled/{rpc/rpc-client.ts → runtime/rpc-rpc-client.ts} +2 -2
  42. package/src/tui-compiled/{sidebar-state.ts → runtime/sidebar-state.ts} +2 -2
  43. package/src/tui-compiled/{tui/command-dialogs.tsx → runtime/tui-command-dialogs.tsx} +3 -4
  44. package/src/tui-compiled/{tui.tsx → runtime/tui.tsx} +10 -10
  45. package/src/tui-compiled/shared/internal.ts +6 -0
  46. package/src/{logger.ts → tui-compiled/shared/logger.ts} +82 -21
  47. package/src/tui-compiled/shared/paths.ts +33 -0
  48. package/src/{core → tui-compiled/shared}/refresh-file-lock.ts +7 -4
  49. package/dist/cli.d.ts +0 -2
  50. package/dist/cli.js +0 -15
  51. package/dist/codex-http.d.ts +0 -3
  52. package/dist/commands.d.ts +0 -88
  53. package/dist/config.d.ts +0 -47
  54. package/dist/core/account-paths.d.ts +0 -25
  55. package/dist/core/accounts.d.ts +0 -330
  56. package/dist/core/atomic-write.d.ts +0 -1
  57. package/dist/core/background-quota-refresh.d.ts +0 -46
  58. package/dist/core/backoff.d.ts +0 -53
  59. package/dist/core/cachekeep.d.ts +0 -118
  60. package/dist/core/oauth.d.ts +0 -138
  61. package/dist/core/provider.d.ts +0 -70
  62. package/dist/core/quota-manager.d.ts +0 -192
  63. package/dist/core/refresh-all-quota.d.ts +0 -86
  64. package/dist/core/refresh-file-lock.d.ts +0 -12
  65. package/dist/core/reset-credits.d.ts +0 -116
  66. package/dist/core/sticky-routing.d.ts +0 -43
  67. package/dist/dump.d.ts +0 -20
  68. package/dist/hosted-web-search.d.ts +0 -5
  69. package/dist/index-8f1200qx.js +0 -6
  70. package/dist/index-nrvjr97q.js +0 -3
  71. package/dist/index-qaggaze1.js +0 -2
  72. package/dist/index-sdcpzbnk.js +0 -2
  73. package/dist/index-zf3axndm.js +0 -89
  74. package/dist/logger.d.ts +0 -22
  75. package/dist/model-costs.d.ts +0 -29
  76. package/dist/prompt-context.d.ts +0 -19
  77. package/dist/quota-normalize-dvwtmy7f.js +0 -1
  78. package/dist/quota-normalize.d.ts +0 -43
  79. package/dist/raw-ws-bun.d.ts +0 -40
  80. package/dist/raw-ws-node.d.ts +0 -37
  81. package/dist/raw-ws-upgrade.d.ts +0 -2
  82. package/dist/raw-ws.d.ts +0 -3
  83. package/dist/response-stream-error.d.ts +0 -12
  84. package/dist/rpc/notifications.d.ts +0 -5
  85. package/dist/rpc/rpc-server.d.ts +0 -17
  86. package/dist/token-util-jcj7k7pa.js +0 -1
  87. package/dist/tui/command-dialogs.d.ts +0 -21
  88. package/dist/util/error.d.ts +0 -1
  89. package/dist/util/open-url.d.ts +0 -6
  90. package/dist/util/proxy-env.d.ts +0 -4
  91. package/dist/util/record.d.ts +0 -1
  92. package/dist/util/stable-json.d.ts +0 -1
  93. package/dist/util/uuid-v7.d.ts +0 -1
  94. package/dist/version.d.ts +0 -1
  95. package/dist/ws-pool.d.ts +0 -57
  96. package/dist/ws.d.ts +0 -53
  97. package/src/rpc/notifications.ts +0 -54
  98. package/src/rpc/protocol.ts +0 -33
  99. package/src/rpc/rpc-server.ts +0 -172
  100. package/src/tui-compiled/core/refresh-file-lock.ts +0 -381
  101. package/src/tui-compiled/logger.ts +0 -196
  102. package/src/tui-compiled/rpc/protocol.ts +0 -33
  103. package/src/util/error.ts +0 -9
  104. package/src/util/open-url.ts +0 -30
  105. package/src/util/proxy-env.ts +0 -42
  106. package/src/util/record.ts +0 -3
  107. package/src/util/stable-json.ts +0 -15
  108. package/src/util/uuid-v7.ts +0 -18
  109. /package/src/{rpc/rpc-dir.ts → tui-compiled/raw/rpc-rpc-dir.ts} +0 -0
  110. /package/src/tui-compiled/{tui-preferences.ts → raw/tui-preferences.ts} +0 -0
  111. /package/src/tui-compiled/{rpc/rpc-dir.ts → runtime/rpc-rpc-dir.ts} +0 -0
  112. /package/src/{tui-preferences.ts → tui-compiled/runtime/tui-preferences.ts} +0 -0
  113. /package/src/tui-compiled/{util → shared/util}/error.ts +0 -0
  114. /package/src/tui-compiled/{util → shared/util}/open-url.ts +0 -0
package/dist/index.js CHANGED
@@ -1,218 +1,123 @@
1
- import{d as g1,e as jY,f as X4}from"./index-87145jkw.js";import{A as t0,B as S1,C as W1,D as l4,E as d4,F as i0,G as i4,H as M1,I as u0,J as tX,K as D0,L as G0,M as DY,N as PY,O as LX,P as MY,Q as n4,R as o4,S as r4,h as b4,i as x4,j as vY,k as hY,l as v4,m as h4,n as g4,o as o1,p as r1,q as B8,s as y4,t as f4,u as m4,v as c4,w as u4,x as p4,y as sX,z as aX}from"./index-zf3axndm.js";import{$ as A1,U as d8,X as EY,Y as s4,da as a4,ea as t4,fa as e4,ka as Yz,la as O8,ma as Xz,na as Jz,oa as Qz,pa as $z}from"./index-sdcpzbnk.js";import{wa as gY}from"./index-8f1200qx.js";import{xa as mJ,ya as cJ}from"./index-qaggaze1.js";import{Aa as xY,Ba as a8,Ca as FJ,Da as N0}from"./index-nrvjr97q.js";import{Ga as Gz}from"./index-zg1x8sty.js";import{Ja as U9}from"./index-zxqb5ydj.js";import{mkdirSync as TZ,readFileSync as RZ,renameSync as _Z,statSync as CZ,writeFileSync as IZ}from"node:fs";import zX from"node:os";import{join as SZ}from"node:path";import{readFileSync as Bz}from"node:fs";import{homedir as Oz,tmpdir as Fz}from"node:os";import{join as CY}from"node:path";var qz="https://chatgpt.com/backend-api/codex/responses",jz="openai-auth.json",a0={noWebSearch:"CORTEXKIT_OPENAI_AUTH_NO_WEB_SEARCH",webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",responsesLite:"CORTEXKIT_OPENAI_AUTH_RESPONSES_LITE",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",codexApiEndpoint:"CORTEXKIT_OPENAI_AUTH_CODEX_ENDPOINT",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function IY(){let Y=process.env[a0.configDir]?.trim();if(Y)return Y;return CY(process.env.XDG_CONFIG_HOME||CY(Oz(),".config"),"opencode")}function W0(){return process.env[a0.configFile]?.trim()||CY(IY(),jz)}function Dz(){try{let Y=JSON.parse(Bz(W0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function IX(Y){let X=process.env[Y];if(X===void 0)return;let J=X.trim().toLowerCase();if(J==="1"||J==="true"||J==="yes"||J==="on")return!0;if(J===""||J==="0"||J==="false"||J==="no"||J==="off")return!1;return}function RY(Y,X,J){let Q=IX(Y);if(Q!==void 0)return Q;if(typeof X==="boolean")return X;return J}function Pz(){let Y=Dz(),X=IX(a0.noWebSearch),J=X!==void 0?!X:typeof Y.webSearch==="boolean"?Y.webSearch:!0,Q;if(Y.dump!==void 0&&Y.dump!==null){if(typeof Y.dump==="object")Q=Y.dump.enabled;else if(typeof Y.dump==="boolean")Q=Y.dump}return{webSearch:J,webSockets:RY(a0.webSockets,Y.webSockets,!1),rawWebSocket:RY(a0.rawWebSocket,Y.rawWebSocket,!1),responsesLite:RY(a0.responsesLite,Y.responsesLite,!1),dump:RY(a0.dump,Q,!1),dumpDir:process.env[a0.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():CY(Fz(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[a0.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():qz)}}var _Y;function E0(){if(!_Y)_Y=Pz();return _Y}function M8(){return _Y=void 0,E0()}var E8="/backend-api/wham/rate-limit-reset-credits",Mz=`https://chatgpt.com${E8}`,vX=`${E8}/consume`,Ez=`https://chatgpt.com${vX}`,Az=300000,wz=60000,Tz=15000,Rz=60000;class b0 extends Error{kind;cooldownUntil;constructor(Y,X,J){super(X);this.name="ResetRedemptionError",this.kind=Y,this.cooldownUntil=J}}class P1 extends Error{kind;status;constructor(Y,X,J){super(X);this.name="ResetCreditError",this.kind=Y,this.status=J}}function hX(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 SY(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}function gX(Y){if(!Y)return;return{...Y.inFlight?{inFlight:{...Y.inFlight}}:{},...Y.lastOutcome?{lastOutcome:{...Y.lastOutcome}}:{},...Y.cooldownUntil!==void 0?{cooldownUntil:Y.cooldownUntil}:{}}}function A8(Y){if(!SY(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 yX(Y){return Boolean(Y&&Object.hasOwn(Y,"inFlight"))}function fX(Y,X){return X-Y.startedAt<Az}function kY(Y,X){if(!u0(X))return;return Y.reset?.[X]}function mX(Y){if(!Y.reset)Y.reset=Object.create(null);return Y.reset}function cX(Y,X,J){if(!u0(X))return;let Q=mX(Y),$=Q[X]??{},G=$.lastOutcome;delete $.inFlight,$.lastOutcome={code:"ambiguous_local",at:J,...G?{previousOutcome:{code:G.code,at:G.at}}:{}},Q[X]=$}function uX(Y,X){let J=gX(Y),Q=A8(Y?.inFlight);if(yX(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&&fX(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 _z(Y,X){if(!u0(X))return{kind:"fresh",beforeState:void 0};let J=await Y.loadAccountsFn(Y.configPath);return uX(J?kY(J,X):void 0,Y.now())}async function Cz(Y,X){let J;if(await Y.mutateAccountsFn((Q)=>{let $=Y.now(),G=kY(Q,X);if(J=uX(G,$),J.kind==="corrupt")cX(Q,X,$);return Q},Y.configPath),!J)throw Error("corrupt reset state mutation did not run");return J}async function Iz(Y,X,J){if(!u0(X))return{kind:"fresh",beforeState:void 0};let Q;if(await Y.mutateAccountsFn(($)=>{let G=Y.now(),W=kY($,X),U=gX(W),H=A8(W?.inFlight);if(yX(W)&&!H)return cX($,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(H&&fX(H,G))return Q={kind:"claim",beforeState:U,claim:{inFlight:H,selectedCredit:{id:H.creditId}}},$;if(H)return Q={kind:"expired_unreconciled",beforeState:U,claim:{inFlight:H,selectedCredit:{id:H.creditId}}},$;let L=bY(J);if(!L)return Q={kind:"fresh",beforeState:U},$;let V={redeemRequestId:Y.randomUUID(),creditId:L.id,startedAt:G},B=mX($);return B[X]={...W,inFlight:V},Q={kind:"claim",beforeState:U,claim:{inFlight:V,selectedCredit:L}},$},Y.configPath),!Q)throw Error("reset claim mutation did not run");return Q}async function Sz(Y,X,J,Q){if(!u0(X))return;if(!R8(Q.kind))return;await Y.mutateAccountsFn(($)=>{let G=kY($,X),W=A8(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+Rz;else delete G.cooldownUntil;return $},Y.configPath)}function t1(Y,X){if(!Y||Y.usedPercent<100)return!1;if(!Y.resetsAt)return!0;let J=Date.parse(Y.resetsAt);return!Number.isFinite(J)||J>X}function w8(Y,X,J){if(!(X||t1(Y.primary,J)||t1(Y.secondary,J)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function SX(Y,X){let J=Y[X];if(J===void 0||J===null)return;return typeof J==="string"?J:null}function kz(Y){if(!SY(Y))return;let X=SX(Y,"granted_at"),J=SX(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 T8(Y,X,J){let Q;try{Q=await Y(Mz,{method:"GET",headers:hX(X,E8,J),signal:AbortSignal.timeout(Tz)})}catch{throw new P1("http_error","reset credit list request failed")}if(!Q.ok)throw new P1("http_error",`reset credit list request failed: ${Q.status}`,Q.status);let $;try{$=await Q.json()}catch{throw new P1("invalid_response","reset credit list response was not valid JSON",Q.status)}if(!SY($))throw new P1("invalid_response","reset credit list response was not an object",Q.status);return{credits:(Array.isArray($.credits)?$.credits:[]).flatMap((W)=>{let U=kz(W);return U===void 0?[]:[U]}),availableCount:typeof $.available_count==="number"&&Number.isFinite($.available_count)?$.available_count:void 0}}function bY(Y){return[...Y].filter(pX).sort((X,J)=>Date.parse(X.expiresAt)-Date.parse(J.expiresAt))[0]}function pX(Y){return Y.status==="available"&&Y.isSupportedByPlan&&Y.resetType==="codex_rate_limits"}function lX(Y){return Y.filter(pX).length}function R8(Y){return Y==="reset"||Y==="already_redeemed"||Y==="nothing_to_reset"||Y==="no_credit"}async function bz(Y,X,J,Q,$){let G;try{G=await Y(Ez,{method:"POST",headers:{...hX(X,vX,J),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:$,credit_id:Q}),signal:AbortSignal.timeout(wz)})}catch(L){return{kind:"ambiguous",raw:L}}let W;try{W=await G.text()}catch(L){return G.ok?{kind:"ambiguous",raw:L}:{kind:"http_error",raw:L,status:G.status}}let U=W,H=!1;try{U=JSON.parse(W),H=!0}catch{}if(!G.ok)return{kind:"http_error",raw:U,status:G.status};if(!H||!SY(U)||!R8(U.code))return{kind:"ambiguous",raw:U};return{kind:U.code,raw:U}}function kX(Y){if(Y.kind==="cooldown")throw new b0("cooldown_active","reset credit redemption is cooling down",Y.cooldownUntil);throw Error(`unexpected reset state decision: ${Y.kind}`)}function bX(){throw new b0("expired_unreconciled","the previous reset attempt outcome is unknown")}function xX(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 xz(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 dX(Y,X){if(!u0(X.accountKey))throw new b0("invalid_account_key","the reset account key is reserved");let J=await Y.resolveTarget(X.accountKey);if(J.chatgptAccountId!==X.expectedChatgptAccountId)throw new b0("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let Q=J.accountKey==="main"?void 0:J.chatgptAccountId,$=await _z(Y,X.accountKey);if($.kind==="corrupt"){if($=await Cz(Y,X.accountKey),$.kind==="corrupt")return xX(J,$.beforeState)}if($.kind==="cooldown")kX($);let G;if($.kind==="claim")G=$.claim;else if($.kind==="expired_unreconciled"){if(!X.retry)bX();G=$.claim}else{if(X.retry)throw new b0("retry_without_inflight","there is no active reset credit redemption to retry");let[H,L]=await Promise.all([Y.fetchUsage(J),T8(Y.fetchImpl,J.accessToken,Q)]),V=w8(H,Y.hasActiveRateLimitMark(X.accountKey),Y.now());if(!V.ok)throw new b0("not_exhausted",V.reason);if(!bY(L.credits))throw new b0("no_eligible_credit","no eligible reset credit was returned");let B=await Iz(Y,X.accountKey,L.credits);if(B.kind==="corrupt")return xX(J,B.beforeState);if(B.kind==="cooldown")kX(B);if(B.kind==="expired_unreconciled")bX();if(B.kind!=="claim")throw new b0("no_eligible_credit","no eligible reset credit was available while claiming");G=B.claim}let W=await bz(Y.fetchImpl,J.accessToken,Q,G.inFlight.creditId,G.inFlight.redeemRequestId),U=!1;try{await Sz(Y,X.accountKey,G.inFlight,W)}catch{U=R8(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.":xz(W),...U?{finalizeStateWriteFailed:!0}:{}}}function C(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var I8="openai-quota",S8="openai-account",k8="openai-routing",b8="openai-killswitch",x8="openai-dump",v8="openai-logging",h8="openai-cachekeep",E1="openai-reset",eX=["openai-quota","openai-account","openai-routing","openai-killswitch","openai-dump","openai-logging","openai-cachekeep","openai-reset"],d=N0("commands");function iX(Y){if(Y==="fallback-first")return"Try usable fallback accounts before the main account.";if(Y==="sticky-balanced")return"Keep each session on its assigned account while balancing new sessions.";return"Try the main account first. Use fallback accounts only when required."}var vz=900000;function nX(Y,X){if(typeof Y!=="number"||!Number.isFinite(Y))return" (age unknown)";let J=X-Y;if(J<vz)return"";let Q=Math.floor(J/3600000);if(Q>=24)return` (${Math.floor(Q/24)}d old)`;if(Q>=1)return` (${Q}h old)`;return` (${Math.floor(J/60000)}m old)`}async function hz(Y){let X=await Y.refreshAllQuota?.(),J=Y.quotaManager.getMain(),Q=Date.now(),$=["## OpenAI Quota",""];if(J?.quota){let U=J.quota;$.push("### Main account");for(let H of["primary","secondary"]){let L=U[H];if(L){let V=Math.round(L.usedPercent),B="█".repeat(Math.max(0,Math.min(Math.round(V/10),10)))+"░".repeat(Math.max(0,10-Math.min(Math.round(V/10),10)));$.push(`- ${H}: ${B} ${V}% used (${Math.round(L.remainingPercent)}% remaining)${nX(L.checkedAt??J.checkedAt,Q)}`)}}if(U.resetCreditsAvailable!==void 0)$.push(`- resets: ${U.resetCreditsAvailable}`)}else $.push("No main quota snapshot available. Send a request first.");let W=[...Y.quotaManager.getAllFallbacks().entries()].filter(([,U])=>U);if(W.length>0){$.push(""),$.push("### Fallback accounts");for(let[U,H]of W){if(!H?.quota)continue;$.push(`**${U}**`);for(let L of["primary","secondary"]){let V=H.quota[L];if(V){let B=Math.round(V.usedPercent);$.push(` - ${L}: ${B}% used (${Math.round(V.remainingPercent)}% remaining)${nX(V.checkedAt??H.checkedAt,Q)}`)}}if(H.quota.resetCreditsAvailable!==void 0)$.push(` - resets: ${H.quota.resetCreditsAvailable}`)}}if(X?.length){let U=X.filter((H)=>!H.ok);if(U.length>0){$.push("");for(let H of U)$.push(H.permanent?`- ${H.account}: sign-in no longer accepted — remove and add this account again`:`- ${H.account}: fetch failed — Refresh to retry`)}}return{command:"openai-quota",text:$.join(`
2
- `),knobs:{}}}function v1(Y){return{id:Y.id,type:Y.type??"oauth",enabled:Y.enabled,label:Y.label}}async function gz(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 H=U.type??"oauth";G.push(`- \`${U.id}\` (${H})`)}}return G.push(""),G.push("Commands: `/openai-account add [label]` | `/openai-account remove <id>`"),{command:"openai-account",text:G.join(`
3
- `),knobs:{accounts:$.map(v1)}}}if(J[0]==="remove"&&J[1]){let G=J[1],W=await tX(X.accountStoragePath),U=W?W.has(G):!1,H=!1,L=await G0((B)=>{let K=B.accounts.findIndex((N)=>N.id===G);if(K===-1)return B;return B.accounts.splice(K,1),H=!0,B},X.accountStoragePath,{allowDrop:[G]});if(!(H||U))return{command:"openai-account",text:`## Account Not Found
4
-
5
- No account with id \`${G}\` exists.`,knobs:{accounts:L.accounts.map(v1)}};return d.info("account removed",{id:G}),X.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Account Removed
6
-
7
- Removed account \`${G}\`.`,knobs:{accounts:L.accounts.map(v1)}}}if(J[0]==="order"&&J.length>=3){let G=!1,W=await G0((U)=>{let H=U.accounts.findIndex((B)=>B.id===J[1]),L=U.accounts.findIndex((B)=>B.id===J[2]);if(H===-1||L===-1)return U;G=!0;let V=U.accounts[H];return U.accounts[H]=U.accounts[L],U.accounts[L]=V,U},X.accountStoragePath);if(!G)return{command:"openai-account",text:`## Invalid Order
8
-
9
- Both account IDs must exist.`,knobs:{accounts:W.accounts.map(v1)}};return d.info("accounts reordered",{a:J[1],b:J[2]}),X.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Accounts Reordered
10
-
11
- Swapped positions of \`${J[1]}\` and \`${J[2]}\`.`,knobs:{accounts:W.accounts.map(v1)}}}if(J[0]==="add"){let G=J.includes("--headless"),W=J.filter((N)=>N!=="add"&&N!=="--headless"),U=W.length>0?W.join(" "):void 0,{url:H,instructions:L,completion:V}=await aX({label:U,headless:G}),B=X.notify,K=X.sessionId;if(V.then(async(N)=>{let O=!1;if(await G0((j)=>{if(N.accountId&&j.mainAccountId&&N.accountId===j.mainAccountId)return O=!0,j;return sX(j.accounts,N),j},X.accountStoragePath),O){d.warn("account add rejected (main identity)",{id:N.id,sessionId:K}),B?.({command:"openai-account",text:`## Add Failed
12
-
13
- ${"That account is already your main account — not added as a fallback."}`,knobs:{}});return}d.info("account added",{id:N.id,label:N.label}),X.refreshSidebar?.().catch(()=>{}),B?.({command:"openai-account",text:`## Account Added
14
-
15
- Added account \`${N.id}\`${N.label?` ("${N.label}")`:""}.
16
-
17
- Run \`/openai-account\` to confirm.`,knobs:{}})}).catch((N)=>{let O=N instanceof Error?N.message:String(N??"unknown error");d.warn("account add failed",{error:O,sessionId:K}),B?.({command:"openai-account",text:`## Add Failed
18
-
19
- Account add failed: ${O}`,knobs:{}})}),G){let N=L.match(/Enter code: (.+)/)?.[1]??L;return{command:"openai-account",text:`## Device Code
20
-
21
- 1. Open this verification URL:
22
-
23
- ${H}
24
-
25
- 2. Enter the code: **${N}**
26
-
27
- ${L}
28
-
29
- The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{verificationUrl:H,userCode:N,instructions:L}}}return{command:"openai-account",text:`## Add OpenAI Account
30
-
31
- Open this URL and complete sign-in:
32
-
33
- ${H}
34
-
35
- ${L}
36
-
37
- The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{url:H,instructions:L}}}return{command:"openai-account",text:"## Account Commands\n\n- `/openai-account` — show accounts\n- `/openai-account add [label]` — add a new account\n- `/openai-account remove <id>` — remove\n- `/openai-account order <a> <b>` — swap fallback positions\n\nRouting modes are `main-first`, `fallback-first`, and `sticky-balanced`. `/openai-routing reset` clears the current session pin.",knobs:{accounts:$.map(v1)}}}async function yz(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
-
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
-
41
- This runtime cannot clear the current session pin.`,knobs:{mode:$}};return await X.clearStickyRouting(X.sessionId),d.info("routing session pin cleared"),{command:"openai-routing",text:`## OpenAI Routing Reset
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 U=J[0];return await G0((H)=>{return H.routing={...H.routing??{},mode:U},H},X.accountStoragePath),d.info("routing mode changed",{mode:U}),{command:"openai-routing",text:`## OpenAI Routing Updated
44
-
45
- Mode: \`${U}\`
46
- - ${iX(U)}
47
-
48
- Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:U}}}let G=$==="sticky-balanced"&&X.sessionId?await X.getStickyRouting?.(X.sessionId):void 0,W=$==="sticky-balanced"?G?`
49
- - Session pin: \`${G}\`. Use \`/openai-routing reset\` to clear it.`:`
50
- - Session pin: none yet. A request will choose one when a usable account is available.`:"";return{command:"openai-routing",text:`## OpenAI Routing
51
-
52
- - Mode: \`${$}\`
53
- - ${iX($)}${W}
54
-
55
- Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:$}}}async function fz(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 H=Q.main??{},L=H.primary??H["5h"]??M1.primary,V=H.secondary??H["1w"]??M1.secondary;U.push(`| main | ≥ ${L}% | ≥ ${V}% |`);for(let B of $){let K=Q.accounts?.[B]??Q.main??{},N=K.primary??K["5h"]??M1.primary,O=K.secondary??K["1w"]??M1.secondary;U.push(`| ${B} | ≥ ${N}% | ≥ ${O}% |`)}}return U.push(""),U.push("Commands: `/openai-killswitch on` | `/openai-killswitch off` | `/openai-killswitch set <acct>:<5h>,<1w> ...`"),{command:"openai-killswitch",text:U.join(`
56
- `),knobs:{config:Q,accountIds:$}}}if(G[0]==="on"){let W={...Q,enabled:!0,main:Q.main??{primary:M1.primary,secondary:M1.secondary}};return await G0((U)=>{return U.killswitch=W,U},X.accountStoragePath),d.info("killswitch enabled"),{command:"openai-killswitch",text:"## Killswitch Enabled",knobs:{config:W,accountIds:$}}}if(G[0]==="off"){let W={...Q,enabled:!1};return await G0((U)=>{return U.killswitch=W,U},X.accountStoragePath),d.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 H=G[U]?.match(/^([^:]+):(\d+),(\d+)$/);if(!H)continue;let[,L,V,B]=H,K={primary:Number.parseInt(V,10),secondary:Number.parseInt(B,10)};if(L==="main")W.main=K;else if(L==="all"){W.main=K;for(let N of $)W.accounts[N]=K}else W.accounts[L]=K}return await G0((U)=>{return U.killswitch=W,U},X.accountStoragePath),d.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 mz(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),Q=E0(),$=Q.dump;if(J.length===0)return{command:"openai-dump",text:`## Request Dump
57
-
58
- - Enabled: ${$?"ON":"OFF"}
1
+ import{A as QK,d as u9,g as k1,h as r4,k as DY,o as s4,p as a4,q as t4,v as e4,w as C9,x as YK,y as XK,z as JK}from"./index-2xppkvkx.js";import{F as lJ,G as dJ}from"./index-3w4vmckx.js";import{$ as YJ,Aa as Y1,Ba as X1,Ca as J1,Da as Q1,Ea as G1,Fa as $1,Ga as W1,Ha as o1,I as h8,Ia as b9,J as m4,Ja as UY,K as c4,L as p1,M as u4,N as n1,O as n9,P as PJ,Q as D0,R as p4,S as n8,T as r8,U as oY,V as nY,W as tY,X as s8,Y as a8,Z as t8,_ as e8,aa as XJ,ba as JJ,ca as QJ,da as S8,ea as k8,fa as T1,ga as xY,ha as AY,ia as r1,ja as l4,ka as i1,la as V0,ma as d4,na as TY,oa as g8,pa as O0,qa as B0,ra as I1,sa as _1,ta as K8,ua as S1,va as i4,wa as o4,xa as n4,ya as k,za as eY}from"./index-nshbgkz1.js";import{Ma as GK}from"./index-944gsj1s.js";import{Oa as hY,Pa as C1,Qa as W4}from"./index-xyg86jgt.js";import{Ua as $X}from"./index-507jh8bv.js";import{mkdirSync as MV,readFileSync as EV,renameSync as wV,statSync as AV,writeFileSync as TV}from"node:fs";import $8 from"node:os";import{join as RV}from"node:path";import{execFileSync as bK}from"node:child_process";import{readFileSync as BK}from"node:fs";import{homedir as FK,tmpdir as OK}from"node:os";import{join as y1}from"node:path";var qK="https://chatgpt.com/backend-api/codex/responses",jK="openai-auth.json",t0={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 f1(){let Y=process.env[t0.configDir]?.trim();if(Y)return Y;return y1(process.env.XDG_CONFIG_HOME||y1(FK(),".config"),"opencode")}function s(){return process.env[t0.configFile]?.trim()||y1(f1(),jK)}function DK(){try{let Y=JSON.parse(BK(s(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function C8(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 h1(Y,X,J){let Q=C8(Y);if(Q!==void 0)return Q;if(typeof X==="boolean")return X;return J}function PK(){let Y=DK(),X=C8(t0.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:h1(t0.webSockets,Y.webSockets,!1),rawWebSocket:h1(t0.rawWebSocket,Y.rawWebSocket,!1),responsesLite:h1(t0.responsesLite,Y.responsesLite,!1),dump:h1(t0.dump,Q,!1),dumpDir:process.env[t0.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():y1(OK(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[t0.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():qK)}}var g1;function C0(){if(!g1)g1=PK();return g1}function k9(){return g1=void 0,C0()}import{realpathSync as I8}from"node:fs";import{homedir as MK}from"node:os";import{basename as EK,dirname as wK,join as c1,resolve as x8}from"node:path";function AK(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return c1(process.env.XDG_CONFIG_HOME||c1(MK(),".config"),"opencode")}function b8(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||c1(AK(),S8)}function m1(Y,X){let J=x8(Y);return X==="win32"||X==="darwin"?J.toLowerCase():J}function _8(Y){try{return I8.native(Y)}catch{try{return c1(I8.native(wK(Y)),EK(Y))}catch{return}}}function TK(Y,X,J=process.platform){if(m1(Y,J)===m1(X,J))return!0;let Q=_8(Y),G=_8(X);return Q!==void 0&&G!==void 0&&m1(Q,J)===m1(G,J)}function u1(Y=b8()){let X=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(X){if(TK(Y,X))throw Error(`OPENCODE_OPENAI_AUTH_STATE_FILE resolves to the config path (${x8(Y)}). Set OPENCODE_OPENAI_AUTH_STATE_FILE to a different file.`);return X}return k8(Y)}function H0(Y=b8()){return{configPath:Y,statePath:u1(Y)}}var aY="0.8.0";import{readFile as RK}from"node:fs/promises";function v8(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}async function y8(Y){let X=await g8(Y.configPath),J=[];try{let G=JSON.parse(await RK(Y.statePath,"utf8"));if(v8(G)){let $=G.accounts;if(v8($))J=Object.keys($)}}catch(G){if(G.code!=="ENOENT")throw G}return{rosterIds:X?[...X]:[],stateIds:J,orphanStateIds:X?J.filter((G)=>!X.has(G)):[]}}function x9(Y){if(!Y)return;let X=Y.accounts.find((J)=>J.id==="main"&&V0(J));if(X)return X;if(!Y.mainAccountId)return;return Y.accounts.find((J)=>V0(J)&&J.accountId===Y.mainAccountId)}function CK(Y,X){let J=Y.lastRefreshError;return p1(J,Y.refresh,X)&&J!==void 0&&J.nextRetryAt!==void 0&&J.nextRetryAt-J.checkedAt>=h8}function f8(Y){let X=[],J=[],Q=Y.now??Date.now(),G=x9(Y.storage),$=!1;if(!Y.auth)X.push({code:"auth-slot-missing",message:"OpenCode's OpenAI auth slot is missing."}),$=!0;else if(Y.auth.type!=="oauth")X.push({code:"auth-slot-not-oauth",message:"OpenCode's OpenAI auth slot is not OAuth."}),$=!0;else if(G&&(!Y.auth.refresh||G.refresh!==Y.auth.refresh))X.push({code:"main-refresh-not-in-store",message:"OpenCode's main credential does not match the copy in the account store."}),$=!0;if($&&G){let L={type:"restore-main-credential"};J.push(L);let U=X.find((H)=>H.code==="auth-slot-missing"||H.code==="auth-slot-not-oauth"||H.code==="main-refresh-not-in-store");if(U)U.repair=L}let W=Y.storage?.accounts??[];if(W.length===0)X.push({code:"no-accounts",message:"The account store has no accounts."});else if(!W.some((L)=>L.enabled!==!1))X.push({code:"no-enabled-accounts",message:"The account store has no enabled accounts."});for(let L of W){if(!V0(L))continue;if(!CK(L,Q))continue;let U={type:"clear-refresh-backoff",accountId:L.id};J.push(U),X.push({code:"armed-non-transient-refresh-backoff",accountId:L.id,message:`Account ${L.id} has an armed non-transient refresh backoff.`,repair:U})}let z=[...Y.orphanStateIds??[]];if(z.length>0){let L={type:"prune-orphan-state-ids",ids:z};J.push(L),X.push({code:"orphan-state-ids",message:`State contains ids absent from the config roster: ${z.join(", ")}.`,repair:L})}return{findings:X,repairs:J}}function m8(Y){let X=["OpenAI auth doctor"];if(Y.findings.length===0)return X.push("No problems found."),X.join(`
2
+ `);for(let J of Y.findings){let Q=J.repair?" (repair available)":"";X.push(`- ${J.message}${Q}`)}return X.join(`
3
+ `)}var i={hide:"\x1B[?25l",show:"\x1B[?25h",up:(Y=1)=>`\x1B[${Y}A`,clearLine:"\x1B[2K",clearScreen:"\x1B[2J",moveTo:(Y,X)=>`\x1B[${Y};${X}H`,cyan:"\x1B[36m",green:"\x1B[32m",red:"\x1B[31m",dim:"\x1B[2m",reset:"\x1B[0m"};function c8(Y){let X=Y.toString();if(X==="\x1B[A"||X==="\x1BOA")return"up";if(X==="\x1B[B"||X==="\x1BOB")return"down";if(X==="\r"||X===`
4
+ `)return"enter";if(X==="\x03")return"escape";if(X==="\x1B")return"escape-start";return null}function u8(){return Boolean(process.stdin.isTTY)}var IK=50,p8=`${String.fromCharCode(27)}\\[[0-9;]*m`,_K=new RegExp(p8,"g"),SK=new RegExp(`^${p8}`);function kK(Y){return Y.replace(_K,"")}function l1(Y,X){if(X<=0)return"";if(kK(Y).length<=X)return Y;let J=X>=3?"...":".".repeat(X),Q=Math.max(0,X-J.length),G="",$=0,W=0;while($<Y.length&&W<Q){if(Y[$]==="\x1B"){let z=Y.slice($).match(SK);if(z){G+=z[0],$+=z[0].length;continue}}G+=Y[$],$+=1,W+=1}return G.includes("\x1B[")?`${G}${i.reset}${J}`:G+J}function xK(Y){if(Y==="red")return i.red;if(Y==="cyan")return i.cyan;return""}async function d1(Y,X){if(!u8())throw Error("Interactive select requires a TTY terminal");if(Y.length===0)throw Error("No menu items provided");if(Y.length===1)return Y[0]?.value??null;let{stdin:J,stdout:Q}=process,G=0,$=null,W=!1,z=0,L=()=>{let U=Q.columns??80,H=Q.rows??24,B=z;if(X.clearScreen)Q.write(i.clearScreen+i.moveTo(1,1));else if(B>0)Q.write(i.up(B));let V=0,Z=(E)=>{Q.write(`${i.clearLine}${E}
5
+ `),V+=1},j=X.subtitle?3:0,O=Math.max(1,Math.min(Y.length,H-(1+j+2)-1)),C=Math.max(0,Math.min(G-Math.floor(O/2),Math.max(0,Y.length-O))),R=Y.slice(C,C+O);if(Z(`${i.dim}┌ ${i.reset}${l1(X.message,Math.max(1,U-4))}`),X.subtitle)Z(`${i.dim}│${i.reset}`),Z(`${i.cyan}◆${i.reset} ${l1(X.subtitle,Math.max(1,U-4))}`),Z("");for(let E=0;E<R.length;E++){let T=R[E];if(!T)continue;let g=C+E===G,u=xK(T.color),l=u?`${g?"":i.dim}${u}${T.label}${i.reset}`:g?T.label:`${i.dim}${T.label}${i.reset}`;l=l1(l,Math.max(1,U-8)),Z(g?`${i.cyan}│${i.reset} ${i.green}●${i.reset} ${l}`:`${i.cyan}│${i.reset} ${i.dim}○${i.reset} ${l}`)}let D=R.length<Y.length?` (${C+1}-${C+R.length}/${Y.length})`:"";Z(`${i.cyan}│${i.reset} ${i.dim}${l1(`Up/Down to select | Enter: confirm | Esc: back${D}`,Math.max(1,U-6))}${i.reset}`),Z(`${i.cyan}└${i.reset}`);for(let E=V;E<B;E++)Z("");z=V};return new Promise((U)=>{let H=J.isRaw??!1,B=()=>{if(W)return;if(W=!0,$)clearTimeout($);J.removeListener("data",j);try{J.setRawMode(H),J.pause(),Q.write(i.show)}catch{}process.removeListener("SIGINT",Z),process.removeListener("SIGTERM",Z)},V=(O)=>{B(),U(O)},Z=()=>V(null),j=(O)=>{if($)clearTimeout($),$=null;switch(c8(O)){case"up":G=(G-1+Y.length)%Y.length,L();break;case"down":G=(G+1)%Y.length,L();break;case"enter":V(Y[G]?.value??null);break;case"escape":V(null);break;case"escape-start":$=setTimeout(()=>V(null),IK);break}};process.once("SIGINT",Z),process.once("SIGTERM",Z);try{J.setRawMode(!0)}catch{B(),U(null);return}J.resume(),Q.write(i.hide),L(),J.on("data",j)})}var l8=[{label:"Add account",value:"add-account",color:"cyan"},{label:"Auth current",value:"auth-current",color:"cyan"},{label:"Check quotas",value:"check-quotas",color:"cyan"},{label:"Auth doctor",value:"auth-doctor",color:"cyan"},{label:"Apply repairs",value:"apply-repairs",color:"cyan"},{label:"Delete all accounts",value:"delete-all",color:"red"}],IB=l8.map((Y)=>Y.label);async function d8(){return await d1(l8,{message:"OpenAI accounts",subtitle:"Select an account action",clearScreen:!0})??"cancel"}async function i8(Y,X=!1){return await d1(X?[{label:"Yes",value:!0},{label:"No",value:!1}]:[{label:"No",value:!1},{label:"Yes",value:!0}],{message:Y})??!1}function vK(Y,X=process.platform,J=bK){try{if(X==="win32")J("cmd",["/c","start","",Y],{stdio:"ignore",timeout:3000});else J(X==="darwin"?"open":"xdg-open",[Y],{stdio:"ignore",timeout:3000});return!0}catch{return!1}}function hK(){return{url:"",instructions:"",method:"auto",callback:async()=>({type:"failed"})}}async function gK(){let{redirectUri:Y}=await t8(),X=await r8(),J=n8(crypto.getRandomValues(new Uint8Array(32)).buffer),Q=s8(Y,X,J),G=e8(X,J);return{url:Q,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let $=await G;return{type:"success",refresh:$.refresh_token,access:$.access_token,expires:Date.now()+($.expires_in??3600)*1000,accountId:tY($)}}finally{a8(J)}}}}async function yK(Y){let{deviceData:X,url:J,instructions:Q}=await YJ(Y);return{url:J,instructions:Q,method:"auto",async callback(){try{let G=await XJ(X,Y);return{type:"success",refresh:G.refresh_token,access:G.access_token,expires:Date.now()+(G.expires_in??3600)*1000,accountId:tY(G)}}catch{return{type:"failed"}}}}}function o8(Y){if(console.log(`
6
+ Open this URL in your browser and complete sign-in:
7
+ `),console.log(`${Y.url}
8
+ `),Y.instructions)console.log(`${Y.instructions}
9
+ `)}function GJ({client:Y,getAuth:X,getPaths:J=()=>H0(s()),fetchImpl:Q=fetch,packageVersion:G=aY,dependencies:$}){let W={authorizeBrowser:$?.authorizeBrowser??gK,authorizeHeadless:$?.authorizeHeadless??(()=>yK(G)),beginAccountLogin:$?.beginAccountLogin??QJ,loadAccounts:$?.loadAccounts??O0,mutateAccounts:$?.mutateAccounts??B0,refreshAllQuota:$?.refreshAllQuota??UY,showAuthMenu:$?.showAuthMenu??d8,confirm:$?.confirm??i8,readStoreIds:$?.readStoreIds??y8,openBrowser:$?.openBrowser??vK,now:$?.now??Date.now},z=async()=>await X?.().catch(()=>{return})??{type:"missing"},L=async()=>{if((await z()).type!=="missing")return!0;return((await W.loadAccounts(J()))?.accounts.length??0)>0},U=async(D)=>{await Y.auth.set({path:{id:"openai"},body:{type:"oauth",...D}})},H=async()=>{let D=new AbortController,E=await W.beginAccountLogin({version:G,signal:D.signal});E.completion.catch(()=>{}),o8(E);let T=!1;try{T=await W.openBrowser(E.url)!==!1}catch{T=!1}if(!T)D.abort(),console.log(`Could not open a browser. Switching to device authorization.
10
+ `),E=await W.beginAccountLogin({version:G,headless:!0}),o8(E);return E.completion},B=async()=>{let D=await H(),E=!1;if(await W.mutateAccounts((T)=>{if(D.accountId&&T.mainAccountId&&D.accountId===T.mainAccountId)return E=!0,T;return JJ(T.accounts,D),T},J()),E){console.log("That account is already the OpenCode main credential.");return}console.log(`Added fallback account ${D.id}.`)},V=async()=>{let D=await H();await U({refresh:D.refresh,access:D.access??"",expires:D.expires??0}),console.log("Updated the OpenCode main credential.")},Z=async()=>{let D=J(),E=await W.loadAccounts(D),T=new i1({storage:E,configPath:D.configPath,fetchImpl:Q,now:W.now}),g={refreshAccount:async(Q0)=>Q0},u=async()=>{throw Error("No usable main access token for quota check")},l=async(Q0)=>{let c=await W.loadAccounts(Q0);if(!c)return null;return{...c,accounts:c.accounts.map((S0)=>V0(S0)?{...S0,lastRefreshError:void 0}:{...S0})}},T0=await W.refreshAllQuota({getAuth:z,codexRefreshFn:u,refreshMainWithLease:u,fallbackManager:g,quotaManager:T,loadAccounts:l,writeSidebarState:async()=>{},client:{auth:{set:async()=>{throw Error("Quota checks cannot write credentials")}}},fetchImpl:Q,now:W.now,paths:D,storageMainAccountId:E?.mainAccountId,isOAuthAccountFn:V0,whamFn:AY,respectBackoff:!1,readSidebarState:async()=>({main:{},fallbacks:[]})});fK(T0)},j=async()=>{let D=J(),[E,T,g]=await Promise.all([W.loadAccounts(D),W.readStoreIds(D),z()]),u=f8({auth:g.type==="missing"?void 0:g,storage:E,orphanStateIds:T.orphanStateIds,now:W.now()});return console.log(m8(u)),u},O=async()=>{let D=await j();if(D.repairs.length===0){console.log("No repairs are available.");return}if(!await W.confirm("Apply the listed auth repairs?")){console.log("Repairs cancelled.");return}let E=J();for(let T of D.repairs){if(T.type==="restore-main-credential"){let g=await W.loadAccounts(E),u=x9(g);if(!u)continue;await U({refresh:u.refresh,access:u.access??"",expires:u.expires??0});continue}if(T.type==="prune-orphan-state-ids"){await W.mutateAccounts((g)=>g,E);continue}await W.mutateAccounts((g)=>{let u=g.accounts.find((l)=>l.id===T.accountId&&V0(l));if(u)u.lastRefreshError=void 0;return g},E)}console.log(`Applied ${D.repairs.length} auth repair(s).`)},C=async()=>{if(!await W.confirm("Delete all fallback accounts?")){console.log("Delete cancelled.");return}let D=[];await W.mutateAccounts((E,T)=>{let g=new Set([...T?.rawRosterIds??[],...E.accounts.map((u)=>u.id)].filter((u)=>u!=="main"));return D.splice(0,D.length,...g),E.accounts=E.accounts.filter((u)=>u.id==="main"),E},J(),{allowDrop:D}),console.log("Deleted all fallback accounts.")},R=async(D)=>{switch(D){case"add-account":await B();break;case"auth-current":await V();break;case"check-quotas":await Z();break;case"auth-doctor":await j();break;case"apply-repairs":await O();break;case"delete-all":await C();break;case"cancel":break}};return[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:async(D)=>{if(D&&await L())return await R(await W.showAuthMenu()),hK();return W.authorizeBrowser()}},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:W.authorizeHeadless},{label:"Manually enter API Key",type:"api"}]}function fK(Y){for(let X of Y)console.log(X.ok?`${X.account}: quota refreshed`:`${X.account}: ${X.error??"quota refresh failed"}`)}var v0=D0("commands");function E0(Y){return{configPath:Y.accountStoragePath,statePath:Y.accountStatePath}}async function uK(Y,X){let J=await X.loadAccounts(E0(X))??{version:1,accounts:[]},Q=J.killswitch??{},G=(J.accounts??[]).filter((W)=>W.enabled!==!1).map((W)=>W.id),$=Y.trim().toLowerCase().split(/\s+/).filter(Boolean);if($.length===0){let W=Q.enabled===!0,z=["## Killswitch","",`Status: **${W?"ON":"OFF"}**`];if(W){z.push(""),z.push("| Account | primary threshold | secondary threshold |"),z.push("| ------- | ------------ | ------------ |");let L=Q.main??{},U=L.primary??L["5h"]??TY.primary,H=L.secondary??L["1w"]??TY.secondary;z.push(`| main | ≥ ${U}% | ≥ ${H}% |`);for(let B of G){let V=Q.accounts?.[B]??Q.main??{},Z=V.primary??V["5h"]??TY.primary,j=V.secondary??V["1w"]??TY.secondary;z.push(`| ${B} | ≥ ${Z}% | ≥ ${j}% |`)}}return z.push(""),z.push("Commands: `/openai-killswitch on` | `/openai-killswitch off` | `/openai-killswitch set <acct>:<5h>,<1w> ...`"),{command:"openai-killswitch",text:z.join(`
11
+ `),knobs:{config:Q,accountIds:G}}}if($[0]==="on"){let W={...Q,enabled:!0,main:Q.main??{primary:TY.primary,secondary:TY.secondary}};return await B0((z)=>{return z.killswitch=W,z},E0(X)),v0.info("killswitch enabled"),{command:"openai-killswitch",text:"## Killswitch Enabled",knobs:{config:W,accountIds:G}}}if($[0]==="off"){let W={...Q,enabled:!1};return await B0((z)=>{return z.killswitch=W,z},E0(X)),v0.info("killswitch disabled"),{command:"openai-killswitch",text:"## Killswitch Disabled",knobs:{config:W,accountIds:G}}}if($[0]==="set"&&$.length>1){let W={...Q,enabled:!0,accounts:{...Q.accounts??{}}};for(let z=1;z<$.length;z++){let L=$[z]?.match(/^([^:]+):(\d+),(\d+)$/);if(!L)continue;let[,U,H,B]=L,V={primary:Number.parseInt(H,10),secondary:Number.parseInt(B,10)};if(U==="main")W.main=V;else if(U==="all"){W.main=V;for(let Z of G)W.accounts[Z]=V}else W.accounts[U]=V}return await B0((z)=>{return z.killswitch=W,z},E0(X)),v0.info("killswitch thresholds updated",{count:$.length-1}),{command:"openai-killswitch",text:"## Killswitch Updated",knobs:{config:W,accountIds:G}}}return{command:"openai-killswitch",text:"Usage: `/openai-killswitch`, `/openai-killswitch on`, `/openai-killswitch off`, `/openai-killswitch set <acct>:<5h>,<1w> ...`",knobs:{config:Q,accountIds:G}}}async function pK(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),Q=C0(),G=Q.dump;if(J.length===0)return{command:"openai-dump",text:`## Request Dump
12
+
13
+ - Enabled: ${G?"ON":"OFF"}
59
14
  - Directory: ${Q.dumpDir}
60
15
 
61
- Usage: \`/openai-dump on\` or \`/openai-dump off\``,knobs:{enabled:$}};if(J[0]==="on"){await G0((W)=>{return W.dump={...W.dump??{},enabled:!0},W},X.accountStoragePath);let G=M8();return d.info("request dump enabled"),{command:"openai-dump",text:`## Request Dump Enabled
16
+ Usage: \`/openai-dump on\` or \`/openai-dump off\``,knobs:{enabled:G}};if(J[0]==="on"){await B0((W)=>{return W.dump={...W.dump??{},enabled:!0},W},E0(X));let $=k9();return v0.info("request dump enabled"),{command:"openai-dump",text:`## Request Dump Enabled
62
17
 
63
- Dump directory: ${G.dumpDir}
18
+ Dump directory: ${$.dumpDir}
64
19
 
65
- Warning: body dumps may contain prompt/session content. Turn this off after debugging.`,knobs:{enabled:!0}}}if(J[0]==="off")return await G0((G)=>{return G.dump={...G.dump??{},enabled:!1},G},X.accountStoragePath),M8(),d.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 cz(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
20
+ Warning: body dumps may contain prompt/session content. Turn this off after debugging.`,knobs:{enabled:!0}}}if(J[0]==="off")return await B0(($)=>{return $.dump={...$.dump??{},enabled:!1},$},E0(X)),k9(),v0.info("request dump disabled"),{command:"openai-dump",text:"## Request Dump Disabled",knobs:{enabled:!1}};return{command:"openai-dump",text:"Usage: `/openai-dump`, `/openai-dump on`, or `/openai-dump off`.",knobs:{enabled:G}}}async function lK(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(E0(X)))?.logging?.level??"info";return{command:"openai-logging",text:`## Logging
66
21
 
67
22
  - Level: \`${W}\`
68
23
 
69
- Valid levels: ${Q.map((U)=>`\`${U}\``).join(", ")}
24
+ Valid levels: ${Q.map((z)=>`\`${z}\``).join(", ")}
70
25
 
71
- Usage: \`/openai-logging <level>\``,knobs:{level:W}}}let $=J[0];if($&&Q.includes($)){let G=$;return xY(G),await G0((W)=>{return W.logging={...W.logging??{},level:G},W},X.accountStoragePath),d.info("log level changed",{level:G}),{command:"openai-logging",text:`## Logging Updated
26
+ Usage: \`/openai-logging <level>\``,knobs:{level:W}}}let G=J[0];if(G&&Q.includes(G)){let $=G;return n1($),await B0((W)=>{return W.logging={...W.logging??{},level:$},W},E0(X)),v0.info("log level changed",{level:$}),{command:"openai-logging",text:`## Logging Updated
72
27
 
73
- Level set to \`${G}\`.`,knobs:{level:G}}}return{command:"openai-logging",text:`## Invalid Level
28
+ Level set to \`${$}\`.`,knobs:{level:$}}}return{command:"openai-logging",text:`## Invalid Level
74
29
 
75
- Valid levels: ${Q.map((G)=>`\`${G}\``).join(", ")}`,knobs:{level:"info"}}}function uz(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 pz(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
30
+ Valid levels: ${Q.map(($)=>`\`${$}\``).join(", ")}`,knobs:{level:"info"}}}function dK(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 iK(Y,X){let J=X.cacheKeepManager,Q=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),G=await X.loadAccounts(E0(X)),$=G?.cachekeep?.enabled===!0;if(Q.length===0||Q[0]==="status"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
76
31
 
77
- Status: **not available** (manager not wired)`,knobs:{}};let U=J.status(),H=U.window,L=H?`${String(H.startHour).padStart(2,"0")}-${String(H.endHour).padStart(2,"0")}`:"always (no window)",V=["## Cachekeep","",`Status: **${G?"ON":"OFF"}**`,`Timer: **${U.running?"armed":"idle"}**`,`Subagent warming: **${$?.cachekeep?.subagents===!0?"ON":"OFF"}**`,`Idle policy: **sustain ${U.sustain?"ON":"OFF"} (main only)**`,`Window: **${L}**`];if(V.push(`Tracked sessions: **${U.tracked}**`),U.targets.length>0){V.push("");for(let K of U.targets){let N=K.sessionKey.length>12?`${K.sessionKey.slice(0,12)}…`:K.sessionKey,O=Math.ceil((K.cacheExpiresAt-U.generatedAt)/1000);V.push(`- \`${N}\` (${K.accountId??"main"}) — expires in ${O}s`+(K.lastWarmedAt?`, last warm ${Math.ceil((U.generatedAt-K.lastWarmedAt)/1000)}s ago`:"")+(K.backoffUntil&&K.backoffUntil>U.generatedAt?`, backoff ${Math.ceil((K.backoffUntil-U.generatedAt)/1000)}s`:""))}}V.push(""),V.push(`TTL: ${Math.round(U.ttlMs/1000)}s | Lead: ${Math.round(U.leadMs/1000)}s | Max idle warm: ${Math.round(U.maxIdleWarmMs/60000)}min`),V.push(""),V.push("Commands: `/openai-cachekeep on` | `/openai-cachekeep off` | `/openai-cachekeep sustain on` | `/openai-cachekeep sustain off` | `/openai-cachekeep HH-HH` | `/openai-cachekeep window clear` | `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off` | `/openai-cachekeep`");let B=Math.max(0,...U.targets.map((K)=>K.lastWarmedAt??0));return{command:"openai-cachekeep",text:V.join(`
78
- `),knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:U.sustain,window:H,running:U.running,tracked:U.tracked,lastWarmAt:B||void 0,generatedAt:U.generatedAt,maxIdleWarmMs:U.maxIdleWarmMs,maxSubagentIdleMs:U.maxSubagentIdleMs}}}if(Q[0]==="on"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
32
+ Status: **not available** (manager not wired)`,knobs:{}};let z=J.status(),L=z.window,U=L?`${String(L.startHour).padStart(2,"0")}-${String(L.endHour).padStart(2,"0")}`:"always (no window)",H=["## Cachekeep","",`Status: **${$?"ON":"OFF"}**`,`Timer: **${z.running?"armed":"idle"}**`,`Subagent warming: **${G?.cachekeep?.subagents===!0?"ON":"OFF"}**`,`Idle policy: **sustain ${z.sustain?"ON":"OFF"} (main only)**`,`Window: **${U}**`];if(H.push(`Tracked sessions: **${z.tracked}**`),z.targets.length>0){H.push("");for(let V of z.targets){let Z=V.sessionKey.length>12?`${V.sessionKey.slice(0,12)}…`:V.sessionKey,j=Math.ceil((V.cacheExpiresAt-z.generatedAt)/1000);H.push(`- \`${Z}\` (${V.accountId??"main"}) — expires in ${j}s`+(V.lastWarmedAt?`, last warm ${Math.ceil((z.generatedAt-V.lastWarmedAt)/1000)}s ago`:"")+(V.backoffUntil&&V.backoffUntil>z.generatedAt?`, backoff ${Math.ceil((V.backoffUntil-z.generatedAt)/1000)}s`:""))}}H.push(""),H.push(`TTL: ${Math.round(z.ttlMs/1000)}s | Lead: ${Math.round(z.leadMs/1000)}s | Max idle warm: ${Math.round(z.maxIdleWarmMs/60000)}min`),H.push(""),H.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 B=Math.max(0,...z.targets.map((V)=>V.lastWarmedAt??0));return{command:"openai-cachekeep",text:H.join(`
33
+ `),knobs:{enabled:$,subagents:G?.cachekeep?.subagents===!0,sustain:z.sustain,window:L,running:z.running,tracked:z.tracked,lastWarmAt:B||void 0,generatedAt:z.generatedAt,maxIdleWarmMs:z.maxIdleWarmMs,maxSubagentIdleMs:z.maxSubagentIdleMs}}}if(Q[0]==="on"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
79
34
 
80
- Cannot start: manager not wired.`,knobs:{}};await G0((L)=>{return L.cachekeep={...L.cachekeep??{},enabled:!0},L},X.accountStoragePath),d.info("cachekeep enabled"),X.setCacheKeepEnabled?.(!0),J.start();let U=J.status(),H=Math.max(0,...U.targets.map((L)=>L.lastWarmedAt??0));return{command:"openai-cachekeep",text:`## Cachekeep Enabled
35
+ Cannot start: manager not wired.`,knobs:{}};await B0((U)=>{return U.cachekeep={...U.cachekeep??{},enabled:!0},U},E0(X)),v0.info("cachekeep enabled"),X.setCacheKeepEnabled?.(!0),J.start();let z=J.status(),L=Math.max(0,...z.targets.map((U)=>U.lastWarmedAt??0));return{command:"openai-cachekeep",text:`## Cachekeep Enabled
81
36
 
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:H||void 0,generatedAt:U.generatedAt,maxIdleWarmMs:U.maxIdleWarmMs,maxSubagentIdleMs:U.maxSubagentIdleMs}}}if(Q[0]==="off")return await G0((U)=>{return U.cachekeep={...U.cachekeep??{},enabled:!1},U},X.accountStoragePath),d.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 H=U==="on";await G0((V)=>{return V.cachekeep={...V.cachekeep??{},sustain:H},V},X.accountStoragePath),d.info(`cachekeep sustain ${H?"enabled":"disabled"}`),X.setCacheKeepSustain?.(H);let L=J?.status();return{command:"openai-cachekeep",text:H?`## Cachekeep Sustain Enabled
37
+ TTL: ${Math.round(z.ttlMs/1000)}s | Max idle warm ${Math.round(z.maxIdleWarmMs/60000)}min`,knobs:{enabled:!0,subagents:G?.cachekeep?.subagents===!0,sustain:z.sustain,window:z.window,running:z.running,tracked:z.tracked,lastWarmAt:L||void 0,generatedAt:z.generatedAt,maxIdleWarmMs:z.maxIdleWarmMs,maxSubagentIdleMs:z.maxSubagentIdleMs}}}if(Q[0]==="off")return await B0((z)=>{return z.cachekeep={...z.cachekeep??{},enabled:!1},z},E0(X)),v0.info("cachekeep disabled"),X.setCacheKeepEnabled?.(!1),J?.stop(),{command:"openai-cachekeep",text:"## Cachekeep Disabled",knobs:{enabled:!1,sustain:G?.cachekeep?.sustain===!0,running:!1,tracked:0}};if(Q[0]==="sustain"){let z=Q[1];if(Q.length!==2||z!=="on"&&z!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep sustain on` | `/openai-cachekeep sustain off`",knobs:{}};let L=z==="on";await B0((H)=>{return H.cachekeep={...H.cachekeep??{},sustain:L},H},E0(X)),v0.info(`cachekeep sustain ${L?"enabled":"disabled"}`),X.setCacheKeepSustain?.(L);let U=J?.status();return{command:"openai-cachekeep",text:L?`## Cachekeep Sustain Enabled
83
38
 
84
39
  Sustain keeps main-agent sessions warming past the idle cap for this process. Clock windows still apply.
85
40
 
86
41
  Before enabling sustain with Magic Context, set a non-expiring \`cache_ttl\` for models used by main sessions; elapsed-time cold-cache assumptions are no longer valid.`:`## Cachekeep Sustain Disabled
87
42
 
88
- Main-agent sessions again stop warming at the configured idle cap.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:H,window:L?.window,running:L?.running??!1,tracked:L?.tracked??0,generatedAt:L?.generatedAt??Date.now(),maxIdleWarmMs:L?.maxIdleWarmMs??3600000,maxSubagentIdleMs:L?.maxSubagentIdleMs??1800000}}}if(Q[0]==="subagents"){let U=Q[1];if(!U||U!=="on"&&U!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off`",knobs:{}};let H=U==="on";await G0((V)=>{return V.cachekeep={...V.cachekeep??{},subagents:H},V},X.accountStoragePath),d.info(H?"cachekeep subagent warming enabled":"cachekeep subagent warming disabled"),X.setCacheKeepSubagents?.(H);let L=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Subagent Warming
89
-
90
- Subagent warming: **${H?"ON":"OFF"}**`,knobs:{enabled:G,subagents:H,sustain:L?.sustain??$?.cachekeep?.sustain===!0,window:L?.window,running:L?.running??!1,tracked:L?.tracked??0,generatedAt:L?.generatedAt??Date.now(),maxIdleWarmMs:L?.maxIdleWarmMs??3600000,maxSubagentIdleMs:L?.maxSubagentIdleMs??1800000}}}if(Q[0]==="window"){let U=Q[1];if(U==="clear"||U==="off"){await G0((L)=>{if(L.cachekeep)delete L.cachekeep.startHour,delete L.cachekeep.endHour;return L},X.accountStoragePath),X.setCacheKeepWindow?.(void 0),d.info("cachekeep window cleared");let H=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Cleared
91
-
92
- Cachekeep will now warm on every tick (within idle caps).`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:H?.sustain??$?.cachekeep?.sustain===!0,window:void 0,running:H?.running??!1,tracked:H?.tracked??0,generatedAt:H?.generatedAt??Date.now(),maxIdleWarmMs:H?.maxIdleWarmMs??3600000,maxSubagentIdleMs:H?.maxSubagentIdleMs??1800000}}}return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep window clear`",knobs:{}}}let W=Q[0];if(W&&/^\d{1,2}-\d{1,2}$/.test(W)){let U=uz(W);if(!U.ok)return{command:"openai-cachekeep",text:`## Cachekeep Window Invalid
93
-
94
- ${U.reason}`,knobs:{}};let{startHour:H,endHour:L}=U;await G0((K)=>{return K.cachekeep={...K.cachekeep??{},startHour:H,endHour:L},K},X.accountStoragePath),X.setCacheKeepWindow?.({startHour:H,endHour:L}),d.info("cachekeep window set",{startHour:H,endHour:L});let V=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Set
95
-
96
- Warming limited to **${`${String(H).padStart(2,"0")}-${String(L).padStart(2,"0")}`}** local hours.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:V?.sustain??$?.cachekeep?.sustain===!0,window:{startHour:H,endHour:L},running:V?.running??!1,tracked:V?.tracked??0,generatedAt:V?.generatedAt??Date.now(),maxIdleWarmMs:V?.maxIdleWarmMs??3600000,maxSubagentIdleMs:V?.maxSubagentIdleMs??1800000}}}return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep`, `/openai-cachekeep on`, `/openai-cachekeep off`, `/openai-cachekeep sustain on`, `/openai-cachekeep sustain off`, `/openai-cachekeep HH-HH`, `/openai-cachekeep window clear`, `/openai-cachekeep subagents on`, `/openai-cachekeep subagents off`",knobs:{}}}function YJ(Y){let X=[Y.primary?.usedPercent,Y.secondary?.usedPercent].filter((J)=>J!==void 0);return X.length>0?Math.max(...X):void 0}function lz(Y,X){let J=[Y.primary,Y.secondary].filter(($)=>$!==void 0),Q=J.filter(($)=>t1($,X));return(Q.length>0?Q:J).sort(($,G)=>G.usedPercent-$.usedPercent)[0]?.resetsAt}function dz(Y,X){if(!Y)return!1;let J=[Y.primary,Y.secondary].filter((Q)=>Q!==void 0);if(J.length===0)return!1;return J.every((Q)=>!t1(Q,X))}function _8(Y){if(!Y)return;try{return decodeURIComponent(Y)}catch{return}}async function oX(Y,X){try{let J=await X.resolveResetTarget(Y),Q=J.accountKey==="main"?void 0:J.chatgptAccountId,[$,G]=await Promise.all([W1({accessToken:J.accessToken,fetchImpl:X.fetchImpl,now:X.now,accountId:J.chatgptAccountId}),T8(X.fetchImpl,J.accessToken,Q)]),W=bY(G.credits),U=lX(G.credits),H=G.availableCount??$.resetCreditsAvailable??(U>0?U:void 0),L=$.resetCreditsApplicable,V=w8($,X.quotaManager.isRateLimited(Y),X.now()),B;if(!J.chatgptAccountId)B="stable ChatGPT account identity unavailable";else if(!V.ok)B=V.reason;else if(!W)B="no eligible credit";return{accountKey:J.accountKey,label:J.label,chatgptAccountId:J.chatgptAccountId,usedPercent:YJ($),resetTime:lz($,X.now()),availableCount:H,applicableAvailableCount:L,eligible:B===void 0,reason:B,selectedCreditId:W?.id,selectedCreditExpiresAt:W?.expiresAt}}catch(J){return d.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 iz(Y){let X=["## Reset credits","","Select an account to fetch a fresh confirmation preview:",""];for(let J of Y){let Q=J.usedPercent===void 0?"quota unavailable":`${J.usedPercent}% used`,$=J.availableCount===void 0?"credits unavailable":`${J.applicableAvailableCount===void 0?"?":J.applicableAvailableCount}/${J.availableCount} applicable/available`,G=J.eligible?`eligible · credit ${J.selectedCreditId} expires ${J.selectedCreditExpiresAt}`:J.reason;X.push(`- **${J.label}** (\`${J.accountKey}\`) — ${Q}; ${$}; ${G}`)}return X.push(""),X.push("Command: `/openai-reset select <encodedAccountKey>`"),X.join(`
97
- `)}function rX(Y){let X=["## Confirm reset credit","",`Account: **${Y.label}** (\`${Y.accountKey}\`)`,`Current quota: **${Y.usedPercent??"unknown"}% used**`,`Credit: **Spend 1 of ${Y.availableCount??"unknown"}**`,`Credit expires: **${Y.selectedCreditExpiresAt??"unavailable"}**`,`Quota resets: **${Y.resetTime??"unavailable"}**`,""];if((Y.availableCount??0)>0&&Y.applicableAvailableCount===0)X.push("The server does not currently count this credit as applicable; redemption may return a no-op, and a no-op does not spend the credit."),X.push("");if(Y.eligible&&Y.chatgptAccountId)X.push(`Confirm: \`/openai-reset confirm ${encodeURIComponent(Y.accountKey)} ${encodeURIComponent(Y.chatgptAccountId)}\``);else X.push(`Cannot reset: **${Y.reason??"not eligible"}**`);return X.join(`
98
- `)}function R0(Y,X,J,Q={}){return{command:E1,text:J,knobs:{stage:"result",accountKey:Y,code:X,...Q}}}function nz(Y,X,J){if(X instanceof b0){let $={identity_mismatch:"The account identity changed before redemption. Reopen the reset account list.",invalid_account_key:"The selected account key is reserved. Reopen the reset account list.",cooldown_active:"This account just reset — re-checking quota. Wait for the cooldown before another redemption.",expired_unreconciled:"The previous attempt outcome is unknown — retry replays the same identifiers, or wait until quota reflects the earlier attempt.",retry_without_inflight:"There is no active reset redemption to retry. Reopen the account list.",not_exhausted:"No credit was spent: the fresh account state is not exhausted.",no_eligible_credit:"No credit was spent: no eligible credit was returned."};return R0(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 R0(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 P1)return R0(Y,X.kind,`## Reset credit
107
-
108
- No redemption was attempted: reset credit availability could not be loaded.
109
-
110
- Code: \`${X.kind}\``);return d.warn("reset command failed before a known result",{accountKey:Y,error:X?.message??String(X)}),R0(Y,"error",`## Reset credit
111
-
112
- The reset request failed before a known result: internal command failure — see plugin log.`)}async function oz(Y,X,J){let{accountKey:Q}=Y.target,$=Y.outcome.kind;if(Y.finalizeStateWriteFailed)return R0(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(N){W.error=N?.message??String(N)}let U=!W.ok&&W.error!==void 0;if(U)d.warn("reset quota re-check failed",{accountKey:Q,error:W.error});let H=Q==="main"?X.quotaManager.getMain():X.quotaManager.getFallback(Q),L=W.ok&&dz(H?.quota,X.now()),V=H?.quota.resetCreditsApplicable,B=L?"Post-verification: **window fresh**.":`Post-verification: **window not yet refreshed** (server code \`${$}\`).`,K=U?`
117
-
118
- quota re-check failed — see log.`:"";return R0(Q,$,`## Reset credit result
119
-
120
- Account: **${Y.target.label}** (\`${Q}\`)
121
-
122
- Code: \`${$}\`
123
-
124
- ${B}${K}${V===void 0?"":`
125
-
126
- Remaining applicable credits: **${V}**`}`,{verifiedFresh:L,afterUsedPercent:YJ(H?.quota??{}),remainingCredits:V})}if($==="ambiguous_local")return R0(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 R0(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 R0(Q,$,`## Reset credit result
43
+ Main-agent sessions again stop warming at the configured idle cap.`,knobs:{enabled:$,subagents:G?.cachekeep?.subagents===!0,sustain:L,window:U?.window,running:U?.running??!1,tracked:U?.tracked??0,generatedAt:U?.generatedAt??Date.now(),maxIdleWarmMs:U?.maxIdleWarmMs??3600000,maxSubagentIdleMs:U?.maxSubagentIdleMs??1800000}}}if(Q[0]==="subagents"){let z=Q[1];if(!z||z!=="on"&&z!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off`",knobs:{}};let L=z==="on";await B0((H)=>{return H.cachekeep={...H.cachekeep??{},subagents:L},H},E0(X)),v0.info(L?"cachekeep subagent warming enabled":"cachekeep subagent warming disabled"),X.setCacheKeepSubagents?.(L);let U=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Subagent Warming
139
44
 
140
- Account: **${Y.target.label}** (\`${Q}\`)
45
+ Subagent warming: **${L?"ON":"OFF"}**`,knobs:{enabled:$,subagents:L,sustain:U?.sustain??G?.cachekeep?.sustain===!0,window:U?.window,running:U?.running??!1,tracked:U?.tracked??0,generatedAt:U?.generatedAt??Date.now(),maxIdleWarmMs:U?.maxIdleWarmMs??3600000,maxSubagentIdleMs:U?.maxSubagentIdleMs??1800000}}}if(Q[0]==="window"){let z=Q[1];if(z==="clear"||z==="off"){await B0((U)=>{if(U.cachekeep)delete U.cachekeep.startHour,delete U.cachekeep.endHour;return U},E0(X)),X.setCacheKeepWindow?.(void 0),v0.info("cachekeep window cleared");let L=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Cleared
141
46
 
142
- Code: \`${$}\`
47
+ Cachekeep will now warm on every tick (within idle caps).`,knobs:{enabled:$,subagents:G?.cachekeep?.subagents===!0,sustain:L?.sustain??G?.cachekeep?.sustain===!0,window:void 0,running:L?.running??!1,tracked:L?.tracked??0,generatedAt:L?.generatedAt??Date.now(),maxIdleWarmMs:L?.maxIdleWarmMs??3600000,maxSubagentIdleMs:L?.maxSubagentIdleMs??1800000}}}return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep window clear`",knobs:{}}}let W=Q[0];if(W&&/^\d{1,2}-\d{1,2}$/.test(W)){let z=dK(W);if(!z.ok)return{command:"openai-cachekeep",text:`## Cachekeep Window Invalid
143
48
 
144
- ${G[$]??"The server returned a no-op result. No reset was confirmed."}`)}async function rz(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 d.warn("reset command dependencies unwired",{missingDeps:J}),{command:E1,text:`## Reset credit
49
+ ${z.reason}`,knobs:{}};let{startHour:L,endHour:U}=z;await B0((V)=>{return V.cachekeep={...V.cachekeep??{},startHour:L,endHour:U},V},E0(X)),X.setCacheKeepWindow?.({startHour:L,endHour:U}),v0.info("cachekeep window set",{startHour:L,endHour:U});let H=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Set
145
50
 
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((L)=>L.enabled!==!1&&L.type==="oauth").map((L)=>L.id)];d.debug("reset accounts stage requested",{accountKeys:U});let H=await Promise.all(U.map((L)=>oX(L,Q)));return d.debug("reset accounts stage built",{rows:H.map((L)=>({accountKey:L.accountKey,eligible:L.eligible,reason:L.reason,usedPercent:L.usedPercent,availableCount:L.availableCount,applicableAvailableCount:L.applicableAvailableCount}))}),{command:E1,text:iz(H),knobs:{stage:"accounts",accounts:H}}}if(G==="select"){let W=_8($[1]);if(!W||!u0(W)||$.length!==2)return R0("","invalid_command","Usage: `/openai-reset select <encodedAccountKey>`");let U=await oX(W,Q);if(!U.eligible)return R0(W,"not_eligible",rX(U));return{command:E1,text:rX(U),knobs:{stage:"confirm",preview:U}}}if(G==="confirm"||G==="retry"){let W=_8($[1]),U=_8($[2]);if(!W||!u0(W)||!U||$.length!==3)return R0(W??"","invalid_command",`Usage: \`/openai-reset ${G} <encodedAccountKey> <encodedChatgptAccountId>\``);d.info("reset redemption decision",{accountKey:W,action:G}),d.debug("reset redemption identity binding",{accountKey:W,expectedChatgptAccountId:U});try{let H=await dX({configPath:X.accountStoragePath,mutateAccountsFn:G0,loadAccountsFn:X.loadAccounts,now:Q.now,randomUUID:Q.randomUUID,fetchImpl:Q.fetchImpl,resolveTarget:Q.resolveResetTarget,fetchUsage:(L)=>W1({accessToken:L.accessToken,fetchImpl:Q.fetchImpl,now:Q.now,accountId:L.chatgptAccountId}),hasActiveRateLimitMark:(L)=>X.quotaManager.isRateLimited(L)},{accountKey:W,expectedChatgptAccountId:U,retry:G==="retry"});return d.info("reset redemption outcome",{accountKey:W,code:H.outcome.kind}),oz(H,Q,U)}catch(H){let L=nz(W,H,U);return d.info("reset redemption outcome",{accountKey:W,code:L.knobs.code}),L}}return R0("","invalid_command","Usage: `/openai-reset` | `/openai-reset select <encodedAccountKey>` | `/openai-reset confirm <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset retry <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset refresh`")}var sz=new Set(["access","refresh","apikey","authheader","password","secret"]);function az(Y){let X=Y.toLowerCase().replace(/[-_]/g,"");if(sz.has(X))return!0;return X.endsWith("token")}function C8(Y,X,J){if(Array.isArray(Y))return Y.map(($,G)=>C8($,`${X}[${G}]`,J));if(!C(Y))return Y;let Q={};for(let[$,G]of Object.entries(Y)){if(az($)){J.push(`${X}.${$}`);continue}Q[$]=C8(G,`${X}.${$}`,J)}return Q}async function g8(Y,X,J){let Q=await tz(Y,X,J),$=[],G=C8(Q.knobs,"knobs",$);if($.length>0)return d.warn("credential-shaped knob stripped before RPC",{command:Y,fields:$}),{...Q,knobs:G};return Q}async function tz(Y,X,J){switch(Y){case"openai-quota":return hz(J);case"openai-account":return gz(X,J);case"openai-routing":return yz(X,J);case"openai-killswitch":return fz(X,J);case"openai-dump":return mz(X,J);case"openai-logging":return cz(X,J);case"openai-cachekeep":return pz(X,J);case"openai-reset":return rz(X,J);default:throw Error(`unhandled command: ${Y}`)}}var y8=N0("quota");function ez(Y){return Y?.status===401}async function h1(Y,X={}){let J=Y.whamFn;if(!J)throw Error("whamFn is required for refreshAllQuota");let Q=[],$=Y.logger??y8,G=(N)=>{Q.push(N);let O={pid:process.pid,accountId:N.account,status:N.ok?"ok":"error",...N.error?{error:N.error}:{}};if(N.ok)$.debug("quota refresh succeeded",O);else $.warn("quota refresh failed",O)},W=Y.skipFresherThanMs,U=!1,H;if(W!==void 0)try{H=await(Y.readSidebarState??A1)()}catch{}let L=new Map(H?.fallbacks.map((N)=>[N.id,N])??[]),V=(...N)=>W!==void 0&&N.some((O)=>typeof O==="number"&&Number.isFinite(O)&&O<=Y.now()&&Y.now()-O<W),B=await Y.loadAccounts(Y.configPath).catch(()=>{return}),K=B?.mainAccountId??Y.storageMainAccountId;if(!X.accountKey||X.accountKey==="main")try{let N=await Y.getAuth();if(N.type==="oauth"){let O=H&&K!==void 0&&H.main.mainAccountId===K?H.main.quota:void 0;if(V(Y.quotaManager.peekMainForPolicy(K)?.checkedAt,O?.primary?.checkedAt,O?.secondary?.checkedAt,O?.checkedAt))G({account:"main",ok:!0});else{if(!N.access||(N.expires??0)<Y.now()){let A=await Y.refreshMainWithLease();N={...N,access:A.access,expires:A.expires}}if(N.access)if(Y.respectBackoff&&Y.quotaManager.isBackedOff())G({account:"main",ok:!0});else{let A=await J({accessToken:N.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:K,accountKey:"main"});Y.quotaManager.setMain(N.access,{quota:A,refreshAfter:Y.now()+300000,checkedAt:Y.now()},K,!0),U=!0,G({account:"main",ok:!0})}else G({account:"main",ok:!1,error:"no access token"})}}else G({account:"main",ok:!1,error:"auth type is not oauth"})}catch(N){G({account:"main",ok:!1,error:t0(N)})}if(B)for(let N of B.accounts){if(X.accountKey&&(X.accountKey==="main"||N.id!==X.accountKey))continue;if(N.enabled===!1||!Y.isOAuthAccountFn(N)){if(X.accountKey)G({account:N.id,ok:!1,error:"account is not an enabled OAuth fallback"});continue}try{let O=L.get(N.id),j=N.accountId,A=O&&j!==void 0&&O.accountId===j?O.quota:void 0;if(V(Y.quotaManager.peekFallbackForPolicy(N.id,j)?.checkedAt,A?.primary?.checkedAt,A?.secondary?.checkedAt,A?.checkedAt)){G({account:N.id,ok:!0});continue}if(Y.respectBackoff&&Y.quotaManager.isFallbackBackedOff(N.id,N.access)){G({account:N.id,ok:!0});continue}let x=N.lastRefreshError;if(vY(x,N.refresh,Y.now())){G({account:N.id,ok:!1,error:hY(x,Y.now()),permanent:!0});continue}let E;try{E=await Y.fallbackManager.refreshAccount(N,B)}catch(y){y8.warn("fallback token refresh failed during quota poll",{pid:process.pid,accountId:N.id,error:t0(y)}),E=N}if(!E.access||(E.expires??0)<Y.now()){G({account:N.id,ok:!1,error:"no usable access token"});continue}let k;try{k=await J({accessToken:E.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:E.accountId,accountKey:N.id})}catch(y){if(!ez(y))throw y;if(y8.warn("quota endpoint rejected the token; forcing a refresh",{pid:process.pid,accountId:N.id}),E=await Y.fallbackManager.refreshAccount(N,B,{force:!0}),!E.access){G({account:N.id,ok:!1,error:"no usable access token after forced refresh"});continue}k=await J({accessToken:E.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:E.accountId,accountKey:N.id})}Y.quotaManager.setFallback(N.id,{quota:k,refreshAfter:Y.now()+300000,checkedAt:Y.now()},E.access,!0,E.accountId),U=!0,G({account:N.id,ok:!0})}catch(O){G({account:N.id,ok:!1,error:t0(O)})}}if(X.accountKey&&X.accountKey!=="main"&&!Q.some((N)=>N.account===X.accountKey))Q.push({account:X.accountKey,ok:!1,error:"account not found"});if(W===void 0||U){let N=await Y.loadAccounts(Y.configPath);await Y.writeSidebarState(Y.quotaManager,N)}return Q}var YU=300000,XU=30000,JU=240000,QU="bg-quota-refresh",$U=120000;function GU(Y,X){return gY({name:QU,ttlMs:$U,path:Y,renew:!0,...X})}function XJ(Y,X=h1,J=()=>GU(Y.configPath)){return WU(Y,X,J)}async function WU(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:JU})}finally{await Q?.release().catch(()=>{})}}class f8{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)*XU);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=$},YU+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 m8(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 c8(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 yY(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"),m8(Y.body))X.set("x-openai-internal-codex-responses-lite","true");return{...Y,headers:X,body:c8(Y.body)}}function WJ(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 zJ(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 JJ(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 zU=300000,UJ=1800000,QJ=2*UJ+900000,UU=3600000,$J=1800000,GJ=60000,LU=32,HU=8388608,u8=600000;function LJ(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 NU(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 VU(Y,X){return LJ(Y)?UJ:X}function p8(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function HJ(Y){if(!Y||typeof Y!=="object")return p8();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 ZU(Y){try{let X=JSON.parse(Y);return HJ(X.usage)}catch{return p8()}}function KU(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),H=U.type??W;if(H!=="response.completed"&&H!=="response.done")return;let L=U.response;Q=HJ(L?.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??p8()}class l8{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??zU,this.tickIntervalMs=Y.tickIntervalMs??GJ,this.leadMs=Y.leadMs??this.tickIntervalMs+15000;let X=Y.maxIdleWarmMs??Y.maxDurationMs;this.maxIdleWarmMs=typeof X==="number"&&Number.isFinite(X)&&X>0?X:UU;let J=Y.maxSubagentIdleMs??$J;this.maxSubagentIdleMs=typeof J==="number"&&Number.isFinite(J)&&J>0?J:$J,this.tickIntervalMs=Y.tickIntervalMs??GJ,this.maxTargets=Y.maxTargets??LU,this.maxBytes=Y.maxBytes??HU,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&&!JJ(U,new Date(this.now()))){this.log.debug("cachekeep track skipped (outside window)",this.logPayload({sessionKey:Y,startHour:U.startHour,endHour:U.endHour}));return}if(this.targets.has(Y)){let V=this.targets.get(Y);if(V)this.totalBytes-=V.bodyText.length;this.targets.delete(Y)}else this.log.debug("cachekeep captured target",this.logPayload({sessionKey:Y,accountId:J}));while(this.targets.size>=this.maxTargets||this.totalBytes+W>this.maxBytes&&this.targets.size>0){let V,B=Number.POSITIVE_INFINITY;for(let[N,O]of this.targets){let j=Math.max(O.lastRealRequestAt,O.lastWarmedAt??0);if(j<B)V=N,B=j}if(V===void 0)break;let K=this.targets.get(V);if(K)this.totalBytes-=K.bodyText.length;this.targets.delete(V)}let H=VU(X,this.ttlMs),L={bodyText:X,accountId:J||void 0,chatgptAccountId:Q,route:"main",ttlMs:H,cacheExpiresAt:this.now()+H,warmCount:0,lastRealRequestAt:this.now(),replayHeaders:$,isSubagent:G,is56:LJ(X)};this.targets.set(Y,L),this.totalBytes+=W,this.start()}isGpt56Subagent(Y){return Y.isSubagent===!0&&Y.is56}pruneStale(){let Y=this.now(),X=Y-this.maxIdleWarmMs,J=Y-this.maxSubagentIdleMs,Q=Y-QJ;for(let[$,G]of this.targets){let W,U;if(this.isGpt56Subagent(G))W=Q,U=QJ;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&&!JJ(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()+u8;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 $=NU(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=yY({method:"POST",headers:Q,body:$,signal:AbortSignal.any([AbortSignal.timeout(30000),this.abortController.signal])}),U=await this.fetchImpl(this.codexResponsesUrl,W),H="";try{H=await U.text()}catch{}if(this.disposed||this.targets.get(Y)!==X)return;if(!U.ok){X.backoffUntil=this.now()+u8,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",status:U.status,error:`HTTP ${U.status}`,responseBody:H.slice(0,600)}));return}let L=U.headers.get("content-type")??"",V=L.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(H.slice(0,200));this.log.debug("cachekeep warm response",this.logPayload({status:U.status,contentType:L,bodyLen:H.length,isSse:V}));let B=V?KU(H):ZU(H),K=g1(U.headers),N=K.primary?.usedPercent??null,O=K.secondary?.usedPercent??null;if(this.log.debug("cachekeep fired",this.logPayload({session:Y,accountId:X.accountId??"main",input_tokens:B.input_tokens,cached_tokens:B.cached_tokens,hit_rate:B.hit_rate,output_tokens:B.output_tokens,quota_primary_pct:N,quota_secondary_pct:O})),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()+u8,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",error:$ instanceof Error?$.message:String($)}))}}}var ZJ=900000,BU=0.016666666666666666,NJ=0.000001;function i8(Y,X){for(let J of[Y?.primary?.checkedAt,Y?.checkedAt,X])if(typeof J==="number"&&Number.isFinite(J))return J;return}function n8(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let X=i8(Y.quota,Y.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||Y.now-X>ZJ)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let J=d8(Y.quota).sort((Q,$)=>{let G=Q.windowMs,W=$.windowMs,U=typeof G==="number"&&Number.isFinite(G),H=typeof W==="number"&&Number.isFinite(W);if(U!==H)return U?-1:1;if(U&&H)return W-G;return 0});for(let{key:Q,window:$}of J)if(Number.isFinite($.remainingPercent)&&$.remainingPercent<=0)return{action:"migrate",reason:"exhausted",windowKey:Q,...typeof $.resetsAt==="string"?{resetsAt:$.resetsAt}:{}};if(Y.status===void 0||Y.status===0||!Number.isFinite(Y.status)||Y.status>=500&&Y.status<=599||Y.status===429)return{action:"retain",reason:"transient"};return{action:"retain",reason:"healthy"}}function OU(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,BU);return Q/G}function VJ(Y,X){if(Y<X)return-1;if(Y>X)return 1;return 0}function FU(Y,X){if(!Y.quota)return;let J=i8(Y.quota,Y.quotaCheckedAt);if(J===void 0||X-J>ZJ)return;let Q=d8(Y.quota).map(({key:G,window:W})=>{return OU(W,Y.reservePercent[G]??0,X)}),$=Q.length>0?Math.min(...Q):0;return $>0?{candidate:Y,quotaCheckedAt:J,weight:$}:void 0}function KJ(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(($)=>FU($,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,NJ),H=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,NJ);return U-H||G.candidate.configuredOrder-W.candidate.configuredOrder||VJ(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||VJ($.accountId,G.accountId)})[0];if(!Q)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Q.accountId,quotaCheckedAt:i8(Q.quota,Q.quotaCheckedAt),source:"mode-fallback"}}import{createHash as qU}from"node:crypto";import{chmod as jU,mkdir as DU,readdir as PU,readFile as MU,writeFile as o8}from"node:fs/promises";import{join as qJ}from"node:path";var t8=N0("dump"),z1="x-cortexkit-openai-auth-dump-session",EU=["http","prewarm","main"],BJ=0,y1=new Map,AU=100;function r8(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function jJ(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 DJ(Y){return qU("sha256").update(Y).digest("hex")}function s8(Y){return DJ(JSON.stringify(Y))}function PJ(Y){try{let X=JSON.parse(Y);return X!=null&&typeof X==="object"&&!Array.isArray(X)?X:void 0}catch{return}}function wU(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 TU(Y,X){if(!y1.has(Y))while(y1.size>=AU){let J=y1.keys().next().value;if(J===void 0)break;y1.delete(J)}y1.set(Y,X)}var OJ=new Set;async function RU(Y,X,J){let Q=jJ(X),$=EU.map((G)=>`-${Q}-${J}-${G}.body.json`);try{let W=(await PU(Y)).filter((U)=>$.some((H)=>U.endsWith(H))).sort().pop();if(!W)return;return await MU(qJ(Y,W),"utf8")}catch{return}}function _U(Y){if(Y===void 0)return;return Object.fromEntries(new Headers(Y).entries())}function e8(Y){if(Array.isArray(Y))return Y.map(e8);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]=e8(Q)}return X}function CU(Y){let X=PJ(Y);if(X===void 0)return Y;let J=IU(X),Q=JSON.stringify(J);if(Q===void 0)return Y;return JSON.stringify(X)===Q?Y:Q}function IU(Y){if(!C(Y))return a8(Y);let X={};for(let[J,Q]of Object.entries(Y))X[J]=J==="tools"?FJ(Q):a8({[J]:Q})[J];return X}function SU(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function kU(Y){let X=PJ(Y);if(!X)return{parseable:!1};let J=Array.isArray(X.input)?X.input:[],Q=Array.isArray(X.tools)?X.tools:[],$=Q.map(SU),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:s8(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:s8(J[0]),toolsCount:Q.length,toolTypes:$,toolsHash:s8(Q),hasWebSearch:$.includes("web_search"),clientMetadataKeys:G?Object.keys(G).sort():[]}}async function f1(Y){let X=E0();if(!X.dump)return;BJ++;let J=Y.sessionID?.trim()||"session-unknown",Q=`${new Date().toISOString().replace(/[:.]/g,"-")}-${process.pid}-${String(BJ).padStart(5,"0")}-${jJ(J)}-${Y.transport}-${Y.phase}`,$=qJ(X.dumpDir,Q),G={body:`${$}.body.json`,metadata:`${$}.meta.json`,request:`${$}.request.json`},W=`${Y.transport}:${J}`,U=y1.get(W),H=U?"memory":void 0;if(U===void 0&&!OJ.has(W)){if(OJ.add(W),U=await RU(X.dumpDir,J,Y.transport),U!==void 0)H="disk"}try{await DU(X.dumpDir,{recursive:!0,mode:448}),await jU(X.dumpDir,448).catch(()=>{});let L=CU(Y.bodyText),V={id:Q,createdAt:new Date().toISOString(),session:r8(J),transport:Y.transport,phase:Y.phase,accountId:Y.accountId,status:Y.status,error:Y.error,bodyBytes:Y.bodyText.length,bodyHash:DJ(Y.bodyText),diff:wU(U,L),baselineSource:H,body:kU(Y.bodyText),files:G};await Promise.all([o8(G.body,L,{encoding:"utf8",mode:384}),o8(G.metadata,`${JSON.stringify(V,null,2)}
148
- `,{encoding:"utf8",mode:384}),o8(G.request,`${JSON.stringify(e8({url:Y.url,method:Y.method,accountId:Y.accountId,headers:_U(Y.headers)}),null,2)}
149
- `,{encoding:"utf8",mode:384})]),t8.debug("dumped request",{id:Q,session:r8(J),body:G.body,meta:G.metadata}),TU(W,L)}catch(L){t8.warn("request dump failed",{session:r8(J),error:L instanceof Error?L.message:String(L)})}}async function e0(Y){if(!E0().dump)return;t8.debug("diagnostic",Y)}import{tool as e1}from"@opencode-ai/plugin";var fY="ws_",AJ=new Map,wJ=e1({description:"Provider-executed OpenAI web search. This tool is handled server-side by OpenAI; the local plugin records the hosted action for deterministic replay.",args:{type:e1.schema.string().optional(),query:e1.schema.string().optional(),queries:e1.schema.array(e1.schema.string()).optional()},async execute(Y){return{title:"OpenAI Web Search",output:JSON.stringify({action:Y}),metadata:{action:Y}}}});function X9(Y){if(bU(Y))return;if(!vU(Y))return Y;let X=Y.item;return AJ.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 TJ(Y){if(!Y.body)return Y;if(!(Y.headers.get("content-type")??"").includes("text/event-stream"))return Y;return new Response(xU(Y.body),{status:Y.status,statusText:Y.statusText,headers:Y.headers})}function RJ(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(fY)){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(hU(W)){J.set(W.call_id,W),X=!0;continue}if(gU(W,J)){Q.push(Y9(W.call_id,W.output,J.get(W.call_id))),X=!0;continue}if(yU(W)){let U=AJ.get(W.id);if(U)Q.push(Y9(W.id,U));else{let H=$.get(W.id),L=G.get(W.id);if(H||L)Q.push(Y9(W.id,L,H));else Q.push(W)}X=!0;continue}Q.push(W)}if(X)Y.input=Q;return X}function bU(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 xU(Y){let X=new TextDecoder,J=new TextEncoder,Q="";return Y.pipeThrough(new TransformStream({transform($,G){Q+=X.decode($,{stream:!0});let W=MJ(Q);while(W){let U=Q.slice(0,W.index);Q=Q.slice(W.index+W.length);let H=EJ(U);if(H)G.enqueue(J.encode(H));W=MJ(Q)}},flush($){if(Q+=X.decode(),!Q)return;let G=EJ(Q);if(G)$.enqueue(J.encode(G))}}))}function MJ(Y){let X=Y.indexOf(`
51
+ Warming limited to **${`${String(L).padStart(2,"0")}-${String(U).padStart(2,"0")}`}** local hours.`,knobs:{enabled:$,subagents:G?.cachekeep?.subagents===!0,sustain:H?.sustain??G?.cachekeep?.sustain===!0,window:{startHour:L,endHour:U},running:H?.running??!1,tracked:H?.tracked??0,generatedAt:H?.generatedAt??Date.now(),maxIdleWarmMs:H?.maxIdleWarmMs??3600000,maxSubagentIdleMs:H?.maxSubagentIdleMs??1800000}}}return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep`, `/openai-cachekeep on`, `/openai-cachekeep off`, `/openai-cachekeep sustain on`, `/openai-cachekeep sustain off`, `/openai-cachekeep HH-HH`, `/openai-cachekeep window clear`, `/openai-cachekeep subagents on`, `/openai-cachekeep subagents off`",knobs:{}}}var oK={"openai-killswitch":uK,"openai-dump":pK,"openai-logging":lK,"openai-cachekeep":iK};function v9(Y,X,J){return b9(Y,X,J,oK)}var nK=300000,rK=30000,sK=240000,aK="bg-quota-refresh",tK=120000;function eK(Y,X){return r1({name:aK,ttlMs:tK,path:Y,renew:!0,...X})}function $J(Y,X=UY,J=()=>eK(Y.paths.configPath)){return Yz(Y,X,J)}async function Yz(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:sK})}finally{await Q?.release().catch(()=>{})}}class h9{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)*rK);if(this.timer=this.setIntervalFn(()=>{let Q=this.run;if(this.stopped||!Q||this.tickPromise)return;let G=Q().catch(($)=>{try{this.onError?.($)}catch{}}).finally(()=>{if(this.tickPromise===G)this.tickPromise=void 0});this.tickPromise=G},nK+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 g9(Y){if(typeof Y!=="string")return!1;try{let X=JSON.parse(Y);return k(X)&&k(X.client_metadata)&&X.client_metadata.ws_request_header_x_openai_internal_codex_responses_lite==="true"}catch{return!1}}function y9(Y){if(typeof Y!=="string")return Y;try{let X=JSON.parse(Y);if(!k(X)||!k(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 s1(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"),g9(Y.body))X.set("x-openai-internal-codex-responses-lite","true");return{...Y,headers:X,body:y9(Y.body)}}function LJ(Y){if(!Y.enabled||typeof Y.body!=="string")return;let X=Y.headers.has("x-parent-session-id");if(X&&!Y.includeSubagents)return;let J=Y.headers.get("session-id")??Y.headers.get("x-opencode-session")??Y.headers.get("x-session-affinity")??void 0;if(!J)return;let Q={};for(let G of["session-id","x-session-affinity","x-parent-session-id","user-agent","version","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-client-request-id","thread-id","x-openai-internal-codex-responses-lite"]){let $=Y.headers.get(G);if($)Q[G]=$}return{sessionKey:J,bodyText:Y.body,replayHeaders:Q,isSubagent:X}}function HJ(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 WJ(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 Xz=300000,NJ=1800000,KJ=2*NJ+900000,Jz=3600000,zJ=1800000,UJ=60000,Qz=32,Gz=8388608,f9=600000;function ZJ(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 $z(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 Wz(Y,X){return ZJ(Y)?NJ:X}function m9(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function VJ(Y){if(!Y||typeof Y!=="object")return m9();let X=Y,J=Number(X.input_tokens)||Number(X.prompt_tokens)||0,Q=Number(X.output_tokens)||Number(X.completion_tokens)||0,G=X.input_tokens_details??X.prompt_tokens_details,$=Number(G?.cached_tokens)||Number(X.cached_tokens)||0,W=J>0?$/J:null;return{input_tokens:J,output_tokens:Q,cached_tokens:$,hit_rate:W}}function Kz(Y){try{let X=JSON.parse(Y);return VJ(X.usage)}catch{return m9()}}function zz(Y){let X,J=[],Q,G=()=>{if(!J.length)return;let $=J.join(`
52
+ `).trim();J=[];let W=X;if(X=void 0,!$||$==="[DONE]")return;try{let z=JSON.parse($),L=z.type??W;if(L!=="response.completed"&&L!=="response.done")return;let U=z.response;Q=VJ(U?.usage??z.usage)}catch{}};for(let $ of Y.split(/\r?\n/)){if($===""){G();continue}if($.startsWith("event:")){X=$.slice(6).trim();continue}if($.startsWith("data:"))J.push($.slice(5).trim())}return G(),Q??m9()}class c9{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??Xz,this.tickIntervalMs=Y.tickIntervalMs??UJ,this.leadMs=Y.leadMs??this.tickIntervalMs+15000;let X=Y.maxIdleWarmMs??Y.maxDurationMs;this.maxIdleWarmMs=typeof X==="number"&&Number.isFinite(X)&&X>0?X:Jz;let J=Y.maxSubagentIdleMs??zJ;this.maxSubagentIdleMs=typeof J==="number"&&Number.isFinite(J)&&J>0?J:zJ,this.tickIntervalMs=Y.tickIntervalMs??UJ,this.maxTargets=Y.maxTargets??Qz,this.maxBytes=Y.maxBytes??Gz,this.getWindow=Y.getWindow,this.getSustain=Y.getSustain}track(Y,X,J,Q,G={},$=!1){this.pruneStale();let W=X.length;if(W>this.maxBytes){this.log.debug("cachekeep track skipped (body exceeds maxBytes)",this.logPayload({sessionKey:Y,bodyBytes:W,maxBytes:this.maxBytes}));return}let z=this.getWindow?.();if(z&&!WJ(z,new Date(this.now()))){this.log.debug("cachekeep track skipped (outside window)",this.logPayload({sessionKey:Y,startHour:z.startHour,endHour:z.endHour}));return}if(this.targets.has(Y)){let H=this.targets.get(Y);if(H)this.totalBytes-=H.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 H,B=Number.POSITIVE_INFINITY;for(let[Z,j]of this.targets){let O=Math.max(j.lastRealRequestAt,j.lastWarmedAt??0);if(O<B)H=Z,B=O}if(H===void 0)break;let V=this.targets.get(H);if(V)this.totalBytes-=V.bodyText.length;this.targets.delete(H)}let L=Wz(X,this.ttlMs),U={bodyText:X,accountId:J||void 0,chatgptAccountId:Q,route:"main",ttlMs:L,cacheExpiresAt:this.now()+L,warmCount:0,lastRealRequestAt:this.now(),replayHeaders:G,isSubagent:$,is56:ZJ(X)};this.targets.set(Y,U),this.totalBytes+=W,this.start()}isGpt56Subagent(Y){return Y.isSubagent===!0&&Y.is56}pruneStale(){let Y=this.now(),X=Y-this.maxIdleWarmMs,J=Y-this.maxSubagentIdleMs,Q=Y-KJ;for(let[G,$]of this.targets){let W,z;if(this.isGpt56Subagent($))W=Q,z=KJ;else W=$.isSubagent?J:X,z=$.isSubagent?this.maxSubagentIdleMs:this.maxIdleWarmMs;if(!($.isSubagent!==!0&&this.getSustain?.()===!0)&&$.lastRealRequestAt<W)this.log.debug("cachekeep pruned idle target",this.logPayload({sessionKey:G,accountId:$.accountId??"main",lastRealRequestAt:$.lastRealRequestAt,maxIdleWarmMs:z})),this.totalBytes-=$.bodyText.length,this.targets.delete(G)}}start(){if(this.disposed=!1,this.timer)return;if(this.startedAt=this.now(),this.log.debug("cachekeep started",this.logPayload({ttlMs:this.ttlMs,leadMs:this.leadMs,maxIdleWarmMs:this.maxIdleWarmMs})),this.timer=setInterval(()=>{this.tick().catch(()=>{})},this.tickIntervalMs),"unref"in this.timer)this.timer.unref()}stop(){if(this.disposed=!0,this.abortController.abort(),this.abortController=new AbortController,this.timer)clearInterval(this.timer),this.timer=null;this.startedAt=null,this.targets.clear(),this.totalBytes=0,this.log.debug("cachekeep stopped",this.logPayload())}remove(Y){let X=this.targets.get(Y);if(X)this.totalBytes-=X.bodyText.length,this.targets.delete(Y),this.log.debug("cachekeep removed target",this.logPayload({sessionKey:Y}))}status(){let Y=this.now(),X=Array.from(this.targets.entries()).map(([J,Q])=>({sessionKey:J,accountId:Q.accountId,route:Q.route,cacheExpiresAt:Q.cacheExpiresAt,lastRealRequestAt:Q.lastRealRequestAt,lastWarmedAt:Q.lastWarmedAt,backoffUntil:Q.backoffUntil,bodyBytes:Q.bodyText.length}));return{running:this.timer!=null,tracked:this.targets.size,generatedAt:Y,startedAt:this.startedAt,maxIdleWarmMs:this.maxIdleWarmMs,maxSubagentIdleMs:this.maxSubagentIdleMs,ttlMs:this.ttlMs,leadMs:this.leadMs,sustain:this.getSustain?.()===!0,window:this.getWindow?.(),targets:X}}async tick(){if(this.tickInFlight)return;this.tickInFlight=!0;try{this.pruneStale();let Y=this.getWindow?.();if(Y&&!WJ(Y,new Date(this.now())))return;let X=this.now(),J=X+this.leadMs;for(let[Q,G]of this.targets)if(G.backoffUntil&&X>=G.backoffUntil&&G.cacheExpiresAt<=J)await this.prewarm(Q,G);for(let[Q,G]of this.targets){if(G.backoffUntil&&X<G.backoffUntil)continue;if(G.cacheExpiresAt<=J)await this.prewarm(Q,G)}}finally{this.tickInFlight=!1}}async prewarm(Y,X){let J;try{if(X.accountId&&X.accountId!=="main")J=await this.refreshFallback(X.accountId);else J=await this.getMainToken()}catch(G){if(!this.disposed&&this.targets.get(Y)===X)X.backoffUntil=this.now()+f9;this.log.debug("cachekeep skip (no token)",this.logPayload({sessionKey:Y,accountId:X.accountId??"main",error:G instanceof Error?G.message:String(G)}));return}if(this.disposed||this.targets.get(Y)!==X)return;let Q={...X.replayHeaders,authorization:`Bearer ${J}`,"content-type":"application/json"};if(X.chatgptAccountId)Q["ChatGPT-Account-Id"]=X.chatgptAccountId;else delete Q["ChatGPT-Account-Id"];try{let G=$z(X.bodyText),$;try{let O=JSON.parse(G);$={warmBodyKeys:Object.keys(O),stream:O.stream,max_output_tokens:O.max_output_tokens,store:O.store,has_stream_options:"stream_options"in O,has_max_tokens:"max_tokens"in O,model:O.model}}catch{}this.log.debug("cachekeep warm request",this.logPayload({...$,headerKeys:Object.keys(Q),hasChatGptAccountId:"ChatGPT-Account-Id"in Q}));let W=s1({method:"POST",headers:Q,body:G,signal:AbortSignal.any([AbortSignal.timeout(30000),this.abortController.signal])}),z=await this.fetchImpl(this.codexResponsesUrl,W),L="";try{L=await z.text()}catch{}if(this.disposed||this.targets.get(Y)!==X)return;if(!z.ok){X.backoffUntil=this.now()+f9,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",status:z.status,error:`HTTP ${z.status}`,responseBody:L.slice(0,600)}));return}let U=z.headers.get("content-type")??"",H=U.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(L.slice(0,200));this.log.debug("cachekeep warm response",this.logPayload({status:z.status,contentType:U,bodyLen:L.length,isSse:H}));let B=H?zz(L):Kz(L),V=hY(z.headers),Z=V.primary?.usedPercent??null,j=V.secondary?.usedPercent??null;if(this.log.debug("cachekeep fired",this.logPayload({session:Y,accountId:X.accountId??"main",input_tokens:B.input_tokens,cached_tokens:B.cached_tokens,hit_rate:B.hit_rate,output_tokens:B.output_tokens,quota_primary_pct:Z,quota_secondary_pct:j})),X.cacheExpiresAt=this.now()+X.ttlMs,X.lastWarmedAt=this.now(),X.backoffUntil=void 0,X.warmCount+=1,this.isGpt56Subagent(X)&&X.warmCount>=2){if(this.targets.get(Y)===X)this.totalBytes-=X.bodyText.length,this.targets.delete(Y);return}}catch(G){if(this.disposed||this.targets.get(Y)!==X)return;X.backoffUntil=this.now()+f9,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",error:G instanceof Error?G.message:String(G)}))}}}var OJ=900000,Uz=0.016666666666666666,BJ=0.000001;function p9(Y,X){for(let J of[Y?.primary?.checkedAt,Y?.checkedAt,X])if(typeof J==="number"&&Number.isFinite(J))return J;return}function l9(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let X=p9(Y.quota,Y.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||Y.now-X>OJ)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let J=u9(Y.quota).sort((Q,G)=>{let $=Q.windowMs,W=G.windowMs,z=typeof $==="number"&&Number.isFinite($),L=typeof W==="number"&&Number.isFinite(W);if(z!==L)return z?-1:1;if(z&&L)return W-$;return 0});for(let{key:Q,window:G}of J)if(Number.isFinite(G.remainingPercent)&&G.remainingPercent<=0)return{action:"migrate",reason:"exhausted",windowKey:Q,...typeof G.resetsAt==="string"?{resetsAt:G.resetsAt}:{}};if(Y.status===void 0||Y.status===0||!Number.isFinite(Y.status)||Y.status>=500&&Y.status<=599||Y.status===429)return{action:"retain",reason:"transient"};return{action:"retain",reason:"healthy"}}function Lz(Y,X,J){let Q=Math.max(0,Y.remainingPercent-X);if(Q<=0)return 0;if(!Y.resetsAt)return Q;let G=Date.parse(Y.resetsAt);if(!Number.isFinite(G)||G<=J)return Q;let $=Math.max((G-J)/3600000,Uz);return Q/$}function FJ(Y,X){if(Y<X)return-1;if(Y>X)return 1;return 0}function Hz(Y,X){if(!Y.quota)return;let J=p9(Y.quota,Y.quotaCheckedAt);if(J===void 0||X-J>OJ)return;let Q=u9(Y.quota).map(({key:$,window:W})=>{return Lz(W,Y.reservePercent[$]??0,X)}),G=Q.length>0?Math.min(...Q):0;return G>0?{candidate:Y,quotaCheckedAt:J,weight:G}:void 0}function qJ(Y){let X=Y.candidates.filter((G)=>G.killswitchPasses!==!1);if(Y.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if(X.length===0)return;let J=X.map((G)=>Hz(G,Y.now)).filter((G)=>G!==void 0);if(J.length>0){J.sort(($,W)=>{let z=((Y.pendingBytes.get($.candidate.accountId)??0)+Y.requestBytes)/Math.max($.weight,BJ),L=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,BJ);return z-L||$.candidate.configuredOrder-W.candidate.configuredOrder||FJ($.candidate.accountId,W.candidate.accountId)});let G=J[0];if(G)return{accountId:G.candidate.accountId,quotaCheckedAt:G.quotaCheckedAt,source:"weighted"}}Y.onEmptyWeightedSet?.();let Q=[...X].sort((G,$)=>{let W=(G.resetCreditsApplicable??0)>0?1:0;return(($.resetCreditsApplicable??0)>0?1:0)-W||G.configuredOrder-$.configuredOrder||FJ(G.accountId,$.accountId)})[0];if(!Q)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Q.accountId,quotaCheckedAt:p9(Q.quota,Q.quotaCheckedAt),source:"mode-fallback"}}import{createHash as Nz}from"node:crypto";import{chmod as Zz,mkdir as Vz,readdir as Bz,readFile as Fz,writeFile as d9}from"node:fs/promises";import{join as MJ}from"node:path";var r9=D0("dump"),LY="x-cortexkit-openai-auth-dump-session",Oz=["http","prewarm","main"],jJ=0,gY=new Map,qz=100;function i9(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function EJ(Y){let X=Y.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!X)return"session-unknown";return X.length<=80?X:X.slice(0,80)}function wJ(Y){return Nz("sha256").update(Y).digest("hex")}function o9(Y){return wJ(JSON.stringify(Y))}function AJ(Y){try{let X=JSON.parse(Y);return X!=null&&typeof X==="object"&&!Array.isArray(X)?X:void 0}catch{return}}function jz(Y,X){if(Y===void 0)return null;if(Y===X)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:Y.length,currentBytes:X.length};let J=0;while(J<Y.length&&J<X.length&&Y[J]===X[J])J++;let Q=Y.length-1,G=X.length-1;while(Q>=J&&G>=J&&Y[Q]===X[G])Q--,G--;return{changed:!0,firstByte:J,lastPreviousByte:Q,lastCurrentByte:G,changedPreviousBytes:Q-J+1,changedCurrentBytes:G-J+1,previousBytes:Y.length,currentBytes:X.length}}function Dz(Y,X){if(!gY.has(Y))while(gY.size>=qz){let J=gY.keys().next().value;if(J===void 0)break;gY.delete(J)}gY.set(Y,X)}var DJ=new Set;async function Pz(Y,X,J){let Q=EJ(X),G=Oz.map(($)=>`-${Q}-${J}-${$}.body.json`);try{let W=(await Bz(Y)).filter((z)=>G.some((L)=>z.endsWith(L))).sort().pop();if(!W)return;return await Fz(MJ(Y,W),"utf8")}catch{return}}function Mz(Y){if(Y===void 0)return;return Object.fromEntries(new Headers(Y).entries())}function s9(Y){if(Array.isArray(Y))return Y.map(s9);if(Y==null||typeof Y!=="object")return Y;let X={};for(let[J,Q]of Object.entries(Y)){let G=J.toLowerCase();if(G==="authorization"||G==="chatgpt-account-id"||G==="cookie"||G==="set-cookie"){X[J]="[redacted]";continue}X[J]=s9(Q)}return X}function Ez(Y){let X=AJ(Y);if(X===void 0)return Y;let J=wz(X),Q=JSON.stringify(J);if(Q===void 0)return Y;return JSON.stringify(X)===Q?Y:Q}function wz(Y){if(!k(Y))return n9(Y);let X={};for(let[J,Q]of Object.entries(Y))X[J]=J==="tools"?PJ(Q):n9({[J]:Q})[J];return X}function Az(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function Tz(Y){let X=AJ(Y);if(!X)return{parseable:!1};let J=Array.isArray(X.input)?X.input:[],Q=Array.isArray(X.tools)?X.tools:[],G=Q.map(Az),$=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:o9(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:o9(J[0]),toolsCount:Q.length,toolTypes:G,toolsHash:o9(Q),hasWebSearch:G.includes("web_search"),clientMetadataKeys:$?Object.keys($).sort():[]}}async function yY(Y){let X=C0();if(!X.dump)return;jJ++;let J=Y.sessionID?.trim()||"session-unknown",Q=`${new Date().toISOString().replace(/[:.]/g,"-")}-${process.pid}-${String(jJ).padStart(5,"0")}-${EJ(J)}-${Y.transport}-${Y.phase}`,G=MJ(X.dumpDir,Q),$={body:`${G}.body.json`,metadata:`${G}.meta.json`,request:`${G}.request.json`},W=`${Y.transport}:${J}`,z=gY.get(W),L=z?"memory":void 0;if(z===void 0&&!DJ.has(W)){if(DJ.add(W),z=await Pz(X.dumpDir,J,Y.transport),z!==void 0)L="disk"}try{await Vz(X.dumpDir,{recursive:!0,mode:448}),await Zz(X.dumpDir,448).catch(()=>{});let U=Ez(Y.bodyText),H={id:Q,createdAt:new Date().toISOString(),session:i9(J),transport:Y.transport,phase:Y.phase,accountId:Y.accountId,status:Y.status,error:Y.error,bodyBytes:Y.bodyText.length,bodyHash:wJ(Y.bodyText),diff:jz(z,U),baselineSource:L,body:Tz(Y.bodyText),files:$};await Promise.all([d9($.body,U,{encoding:"utf8",mode:384}),d9($.metadata,`${JSON.stringify(H,null,2)}
53
+ `,{encoding:"utf8",mode:384}),d9($.request,`${JSON.stringify(s9({url:Y.url,method:Y.method,accountId:Y.accountId,headers:Mz(Y.headers)}),null,2)}
54
+ `,{encoding:"utf8",mode:384})]),r9.debug("dumped request",{id:Q,session:i9(J),body:$.body,meta:$.metadata}),Dz(W,U)}catch(U){r9.warn("request dump failed",{session:i9(J),error:U instanceof Error?U.message:String(U)})}}async function e0(Y){if(!C0().dump)return;r9.debug("diagnostic",Y)}import{tool as K1}from"@opencode-ai/plugin";var a1="ws_",CJ=new Map,IJ=K1({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:K1.schema.string().optional(),query:K1.schema.string().optional(),queries:K1.schema.array(K1.schema.string()).optional()},async execute(Y){return{title:"OpenAI Web Search",output:JSON.stringify({action:Y}),metadata:{action:Y}}}});function t9(Y){if(Rz(Y))return;if(!Iz(Y))return Y;let X=Y.item;return CJ.set(X.id,X),{...Y,item:{type:"function_call",id:X.id,call_id:X.id,name:"web_search",arguments:JSON.stringify(k(X.action)?X.action:{})}}}function _J(Y){if(!Y.body)return Y;if(!(Y.headers.get("content-type")??"").includes("text/event-stream"))return Y;return new Response(Cz(Y.body),{status:Y.status,statusText:Y.statusText,headers:Y.headers})}function SJ(Y){if(!Array.isArray(Y.input))return!1;let X=!1,J=new Map,Q=[],G=new Map,$=new Map;for(let W of Y.input)if(k(W)&&typeof W.call_id==="string"&&W.call_id.startsWith(a1)){if(W.type==="function_call")G.set(W.call_id,W);else if(W.type==="function_call_output"&&typeof W.output==="string")$.set(W.call_id,W.output)}for(let W of Y.input){if(_z(W)){J.set(W.call_id,W),X=!0;continue}if(Sz(W,J)){Q.push(a9(W.call_id,W.output,J.get(W.call_id))),X=!0;continue}if(kz(W)){let z=CJ.get(W.id);if(z)Q.push(a9(W.id,z));else{let L=G.get(W.id),U=$.get(W.id);if(L||U)Q.push(a9(W.id,U,L));else Q.push(W)}X=!0;continue}Q.push(W)}if(X)Y.input=Q;return X}function Rz(Y){if(typeof Y.type==="string"&&Y.type.startsWith("response.web_search_call."))return!0;return Y.type==="response.output_item.added"&&k(Y.item)&&Y.item.type==="web_search_call"}function Cz(Y){let X=new TextDecoder,J=new TextEncoder,Q="";return Y.pipeThrough(new TransformStream({transform(G,$){Q+=X.decode(G,{stream:!0});let W=TJ(Q);while(W){let z=Q.slice(0,W.index);Q=Q.slice(W.index+W.length);let L=RJ(z);if(L)$.enqueue(J.encode(L));W=TJ(Q)}},flush(G){if(Q+=X.decode(),!Q)return;let $=RJ(Q);if($)G.enqueue(J.encode($))}}))}function TJ(Y){let X=Y.indexOf(`
150
55
 
151
56
  `),J=Y.indexOf(`\r
152
57
  \r
153
- `);if(X===-1)return J===-1?void 0:{index:J,length:4};if(J===-1||X<J)return{index:X,length:2};return{index:J,length:4}}function EJ(Y){let X=Y.split(/\r?\n/).filter((J)=>J.startsWith("data:")).map((J)=>J.slice(5).trimStart()).join(`
58
+ `);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 RJ(Y){let X=Y.split(/\r?\n/).filter((J)=>J.startsWith("data:")).map((J)=>J.slice(5).trimStart()).join(`
154
59
  `);if(!X)return`${Y}
155
60
 
156
61
  `;if(X==="[DONE]")return`data: [DONE]
157
62
 
158
- `;try{let J=JSON.parse(X);if(!C(J))return`${Y}
63
+ `;try{let J=JSON.parse(X);if(!k(J))return`${Y}
159
64
 
160
- `;let Q=X9(J);if(!Q)return"";return`data: ${JSON.stringify(Q)}
65
+ `;let Q=t9(J);if(!Q)return"";return`data: ${JSON.stringify(Q)}
161
66
 
162
67
  `}catch{return`${Y}
163
68
 
164
- `}}function vU(Y){return Y.type==="response.output_item.done"&&C(Y.item)&&Y.item.type==="web_search_call"&&typeof Y.item.id==="string"}function hU(Y){return C(Y)&&Y.type==="function_call"&&Y.name==="web_search"&&typeof Y.call_id==="string"&&Y.call_id.startsWith(fY)}function gU(Y,X){return C(Y)&&Y.type==="function_call_output"&&typeof Y.call_id==="string"&&typeof Y.output==="string"&&Y.call_id.startsWith(fY)&&X.has(Y.call_id)}function yU(Y){return C(Y)&&Y.type==="item_reference"&&typeof Y.id==="string"&&Y.id.startsWith(fY)}function Y9(Y,X,J){let Q=fU(X),$=C(Q?.action)?Q.action:mU(J?.arguments);return{type:"web_search_call",status:"completed",...$?{action:$}:{}}}function fU(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 mU(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 cU}from"node:fs/promises";import{homedir as uU}from"node:os";import{join as _J}from"node:path";var pU="https://models.dev/api.json",lU="OPENCODE_OPENAI_AUTH_MODELS_CACHE",dU="OPENCODE_MODELS_PATH",iU="OPENCODE_DISABLE_MODELS_FETCH",nU=1e4,oU=300000;function U1(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function CJ(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function J9(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=CJ(Y.cache_read),$=CJ(Y.cache_write);if(Q===null||$===null)return null;return{input:X,output:J,cache:{read:Q,write:$}}}function rU(Y){let X=U1(Y);if(!X)return null;let J=J9(X);if(!J)return null;let Q=J;if(Array.isArray(X.tiers)){let W=[];for(let U of X.tiers){let H=U1(U);if(!H)continue;let L=U1(H.tier),V=L?.size;if(L?.type!=="context")continue;if(typeof V!=="number"||!Number.isFinite(V)||V<=0)continue;let B=J9(H);if(!B)continue;W.push({...B,tier:{type:"context",size:V}})}if(W.length>0)Q.tiers=W}let $=U1(X.context_over_200k),G=$?J9($):null;if(G)Q.experimentalOver200K=G;return Q}function IJ(Y){let X=U1(Y),J=U1(X?.openai),Q=U1(J?.models);if(!Q)return null;let $={};for(let[G,W]of Object.entries(Q)){let U=U1(W),H=rU(U?.cost);if(H)$[G]=H}return Object.keys($).length>0?$:null}function sU(){let Y=process.env[lU]?.trim();if(Y)return Y;let X=process.env[dU]?.trim();if(X)return X;let J=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||_J(uU(),".cache");return _J(J,"opencode","models.json")}function aU(){let Y=process.env[iU]?.toLowerCase();return Y==="true"||Y==="1"}async function tU(){try{let Y=IJ(JSON.parse(await cU(sU(),"utf8")));if(Y)return Y}catch{}if(aU())return null;try{let Y=await fetch(pU,{signal:AbortSignal.timeout(nU)});if(!Y.ok)return null;return IJ(await Y.json())}catch{return null}}var m1;function SJ(){let Y=Date.now();if(m1&&m1.expiresAt>Y)return m1.promise;let X={expiresAt:Y+oU,promise:tU()};return m1=X,X.promise.then((J)=>{if(J===null&&m1===X)m1=void 0}),X.promise}function c1(Y){return typeof Y==="object"&&Y!==null}function eU(Y){if(Array.isArray(Y))return Y;if(c1(Y)&&Array.isArray(Y.data))return Y.data;return[]}function YL(Y){if(!c1(Y)||!c1(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function kJ(Y){if(!c1(Y)||!c1(Y.info))return null;let X=Y.info,J=c1(X.model)?X.model:void 0,Q=typeof X.agent==="string"?X.agent:void 0,$=typeof J?.providerID==="string"?J.providerID:typeof X.providerID==="string"?X.providerID:void 0,G=typeof J?.modelID==="string"?J.modelID:typeof X.modelID==="string"?X.modelID:void 0,W=typeof J?.variant==="string"?J.variant:typeof X.variant==="string"?X.variant:void 0;if(!Q&&(!$||!G)&&!W)return null;let U={};if(Q)U.agent=Q;if($&&G)U.model={providerID:$,modelID:G};if(W)U.variant=W;return U}function bJ(Y,X){return{agent:Y.agent??X.agent,model:Y.model??X.model,variant:Y.variant??X.variant}}function xJ(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function vJ(Y,X){if(!Y||!X)return null;let J=Y;if(typeof J.session?.messages!=="function")return null;let Q=[];try{Q=eU(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(YL(Q[G])!=="assistant")continue;let W=kJ(Q[G]);if(!W)continue;if($=bJ($,W),xJ($))return $}for(let G=Q.length-1;G>=0;G--){let W=kJ(Q[G]);if(!W)continue;if($=bJ($,W),xJ($))return $}if(!$.agent&&!$.model&&!$.variant)return null;return $}var L1=[],XL=1,Q9=0,hJ=new Map;function $9(Y,X){if(L1.push({id:XL++,type:"open-dialog",payload:Y,sessionId:X}),L1.length>100)L1=L1.slice(L1.length-100)}function gJ(Y=0,X){let J=Date.now();if(Q9=J,X!==void 0)hJ.set(X,J);let Q=($)=>X===void 0||$.sessionId===void 0||$.sessionId===X;if(Y>0)L1=L1.filter(($)=>{if($.id>Y)return!0;if(X===void 0)return!1;return $.sessionId!==X});return L1.filter(($)=>$.id>Y&&Q($))}function yJ(Y){let X=Date.now();if(Y!==void 0){let J=hJ.get(Y)??0;return J>0&&X-J<3000}return Q9>0&&X-Q9<3000}import{randomBytes as JL,timingSafeEqual as QL}from"node:crypto";import{unlink as $L}from"node:fs/promises";import{createServer as GL}from"node:http";import{join as WL}from"node:path";var fJ=N0("rpc");function zL(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 UL(Y,X){if(!Y?.startsWith("Bearer "))return!1;let J=Buffer.from(Y.slice(7)),Q=Buffer.from(X);return J.length===Q.length&&QL(J,Q)}async function uJ(Y){let X=JL(32).toString("hex"),J=Y.timeoutMs??90000,Q=Y.receiptTimeoutMs??2000,$=GL((U,H)=>{U.setTimeout(J,()=>{U.socket.destroy()}),G(U,H)});$.requestTimeout=Q,$.headersTimeout=Q;async function G(U,H){let L=(V,B)=>{if(H.headersSent||H.writableEnded||H.destroyed)return;H.writeHead(V,{"content-type":"application/json"}),H.end(JSON.stringify(B))};try{let V=U.url??"";if(U.method==="GET"&&V==="/health")return L(200,{ok:!0});if(U.method!=="POST"||!V.startsWith("/rpc/"))return L(404,{error:"not found"});if(!UL(U.headers.authorization,X))return L(401,{error:"unauthorized"});let B=V.slice(5),K=await zL(U),N=JSON.parse(K||"{}");if(B==="pending-notifications"){let O=Y.drain(Number(N.lastReceivedId??0),typeof N.sessionId==="string"?N.sessionId:void 0);return L(200,{messages:O})}if(B==="apply"){let O=await Y.apply(N);return L(200,O)}return L(404,{error:"unknown method"})}catch(V){L(500,{error:V instanceof Error?V.message:String(V)})}}let W=await new Promise((U,H)=>{$.on("error",H),$.listen(0,"127.0.0.1",()=>{let L=$.address();if(L&&typeof L==="object")U(L.port);else H(Error("no port"))})});if($.unref(),Y.sweepRoot)try{await cJ(Y.sweepRoot,Y.dir)}catch(U){fJ.warn("rpc state sweep failed",{pid:process.pid,error:U instanceof Error?U.message:String(U)})}try{await mJ(Y.dir,{port:W,token:X,pid:process.pid},{secureDir:Y.secureDir}),fJ.debug("rpc server pid",{pid:process.pid,rpcPort:W})}catch(U){throw await new Promise((H)=>$.close(()=>H())),U}return{port:W,token:X,async stop(){await new Promise((U)=>$.close(()=>U())),await $L(WL(Y.dir,`port-${process.pid}.json`)).catch(()=>{})}}}function Y1(Y){return JSON.stringify(G9(Y))??"undefined"}function G9(Y){if(Array.isArray(Y))return Y.map(G9);if(!C(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((X)=>[X,G9(Y[X])]))}function w1(){let Y=crypto.getRandomValues(new Uint8Array(16)),X=Date.now();Y[0]=X/1099511627776&255,Y[1]=X/4294967296&255,Y[2]=X/16777216&255,Y[3]=X/65536&255,Y[4]=X/256&255,Y[5]=X&255,Y[6]=(Y[6]??0)&15|112,Y[8]=(Y[8]??0)&63|128;let J=Array.from(Y,(Q)=>Q.toString(16).padStart(2,"0")).join("");return`${J.slice(0,8)}-${J.slice(8,12)}-${J.slice(12,16)}-${J.slice(16,20)}-${J.slice(20)}`}var F1={};U9(F1,{withoutInternalHeaders:()=>D4,sanitizeHttpFallbackBody:()=>c8,orderCodexBody:()=>qY,hasWebSocketResponsesLiteMetadata:()=>m8,createWebSocketFetch:()=>HZ,applyTurnId:()=>O4,advanceTurn:()=>GX,TITLE_HEADER:()=>$X,QUOTA_ACCOUNT_HEADER:()=>Z8,OpenAIWebSocketPool:()=>F1,CODEX_BODY_KEY_ORDER:()=>K4});import{createHash as GZ}from"node:crypto";var jQ="vercel.ai.error",LL=Symbol.for(jQ),pJ,lJ,D=class Y extends(lJ=Error,pJ=LL,lJ){constructor({name:X,message:J,cause:Q}){super(J);this[pJ]=!0,this.name=X,this.cause=Q}static isInstance(X){return Y.hasMarker(X,jQ)}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}},DQ="AI_APICallError",PQ=`vercel.ai.error.${DQ}`,HL=Symbol.for(PQ),dJ,iJ,YY=class extends(iJ=D,dJ=HL,iJ){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:H}){super({name:DQ,message:Y,cause:W});this[dJ]=!0,this.url=X,this.requestBodyValues=J,this.statusCode=Q,this.responseHeaders=$,this.responseBody=G,this.isRetryable=U,this.data=H}static isInstance(Y){return D.hasMarker(Y,PQ)}},MQ="AI_EmptyResponseBodyError",EQ=`vercel.ai.error.${MQ}`,NL=Symbol.for(EQ),nJ,oJ,VL=class extends(oJ=D,nJ=NL,oJ){constructor({message:Y="Empty response body"}={}){super({name:MQ,message:Y});this[nJ]=!0}static isInstance(Y){return D.hasMarker(Y,EQ)}};function T1(Y){if(Y==null)return"unknown error";if(typeof Y==="string")return Y;if(Y instanceof Error)return Y.toString();return JSON.stringify(Y)}var AQ="AI_InvalidArgumentError",wQ=`vercel.ai.error.${AQ}`,ZL=Symbol.for(wQ),rJ,sJ,TQ=class extends(sJ=D,rJ=ZL,sJ){constructor({message:Y,cause:X,argument:J}){super({name:AQ,message:Y,cause:X});this[rJ]=!0,this.argument=J}static isInstance(Y){return D.hasMarker(Y,wQ)}},RQ="AI_InvalidPromptError",_Q=`vercel.ai.error.${RQ}`,KL=Symbol.for(_Q),aJ,tJ,BL=class extends(tJ=D,aJ=KL,tJ){constructor({prompt:Y,message:X,cause:J}){super({name:RQ,message:`Invalid prompt: ${X}`,cause:J});this[aJ]=!0,this.prompt=Y}static isInstance(Y){return D.hasMarker(Y,_Q)}},CQ="AI_InvalidResponseDataError",IQ=`vercel.ai.error.${CQ}`,OL=Symbol.for(IQ),eJ,YQ,FL=class extends(YQ=D,eJ=OL,YQ){constructor({data:Y,message:X=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:CQ,message:X});this[eJ]=!0,this.data=Y}static isInstance(Y){return D.hasMarker(Y,IQ)}},SQ="AI_JSONParseError",kQ=`vercel.ai.error.${SQ}`,qL=Symbol.for(kQ),XQ,JQ,mY=class extends(JQ=D,XQ=qL,JQ){constructor({text:Y,cause:X}){super({name:SQ,message:`JSON parsing failed: Text: ${Y}.
165
- Error message: ${T1(X)}`,cause:X});this[XQ]=!0,this.text=Y}static isInstance(Y){return D.hasMarker(Y,kQ)}},bQ="AI_LoadAPIKeyError",xQ=`vercel.ai.error.${bQ}`,jL=Symbol.for(xQ),QQ,$Q,DL=class extends($Q=D,QQ=jL,$Q){constructor({message:Y}){super({name:bQ,message:Y});this[QQ]=!0}static isInstance(Y){return D.hasMarker(Y,xQ)}},vQ="AI_LoadSettingError",hQ=`vercel.ai.error.${vQ}`,PL=Symbol.for(hQ),GQ,WQ,ML=class extends(WQ=D,GQ=PL,WQ){constructor({message:Y}){super({name:vQ,message:Y});this[GQ]=!0}static isInstance(Y){return D.hasMarker(Y,hQ)}},gQ="AI_NoContentGeneratedError",yQ=`vercel.ai.error.${gQ}`,EL=Symbol.for(yQ),zQ,UQ,AL=class extends(UQ=D,zQ=EL,UQ){constructor({message:Y="No content generated."}={}){super({name:gQ,message:Y});this[zQ]=!0}static isInstance(Y){return D.hasMarker(Y,yQ)}},fQ="AI_NoSuchModelError",mQ=`vercel.ai.error.${fQ}`,wL=Symbol.for(mQ),LQ,HQ,W9=class extends(HQ=D,LQ=wL,HQ){constructor({errorName:Y=fQ,modelId:X,modelType:J,message:Q=`No such ${J}: ${X}`}){super({name:Y,message:Q});this[LQ]=!0,this.modelId=X,this.modelType=J}static isInstance(Y){return D.hasMarker(Y,mQ)}},cQ="AI_NoSuchProviderReferenceError",uQ=`vercel.ai.error.${cQ}`,TL=Symbol.for(uQ),NQ,VQ,RL=class extends(VQ=D,NQ=TL,VQ){constructor({provider:Y,reference:X,message:J=`No provider reference found for provider '${Y}'. Available providers: ${Object.keys(X).join(", ")}`}){super({name:cQ,message:J});this[NQ]=!0,this.provider=Y,this.reference=X}static isInstance(Y){return D.hasMarker(Y,uQ)}},pQ="AI_TooManyEmbeddingValuesForCallError",lQ=`vercel.ai.error.${pQ}`,_L=Symbol.for(lQ),ZQ,KQ,CL=class extends(KQ=D,ZQ=_L,KQ){constructor(Y){super({name:pQ,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[ZQ]=!0,this.provider=Y.provider,this.modelId=Y.modelId,this.maxEmbeddingsPerCall=Y.maxEmbeddingsPerCall,this.values=Y.values}static isInstance(Y){return D.hasMarker(Y,lQ)}},dQ="AI_TypeValidationError",iQ=`vercel.ai.error.${dQ}`,IL=Symbol.for(iQ),BQ,OQ,p0=class Y extends(OQ=D,BQ=IL,OQ){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:dQ,message:`${$}: Value: ${JSON.stringify(X)}.
166
- Error message: ${T1(J)}`,cause:J});this[BQ]=!0,this.value=X,this.context=Q}static isInstance(X){return D.hasMarker(X,iQ)}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})}},nQ="AI_UnsupportedFunctionalityError",oQ=`vercel.ai.error.${nQ}`,SL=Symbol.for(oQ),FQ,qQ,kL=class extends(qQ=D,FQ=SL,qQ){constructor({functionality:Y,message:X=`'${Y}' functionality not supported.`}){super({name:nQ,message:X});this[FQ]=!0,this.functionality=Y}static isInstance(Y){return D.hasMarker(Y,oQ)}};var SB=Object.freeze({status:"aborted"});function q(Y,X,J){function Q(U,H){var L;Object.defineProperty(U,"_zod",{value:U._zod??{},enumerable:!1}),(L=U._zod).traits??(L.traits=new Set),U._zod.traits.add(Y),X(U,H);for(let V in W.prototype)if(!(V in U))Object.defineProperty(U,V,{value:W.prototype[V].bind(U)});U._zod.constr=W,U._zod.def=H}let $=J?.Parent??Object;class G extends ${}Object.defineProperty(G,"name",{value:Y});function W(U){var H;let L=J?.Parent?new G:this;Q(L,U),(H=L._zod).deferred??(H.deferred=[]);for(let V of L._zod.deferred)V();return L}return Object.defineProperty(W,"init",{value:Q}),Object.defineProperty(W,Symbol.hasInstance,{value:(U)=>{if(J?.Parent&&U instanceof J.Parent)return!0;return U?._zod?.traits?.has(Y)}}),Object.defineProperty(W,"name",{value:Y}),W}var kB=Symbol("zod_brand");class X1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class XY extends Error{constructor(Y){super(`Encountered unidirectional transform during encode: ${Y}`);this.name="ZodEncodeError"}}var cY={};function l0(Y){if(Y)Object.assign(cY,Y);return cY}var m={};U9(m,{unwrapMessage:()=>JY,uint8ArrayToHex:()=>$H,uint8ArrayToBase64url:()=>JH,uint8ArrayToBase64:()=>J$,stringifyPrimitive:()=>tQ,shallowClone:()=>sQ,safeExtend:()=>sL,required:()=>eL,randomString:()=>pL,propertyKeyTypes:()=>N9,promiseAllObject:()=>uL,primitiveTypes:()=>aQ,prefixIssues:()=>Q1,pick:()=>nL,partial:()=>tL,optionalKeys:()=>V9,omit:()=>oL,objectClone:()=>fL,numKeys:()=>lL,nullish:()=>$Y,normalizeParams:()=>g,mergeDefs:()=>N1,merge:()=>aL,jsonStringifyReplacer:()=>u1,joinValues:()=>yL,issue:()=>l1,isPlainObject:()=>V1,isObject:()=>R1,hexToUint8Array:()=>QH,getSizableOrigin:()=>Y$,getParsedType:()=>dL,getLengthableOrigin:()=>WY,getEnumValues:()=>QY,getElementAtPath:()=>cL,floatSafeRemainder:()=>L9,finalizeIssue:()=>v0,extend:()=>rL,escapeRegex:()=>J1,esc:()=>uY,defineLazy:()=>p,createTransparentProxy:()=>iL,cloneDef:()=>mL,clone:()=>x0,cleanRegex:()=>GY,cleanEnum:()=>YH,captureStackTrace:()=>pY,cached:()=>p1,base64urlToUint8Array:()=>XH,base64ToUint8Array:()=>X$,assignProp:()=>H1,assertNotEqual:()=>xL,assertNever:()=>hL,assertIs:()=>vL,assertEqual:()=>bL,assert:()=>gL,allowsEval:()=>H9,aborted:()=>Z1,NUMBER_FORMAT_RANGES:()=>Z9,Class:()=>Q$,BIGINT_FORMAT_RANGES:()=>eQ});function bL(Y){return Y}function xL(Y){return Y}function vL(Y){}function hL(Y){throw Error()}function gL(Y){}function QY(Y){let X=Object.values(Y).filter((Q)=>typeof Q==="number");return Object.entries(Y).filter(([Q,$])=>X.indexOf(+Q)===-1).map(([Q,$])=>$)}function yL(Y,X="|"){return Y.map((J)=>tQ(J)).join(X)}function u1(Y,X){if(typeof X==="bigint")return X.toString();return X}function p1(Y){return{get value(){{let J=Y();return Object.defineProperty(this,"value",{value:J}),J}throw Error("cached value already set")}}}function $Y(Y){return Y===null||Y===void 0}function GY(Y){let X=Y.startsWith("^")?1:0,J=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(X,J)}function L9(Y,X){let J=(Y.toString().split(".")[1]||"").length,Q=X.toString(),$=(Q.split(".")[1]||"").length;if($===0&&/\d?e-\d?/.test(Q)){let H=Q.match(/\d?e-(\d?)/);if(H?.[1])$=Number.parseInt(H[1])}let G=J>$?J:$,W=Number.parseInt(Y.toFixed(G).replace(".","")),U=Number.parseInt(X.toFixed(G).replace(".",""));return W%U/10**G}var rQ=Symbol("evaluating");function p(Y,X,J){let Q=void 0;Object.defineProperty(Y,X,{get(){if(Q===rQ)return;if(Q===void 0)Q=rQ,Q=J();return Q},set($){Object.defineProperty(Y,X,{value:$})},configurable:!0})}function fL(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function H1(Y,X,J){Object.defineProperty(Y,X,{value:J,writable:!0,enumerable:!0,configurable:!0})}function N1(...Y){let X={};for(let J of Y){let Q=Object.getOwnPropertyDescriptors(J);Object.assign(X,Q)}return Object.defineProperties({},X)}function mL(Y){return N1(Y._zod.def)}function cL(Y,X){if(!X)return Y;return X.reduce((J,Q)=>J?.[Q],Y)}function uL(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 pL(Y=10){let J="";for(let Q=0;Q<Y;Q++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function uY(Y){return JSON.stringify(Y)}var pY="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function R1(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var H9=p1(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function V1(Y){if(R1(Y)===!1)return!1;let X=Y.constructor;if(X===void 0)return!0;let J=X.prototype;if(R1(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function sQ(Y){if(V1(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function lL(Y){let X=0;for(let J in Y)if(Object.prototype.hasOwnProperty.call(Y,J))X++;return X}var dL=(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}`)}},N9=new Set(["string","number","symbol"]),aQ=new Set(["string","number","bigint","boolean","symbol","undefined"]);function J1(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function x0(Y,X,J){let Q=new Y._zod.constr(X??Y._zod.def);if(!X||J?.parent)Q._zod.parent=Y;return Q}function g(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 iL(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 tQ(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function V9(Y){return Object.keys(Y).filter((X)=>{return Y[X]._zod.optin==="optional"&&Y[X]._zod.optout==="optional"})}var Z9={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]},eQ={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function nL(Y,X){let J=Y._zod.def,Q=N1(Y._zod.def,{get shape(){let $={};for(let G in X){if(!(G in J.shape))throw Error(`Unrecognized key: "${G}"`);if(!X[G])continue;$[G]=J.shape[G]}return H1(this,"shape",$),$},checks:[]});return x0(Y,Q)}function oL(Y,X){let J=Y._zod.def,Q=N1(Y._zod.def,{get shape(){let $={...Y._zod.def.shape};for(let G in X){if(!(G in J.shape))throw Error(`Unrecognized key: "${G}"`);if(!X[G])continue;delete $[G]}return H1(this,"shape",$),$},checks:[]});return x0(Y,Q)}function rL(Y,X){if(!V1(X))throw Error("Invalid input to extend: expected a plain object");let J=Y._zod.def.checks;if(J&&J.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let $=N1(Y._zod.def,{get shape(){let G={...Y._zod.def.shape,...X};return H1(this,"shape",G),G},checks:[]});return x0(Y,$)}function sL(Y,X){if(!V1(X))throw Error("Invalid input to safeExtend: expected a plain object");let J={...Y._zod.def,get shape(){let Q={...Y._zod.def.shape,...X};return H1(this,"shape",Q),Q},checks:Y._zod.def.checks};return x0(Y,J)}function aL(Y,X){let J=N1(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape,...X._zod.def.shape};return H1(this,"shape",Q),Q},get catchall(){return X._zod.def.catchall},checks:[]});return x0(Y,J)}function tL(Y,X,J){let Q=N1(X._zod.def,{get shape(){let $=X._zod.def.shape,G={...$};if(J)for(let W in J){if(!(W in $))throw Error(`Unrecognized key: "${W}"`);if(!J[W])continue;G[W]=Y?new Y({type:"optional",innerType:$[W]}):$[W]}else for(let W in $)G[W]=Y?new Y({type:"optional",innerType:$[W]}):$[W];return H1(this,"shape",G),G},checks:[]});return x0(X,Q)}function eL(Y,X,J){let Q=N1(X._zod.def,{get shape(){let $=X._zod.def.shape,G={...$};if(J)for(let W in J){if(!(W in G))throw Error(`Unrecognized key: "${W}"`);if(!J[W])continue;G[W]=new Y({type:"nonoptional",innerType:$[W]})}else for(let W in $)G[W]=new Y({type:"nonoptional",innerType:$[W]});return H1(this,"shape",G),G},checks:[]});return x0(X,Q)}function Z1(Y,X=0){if(Y.aborted===!0)return!0;for(let J=X;J<Y.issues.length;J++)if(Y.issues[J]?.continue!==!0)return!0;return!1}function Q1(Y,X){return X.map((J)=>{var Q;return(Q=J).path??(Q.path=[]),J.path.unshift(Y),J})}function JY(Y){return typeof Y==="string"?Y:Y?.message}function v0(Y,X,J){let Q={...Y,path:Y.path??[]};if(!Y.message){let $=JY(Y.inst?._zod.def?.error?.(Y))??JY(X?.error?.(Y))??JY(J.customError?.(Y))??JY(J.localeError?.(Y))??"Invalid input";Q.message=$}if(delete Q.inst,delete Q.continue,!X?.reportInput)delete Q.input;return Q}function Y$(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function WY(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function l1(...Y){let[X,J,Q]=Y;if(typeof X==="string")return{message:X,code:"custom",input:J,inst:Q};return{...X}}function YH(Y){return Object.entries(Y).filter(([X,J])=>{return Number.isNaN(Number.parseInt(X,10))}).map((X)=>X[1])}function X$(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 J$(Y){let X="";for(let J=0;J<Y.length;J++)X+=String.fromCharCode(Y[J]);return btoa(X)}function XH(Y){let X=Y.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-X.length%4)%4);return X$(X+J)}function JH(Y){return J$(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function QH(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 $H(Y){return Array.from(Y).map((X)=>X.toString(16).padStart(2,"0")).join("")}class Q${constructor(...Y){}}var $$=(Y,X)=>{Y.name="$ZodError",Object.defineProperty(Y,"_zod",{value:Y._zod,enumerable:!1}),Object.defineProperty(Y,"issues",{value:X,enumerable:!1}),Y.message=JSON.stringify(X,u1,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},lY=q("$ZodError",$$),K9=q("$ZodError",$$,{Parent:Error});function G$(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 W$(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,H=0;while(H<W.path.length){let L=W.path[H];if(H!==W.path.length-1)U[L]=U[L]||{_errors:[]};else U[L]=U[L]||{_errors:[]},U[L]._errors.push(J(W));U=U[L],H++}}};return $(Y),Q}var dY=(Y)=>(X,J,Q,$)=>{let G=Q?Object.assign(Q,{async:!1}):{async:!1},W=X._zod.run({value:J,issues:[]},G);if(W instanceof Promise)throw new X1;if(W.issues.length){let U=new($?.Err??Y)(W.issues.map((H)=>v0(H,G,l0())));throw pY(U,$?.callee),U}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 U=new($?.Err??Y)(W.issues.map((H)=>v0(H,G,l0())));throw pY(U,$?.callee),U}return W.value};var zY=(Y)=>(X,J,Q)=>{let $=Q?{...Q,async:!1}:{async:!1},G=X._zod.run({value:J,issues:[]},$);if(G instanceof Promise)throw new X1;return G.issues.length?{success:!1,error:new(Y??lY)(G.issues.map((W)=>v0(W,$,l0())))}:{success:!0,data:G.value}},z$=zY(K9),UY=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{async:!0}):{async:!0},G=X._zod.run({value:J,issues:[]},$);if(G instanceof Promise)G=await G;return G.issues.length?{success:!1,error:new Y(G.issues.map((W)=>v0(W,$,l0())))}:{success:!0,data:G.value}},U$=UY(K9),L$=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return dY(Y)(X,J,$)};var H$=(Y)=>(X,J,Q)=>{return dY(Y)(X,J,Q)};var N$=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return iY(Y)(X,J,$)};var V$=(Y)=>async(X,J,Q)=>{return iY(Y)(X,J,Q)};var Z$=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return zY(Y)(X,J,$)};var K$=(Y)=>(X,J,Q)=>{return zY(Y)(X,J,Q)};var B$=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return UY(Y)(X,J,$)};var O$=(Y)=>async(X,J,Q)=>{return UY(Y)(X,J,Q)};var F$=/^[cC][^\s-]{8,}$/,q$=/^[0-9a-z]+$/,j$=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,D$=/^[0-9a-vA-V]{20}$/,P$=/^[A-Za-z0-9]{27}$/,M$=/^[a-zA-Z0-9_-]{21}$/,E$=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var A$=/^([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})$/,B9=(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 w$=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function T$(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var R$=/^(?:(?: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-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}|:))$/,C$=/^((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])$/,I$=/^(([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])$/,S$=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,O9=/^[A-Za-z0-9_-]*$/,k$=/^(?=.{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 b$=/^\+(?:[0-9]){6,14}[0-9]$/,x$="(?:(?:\\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])))",v$=new RegExp(`^${x$}$`);function h$(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 g$(Y){return new RegExp(`^${h$(Y)}$`)}function y$(Y){let X=h$({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(`^${x$}T(?:${Q})$`)}var f$=(Y)=>{let X=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${X}$`)};var m$=/^-?\d+$/,c$=/^-?\d+(?:\.\d+)?/,u$=/^(?:true|false)$/i,p$=/^null$/i;var l$=/^[^A-Z]*$/,d$=/^[^a-z]*$/;var Z0=q("$ZodCheck",(Y,X)=>{var J;Y._zod??(Y._zod={}),Y._zod.def=X,(J=Y._zod).onattach??(J.onattach=[])}),i$={number:"number",bigint:"bigint",object:"date"},F9=q("$ZodCheckLessThan",(Y,X)=>{Z0.init(Y,X);let J=i$[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})}}),q9=q("$ZodCheckGreaterThan",(Y,X)=>{Z0.init(Y,X);let J=i$[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})}}),n$=q("$ZodCheckMultipleOf",(Y,X)=>{Z0.init(Y,X),Y._zod.onattach.push((J)=>{var Q;(Q=J._zod.bag).multipleOf??(Q.multipleOf=X.value)}),Y._zod.check=(J)=>{if(typeof J.value!==typeof X.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof J.value==="bigint"?J.value%X.value===BigInt(0):L9(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})}}),o$=q("$ZodCheckNumberFormat",(Y,X)=>{Z0.init(Y,X),X.format=X.format||"float64";let J=X.format?.includes("int"),Q=J?"int":"number",[$,G]=Z9[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=m$}),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 r$=q("$ZodCheckMaxLength",(Y,X)=>{var J;Z0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!$Y($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(X.maximum<$)Q._zod.bag.maximum=X.maximum}),Y._zod.check=(Q)=>{let $=Q.value;if($.length<=X.maximum)return;let W=WY($);Q.issues.push({origin:W,code:"too_big",maximum:X.maximum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),s$=q("$ZodCheckMinLength",(Y,X)=>{var J;Z0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!$Y($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(X.minimum>$)Q._zod.bag.minimum=X.minimum}),Y._zod.check=(Q)=>{let $=Q.value;if($.length>=X.minimum)return;let W=WY($);Q.issues.push({origin:W,code:"too_small",minimum:X.minimum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),a$=q("$ZodCheckLengthEquals",(Y,X)=>{var J;Z0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!$Y($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.minimum=X.length,$.maximum=X.length,$.length=X.length}),Y._zod.check=(Q)=>{let $=Q.value,G=$.length;if(G===X.length)return;let W=WY($),U=G>X.length;Q.issues.push({origin:W,...U?{code:"too_big",maximum:X.length}:{code:"too_small",minimum:X.length},inclusive:!0,exact:!0,input:Q.value,inst:Y,continue:!X.abort})}}),LY=q("$ZodCheckStringFormat",(Y,X)=>{var J,Q;if(Z0.init(Y,X),Y._zod.onattach.push(($)=>{let G=$._zod.bag;if(G.format=X.format,X.pattern)G.patterns??(G.patterns=new Set),G.patterns.add(X.pattern)}),X.pattern)(J=Y._zod).check??(J.check=($)=>{if(X.pattern.lastIndex=0,X.pattern.test($.value))return;$.issues.push({origin:"string",code:"invalid_format",format:X.format,input:$.value,...X.pattern?{pattern:X.pattern.toString()}:{},inst:Y,continue:!X.abort})});else(Q=Y._zod).check??(Q.check=()=>{})}),t$=q("$ZodCheckRegex",(Y,X)=>{LY.init(Y,X),Y._zod.check=(J)=>{if(X.pattern.lastIndex=0,X.pattern.test(J.value))return;J.issues.push({origin:"string",code:"invalid_format",format:"regex",input:J.value,pattern:X.pattern.toString(),inst:Y,continue:!X.abort})}}),e$=q("$ZodCheckLowerCase",(Y,X)=>{X.pattern??(X.pattern=l$),LY.init(Y,X)}),YG=q("$ZodCheckUpperCase",(Y,X)=>{X.pattern??(X.pattern=d$),LY.init(Y,X)}),XG=q("$ZodCheckIncludes",(Y,X)=>{Z0.init(Y,X);let J=J1(X.includes),Q=new RegExp(typeof X.position==="number"?`^.{${X.position}}${J}`:J);X.pattern=Q,Y._zod.onattach.push(($)=>{let G=$._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(Q)}),Y._zod.check=($)=>{if($.value.includes(X.includes,X.position))return;$.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:X.includes,input:$.value,inst:Y,continue:!X.abort})}}),JG=q("$ZodCheckStartsWith",(Y,X)=>{Z0.init(Y,X);let J=new RegExp(`^${J1(X.prefix)}.*`);X.pattern??(X.pattern=J),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(J)}),Y._zod.check=(Q)=>{if(Q.value.startsWith(X.prefix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:X.prefix,input:Q.value,inst:Y,continue:!X.abort})}}),QG=q("$ZodCheckEndsWith",(Y,X)=>{Z0.init(Y,X);let J=new RegExp(`.*${J1(X.suffix)}$`);X.pattern??(X.pattern=J),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(J)}),Y._zod.check=(Q)=>{if(Q.value.endsWith(X.suffix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:X.suffix,input:Q.value,inst:Y,continue:!X.abort})}});var $G=q("$ZodCheckOverwrite",(Y,X)=>{Z0.init(Y,X),Y._zod.check=(J)=>{J.value=X.tx(J.value)}});class j9{constructor(Y=[]){if(this.content=[],this.indent=0,this)this.args=Y}indented(Y){this.indent+=1,Y(this),this.indent-=1}write(Y){if(typeof Y==="function"){Y(this,{execution:"sync"}),Y(this,{execution:"async"});return}let J=Y.split(`
167
- `).filter((G)=>G),Q=Math.min(...J.map((G)=>G.length-G.trimStart().length)),$=J.map((G)=>G.slice(Q)).map((G)=>" ".repeat(this.indent*2)+G);for(let G of $)this.content.push(G)}compile(){let Y=Function,X=this?.args,Q=[...(this?.content??[""]).map(($)=>` ${$}`)];return new Y(...X,Q.join(`
168
- `))}}var WG={major:4,minor:1,patch:8};var o=q("$ZodType",(Y,X)=>{var J;Y??(Y={}),Y._zod.def=X,Y._zod.bag=Y._zod.bag||{},Y._zod.version=WG;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,H)=>{let L=Z1(W),V;for(let B of U){if(B._zod.def.when){if(!B._zod.def.when(W))continue}else if(L)continue;let K=W.issues.length,N=B._zod.check(W);if(N instanceof Promise&&H?.async===!1)throw new X1;if(V||N instanceof Promise)V=(V??Promise.resolve()).then(async()=>{if(await N,W.issues.length===K)return;if(!L)L=Z1(W,K)});else{if(W.issues.length===K)continue;if(!L)L=Z1(W,K)}}if(V)return V.then(()=>{return W});return W},G=(W,U,H)=>{if(Z1(W))return W.aborted=!0,W;let L=$(U,Q,H);if(L instanceof Promise){if(H.async===!1)throw new X1;return L.then((V)=>Y._zod.parse(V,H))}return Y._zod.parse(L,H)};Y._zod.run=(W,U)=>{if(U.skipChecks)return Y._zod.parse(W,U);if(U.direction==="backward"){let L=Y._zod.parse({value:W.value,issues:[]},{...U,skipChecks:!0});if(L instanceof Promise)return L.then((V)=>{return G(V,W,U)});return G(L,W,U)}let H=Y._zod.parse(W,U);if(H instanceof Promise){if(U.async===!1)throw new X1;return H.then((L)=>$(L,Q,U))}return $(H,Q,U)}}Y["~standard"]={validate:($)=>{try{let G=z$(Y,$);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return U$(Y,$).then((W)=>W.success?{value:W.data}:{issues:W.error?.issues})}},vendor:"zod",version:1}}),sY=q("$ZodString",(Y,X)=>{o.init(Y,X),Y._zod.pattern=[...Y?._zod.bag?.patterns??[]].pop()??f$(Y._zod.bag),Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=String(J.value)}catch($){}if(typeof J.value==="string")return J;return J.issues.push({expected:"string",code:"invalid_type",input:J.value,inst:Y}),J}}),s=q("$ZodStringFormat",(Y,X)=>{LY.init(Y,X),sY.init(Y,X)}),BG=q("$ZodGUID",(Y,X)=>{X.pattern??(X.pattern=A$),s.init(Y,X)}),OG=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=B9(Q))}else X.pattern??(X.pattern=B9());s.init(Y,X)}),FG=q("$ZodEmail",(Y,X)=>{X.pattern??(X.pattern=w$),s.init(Y,X)}),qG=q("$ZodURL",(Y,X)=>{s.init(Y,X),Y._zod.check=(J)=>{try{let Q=J.value.trim(),$=new URL(Q);if(X.hostname){if(X.hostname.lastIndex=0,!X.hostname.test($.hostname))J.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:k$.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})}}}),jG=q("$ZodEmoji",(Y,X)=>{X.pattern??(X.pattern=T$()),s.init(Y,X)}),DG=q("$ZodNanoID",(Y,X)=>{X.pattern??(X.pattern=M$),s.init(Y,X)}),PG=q("$ZodCUID",(Y,X)=>{X.pattern??(X.pattern=F$),s.init(Y,X)}),MG=q("$ZodCUID2",(Y,X)=>{X.pattern??(X.pattern=q$),s.init(Y,X)}),EG=q("$ZodULID",(Y,X)=>{X.pattern??(X.pattern=j$),s.init(Y,X)}),AG=q("$ZodXID",(Y,X)=>{X.pattern??(X.pattern=D$),s.init(Y,X)}),wG=q("$ZodKSUID",(Y,X)=>{X.pattern??(X.pattern=P$),s.init(Y,X)}),TG=q("$ZodISODateTime",(Y,X)=>{X.pattern??(X.pattern=y$(X)),s.init(Y,X)}),RG=q("$ZodISODate",(Y,X)=>{X.pattern??(X.pattern=v$),s.init(Y,X)}),_G=q("$ZodISOTime",(Y,X)=>{X.pattern??(X.pattern=g$(X)),s.init(Y,X)}),CG=q("$ZodISODuration",(Y,X)=>{X.pattern??(X.pattern=E$),s.init(Y,X)}),IG=q("$ZodIPv4",(Y,X)=>{X.pattern??(X.pattern=R$),s.init(Y,X),Y._zod.onattach.push((J)=>{let Q=J._zod.bag;Q.format="ipv4"})}),SG=q("$ZodIPv6",(Y,X)=>{X.pattern??(X.pattern=_$),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})}}}),kG=q("$ZodCIDRv4",(Y,X)=>{X.pattern??(X.pattern=C$),s.init(Y,X)}),bG=q("$ZodCIDRv6",(Y,X)=>{X.pattern??(X.pattern=I$),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 xG(Y){if(Y==="")return!0;if(Y.length%4!==0)return!1;try{return atob(Y),!0}catch{return!1}}var vG=q("$ZodBase64",(Y,X)=>{X.pattern??(X.pattern=S$),s.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64"}),Y._zod.check=(J)=>{if(xG(J.value))return;J.issues.push({code:"invalid_format",format:"base64",input:J.value,inst:Y,continue:!X.abort})}});function WH(Y){if(!O9.test(Y))return!1;let X=Y.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),J=X.padEnd(Math.ceil(X.length/4)*4,"=");return xG(J)}var hG=q("$ZodBase64URL",(Y,X)=>{X.pattern??(X.pattern=O9),s.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64url"}),Y._zod.check=(J)=>{if(WH(J.value))return;J.issues.push({code:"invalid_format",format:"base64url",input:J.value,inst:Y,continue:!X.abort})}}),gG=q("$ZodE164",(Y,X)=>{X.pattern??(X.pattern=b$),s.init(Y,X)});function zH(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 yG=q("$ZodJWT",(Y,X)=>{s.init(Y,X),Y._zod.check=(J)=>{if(zH(J.value,X.alg))return;J.issues.push({code:"invalid_format",format:"jwt",input:J.value,inst:Y,continue:!X.abort})}});var P9=q("$ZodNumber",(Y,X)=>{o.init(Y,X),Y._zod.pattern=Y._zod.bag.pattern??c$,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}}),fG=q("$ZodNumber",(Y,X)=>{o$.init(Y,X),P9.init(Y,X)}),mG=q("$ZodBoolean",(Y,X)=>{o.init(Y,X),Y._zod.pattern=u$,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 cG=q("$ZodNull",(Y,X)=>{o.init(Y,X),Y._zod.pattern=p$,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 uG=q("$ZodUnknown",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J)=>J}),pG=q("$ZodNever",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{return J.issues.push({expected:"never",code:"invalid_type",input:J.value,inst:Y}),J}});function zG(Y,X,J){if(Y.issues.length)X.issues.push(...Q1(J,Y.issues));X.value[J]=Y.value}var lG=q("$ZodArray",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value;if(!Array.isArray($))return J.issues.push({expected:"array",code:"invalid_type",input:$,inst:Y}),J;J.value=Array($.length);let G=[];for(let W=0;W<$.length;W++){let U=$[W],H=X.element._zod.run({value:U,issues:[]},Q);if(H instanceof Promise)G.push(H.then((L)=>zG(L,J,W)));else zG(H,J,W)}if(G.length)return Promise.all(G).then(()=>J);return J}});function rY(Y,X,J,Q){if(Y.issues.length)X.issues.push(...Q1(J,Y.issues));if(Y.value===void 0){if(J in Q)X.value[J]=void 0}else X.value[J]=Y.value}function dG(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=V9(Y.shape);return{...Y,keys:X,keySet:new Set(X),numKeys:X.length,optionalKeys:new Set(J)}}function iG(Y,X,J,Q,$,G){let W=[],U=$.keySet,H=$.catchall._zod,L=H.def.type;for(let V of Object.keys(X)){if(U.has(V))continue;if(L==="never"){W.push(V);continue}let B=H.run({value:X[V],issues:[]},Q);if(B instanceof Promise)Y.push(B.then((K)=>rY(K,J,V,X)));else rY(B,J,V,X)}if(W.length)J.issues.push({code:"unrecognized_keys",keys:W,input:X,inst:G});if(!Y.length)return J;return Promise.all(Y).then(()=>{return J})}var UH=q("$ZodObject",(Y,X)=>{o.init(Y,X);let J=p1(()=>dG(X));p(Y._zod,"propValues",()=>{let W=X.shape,U={};for(let H in W){let L=W[H]._zod;if(L.values){U[H]??(U[H]=new Set);for(let V of L.values)U[H].add(V)}}return U});let Q=R1,$=X.catchall,G;Y._zod.parse=(W,U)=>{G??(G=J.value);let H=W.value;if(!Q(H))return W.issues.push({expected:"object",code:"invalid_type",input:H,inst:Y}),W;W.value={};let L=[],V=G.shape;for(let B of G.keys){let N=V[B]._zod.run({value:H[B],issues:[]},U);if(N instanceof Promise)L.push(N.then((O)=>rY(O,W,B,H)));else rY(N,W,B,H)}if(!$)return L.length?Promise.all(L).then(()=>W):W;return iG(L,H,W,U,J.value,Y)}}),nG=q("$ZodObjectJIT",(Y,X)=>{UH.init(Y,X);let J=Y._zod.parse,Q=p1(()=>dG(X)),$=(K)=>{let N=new j9(["shape","payload","ctx"]),O=Q.value,j=(k)=>{let y=uY(k);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};N.write("const input = payload.value;");let A=Object.create(null),x=0;for(let k of O.keys)A[k]=`key_${x++}`;N.write("const newResult = {};");for(let k of O.keys){let y=A[k],u=uY(k);N.write(`const ${y} = ${j(k)};`),N.write(`
169
- if (${y}.issues.length) {
170
- payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
69
+ `}}function Iz(Y){return Y.type==="response.output_item.done"&&k(Y.item)&&Y.item.type==="web_search_call"&&typeof Y.item.id==="string"}function _z(Y){return k(Y)&&Y.type==="function_call"&&Y.name==="web_search"&&typeof Y.call_id==="string"&&Y.call_id.startsWith(a1)}function Sz(Y,X){return k(Y)&&Y.type==="function_call_output"&&typeof Y.call_id==="string"&&typeof Y.output==="string"&&Y.call_id.startsWith(a1)&&X.has(Y.call_id)}function kz(Y){return k(Y)&&Y.type==="item_reference"&&typeof Y.id==="string"&&Y.id.startsWith(a1)}function a9(Y,X,J){let Q=xz(X),G=k(Q?.action)?Q.action:bz(J?.arguments);return{type:"web_search_call",status:"completed",...G?{action:G}:{}}}function xz(Y){if(k(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return k(X)?X:void 0}catch{return}}function bz(Y){if(k(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return k(X)?X:void 0}catch{return}}import{readFile as vz}from"node:fs/promises";import{homedir as hz}from"node:os";import{join as kJ}from"node:path";var gz="https://models.dev/api.json",yz="OPENCODE_OPENAI_AUTH_MODELS_CACHE",fz="OPENCODE_MODELS_PATH",mz="OPENCODE_DISABLE_MODELS_FETCH",cz=1e4,uz=300000;function HY(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function xJ(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function e9(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=xJ(Y.cache_read),G=xJ(Y.cache_write);if(Q===null||G===null)return null;return{input:X,output:J,cache:{read:Q,write:G}}}function pz(Y){let X=HY(Y);if(!X)return null;let J=e9(X);if(!J)return null;let Q=J;if(Array.isArray(X.tiers)){let W=[];for(let z of X.tiers){let L=HY(z);if(!L)continue;let U=HY(L.tier),H=U?.size;if(U?.type!=="context")continue;if(typeof H!=="number"||!Number.isFinite(H)||H<=0)continue;let B=e9(L);if(!B)continue;W.push({...B,tier:{type:"context",size:H}})}if(W.length>0)Q.tiers=W}let G=HY(X.context_over_200k),$=G?e9(G):null;if($)Q.experimentalOver200K=$;return Q}function bJ(Y){let X=HY(Y),J=HY(X?.openai),Q=HY(J?.models);if(!Q)return null;let G={};for(let[$,W]of Object.entries(Q)){let z=HY(W),L=pz(z?.cost);if(L)G[$]=L}return Object.keys(G).length>0?G:null}function lz(){let Y=process.env[yz]?.trim();if(Y)return Y;let X=process.env[fz]?.trim();if(X)return X;let J=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||kJ(hz(),".cache");return kJ(J,"opencode","models.json")}function dz(){let Y=process.env[mz]?.toLowerCase();return Y==="true"||Y==="1"}async function iz(){try{let Y=bJ(JSON.parse(await vz(lz(),"utf8")));if(Y)return Y}catch{}if(dz())return null;try{let Y=await fetch(gz,{signal:AbortSignal.timeout(cz)});if(!Y.ok)return null;return bJ(await Y.json())}catch{return null}}var fY;function vJ(){let Y=Date.now();if(fY&&fY.expiresAt>Y)return fY.promise;let X={expiresAt:Y+uz,promise:iz()};return fY=X,X.promise.then((J)=>{if(J===null&&fY===X)fY=void 0}),X.promise}function mY(Y){return typeof Y==="object"&&Y!==null}function oz(Y){if(Array.isArray(Y))return Y;if(mY(Y)&&Array.isArray(Y.data))return Y.data;return[]}function nz(Y){if(!mY(Y)||!mY(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function hJ(Y){if(!mY(Y)||!mY(Y.info))return null;let X=Y.info,J=mY(X.model)?X.model:void 0,Q=typeof X.agent==="string"?X.agent:void 0,G=typeof J?.providerID==="string"?J.providerID:typeof X.providerID==="string"?X.providerID:void 0,$=typeof J?.modelID==="string"?J.modelID:typeof X.modelID==="string"?X.modelID:void 0,W=typeof J?.variant==="string"?J.variant:typeof X.variant==="string"?X.variant:void 0;if(!Q&&(!G||!$)&&!W)return null;let z={};if(Q)z.agent=Q;if(G&&$)z.model={providerID:G,modelID:$};if(W)z.variant=W;return z}function gJ(Y,X){return{agent:Y.agent??X.agent,model:Y.model??X.model,variant:Y.variant??X.variant}}function yJ(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function fJ(Y,X){if(!Y||!X)return null;let J=Y;if(typeof J.session?.messages!=="function")return null;let Q=[];try{Q=oz(await Promise.resolve(J.session.messages({path:{id:X},query:{limit:100}})))}catch{return null}if(Q.length===0)return null;let G={};for(let $=Q.length-1;$>=0;$--){if(nz(Q[$])!=="assistant")continue;let W=hJ(Q[$]);if(!W)continue;if(G=gJ(G,W),yJ(G))return G}for(let $=Q.length-1;$>=0;$--){let W=hJ(Q[$]);if(!W)continue;if(G=gJ(G,W),yJ(G))return G}if(!G.agent&&!G.model&&!G.variant)return null;return G}var NY=[],rz=1,YX=0,mJ=new Map;function XX(Y,X){if(NY.push({id:rz++,type:"open-dialog",payload:Y,sessionId:X}),NY.length>100)NY=NY.slice(NY.length-100)}function cJ(Y=0,X){let J=Date.now();if(YX=J,X!==void 0)mJ.set(X,J);let Q=(G)=>X===void 0||G.sessionId===void 0||G.sessionId===X;if(Y>0)NY=NY.filter((G)=>{if(G.id>Y)return!0;if(X===void 0)return!1;return G.sessionId!==X});return NY.filter((G)=>G.id>Y&&Q(G))}function uJ(Y){let X=Date.now();if(Y!==void 0){let J=mJ.get(Y)??0;return J>0&&X-J<3000}return YX>0&&X-YX<3000}import{randomBytes as sz,timingSafeEqual as az}from"node:crypto";import{unlink as tz}from"node:fs/promises";import{createServer as ez}from"node:http";import{join as YU}from"node:path";var pJ=D0("rpc");function XU(Y){return new Promise((X,J)=>{let Q=[],G=0;Y.on("data",($)=>{if(G+=$.length,G>1e6){Y.destroy(),J(Error("body too large"));return}Q.push($)}),Y.on("end",()=>X(Buffer.concat(Q).toString("utf8"))),Y.on("error",J)})}function JU(Y,X){if(!Y?.startsWith("Bearer "))return!1;let J=Buffer.from(Y.slice(7)),Q=Buffer.from(X);return J.length===Q.length&&az(J,Q)}async function iJ(Y){let X=sz(32).toString("hex"),J=Y.timeoutMs??90000,Q=Y.receiptTimeoutMs??2000,G=ez((z,L)=>{z.setTimeout(J,()=>{z.socket.destroy()}),$(z,L)});G.requestTimeout=Q,G.headersTimeout=Q;async function $(z,L){let U=(H,B)=>{if(L.headersSent||L.writableEnded||L.destroyed)return;L.writeHead(H,{"content-type":"application/json"}),L.end(JSON.stringify(B))};try{let H=z.url??"";if(z.method==="GET"&&H==="/health")return U(200,{ok:!0});if(z.method!=="POST"||!H.startsWith("/rpc/"))return U(404,{error:"not found"});if(!JU(z.headers.authorization,X))return U(401,{error:"unauthorized"});let B=H.slice(5),V=await XU(z),Z=JSON.parse(V||"{}");if(B==="pending-notifications"){let j=Y.drain(Number(Z.lastReceivedId??0),typeof Z.sessionId==="string"?Z.sessionId:void 0);return U(200,{messages:j})}if(B==="apply"){let j=await Y.apply(Z);return U(200,j)}return U(404,{error:"unknown method"})}catch(H){U(500,{error:H instanceof Error?H.message:String(H)})}}let W=await new Promise((z,L)=>{G.on("error",L),G.listen(0,"127.0.0.1",()=>{let U=G.address();if(U&&typeof U==="object")z(U.port);else L(Error("no port"))})});if(G.unref(),Y.sweepRoot)try{await dJ(Y.sweepRoot,Y.dir)}catch(z){pJ.warn("rpc state sweep failed",{pid:process.pid,error:z instanceof Error?z.message:String(z)})}try{await lJ(Y.dir,{port:W,token:X,pid:process.pid},{secureDir:Y.secureDir}),pJ.debug("rpc server pid",{pid:process.pid,rpcPort:W})}catch(z){throw await new Promise((L)=>G.close(()=>L())),z}return{port:W,token:X,async stop(){await new Promise((z)=>G.close(()=>z())),await tz(YU(Y.dir,`port-${process.pid}.json`)).catch(()=>{})}}}function YY(Y){return JSON.stringify(JX(Y))??"undefined"}function JX(Y){if(Array.isArray(Y))return Y.map(JX);if(!k(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((X)=>[X,JX(Y[X])]))}function RY(){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 jY={};$X(jY,{withoutInternalHeaders:()=>R4,sanitizeHttpFallbackBody:()=>y9,orderCodexBody:()=>R1,hasWebSocketResponsesLiteMetadata:()=>g9,createWebSocketFetch:()=>WV,applyTurnId:()=>E4,advanceTurn:()=>Q8,TITLE_HEADER:()=>J8,QUOTA_ACCOUNT_HEADER:()=>T9,OpenAIWebSocketPool:()=>jY,CODEX_BODY_KEY_ORDER:()=>P4});import{createHash as XV}from"node:crypto";var EQ="vercel.ai.error",QU=Symbol.for(EQ),oJ,nJ,P=class Y extends(nJ=Error,oJ=QU,nJ){constructor({name:X,message:J,cause:Q}){super(J);this[oJ]=!0,this.name=X,this.cause=Q}static isInstance(X){return Y.hasMarker(X,EQ)}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}},wQ="AI_APICallError",AQ=`vercel.ai.error.${wQ}`,GU=Symbol.for(AQ),rJ,sJ,z1=class extends(sJ=P,rJ=GU,sJ){constructor({message:Y,url:X,requestBodyValues:J,statusCode:Q,responseHeaders:G,responseBody:$,cause:W,isRetryable:z=Q!=null&&(Q===408||Q===409||Q===429||Q>=500),data:L}){super({name:wQ,message:Y,cause:W});this[rJ]=!0,this.url=X,this.requestBodyValues=J,this.statusCode=Q,this.responseHeaders=G,this.responseBody=$,this.isRetryable=z,this.data=L}static isInstance(Y){return P.hasMarker(Y,AQ)}},TQ="AI_EmptyResponseBodyError",RQ=`vercel.ai.error.${TQ}`,$U=Symbol.for(RQ),aJ,tJ,WU=class extends(tJ=P,aJ=$U,tJ){constructor({message:Y="Empty response body"}={}){super({name:TQ,message:Y});this[aJ]=!0}static isInstance(Y){return P.hasMarker(Y,RQ)}};function CY(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 CQ="AI_InvalidArgumentError",IQ=`vercel.ai.error.${CQ}`,KU=Symbol.for(IQ),eJ,YQ,_Q=class extends(YQ=P,eJ=KU,YQ){constructor({message:Y,cause:X,argument:J}){super({name:CQ,message:Y,cause:X});this[eJ]=!0,this.argument=J}static isInstance(Y){return P.hasMarker(Y,IQ)}},SQ="AI_InvalidPromptError",kQ=`vercel.ai.error.${SQ}`,zU=Symbol.for(kQ),XQ,JQ,UU=class extends(JQ=P,XQ=zU,JQ){constructor({prompt:Y,message:X,cause:J}){super({name:SQ,message:`Invalid prompt: ${X}`,cause:J});this[XQ]=!0,this.prompt=Y}static isInstance(Y){return P.hasMarker(Y,kQ)}},xQ="AI_InvalidResponseDataError",bQ=`vercel.ai.error.${xQ}`,LU=Symbol.for(bQ),QQ,GQ,HU=class extends(GQ=P,QQ=LU,GQ){constructor({data:Y,message:X=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:xQ,message:X});this[QQ]=!0,this.data=Y}static isInstance(Y){return P.hasMarker(Y,bQ)}},vQ="AI_JSONParseError",hQ=`vercel.ai.error.${vQ}`,NU=Symbol.for(hQ),$Q,WQ,t1=class extends(WQ=P,$Q=NU,WQ){constructor({text:Y,cause:X}){super({name:vQ,message:`JSON parsing failed: Text: ${Y}.
70
+ Error message: ${CY(X)}`,cause:X});this[$Q]=!0,this.text=Y}static isInstance(Y){return P.hasMarker(Y,hQ)}},gQ="AI_LoadAPIKeyError",yQ=`vercel.ai.error.${gQ}`,ZU=Symbol.for(yQ),KQ,zQ,VU=class extends(zQ=P,KQ=ZU,zQ){constructor({message:Y}){super({name:gQ,message:Y});this[KQ]=!0}static isInstance(Y){return P.hasMarker(Y,yQ)}},fQ="AI_LoadSettingError",mQ=`vercel.ai.error.${fQ}`,BU=Symbol.for(mQ),UQ,LQ,FU=class extends(LQ=P,UQ=BU,LQ){constructor({message:Y}){super({name:fQ,message:Y});this[UQ]=!0}static isInstance(Y){return P.hasMarker(Y,mQ)}},cQ="AI_NoContentGeneratedError",uQ=`vercel.ai.error.${cQ}`,OU=Symbol.for(uQ),HQ,NQ,qU=class extends(NQ=P,HQ=OU,NQ){constructor({message:Y="No content generated."}={}){super({name:cQ,message:Y});this[HQ]=!0}static isInstance(Y){return P.hasMarker(Y,uQ)}},pQ="AI_NoSuchModelError",lQ=`vercel.ai.error.${pQ}`,jU=Symbol.for(lQ),ZQ,VQ,QX=class extends(VQ=P,ZQ=jU,VQ){constructor({errorName:Y=pQ,modelId:X,modelType:J,message:Q=`No such ${J}: ${X}`}){super({name:Y,message:Q});this[ZQ]=!0,this.modelId=X,this.modelType=J}static isInstance(Y){return P.hasMarker(Y,lQ)}},dQ="AI_NoSuchProviderReferenceError",iQ=`vercel.ai.error.${dQ}`,DU=Symbol.for(iQ),BQ,FQ,PU=class extends(FQ=P,BQ=DU,FQ){constructor({provider:Y,reference:X,message:J=`No provider reference found for provider '${Y}'. Available providers: ${Object.keys(X).join(", ")}`}){super({name:dQ,message:J});this[BQ]=!0,this.provider=Y,this.reference=X}static isInstance(Y){return P.hasMarker(Y,iQ)}},oQ="AI_TooManyEmbeddingValuesForCallError",nQ=`vercel.ai.error.${oQ}`,MU=Symbol.for(nQ),OQ,qQ,EU=class extends(qQ=P,OQ=MU,qQ){constructor(Y){super({name:oQ,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[OQ]=!0,this.provider=Y.provider,this.modelId=Y.modelId,this.maxEmbeddingsPerCall=Y.maxEmbeddingsPerCall,this.values=Y.values}static isInstance(Y){return P.hasMarker(Y,nQ)}},rQ="AI_TypeValidationError",sQ=`vercel.ai.error.${rQ}`,wU=Symbol.for(sQ),jQ,DQ,h0=class Y extends(DQ=P,jQ=wU,DQ){constructor({value:X,cause:J,context:Q}){let G="Type validation failed";if(Q==null?void 0:Q.field)G+=` for ${Q.field}`;if((Q==null?void 0:Q.entityName)||(Q==null?void 0:Q.entityId)){G+=" (";let $=[];if(Q.entityName)$.push(Q.entityName);if(Q.entityId)$.push(`id: "${Q.entityId}"`);G+=$.join(", "),G+=")"}super({name:rQ,message:`${G}: Value: ${JSON.stringify(X)}.
71
+ Error message: ${CY(J)}`,cause:J});this[jQ]=!0,this.value=X,this.context=Q}static isInstance(X){return P.hasMarker(X,sQ)}static wrap({value:X,cause:J,context:Q}){var G,$,W;if(Y.isInstance(J)&&J.value===X&&((G=J.context)==null?void 0:G.field)===(Q==null?void 0:Q.field)&&(($=J.context)==null?void 0:$.entityName)===(Q==null?void 0:Q.entityName)&&((W=J.context)==null?void 0:W.entityId)===(Q==null?void 0:Q.entityId))return J;return new Y({value:X,cause:J,context:Q})}},aQ="AI_UnsupportedFunctionalityError",tQ=`vercel.ai.error.${aQ}`,AU=Symbol.for(tQ),PQ,MQ,TU=class extends(MQ=P,PQ=AU,MQ){constructor({functionality:Y,message:X=`'${Y}' functionality not supported.`}){super({name:aQ,message:X});this[PQ]=!0,this.functionality=Y}static isInstance(Y){return P.hasMarker(Y,tQ)}};var oF=Object.freeze({status:"aborted"});function q(Y,X,J){function Q(z,L){var U;Object.defineProperty(z,"_zod",{value:z._zod??{},enumerable:!1}),(U=z._zod).traits??(U.traits=new Set),z._zod.traits.add(Y),X(z,L);for(let H in W.prototype)if(!(H in z))Object.defineProperty(z,H,{value:W.prototype[H].bind(z)});z._zod.constr=W,z._zod.def=L}let G=J?.Parent??Object;class $ extends G{}Object.defineProperty($,"name",{value:Y});function W(z){var L;let U=J?.Parent?new $:this;Q(U,z),(L=U._zod).deferred??(L.deferred=[]);for(let H of U._zod.deferred)H();return U}return Object.defineProperty(W,"init",{value:Q}),Object.defineProperty(W,Symbol.hasInstance,{value:(z)=>{if(J?.Parent&&z instanceof J.Parent)return!0;return z?._zod?.traits?.has(Y)}}),Object.defineProperty(W,"name",{value:Y}),W}var nF=Symbol("zod_brand");class XY 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 e1={};function o0(Y){if(Y)Object.assign(e1,Y);return e1}var d={};$X(d,{unwrapMessage:()=>L1,uint8ArrayToHex:()=>tU,uint8ArrayToBase64url:()=>sU,uint8ArrayToBase64:()=>W5,stringifyPrimitive:()=>J5,shallowClone:()=>Y5,safeExtend:()=>lU,required:()=>oU,randomString:()=>gU,propertyKeyTypes:()=>zX,promiseAllObject:()=>hU,primitiveTypes:()=>X5,prefixIssues:()=>QY,pick:()=>cU,partial:()=>iU,optionalKeys:()=>UX,omit:()=>uU,objectClone:()=>xU,numKeys:()=>yU,nullish:()=>N1,normalizeParams:()=>y,mergeDefs:()=>VY,merge:()=>dU,jsonStringifyReplacer:()=>cY,joinValues:()=>kU,issue:()=>pY,isPlainObject:()=>BY,isObject:()=>IY,hexToUint8Array:()=>aU,getSizableOrigin:()=>G5,getParsedType:()=>fU,getLengthableOrigin:()=>V1,getEnumValues:()=>H1,getElementAtPath:()=>vU,floatSafeRemainder:()=>WX,finalizeIssue:()=>f0,extend:()=>pU,escapeRegex:()=>JY,esc:()=>Y9,defineLazy:()=>o,createTransparentProxy:()=>mU,cloneDef:()=>bU,clone:()=>y0,cleanRegex:()=>Z1,cleanEnum:()=>nU,captureStackTrace:()=>X9,cached:()=>uY,base64urlToUint8Array:()=>rU,base64ToUint8Array:()=>$5,assignProp:()=>ZY,assertNotEqual:()=>CU,assertNever:()=>_U,assertIs:()=>IU,assertEqual:()=>RU,assert:()=>SU,allowsEval:()=>KX,aborted:()=>FY,NUMBER_FORMAT_RANGES:()=>LX,Class:()=>K5,BIGINT_FORMAT_RANGES:()=>Q5});function RU(Y){return Y}function CU(Y){return Y}function IU(Y){}function _U(Y){throw Error()}function SU(Y){}function H1(Y){let X=Object.values(Y).filter((Q)=>typeof Q==="number");return Object.entries(Y).filter(([Q,G])=>X.indexOf(+Q)===-1).map(([Q,G])=>G)}function kU(Y,X="|"){return Y.map((J)=>J5(J)).join(X)}function cY(Y,X){if(typeof X==="bigint")return X.toString();return X}function uY(Y){return{get value(){{let J=Y();return Object.defineProperty(this,"value",{value:J}),J}throw Error("cached value already set")}}}function N1(Y){return Y===null||Y===void 0}function Z1(Y){let X=Y.startsWith("^")?1:0,J=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(X,J)}function WX(Y,X){let J=(Y.toString().split(".")[1]||"").length,Q=X.toString(),G=(Q.split(".")[1]||"").length;if(G===0&&/\d?e-\d?/.test(Q)){let L=Q.match(/\d?e-(\d?)/);if(L?.[1])G=Number.parseInt(L[1])}let $=J>G?J:G,W=Number.parseInt(Y.toFixed($).replace(".","")),z=Number.parseInt(X.toFixed($).replace(".",""));return W%z/10**$}var eQ=Symbol("evaluating");function o(Y,X,J){let Q=void 0;Object.defineProperty(Y,X,{get(){if(Q===eQ)return;if(Q===void 0)Q=eQ,Q=J();return Q},set(G){Object.defineProperty(Y,X,{value:G})},configurable:!0})}function xU(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function ZY(Y,X,J){Object.defineProperty(Y,X,{value:J,writable:!0,enumerable:!0,configurable:!0})}function VY(...Y){let X={};for(let J of Y){let Q=Object.getOwnPropertyDescriptors(J);Object.assign(X,Q)}return Object.defineProperties({},X)}function bU(Y){return VY(Y._zod.def)}function vU(Y,X){if(!X)return Y;return X.reduce((J,Q)=>J?.[Q],Y)}function hU(Y){let X=Object.keys(Y),J=X.map((Q)=>Y[Q]);return Promise.all(J).then((Q)=>{let G={};for(let $=0;$<X.length;$++)G[X[$]]=Q[$];return G})}function gU(Y=10){let J="";for(let Q=0;Q<Y;Q++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function Y9(Y){return JSON.stringify(Y)}var X9="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function IY(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var KX=uY(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function BY(Y){if(IY(Y)===!1)return!1;let X=Y.constructor;if(X===void 0)return!0;let J=X.prototype;if(IY(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function Y5(Y){if(BY(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function yU(Y){let X=0;for(let J in Y)if(Object.prototype.hasOwnProperty.call(Y,J))X++;return X}var fU=(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}`)}},zX=new Set(["string","number","symbol"]),X5=new Set(["string","number","bigint","boolean","symbol","undefined"]);function JY(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function y0(Y,X,J){let Q=new Y._zod.constr(X??Y._zod.def);if(!X||J?.parent)Q._zod.parent=Y;return Q}function y(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 mU(Y){let X;return new Proxy({},{get(J,Q,G){return X??(X=Y()),Reflect.get(X,Q,G)},set(J,Q,G,$){return X??(X=Y()),Reflect.set(X,Q,G,$)},has(J,Q){return X??(X=Y()),Reflect.has(X,Q)},deleteProperty(J,Q){return X??(X=Y()),Reflect.deleteProperty(X,Q)},ownKeys(J){return X??(X=Y()),Reflect.ownKeys(X)},getOwnPropertyDescriptor(J,Q){return X??(X=Y()),Reflect.getOwnPropertyDescriptor(X,Q)},defineProperty(J,Q,G){return X??(X=Y()),Reflect.defineProperty(X,Q,G)}})}function J5(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function UX(Y){return Object.keys(Y).filter((X)=>{return Y[X]._zod.optin==="optional"&&Y[X]._zod.optout==="optional"})}var LX={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]},Q5={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function cU(Y,X){let J=Y._zod.def,Q=VY(Y._zod.def,{get shape(){let G={};for(let $ in X){if(!($ in J.shape))throw Error(`Unrecognized key: "${$}"`);if(!X[$])continue;G[$]=J.shape[$]}return ZY(this,"shape",G),G},checks:[]});return y0(Y,Q)}function uU(Y,X){let J=Y._zod.def,Q=VY(Y._zod.def,{get shape(){let G={...Y._zod.def.shape};for(let $ in X){if(!($ in J.shape))throw Error(`Unrecognized key: "${$}"`);if(!X[$])continue;delete G[$]}return ZY(this,"shape",G),G},checks:[]});return y0(Y,Q)}function pU(Y,X){if(!BY(X))throw Error("Invalid input to extend: expected a plain object");let J=Y._zod.def.checks;if(J&&J.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let G=VY(Y._zod.def,{get shape(){let $={...Y._zod.def.shape,...X};return ZY(this,"shape",$),$},checks:[]});return y0(Y,G)}function lU(Y,X){if(!BY(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 ZY(this,"shape",Q),Q},checks:Y._zod.def.checks};return y0(Y,J)}function dU(Y,X){let J=VY(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape,...X._zod.def.shape};return ZY(this,"shape",Q),Q},get catchall(){return X._zod.def.catchall},checks:[]});return y0(Y,J)}function iU(Y,X,J){let Q=VY(X._zod.def,{get shape(){let G=X._zod.def.shape,$={...G};if(J)for(let W in J){if(!(W in G))throw Error(`Unrecognized key: "${W}"`);if(!J[W])continue;$[W]=Y?new Y({type:"optional",innerType:G[W]}):G[W]}else for(let W in G)$[W]=Y?new Y({type:"optional",innerType:G[W]}):G[W];return ZY(this,"shape",$),$},checks:[]});return y0(X,Q)}function oU(Y,X,J){let Q=VY(X._zod.def,{get shape(){let G=X._zod.def.shape,$={...G};if(J)for(let W in J){if(!(W in $))throw Error(`Unrecognized key: "${W}"`);if(!J[W])continue;$[W]=new Y({type:"nonoptional",innerType:G[W]})}else for(let W in G)$[W]=new Y({type:"nonoptional",innerType:G[W]});return ZY(this,"shape",$),$},checks:[]});return y0(X,Q)}function FY(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 QY(Y,X){return X.map((J)=>{var Q;return(Q=J).path??(Q.path=[]),J.path.unshift(Y),J})}function L1(Y){return typeof Y==="string"?Y:Y?.message}function f0(Y,X,J){let Q={...Y,path:Y.path??[]};if(!Y.message){let G=L1(Y.inst?._zod.def?.error?.(Y))??L1(X?.error?.(Y))??L1(J.customError?.(Y))??L1(J.localeError?.(Y))??"Invalid input";Q.message=G}if(delete Q.inst,delete Q.continue,!X?.reportInput)delete Q.input;return Q}function G5(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function V1(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function pY(...Y){let[X,J,Q]=Y;if(typeof X==="string")return{message:X,code:"custom",input:J,inst:Q};return{...X}}function nU(Y){return Object.entries(Y).filter(([X,J])=>{return Number.isNaN(Number.parseInt(X,10))}).map((X)=>X[1])}function $5(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 W5(Y){let X="";for(let J=0;J<Y.length;J++)X+=String.fromCharCode(Y[J]);return btoa(X)}function rU(Y){let X=Y.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-X.length%4)%4);return $5(X+J)}function sU(Y){return W5(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function aU(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 tU(Y){return Array.from(Y).map((X)=>X.toString(16).padStart(2,"0")).join("")}class K5{constructor(...Y){}}var z5=(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,cY,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},J9=q("$ZodError",z5),HX=q("$ZodError",z5,{Parent:Error});function U5(Y,X=(J)=>J.message){let J={},Q=[];for(let G of Y.issues)if(G.path.length>0)J[G.path[0]]=J[G.path[0]]||[],J[G.path[0]].push(X(G));else Q.push(X(G));return{formErrors:Q,fieldErrors:J}}function L5(Y,X){let J=X||function($){return $.message},Q={_errors:[]},G=($)=>{for(let W of $.issues)if(W.code==="invalid_union"&&W.errors.length)W.errors.map((z)=>G({issues:z}));else if(W.code==="invalid_key")G({issues:W.issues});else if(W.code==="invalid_element")G({issues:W.issues});else if(W.path.length===0)Q._errors.push(J(W));else{let z=Q,L=0;while(L<W.path.length){let U=W.path[L];if(L!==W.path.length-1)z[U]=z[U]||{_errors:[]};else z[U]=z[U]||{_errors:[]},z[U]._errors.push(J(W));z=z[U],L++}}};return G(Y),Q}var Q9=(Y)=>(X,J,Q,G)=>{let $=Q?Object.assign(Q,{async:!1}):{async:!1},W=X._zod.run({value:J,issues:[]},$);if(W instanceof Promise)throw new XY;if(W.issues.length){let z=new(G?.Err??Y)(W.issues.map((L)=>f0(L,$,o0())));throw X9(z,G?.callee),z}return W.value};var G9=(Y)=>async(X,J,Q,G)=>{let $=Q?Object.assign(Q,{async:!0}):{async:!0},W=X._zod.run({value:J,issues:[]},$);if(W instanceof Promise)W=await W;if(W.issues.length){let z=new(G?.Err??Y)(W.issues.map((L)=>f0(L,$,o0())));throw X9(z,G?.callee),z}return W.value};var B1=(Y)=>(X,J,Q)=>{let G=Q?{...Q,async:!1}:{async:!1},$=X._zod.run({value:J,issues:[]},G);if($ instanceof Promise)throw new XY;return $.issues.length?{success:!1,error:new(Y??J9)($.issues.map((W)=>f0(W,G,o0())))}:{success:!0,data:$.value}},H5=B1(HX),F1=(Y)=>async(X,J,Q)=>{let G=Q?Object.assign(Q,{async:!0}):{async:!0},$=X._zod.run({value:J,issues:[]},G);if($ instanceof Promise)$=await $;return $.issues.length?{success:!1,error:new Y($.issues.map((W)=>f0(W,G,o0())))}:{success:!0,data:$.value}},N5=F1(HX),Z5=(Y)=>(X,J,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return Q9(Y)(X,J,G)};var V5=(Y)=>(X,J,Q)=>{return Q9(Y)(X,J,Q)};var B5=(Y)=>async(X,J,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return G9(Y)(X,J,G)};var F5=(Y)=>async(X,J,Q)=>{return G9(Y)(X,J,Q)};var O5=(Y)=>(X,J,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return B1(Y)(X,J,G)};var q5=(Y)=>(X,J,Q)=>{return B1(Y)(X,J,Q)};var j5=(Y)=>async(X,J,Q)=>{let G=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return F1(Y)(X,J,G)};var D5=(Y)=>async(X,J,Q)=>{return F1(Y)(X,J,Q)};var P5=/^[cC][^\s-]{8,}$/,M5=/^[0-9a-z]+$/,E5=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,w5=/^[0-9a-vA-V]{20}$/,A5=/^[A-Za-z0-9]{27}$/,T5=/^[a-zA-Z0-9_-]{21}$/,R5=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var C5=/^([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})$/,NX=(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 I5=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function _5(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var S5=/^(?:(?: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])$/,k5=/^(([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}|:))$/,x5=/^((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])$/,b5=/^(([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])$/,v5=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ZX=/^[A-Za-z0-9_-]*$/,h5=/^(?=.{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 g5=/^\+(?:[0-9]){6,14}[0-9]$/,y5="(?:(?:\\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])))",f5=new RegExp(`^${y5}$`);function m5(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 c5(Y){return new RegExp(`^${m5(Y)}$`)}function u5(Y){let X=m5({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(`^${y5}T(?:${Q})$`)}var p5=(Y)=>{let X=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${X}$`)};var l5=/^-?\d+$/,d5=/^-?\d+(?:\.\d+)?/,i5=/^(?:true|false)$/i,o5=/^null$/i;var n5=/^[^A-Z]*$/,r5=/^[^a-z]*$/;var q0=q("$ZodCheck",(Y,X)=>{var J;Y._zod??(Y._zod={}),Y._zod.def=X,(J=Y._zod).onattach??(J.onattach=[])}),s5={number:"number",bigint:"bigint",object:"date"},VX=q("$ZodCheckLessThan",(Y,X)=>{q0.init(Y,X);let J=s5[typeof X.value];Y._zod.onattach.push((Q)=>{let G=Q._zod.bag,$=(X.inclusive?G.maximum:G.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(X.value<$)if(X.inclusive)G.maximum=X.value;else G.exclusiveMaximum=X.value}),Y._zod.check=(Q)=>{if(X.inclusive?Q.value<=X.value:Q.value<X.value)return;Q.issues.push({origin:J,code:"too_big",maximum:X.value,input:Q.value,inclusive:X.inclusive,inst:Y,continue:!X.abort})}}),BX=q("$ZodCheckGreaterThan",(Y,X)=>{q0.init(Y,X);let J=s5[typeof X.value];Y._zod.onattach.push((Q)=>{let G=Q._zod.bag,$=(X.inclusive?G.minimum:G.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(X.value>$)if(X.inclusive)G.minimum=X.value;else G.exclusiveMinimum=X.value}),Y._zod.check=(Q)=>{if(X.inclusive?Q.value>=X.value:Q.value>X.value)return;Q.issues.push({origin:J,code:"too_small",minimum:X.value,input:Q.value,inclusive:X.inclusive,inst:Y,continue:!X.abort})}}),a5=q("$ZodCheckMultipleOf",(Y,X)=>{q0.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):WX(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})}}),t5=q("$ZodCheckNumberFormat",(Y,X)=>{q0.init(Y,X),X.format=X.format||"float64";let J=X.format?.includes("int"),Q=J?"int":"number",[G,$]=LX[X.format];Y._zod.onattach.push((W)=>{let z=W._zod.bag;if(z.format=X.format,z.minimum=G,z.maximum=$,J)z.pattern=l5}),Y._zod.check=(W)=>{let z=W.value;if(J){if(!Number.isInteger(z)){W.issues.push({expected:Q,format:X.format,code:"invalid_type",continue:!1,input:z,inst:Y});return}if(!Number.isSafeInteger(z)){if(z>0)W.issues.push({input:z,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:Q,continue:!X.abort});else W.issues.push({input:z,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:Q,continue:!X.abort});return}}if(z<G)W.issues.push({origin:"number",input:z,code:"too_small",minimum:G,inclusive:!0,inst:Y,continue:!X.abort});if(z>$)W.issues.push({origin:"number",input:z,code:"too_big",maximum:$,inst:Y})}});var e5=q("$ZodCheckMaxLength",(Y,X)=>{var J;q0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let G=Q.value;return!N1(G)&&G.length!==void 0}),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(X.maximum<G)Q._zod.bag.maximum=X.maximum}),Y._zod.check=(Q)=>{let G=Q.value;if(G.length<=X.maximum)return;let W=V1(G);Q.issues.push({origin:W,code:"too_big",maximum:X.maximum,inclusive:!0,input:G,inst:Y,continue:!X.abort})}}),YG=q("$ZodCheckMinLength",(Y,X)=>{var J;q0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let G=Q.value;return!N1(G)&&G.length!==void 0}),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(X.minimum>G)Q._zod.bag.minimum=X.minimum}),Y._zod.check=(Q)=>{let G=Q.value;if(G.length>=X.minimum)return;let W=V1(G);Q.issues.push({origin:W,code:"too_small",minimum:X.minimum,inclusive:!0,input:G,inst:Y,continue:!X.abort})}}),XG=q("$ZodCheckLengthEquals",(Y,X)=>{var J;q0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let G=Q.value;return!N1(G)&&G.length!==void 0}),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.minimum=X.length,G.maximum=X.length,G.length=X.length}),Y._zod.check=(Q)=>{let G=Q.value,$=G.length;if($===X.length)return;let W=V1(G),z=$>X.length;Q.issues.push({origin:W,...z?{code:"too_big",maximum:X.length}:{code:"too_small",minimum:X.length},inclusive:!0,exact:!0,input:Q.value,inst:Y,continue:!X.abort})}}),O1=q("$ZodCheckStringFormat",(Y,X)=>{var J,Q;if(q0.init(Y,X),Y._zod.onattach.push((G)=>{let $=G._zod.bag;if($.format=X.format,X.pattern)$.patterns??($.patterns=new Set),$.patterns.add(X.pattern)}),X.pattern)(J=Y._zod).check??(J.check=(G)=>{if(X.pattern.lastIndex=0,X.pattern.test(G.value))return;G.issues.push({origin:"string",code:"invalid_format",format:X.format,input:G.value,...X.pattern?{pattern:X.pattern.toString()}:{},inst:Y,continue:!X.abort})});else(Q=Y._zod).check??(Q.check=()=>{})}),JG=q("$ZodCheckRegex",(Y,X)=>{O1.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})}}),QG=q("$ZodCheckLowerCase",(Y,X)=>{X.pattern??(X.pattern=n5),O1.init(Y,X)}),GG=q("$ZodCheckUpperCase",(Y,X)=>{X.pattern??(X.pattern=r5),O1.init(Y,X)}),$G=q("$ZodCheckIncludes",(Y,X)=>{q0.init(Y,X);let J=JY(X.includes),Q=new RegExp(typeof X.position==="number"?`^.{${X.position}}${J}`:J);X.pattern=Q,Y._zod.onattach.push((G)=>{let $=G._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(Q)}),Y._zod.check=(G)=>{if(G.value.includes(X.includes,X.position))return;G.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:X.includes,input:G.value,inst:Y,continue:!X.abort})}}),WG=q("$ZodCheckStartsWith",(Y,X)=>{q0.init(Y,X);let J=new RegExp(`^${JY(X.prefix)}.*`);X.pattern??(X.pattern=J),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(J)}),Y._zod.check=(Q)=>{if(Q.value.startsWith(X.prefix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:X.prefix,input:Q.value,inst:Y,continue:!X.abort})}}),KG=q("$ZodCheckEndsWith",(Y,X)=>{q0.init(Y,X);let J=new RegExp(`.*${JY(X.suffix)}$`);X.pattern??(X.pattern=J),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(J)}),Y._zod.check=(Q)=>{if(Q.value.endsWith(X.suffix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:X.suffix,input:Q.value,inst:Y,continue:!X.abort})}});var zG=q("$ZodCheckOverwrite",(Y,X)=>{q0.init(Y,X),Y._zod.check=(J)=>{J.value=X.tx(J.value)}});class FX{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(`
72
+ `).filter(($)=>$),Q=Math.min(...J.map(($)=>$.length-$.trimStart().length)),G=J.map(($)=>$.slice(Q)).map(($)=>" ".repeat(this.indent*2)+$);for(let $ of G)this.content.push($)}compile(){let Y=Function,X=this?.args,Q=[...(this?.content??[""]).map((G)=>` ${G}`)];return new Y(...X,Q.join(`
73
+ `))}}var LG={major:4,minor:1,patch:8};var a=q("$ZodType",(Y,X)=>{var J;Y??(Y={}),Y._zod.def=X,Y._zod.bag=Y._zod.bag||{},Y._zod.version=LG;let Q=[...Y._zod.def.checks??[]];if(Y._zod.traits.has("$ZodCheck"))Q.unshift(Y);for(let G of Q)for(let $ of G._zod.onattach)$(Y);if(Q.length===0)(J=Y._zod).deferred??(J.deferred=[]),Y._zod.deferred?.push(()=>{Y._zod.run=Y._zod.parse});else{let G=(W,z,L)=>{let U=FY(W),H;for(let B of z){if(B._zod.def.when){if(!B._zod.def.when(W))continue}else if(U)continue;let V=W.issues.length,Z=B._zod.check(W);if(Z instanceof Promise&&L?.async===!1)throw new XY;if(H||Z instanceof Promise)H=(H??Promise.resolve()).then(async()=>{if(await Z,W.issues.length===V)return;if(!U)U=FY(W,V)});else{if(W.issues.length===V)continue;if(!U)U=FY(W,V)}}if(H)return H.then(()=>{return W});return W},$=(W,z,L)=>{if(FY(W))return W.aborted=!0,W;let U=G(z,Q,L);if(U instanceof Promise){if(L.async===!1)throw new XY;return U.then((H)=>Y._zod.parse(H,L))}return Y._zod.parse(U,L)};Y._zod.run=(W,z)=>{if(z.skipChecks)return Y._zod.parse(W,z);if(z.direction==="backward"){let U=Y._zod.parse({value:W.value,issues:[]},{...z,skipChecks:!0});if(U instanceof Promise)return U.then((H)=>{return $(H,W,z)});return $(U,W,z)}let L=Y._zod.parse(W,z);if(L instanceof Promise){if(z.async===!1)throw new XY;return L.then((U)=>G(U,Q,z))}return G(L,Q,z)}}Y["~standard"]={validate:(G)=>{try{let $=H5(Y,G);return $.success?{value:$.data}:{issues:$.error?.issues}}catch($){return N5(Y,G).then((W)=>W.success?{value:W.data}:{issues:W.error?.issues})}},vendor:"zod",version:1}}),z9=q("$ZodString",(Y,X)=>{a.init(Y,X),Y._zod.pattern=[...Y?._zod.bag?.patterns??[]].pop()??p5(Y._zod.bag),Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=String(J.value)}catch(G){}if(typeof J.value==="string")return J;return J.issues.push({expected:"string",code:"invalid_type",input:J.value,inst:Y}),J}}),t=q("$ZodStringFormat",(Y,X)=>{O1.init(Y,X),z9.init(Y,X)}),jG=q("$ZodGUID",(Y,X)=>{X.pattern??(X.pattern=C5),t.init(Y,X)}),DG=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=NX(Q))}else X.pattern??(X.pattern=NX());t.init(Y,X)}),PG=q("$ZodEmail",(Y,X)=>{X.pattern??(X.pattern=I5),t.init(Y,X)}),MG=q("$ZodURL",(Y,X)=>{t.init(Y,X),Y._zod.check=(J)=>{try{let Q=J.value.trim(),G=new URL(Q);if(X.hostname){if(X.hostname.lastIndex=0,!X.hostname.test(G.hostname))J.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:h5.source,input:J.value,inst:Y,continue:!X.abort})}if(X.protocol){if(X.protocol.lastIndex=0,!X.protocol.test(G.protocol.endsWith(":")?G.protocol.slice(0,-1):G.protocol))J.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:X.protocol.source,input:J.value,inst:Y,continue:!X.abort})}if(X.normalize)J.value=G.href;else J.value=Q;return}catch(Q){J.issues.push({code:"invalid_format",format:"url",input:J.value,inst:Y,continue:!X.abort})}}}),EG=q("$ZodEmoji",(Y,X)=>{X.pattern??(X.pattern=_5()),t.init(Y,X)}),wG=q("$ZodNanoID",(Y,X)=>{X.pattern??(X.pattern=T5),t.init(Y,X)}),AG=q("$ZodCUID",(Y,X)=>{X.pattern??(X.pattern=P5),t.init(Y,X)}),TG=q("$ZodCUID2",(Y,X)=>{X.pattern??(X.pattern=M5),t.init(Y,X)}),RG=q("$ZodULID",(Y,X)=>{X.pattern??(X.pattern=E5),t.init(Y,X)}),CG=q("$ZodXID",(Y,X)=>{X.pattern??(X.pattern=w5),t.init(Y,X)}),IG=q("$ZodKSUID",(Y,X)=>{X.pattern??(X.pattern=A5),t.init(Y,X)}),_G=q("$ZodISODateTime",(Y,X)=>{X.pattern??(X.pattern=u5(X)),t.init(Y,X)}),SG=q("$ZodISODate",(Y,X)=>{X.pattern??(X.pattern=f5),t.init(Y,X)}),kG=q("$ZodISOTime",(Y,X)=>{X.pattern??(X.pattern=c5(X)),t.init(Y,X)}),xG=q("$ZodISODuration",(Y,X)=>{X.pattern??(X.pattern=R5),t.init(Y,X)}),bG=q("$ZodIPv4",(Y,X)=>{X.pattern??(X.pattern=S5),t.init(Y,X),Y._zod.onattach.push((J)=>{let Q=J._zod.bag;Q.format="ipv4"})}),vG=q("$ZodIPv6",(Y,X)=>{X.pattern??(X.pattern=k5),t.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})}}}),hG=q("$ZodCIDRv4",(Y,X)=>{X.pattern??(X.pattern=x5),t.init(Y,X)}),gG=q("$ZodCIDRv6",(Y,X)=>{X.pattern??(X.pattern=b5),t.init(Y,X),Y._zod.check=(J)=>{let Q=J.value.split("/");try{if(Q.length!==2)throw Error();let[G,$]=Q;if(!$)throw Error();let W=Number($);if(`${W}`!==$)throw Error();if(W<0||W>128)throw Error();new URL(`http://[${G}]`)}catch{J.issues.push({code:"invalid_format",format:"cidrv6",input:J.value,inst:Y,continue:!X.abort})}}});function yG(Y){if(Y==="")return!0;if(Y.length%4!==0)return!1;try{return atob(Y),!0}catch{return!1}}var fG=q("$ZodBase64",(Y,X)=>{X.pattern??(X.pattern=v5),t.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64"}),Y._zod.check=(J)=>{if(yG(J.value))return;J.issues.push({code:"invalid_format",format:"base64",input:J.value,inst:Y,continue:!X.abort})}});function YL(Y){if(!ZX.test(Y))return!1;let X=Y.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),J=X.padEnd(Math.ceil(X.length/4)*4,"=");return yG(J)}var mG=q("$ZodBase64URL",(Y,X)=>{X.pattern??(X.pattern=ZX),t.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64url"}),Y._zod.check=(J)=>{if(YL(J.value))return;J.issues.push({code:"invalid_format",format:"base64url",input:J.value,inst:Y,continue:!X.abort})}}),cG=q("$ZodE164",(Y,X)=>{X.pattern??(X.pattern=g5),t.init(Y,X)});function XL(Y,X=null){try{let J=Y.split(".");if(J.length!==3)return!1;let[Q]=J;if(!Q)return!1;let G=JSON.parse(atob(Q));if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(X&&(!("alg"in G)||G.alg!==X))return!1;return!0}catch{return!1}}var uG=q("$ZodJWT",(Y,X)=>{t.init(Y,X),Y._zod.check=(J)=>{if(XL(J.value,X.alg))return;J.issues.push({code:"invalid_format",format:"jwt",input:J.value,inst:Y,continue:!X.abort})}});var qX=q("$ZodNumber",(Y,X)=>{a.init(Y,X),Y._zod.pattern=Y._zod.bag.pattern??d5,Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=Number(J.value)}catch(W){}let G=J.value;if(typeof G==="number"&&!Number.isNaN(G)&&Number.isFinite(G))return J;let $=typeof G==="number"?Number.isNaN(G)?"NaN":!Number.isFinite(G)?"Infinity":void 0:void 0;return J.issues.push({expected:"number",code:"invalid_type",input:G,inst:Y,...$?{received:$}:{}}),J}}),pG=q("$ZodNumber",(Y,X)=>{t5.init(Y,X),qX.init(Y,X)}),lG=q("$ZodBoolean",(Y,X)=>{a.init(Y,X),Y._zod.pattern=i5,Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=Boolean(J.value)}catch($){}let G=J.value;if(typeof G==="boolean")return J;return J.issues.push({expected:"boolean",code:"invalid_type",input:G,inst:Y}),J}});var dG=q("$ZodNull",(Y,X)=>{a.init(Y,X),Y._zod.pattern=o5,Y._zod.values=new Set([null]),Y._zod.parse=(J,Q)=>{let G=J.value;if(G===null)return J;return J.issues.push({expected:"null",code:"invalid_type",input:G,inst:Y}),J}});var iG=q("$ZodUnknown",(Y,X)=>{a.init(Y,X),Y._zod.parse=(J)=>J}),oG=q("$ZodNever",(Y,X)=>{a.init(Y,X),Y._zod.parse=(J,Q)=>{return J.issues.push({expected:"never",code:"invalid_type",input:J.value,inst:Y}),J}});function HG(Y,X,J){if(Y.issues.length)X.issues.push(...QY(J,Y.issues));X.value[J]=Y.value}var nG=q("$ZodArray",(Y,X)=>{a.init(Y,X),Y._zod.parse=(J,Q)=>{let G=J.value;if(!Array.isArray(G))return J.issues.push({expected:"array",code:"invalid_type",input:G,inst:Y}),J;J.value=Array(G.length);let $=[];for(let W=0;W<G.length;W++){let z=G[W],L=X.element._zod.run({value:z,issues:[]},Q);if(L instanceof Promise)$.push(L.then((U)=>HG(U,J,W)));else HG(L,J,W)}if($.length)return Promise.all($).then(()=>J);return J}});function K9(Y,X,J,Q){if(Y.issues.length)X.issues.push(...QY(J,Y.issues));if(Y.value===void 0){if(J in Q)X.value[J]=void 0}else X.value[J]=Y.value}function rG(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=UX(Y.shape);return{...Y,keys:X,keySet:new Set(X),numKeys:X.length,optionalKeys:new Set(J)}}function sG(Y,X,J,Q,G,$){let W=[],z=G.keySet,L=G.catchall._zod,U=L.def.type;for(let H of Object.keys(X)){if(z.has(H))continue;if(U==="never"){W.push(H);continue}let B=L.run({value:X[H],issues:[]},Q);if(B instanceof Promise)Y.push(B.then((V)=>K9(V,J,H,X)));else K9(B,J,H,X)}if(W.length)J.issues.push({code:"unrecognized_keys",keys:W,input:X,inst:$});if(!Y.length)return J;return Promise.all(Y).then(()=>{return J})}var JL=q("$ZodObject",(Y,X)=>{a.init(Y,X);let J=uY(()=>rG(X));o(Y._zod,"propValues",()=>{let W=X.shape,z={};for(let L in W){let U=W[L]._zod;if(U.values){z[L]??(z[L]=new Set);for(let H of U.values)z[L].add(H)}}return z});let Q=IY,G=X.catchall,$;Y._zod.parse=(W,z)=>{$??($=J.value);let L=W.value;if(!Q(L))return W.issues.push({expected:"object",code:"invalid_type",input:L,inst:Y}),W;W.value={};let U=[],H=$.shape;for(let B of $.keys){let Z=H[B]._zod.run({value:L[B],issues:[]},z);if(Z instanceof Promise)U.push(Z.then((j)=>K9(j,W,B,L)));else K9(Z,W,B,L)}if(!G)return U.length?Promise.all(U).then(()=>W):W;return sG(U,L,W,z,J.value,Y)}}),aG=q("$ZodObjectJIT",(Y,X)=>{JL.init(Y,X);let J=Y._zod.parse,Q=uY(()=>rG(X)),G=(V)=>{let Z=new FX(["shape","payload","ctx"]),j=Q.value,O=(E)=>{let T=Y9(E);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};Z.write("const input = payload.value;");let C=Object.create(null),R=0;for(let E of j.keys)C[E]=`key_${R++}`;Z.write("const newResult = {};");for(let E of j.keys){let T=C[E],g=Y9(E);Z.write(`const ${T} = ${O(E)};`),Z.write(`
74
+ if (${T}.issues.length) {
75
+ payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
171
76
  ...iss,
172
- path: iss.path ? [${u}, ...iss.path] : [${u}]
77
+ path: iss.path ? [${g}, ...iss.path] : [${g}]
173
78
  })));
174
79
  }
175
80
 
176
81
 
177
- if (${y}.value === undefined) {
178
- if (${u} in input) {
179
- newResult[${u}] = undefined;
82
+ if (${T}.value === undefined) {
83
+ if (${g} in input) {
84
+ newResult[${g}] = undefined;
180
85
  }
181
86
  } else {
182
- newResult[${u}] = ${y}.value;
87
+ newResult[${g}] = ${T}.value;
183
88
  }
184
89
 
185
- `)}N.write("payload.value = newResult;"),N.write("return payload;");let E=N.compile();return(k,y)=>E(K,k,y)},G,W=R1,U=!cY.jitless,L=U&&H9.value,V=X.catchall,B;Y._zod.parse=(K,N)=>{B??(B=Q.value);let O=K.value;if(!W(O))return K.issues.push({expected:"object",code:"invalid_type",input:O,inst:Y}),K;if(U&&L&&N?.async===!1&&N.jitless!==!0){if(!G)G=$(X.shape);if(K=G(K,N),!V)return K;return iG([],O,K,N,B,Y)}return J(K,N)}});function UG(Y,X,J,Q){for(let G of Y)if(G.issues.length===0)return X.value=G.value,X;let $=Y.filter((G)=>!Z1(G));if($.length===1)return X.value=$[0].value,$[0];return X.issues.push({code:"invalid_union",input:X.value,inst:J,errors:Y.map((G)=>G.issues.map((W)=>v0(W,Q,l0())))}),X}var M9=q("$ZodUnion",(Y,X)=>{o.init(Y,X),p(Y._zod,"optin",()=>X.options.some(($)=>$._zod.optin==="optional")?"optional":void 0),p(Y._zod,"optout",()=>X.options.some(($)=>$._zod.optout==="optional")?"optional":void 0),p(Y._zod,"values",()=>{if(X.options.every(($)=>$._zod.values))return new Set(X.options.flatMap(($)=>Array.from($._zod.values)));return}),p(Y._zod,"pattern",()=>{if(X.options.every(($)=>$._zod.pattern)){let $=X.options.map((G)=>G._zod.pattern);return new RegExp(`^(${$.map((G)=>GY(G.source)).join("|")})$`)}return});let J=X.options.length===1,Q=X.options[0]._zod.run;Y._zod.parse=($,G)=>{if(J)return Q($,G);let W=!1,U=[];for(let H of X.options){let L=H._zod.run({value:$.value,issues:[]},G);if(L instanceof Promise)U.push(L),W=!0;else{if(L.issues.length===0)return L;U.push(L)}}if(!W)return UG(U,$,Y,G);return Promise.all(U).then((H)=>{return UG(H,$,Y,G)})}}),oG=q("$ZodDiscriminatedUnion",(Y,X)=>{M9.init(Y,X);let J=Y._zod.parse;p(Y._zod,"propValues",()=>{let $={};for(let G of X.options){let W=G._zod.propValues;if(!W||Object.keys(W).length===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf(G)}"`);for(let[U,H]of Object.entries(W)){if(!$[U])$[U]=new Set;for(let L of H)$[U].add(L)}}return $});let Q=p1(()=>{let $=X.options,G=new Map;for(let W of $){let U=W._zod.propValues?.[X.discriminator];if(!U||U.size===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf(W)}"`);for(let H of U){if(G.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);G.set(H,W)}}return G});Y._zod.parse=($,G)=>{let W=$.value;if(!R1(W))return $.issues.push({code:"invalid_type",expected:"object",input:W,inst:Y}),$;let U=Q.value.get(W?.[X.discriminator]);if(U)return U._zod.run($,G);if(X.unionFallback)return J($,G);return $.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:X.discriminator,input:W,path:[X.discriminator],inst:Y}),$}}),rG=q("$ZodIntersection",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value,G=X.left._zod.run({value:$,issues:[]},Q),W=X.right._zod.run({value:$,issues:[]},Q);if(G instanceof Promise||W instanceof Promise)return Promise.all([G,W]).then(([H,L])=>{return LG(J,H,L)});return LG(J,G,W)}});function D9(Y,X){if(Y===X)return{valid:!0,data:Y};if(Y instanceof Date&&X instanceof Date&&+Y===+X)return{valid:!0,data:Y};if(V1(Y)&&V1(X)){let J=Object.keys(X),Q=Object.keys(Y).filter((G)=>J.indexOf(G)!==-1),$={...Y,...X};for(let G of Q){let W=D9(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=D9($,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 LG(Y,X,J){if(X.issues.length)Y.issues.push(...X.issues);if(J.issues.length)Y.issues.push(...J.issues);if(Z1(Y))return Y;let Q=D9(X.value,J.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return Y.value=Q.data,Y}var sG=q("$ZodRecord",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value;if(!V1($))return J.issues.push({expected:"record",code:"invalid_type",input:$,inst:Y}),J;let G=[];if(X.keyType._zod.values){let W=X.keyType._zod.values;J.value={};for(let H of W)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let L=X.valueType._zod.run({value:$[H],issues:[]},Q);if(L instanceof Promise)G.push(L.then((V)=>{if(V.issues.length)J.issues.push(...Q1(H,V.issues));J.value[H]=V.value}));else{if(L.issues.length)J.issues.push(...Q1(H,L.issues));J.value[H]=L.value}}let U;for(let H in $)if(!W.has(H))U=U??[],U.push(H);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((L)=>v0(L,Q,l0())),input:W,path:[W],inst:Y}),J.value[U.value]=U.value;continue}let H=X.valueType._zod.run({value:$[W],issues:[]},Q);if(H instanceof Promise)G.push(H.then((L)=>{if(L.issues.length)J.issues.push(...Q1(W,L.issues));J.value[U.value]=L.value}));else{if(H.issues.length)J.issues.push(...Q1(W,H.issues));J.value[U.value]=H.value}}}if(G.length)return Promise.all(G).then(()=>J);return J}});var aG=q("$ZodEnum",(Y,X)=>{o.init(Y,X);let J=QY(X.entries),Q=new Set(J);Y._zod.values=Q,Y._zod.pattern=new RegExp(`^(${J.filter(($)=>N9.has(typeof $)).map(($)=>typeof $==="string"?J1($):$.toString()).join("|")})$`),Y._zod.parse=($,G)=>{let W=$.value;if(Q.has(W))return $;return $.issues.push({code:"invalid_value",values:J,input:W,inst:Y}),$}}),tG=q("$ZodLiteral",(Y,X)=>{if(o.init(Y,X),X.values.length===0)throw Error("Cannot create literal schema with no valid values");Y._zod.values=new Set(X.values),Y._zod.pattern=new RegExp(`^(${X.values.map((J)=>typeof J==="string"?J1(J):J?J1(J.toString()):String(J)).join("|")})$`),Y._zod.parse=(J,Q)=>{let $=J.value;if(Y._zod.values.has($))return J;return J.issues.push({code:"invalid_value",values:X.values,input:$,inst:Y}),J}});var eG=q("$ZodTransform",(Y,X)=>{o.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new XY(Y.constructor.name);let $=X.transform(J.value,J);if(Q.async)return($ instanceof Promise?$:Promise.resolve($)).then((W)=>{return J.value=W,J});if($ instanceof Promise)throw new X1;return J.value=$,J}});function HG(Y,X){if(Y.issues.length&&X===void 0)return{issues:[],value:void 0};return Y}var Y5=q("$ZodOptional",(Y,X)=>{o.init(Y,X),Y._zod.optin="optional",Y._zod.optout="optional",p(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,void 0]):void 0}),p(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${GY(J.source)})?$`):void 0}),Y._zod.parse=(J,Q)=>{if(X.innerType._zod.optin==="optional"){let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>HG(G,J.value));return HG($,J.value)}if(J.value===void 0)return J;return X.innerType._zod.run(J,Q)}}),X5=q("$ZodNullable",(Y,X)=>{o.init(Y,X),p(Y._zod,"optin",()=>X.innerType._zod.optin),p(Y._zod,"optout",()=>X.innerType._zod.optout),p(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${GY(J.source)}|null)$`):void 0}),p(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,null]):void 0}),Y._zod.parse=(J,Q)=>{if(J.value===null)return J;return X.innerType._zod.run(J,Q)}}),J5=q("$ZodDefault",(Y,X)=>{o.init(Y,X),Y._zod.optin="optional",p(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);if(J.value===void 0)return J.value=X.defaultValue,J;let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>NG(G,X));return NG($,X)}});function NG(Y,X){if(Y.value===void 0)Y.value=X.defaultValue;return Y}var Q5=q("$ZodPrefault",(Y,X)=>{o.init(Y,X),Y._zod.optin="optional",p(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);if(J.value===void 0)J.value=X.defaultValue;return X.innerType._zod.run(J,Q)}}),$5=q("$ZodNonOptional",(Y,X)=>{o.init(Y,X),p(Y._zod,"values",()=>{let J=X.innerType._zod.values;return J?new Set([...J].filter((Q)=>Q!==void 0)):void 0}),Y._zod.parse=(J,Q)=>{let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>VG(G,Y));return VG($,Y)}});function VG(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 G5=q("$ZodCatch",(Y,X)=>{o.init(Y,X),p(Y._zod,"optin",()=>X.innerType._zod.optin),p(Y._zod,"optout",()=>X.innerType._zod.optout),p(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>{if(J.value=G.value,G.issues.length)J.value=X.catchValue({...J,error:{issues:G.issues.map((W)=>v0(W,Q,l0()))},input:J.value}),J.issues=[];return J});if(J.value=$.value,$.issues.length)J.value=X.catchValue({...J,error:{issues:$.issues.map((G)=>v0(G,Q,l0()))},input:J.value}),J.issues=[];return J}});var W5=q("$ZodPipe",(Y,X)=>{o.init(Y,X),p(Y._zod,"values",()=>X.in._zod.values),p(Y._zod,"optin",()=>X.in._zod.optin),p(Y._zod,"optout",()=>X.out._zod.optout),p(Y._zod,"propValues",()=>X.in._zod.propValues),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward"){let G=X.out._zod.run(J,Q);if(G instanceof Promise)return G.then((W)=>oY(W,X.in,Q));return oY(G,X.in,Q)}let $=X.in._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>oY(G,X.out,Q));return oY($,X.out,Q)}});function oY(Y,X,J){if(Y.issues.length)return Y.aborted=!0,Y;return X._zod.run({value:Y.value,issues:Y.issues},J)}var z5=q("$ZodReadonly",(Y,X)=>{o.init(Y,X),p(Y._zod,"propValues",()=>X.innerType._zod.propValues),p(Y._zod,"values",()=>X.innerType._zod.values),p(Y._zod,"optin",()=>X.innerType._zod.optin),p(Y._zod,"optout",()=>X.innerType._zod.optout),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then(ZG);return ZG($)}});function ZG(Y){return Y.value=Object.freeze(Y.value),Y}var U5=q("$ZodLazy",(Y,X)=>{o.init(Y,X),p(Y._zod,"innerType",()=>X.getter()),p(Y._zod,"pattern",()=>Y._zod.innerType._zod.pattern),p(Y._zod,"propValues",()=>Y._zod.innerType._zod.propValues),p(Y._zod,"optin",()=>Y._zod.innerType._zod.optin??void 0),p(Y._zod,"optout",()=>Y._zod.innerType._zod.optout??void 0),Y._zod.parse=(J,Q)=>{return Y._zod.innerType._zod.run(J,Q)}}),L5=q("$ZodCustom",(Y,X)=>{Z0.init(Y,X),o.init(Y,X),Y._zod.parse=(J,Q)=>{return J},Y._zod.check=(J)=>{let Q=J.value,$=X.fn(Q);if($ instanceof Promise)return $.then((G)=>KG(G,J,Q,Y));KG($,J,Q,Y);return}});function KG(Y,X,J,Q){if(!Y){let $={code:"custom",input:J,inst:Q,path:[...Q._zod.def.path??[]],continue:!Q._zod.def.abort};if(Q._zod.def.params)$.params=Q._zod.def.params;X.issues.push(l1($))}}var nB=Symbol("ZodOutput"),oB=Symbol("ZodInput");class aY{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 LH(){return new aY}var _1=LH();function H5(Y,X){return new Y({type:"string",...g(X)})}function N5(Y,X){return new Y({type:"string",format:"email",check:"string_format",abort:!1,...g(X)})}function E9(Y,X){return new Y({type:"string",format:"guid",check:"string_format",abort:!1,...g(X)})}function V5(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...g(X)})}function Z5(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...g(X)})}function K5(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...g(X)})}function B5(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...g(X)})}function O5(Y,X){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...g(X)})}function F5(Y,X){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...g(X)})}function q5(Y,X){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...g(X)})}function j5(Y,X){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...g(X)})}function D5(Y,X){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...g(X)})}function P5(Y,X){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...g(X)})}function M5(Y,X){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...g(X)})}function E5(Y,X){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...g(X)})}function A5(Y,X){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...g(X)})}function w5(Y,X){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...g(X)})}function T5(Y,X){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...g(X)})}function R5(Y,X){return new Y({type:"string",format:"cidrv6",check:"string_format",abort:!1,...g(X)})}function _5(Y,X){return new Y({type:"string",format:"base64",check:"string_format",abort:!1,...g(X)})}function C5(Y,X){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...g(X)})}function I5(Y,X){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...g(X)})}function S5(Y,X){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...g(X)})}function k5(Y,X){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...g(X)})}function b5(Y,X){return new Y({type:"string",format:"date",check:"string_format",...g(X)})}function x5(Y,X){return new Y({type:"string",format:"time",check:"string_format",precision:null,...g(X)})}function v5(Y,X){return new Y({type:"string",format:"duration",check:"string_format",...g(X)})}function h5(Y,X){return new Y({type:"number",checks:[],...g(X)})}function g5(Y,X){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...g(X)})}function y5(Y,X){return new Y({type:"boolean",...g(X)})}function f5(Y,X){return new Y({type:"null",...g(X)})}function m5(Y){return new Y({type:"unknown"})}function c5(Y,X){return new Y({type:"never",...g(X)})}function tY(Y,X){return new F9({check:"less_than",...g(X),value:Y,inclusive:!1})}function HY(Y,X){return new F9({check:"less_than",...g(X),value:Y,inclusive:!0})}function eY(Y,X){return new q9({check:"greater_than",...g(X),value:Y,inclusive:!1})}function NY(Y,X){return new q9({check:"greater_than",...g(X),value:Y,inclusive:!0})}function Y8(Y,X){return new n$({check:"multiple_of",...g(X),value:Y})}function X8(Y,X){return new r$({check:"max_length",...g(X),maximum:Y})}function d1(Y,X){return new s$({check:"min_length",...g(X),minimum:Y})}function J8(Y,X){return new a$({check:"length_equals",...g(X),length:Y})}function A9(Y,X){return new t$({check:"string_format",format:"regex",...g(X),pattern:Y})}function w9(Y){return new e$({check:"string_format",format:"lowercase",...g(Y)})}function T9(Y){return new YG({check:"string_format",format:"uppercase",...g(Y)})}function R9(Y,X){return new XG({check:"string_format",format:"includes",...g(X),includes:Y})}function _9(Y,X){return new JG({check:"string_format",format:"starts_with",...g(X),prefix:Y})}function C9(Y,X){return new QG({check:"string_format",format:"ends_with",...g(X),suffix:Y})}function C1(Y){return new $G({check:"overwrite",tx:Y})}function I9(Y){return C1((X)=>X.normalize(Y))}function S9(){return C1((Y)=>Y.trim())}function k9(){return C1((Y)=>Y.toLowerCase())}function b9(){return C1((Y)=>Y.toUpperCase())}function u5(Y,X,J){return new Y({type:"array",element:X,...g(J)})}function p5(Y,X,J){let Q=g(J);return Q.abort??(Q.abort=!0),new Y({type:"custom",check:"custom",fn:X,...Q})}function l5(Y,X,J){return new Y({type:"custom",check:"custom",fn:X,...g(J)})}function d5(Y){let X=HH((J)=>{return J.addIssue=(Q)=>{if(typeof Q==="string")J.issues.push(l1(Q,J.value,X._zod.def));else{let $=Q;if($.fatal)$.continue=!1;$.code??($.code="custom"),$.input??($.input=J.value),$.inst??($.inst=X),$.continue??($.continue=!X._zod.def.abort),J.issues.push(l1($))}},Y(J.value,J)});return X}function HH(Y,X){let J=new Z0({check:"custom",...g(X)});return J._zod.check=Y,J}class x9{constructor(Y){this.counter=0,this.metadataRegistry=Y?.metadata??_1,this.target=Y?.target??"draft-2020-12",this.unrepresentable=Y?.unrepresentable??"throw",this.override=Y?.override??(()=>{}),this.io=Y?.io??"output",this.seen=new Map}process(Y,X={path:[],schemaPath:[]}){var J;let Q=Y._zod.def,$={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},G=this.seen.get(Y);if(G){if(G.count++,X.schemaPath.includes(Y))G.cycle=X.path;return G.schema}let W={schema:{},count:1,cycle:void 0,path:X.path};this.seen.set(Y,W);let U=Y._zod.toJSONSchema?.();if(U)W.schema=U;else{let V={...X,schemaPath:[...X.schemaPath,Y],path:X.path},B=Y._zod.parent;if(B)W.ref=B,this.process(B,V),this.seen.get(B).isParent=!0;else{let K=W.schema;switch(Q.type){case"string":{let N=K;N.type="string";let{minimum:O,maximum:j,format:A,patterns:x,contentEncoding:E}=Y._zod.bag;if(typeof O==="number")N.minLength=O;if(typeof j==="number")N.maxLength=j;if(A){if(N.format=$[A]??A,N.format==="")delete N.format}if(E)N.contentEncoding=E;if(x&&x.size>0){let k=[...x];if(k.length===1)N.pattern=k[0].source;else if(k.length>1)W.schema.allOf=[...k.map((y)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:y.source}))]}break}case"number":{let N=K,{minimum:O,maximum:j,format:A,multipleOf:x,exclusiveMaximum:E,exclusiveMinimum:k}=Y._zod.bag;if(typeof A==="string"&&A.includes("int"))N.type="integer";else N.type="number";if(typeof k==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")N.minimum=k,N.exclusiveMinimum=!0;else N.exclusiveMinimum=k;if(typeof O==="number"){if(N.minimum=O,typeof k==="number"&&this.target!=="draft-4")if(k>=O)delete N.minimum;else delete N.exclusiveMinimum}if(typeof E==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")N.maximum=E,N.exclusiveMaximum=!0;else N.exclusiveMaximum=E;if(typeof j==="number"){if(N.maximum=j,typeof E==="number"&&this.target!=="draft-4")if(E<=j)delete N.maximum;else delete N.exclusiveMaximum}if(typeof x==="number")N.multipleOf=x;break}case"boolean":{let N=K;N.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema");break}case"null":{if(this.target==="openapi-3.0")K.type="string",K.nullable=!0,K.enum=[null];else K.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":{K.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let N=K,{minimum:O,maximum:j}=Y._zod.bag;if(typeof O==="number")N.minItems=O;if(typeof j==="number")N.maxItems=j;N.type="array",N.items=this.process(Q.element,{...V,path:[...V.path,"items"]});break}case"object":{let N=K;N.type="object",N.properties={};let O=Q.shape;for(let x in O)N.properties[x]=this.process(O[x],{...V,path:[...V.path,"properties",x]});let j=new Set(Object.keys(O)),A=new Set([...j].filter((x)=>{let E=Q.shape[x]._zod;if(this.io==="input")return E.optin===void 0;else return E.optout===void 0}));if(A.size>0)N.required=Array.from(A);if(Q.catchall?._zod.def.type==="never")N.additionalProperties=!1;else if(!Q.catchall){if(this.io==="output")N.additionalProperties=!1}else if(Q.catchall)N.additionalProperties=this.process(Q.catchall,{...V,path:[...V.path,"additionalProperties"]});break}case"union":{let N=K,O=Q.options.map((j,A)=>this.process(j,{...V,path:[...V.path,"anyOf",A]}));N.anyOf=O;break}case"intersection":{let N=K,O=this.process(Q.left,{...V,path:[...V.path,"allOf",0]}),j=this.process(Q.right,{...V,path:[...V.path,"allOf",1]}),A=(E)=>("allOf"in E)&&Object.keys(E).length===1,x=[...A(O)?O.allOf:[O],...A(j)?j.allOf:[j]];N.allOf=x;break}case"tuple":{let N=K;N.type="array";let O=this.target==="draft-2020-12"?"prefixItems":"items",j=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",A=Q.items.map((y,u)=>this.process(y,{...V,path:[...V.path,O,u]})),x=Q.rest?this.process(Q.rest,{...V,path:[...V.path,j,...this.target==="openapi-3.0"?[Q.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(N.prefixItems=A,x)N.items=x}else if(this.target==="openapi-3.0"){if(N.items={anyOf:A},x)N.items.anyOf.push(x);if(N.minItems=A.length,!x)N.maxItems=A.length}else if(N.items=A,x)N.additionalItems=x;let{minimum:E,maximum:k}=Y._zod.bag;if(typeof E==="number")N.minItems=E;if(typeof k==="number")N.maxItems=k;break}case"record":{let N=K;if(N.type="object",this.target==="draft-7"||this.target==="draft-2020-12")N.propertyNames=this.process(Q.keyType,{...V,path:[...V.path,"propertyNames"]});N.additionalProperties=this.process(Q.valueType,{...V,path:[...V.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let N=K,O=QY(Q.entries);if(O.every((j)=>typeof j==="number"))N.type="number";if(O.every((j)=>typeof j==="string"))N.type="string";N.enum=O;break}case"literal":{let N=K,O=[];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 O.push(Number(j));else O.push(j);if(O.length===0);else if(O.length===1){let j=O[0];if(N.type=j===null?"null":typeof j,this.target==="draft-4"||this.target==="openapi-3.0")N.enum=[j];else N.const=j}else{if(O.every((j)=>typeof j==="number"))N.type="number";if(O.every((j)=>typeof j==="string"))N.type="string";if(O.every((j)=>typeof j==="boolean"))N.type="string";if(O.every((j)=>j===null))N.type="null";N.enum=O}break}case"file":{let N=K,O={type:"string",format:"binary",contentEncoding:"binary"},{minimum:j,maximum:A,mime:x}=Y._zod.bag;if(j!==void 0)O.minLength=j;if(A!==void 0)O.maxLength=A;if(x)if(x.length===1)O.contentMediaType=x[0],Object.assign(N,O);else N.anyOf=x.map((E)=>{return{...O,contentMediaType:E}});else Object.assign(N,O);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let N=this.process(Q.innerType,V);if(this.target==="openapi-3.0")W.ref=Q.innerType,K.nullable=!0;else K.anyOf=[N,{type:"null"}];break}case"nonoptional":{this.process(Q.innerType,V),W.ref=Q.innerType;break}case"success":{let N=K;N.type="boolean";break}case"default":{this.process(Q.innerType,V),W.ref=Q.innerType,K.default=JSON.parse(JSON.stringify(Q.defaultValue));break}case"prefault":{if(this.process(Q.innerType,V),W.ref=Q.innerType,this.io==="input")K._prefault=JSON.parse(JSON.stringify(Q.defaultValue));break}case"catch":{this.process(Q.innerType,V),W.ref=Q.innerType;let N;try{N=Q.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}K.default=N;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let N=K,O=Y._zod.pattern;if(!O)throw Error("Pattern not found in template literal");N.type="string",N.pattern=O.source;break}case"pipe":{let N=this.io==="input"?Q.in._zod.def.type==="transform"?Q.out:Q.in:Q.out;this.process(N,V),W.ref=N;break}case"readonly":{this.process(Q.innerType,V),W.ref=Q.innerType,K.readOnly=!0;break}case"promise":{this.process(Q.innerType,V),W.ref=Q.innerType;break}case"optional":{this.process(Q.innerType,V),W.ref=Q.innerType;break}case"lazy":{let N=Y._zod.innerType;this.process(N,V),W.ref=N;break}case"custom":{if(this.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema");break}case"function":{if(this.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema");break}default:}}}let H=this.metadataRegistry.get(Y);if(H)Object.assign(W.schema,H);if(this.io==="input"&&L0(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 $=(L)=>{let V=this.target==="draft-2020-12"?"$defs":"definitions";if(J.external){let O=J.external.registry.get(L[0])?.id,j=J.external.uri??((x)=>x);if(O)return{ref:j(O)};let A=L[1].defId??L[1].schema.id??`schema${this.counter++}`;return L[1].defId=A,{defId:A,ref:`${j("__shared")}#/${V}/${A}`}}if(L[1]===Q)return{ref:"#"};let K=`${"#"}/${V}/`,N=L[1].schema.id??`__schema${this.counter++}`;return{defId:N,ref:K+N}},G=(L)=>{if(L[1].schema.$ref)return;let V=L[1],{ref:B,defId:K}=$(L);if(V.def={...V.schema},K)V.defId=K;let N=V.schema;for(let O in N)delete N[O];N.$ref=B};if(J.cycles==="throw")for(let L of this.seen.entries()){let V=L[1];if(V.cycle)throw Error(`Cycle detected: #/${V.cycle?.join("/")}/<root>
90
+ `)}Z.write("payload.value = newResult;"),Z.write("return payload;");let D=Z.compile();return(E,T)=>D(V,E,T)},$,W=IY,z=!e1.jitless,U=z&&KX.value,H=X.catchall,B;Y._zod.parse=(V,Z)=>{B??(B=Q.value);let j=V.value;if(!W(j))return V.issues.push({expected:"object",code:"invalid_type",input:j,inst:Y}),V;if(z&&U&&Z?.async===!1&&Z.jitless!==!0){if(!$)$=G(X.shape);if(V=$(V,Z),!H)return V;return sG([],j,V,Z,B,Y)}return J(V,Z)}});function NG(Y,X,J,Q){for(let $ of Y)if($.issues.length===0)return X.value=$.value,X;let G=Y.filter(($)=>!FY($));if(G.length===1)return X.value=G[0].value,G[0];return X.issues.push({code:"invalid_union",input:X.value,inst:J,errors:Y.map(($)=>$.issues.map((W)=>f0(W,Q,o0())))}),X}var jX=q("$ZodUnion",(Y,X)=>{a.init(Y,X),o(Y._zod,"optin",()=>X.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),o(Y._zod,"optout",()=>X.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),o(Y._zod,"values",()=>{if(X.options.every((G)=>G._zod.values))return new Set(X.options.flatMap((G)=>Array.from(G._zod.values)));return}),o(Y._zod,"pattern",()=>{if(X.options.every((G)=>G._zod.pattern)){let G=X.options.map(($)=>$._zod.pattern);return new RegExp(`^(${G.map(($)=>Z1($.source)).join("|")})$`)}return});let J=X.options.length===1,Q=X.options[0]._zod.run;Y._zod.parse=(G,$)=>{if(J)return Q(G,$);let W=!1,z=[];for(let L of X.options){let U=L._zod.run({value:G.value,issues:[]},$);if(U instanceof Promise)z.push(U),W=!0;else{if(U.issues.length===0)return U;z.push(U)}}if(!W)return NG(z,G,Y,$);return Promise.all(z).then((L)=>{return NG(L,G,Y,$)})}}),tG=q("$ZodDiscriminatedUnion",(Y,X)=>{jX.init(Y,X);let J=Y._zod.parse;o(Y._zod,"propValues",()=>{let G={};for(let $ of X.options){let W=$._zod.propValues;if(!W||Object.keys(W).length===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf($)}"`);for(let[z,L]of Object.entries(W)){if(!G[z])G[z]=new Set;for(let U of L)G[z].add(U)}}return G});let Q=uY(()=>{let G=X.options,$=new Map;for(let W of G){let z=W._zod.propValues?.[X.discriminator];if(!z||z.size===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf(W)}"`);for(let L of z){if($.has(L))throw Error(`Duplicate discriminator value "${String(L)}"`);$.set(L,W)}}return $});Y._zod.parse=(G,$)=>{let W=G.value;if(!IY(W))return G.issues.push({code:"invalid_type",expected:"object",input:W,inst:Y}),G;let z=Q.value.get(W?.[X.discriminator]);if(z)return z._zod.run(G,$);if(X.unionFallback)return J(G,$);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:X.discriminator,input:W,path:[X.discriminator],inst:Y}),G}}),eG=q("$ZodIntersection",(Y,X)=>{a.init(Y,X),Y._zod.parse=(J,Q)=>{let G=J.value,$=X.left._zod.run({value:G,issues:[]},Q),W=X.right._zod.run({value:G,issues:[]},Q);if($ instanceof Promise||W instanceof Promise)return Promise.all([$,W]).then(([L,U])=>{return ZG(J,L,U)});return ZG(J,$,W)}});function OX(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(BY(Y)&&BY(X)){let J=Object.keys(X),Q=Object.keys(Y).filter(($)=>J.indexOf($)!==-1),G={...Y,...X};for(let $ of Q){let W=OX(Y[$],X[$]);if(!W.valid)return{valid:!1,mergeErrorPath:[$,...W.mergeErrorPath]};G[$]=W.data}return{valid:!0,data:G}}if(Array.isArray(Y)&&Array.isArray(X)){if(Y.length!==X.length)return{valid:!1,mergeErrorPath:[]};let J=[];for(let Q=0;Q<Y.length;Q++){let G=Y[Q],$=X[Q],W=OX(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 ZG(Y,X,J){if(X.issues.length)Y.issues.push(...X.issues);if(J.issues.length)Y.issues.push(...J.issues);if(FY(Y))return Y;let Q=OX(X.value,J.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return Y.value=Q.data,Y}var Y$=q("$ZodRecord",(Y,X)=>{a.init(Y,X),Y._zod.parse=(J,Q)=>{let G=J.value;if(!BY(G))return J.issues.push({expected:"record",code:"invalid_type",input:G,inst:Y}),J;let $=[];if(X.keyType._zod.values){let W=X.keyType._zod.values;J.value={};for(let L of W)if(typeof L==="string"||typeof L==="number"||typeof L==="symbol"){let U=X.valueType._zod.run({value:G[L],issues:[]},Q);if(U instanceof Promise)$.push(U.then((H)=>{if(H.issues.length)J.issues.push(...QY(L,H.issues));J.value[L]=H.value}));else{if(U.issues.length)J.issues.push(...QY(L,U.issues));J.value[L]=U.value}}let z;for(let L in G)if(!W.has(L))z=z??[],z.push(L);if(z&&z.length>0)J.issues.push({code:"unrecognized_keys",input:G,inst:Y,keys:z})}else{J.value={};for(let W of Reflect.ownKeys(G)){if(W==="__proto__")continue;let z=X.keyType._zod.run({value:W,issues:[]},Q);if(z instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(z.issues.length){J.issues.push({code:"invalid_key",origin:"record",issues:z.issues.map((U)=>f0(U,Q,o0())),input:W,path:[W],inst:Y}),J.value[z.value]=z.value;continue}let L=X.valueType._zod.run({value:G[W],issues:[]},Q);if(L instanceof Promise)$.push(L.then((U)=>{if(U.issues.length)J.issues.push(...QY(W,U.issues));J.value[z.value]=U.value}));else{if(L.issues.length)J.issues.push(...QY(W,L.issues));J.value[z.value]=L.value}}}if($.length)return Promise.all($).then(()=>J);return J}});var X$=q("$ZodEnum",(Y,X)=>{a.init(Y,X);let J=H1(X.entries),Q=new Set(J);Y._zod.values=Q,Y._zod.pattern=new RegExp(`^(${J.filter((G)=>zX.has(typeof G)).map((G)=>typeof G==="string"?JY(G):G.toString()).join("|")})$`),Y._zod.parse=(G,$)=>{let W=G.value;if(Q.has(W))return G;return G.issues.push({code:"invalid_value",values:J,input:W,inst:Y}),G}}),J$=q("$ZodLiteral",(Y,X)=>{if(a.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"?JY(J):J?JY(J.toString()):String(J)).join("|")})$`),Y._zod.parse=(J,Q)=>{let G=J.value;if(Y._zod.values.has(G))return J;return J.issues.push({code:"invalid_value",values:X.values,input:G,inst:Y}),J}});var Q$=q("$ZodTransform",(Y,X)=>{a.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new U1(Y.constructor.name);let G=X.transform(J.value,J);if(Q.async)return(G instanceof Promise?G:Promise.resolve(G)).then((W)=>{return J.value=W,J});if(G instanceof Promise)throw new XY;return J.value=G,J}});function VG(Y,X){if(Y.issues.length&&X===void 0)return{issues:[],value:void 0};return Y}var G$=q("$ZodOptional",(Y,X)=>{a.init(Y,X),Y._zod.optin="optional",Y._zod.optout="optional",o(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,void 0]):void 0}),o(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${Z1(J.source)})?$`):void 0}),Y._zod.parse=(J,Q)=>{if(X.innerType._zod.optin==="optional"){let G=X.innerType._zod.run(J,Q);if(G instanceof Promise)return G.then(($)=>VG($,J.value));return VG(G,J.value)}if(J.value===void 0)return J;return X.innerType._zod.run(J,Q)}}),$$=q("$ZodNullable",(Y,X)=>{a.init(Y,X),o(Y._zod,"optin",()=>X.innerType._zod.optin),o(Y._zod,"optout",()=>X.innerType._zod.optout),o(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${Z1(J.source)}|null)$`):void 0}),o(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)}}),W$=q("$ZodDefault",(Y,X)=>{a.init(Y,X),Y._zod.optin="optional",o(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);if(J.value===void 0)return J.value=X.defaultValue,J;let G=X.innerType._zod.run(J,Q);if(G instanceof Promise)return G.then(($)=>BG($,X));return BG(G,X)}});function BG(Y,X){if(Y.value===void 0)Y.value=X.defaultValue;return Y}var K$=q("$ZodPrefault",(Y,X)=>{a.init(Y,X),Y._zod.optin="optional",o(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)}}),z$=q("$ZodNonOptional",(Y,X)=>{a.init(Y,X),o(Y._zod,"values",()=>{let J=X.innerType._zod.values;return J?new Set([...J].filter((Q)=>Q!==void 0)):void 0}),Y._zod.parse=(J,Q)=>{let G=X.innerType._zod.run(J,Q);if(G instanceof Promise)return G.then(($)=>FG($,Y));return FG(G,Y)}});function FG(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 U$=q("$ZodCatch",(Y,X)=>{a.init(Y,X),o(Y._zod,"optin",()=>X.innerType._zod.optin),o(Y._zod,"optout",()=>X.innerType._zod.optout),o(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);let G=X.innerType._zod.run(J,Q);if(G instanceof Promise)return G.then(($)=>{if(J.value=$.value,$.issues.length)J.value=X.catchValue({...J,error:{issues:$.issues.map((W)=>f0(W,Q,o0()))},input:J.value}),J.issues=[];return J});if(J.value=G.value,G.issues.length)J.value=X.catchValue({...J,error:{issues:G.issues.map(($)=>f0($,Q,o0()))},input:J.value}),J.issues=[];return J}});var L$=q("$ZodPipe",(Y,X)=>{a.init(Y,X),o(Y._zod,"values",()=>X.in._zod.values),o(Y._zod,"optin",()=>X.in._zod.optin),o(Y._zod,"optout",()=>X.out._zod.optout),o(Y._zod,"propValues",()=>X.in._zod.propValues),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward"){let $=X.out._zod.run(J,Q);if($ instanceof Promise)return $.then((W)=>W9(W,X.in,Q));return W9($,X.in,Q)}let G=X.in._zod.run(J,Q);if(G instanceof Promise)return G.then(($)=>W9($,X.out,Q));return W9(G,X.out,Q)}});function W9(Y,X,J){if(Y.issues.length)return Y.aborted=!0,Y;return X._zod.run({value:Y.value,issues:Y.issues},J)}var H$=q("$ZodReadonly",(Y,X)=>{a.init(Y,X),o(Y._zod,"propValues",()=>X.innerType._zod.propValues),o(Y._zod,"values",()=>X.innerType._zod.values),o(Y._zod,"optin",()=>X.innerType._zod.optin),o(Y._zod,"optout",()=>X.innerType._zod.optout),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);let G=X.innerType._zod.run(J,Q);if(G instanceof Promise)return G.then(OG);return OG(G)}});function OG(Y){return Y.value=Object.freeze(Y.value),Y}var N$=q("$ZodLazy",(Y,X)=>{a.init(Y,X),o(Y._zod,"innerType",()=>X.getter()),o(Y._zod,"pattern",()=>Y._zod.innerType._zod.pattern),o(Y._zod,"propValues",()=>Y._zod.innerType._zod.propValues),o(Y._zod,"optin",()=>Y._zod.innerType._zod.optin??void 0),o(Y._zod,"optout",()=>Y._zod.innerType._zod.optout??void 0),Y._zod.parse=(J,Q)=>{return Y._zod.innerType._zod.run(J,Q)}}),Z$=q("$ZodCustom",(Y,X)=>{q0.init(Y,X),a.init(Y,X),Y._zod.parse=(J,Q)=>{return J},Y._zod.check=(J)=>{let Q=J.value,G=X.fn(Q);if(G instanceof Promise)return G.then(($)=>qG($,J,Q,Y));qG(G,J,Q,Y);return}});function qG(Y,X,J,Q){if(!Y){let G={code:"custom",input:J,inst:Q,path:[...Q._zod.def.path??[]],continue:!Q._zod.def.abort};if(Q._zod.def.params)G.params=Q._zod.def.params;X.issues.push(pY(G))}}var UO=Symbol("ZodOutput"),LO=Symbol("ZodInput");class U9{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 QL(){return new U9}var _Y=QL();function V$(Y,X){return new Y({type:"string",...y(X)})}function B$(Y,X){return new Y({type:"string",format:"email",check:"string_format",abort:!1,...y(X)})}function DX(Y,X){return new Y({type:"string",format:"guid",check:"string_format",abort:!1,...y(X)})}function F$(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...y(X)})}function O$(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...y(X)})}function q$(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...y(X)})}function j$(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...y(X)})}function D$(Y,X){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...y(X)})}function P$(Y,X){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...y(X)})}function M$(Y,X){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...y(X)})}function E$(Y,X){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...y(X)})}function w$(Y,X){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...y(X)})}function A$(Y,X){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...y(X)})}function T$(Y,X){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...y(X)})}function R$(Y,X){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...y(X)})}function C$(Y,X){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...y(X)})}function I$(Y,X){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...y(X)})}function _$(Y,X){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...y(X)})}function S$(Y,X){return new Y({type:"string",format:"cidrv6",check:"string_format",abort:!1,...y(X)})}function k$(Y,X){return new Y({type:"string",format:"base64",check:"string_format",abort:!1,...y(X)})}function x$(Y,X){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...y(X)})}function b$(Y,X){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...y(X)})}function v$(Y,X){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...y(X)})}function h$(Y,X){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...y(X)})}function g$(Y,X){return new Y({type:"string",format:"date",check:"string_format",...y(X)})}function y$(Y,X){return new Y({type:"string",format:"time",check:"string_format",precision:null,...y(X)})}function f$(Y,X){return new Y({type:"string",format:"duration",check:"string_format",...y(X)})}function m$(Y,X){return new Y({type:"number",checks:[],...y(X)})}function c$(Y,X){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...y(X)})}function u$(Y,X){return new Y({type:"boolean",...y(X)})}function p$(Y,X){return new Y({type:"null",...y(X)})}function l$(Y){return new Y({type:"unknown"})}function d$(Y,X){return new Y({type:"never",...y(X)})}function L9(Y,X){return new VX({check:"less_than",...y(X),value:Y,inclusive:!1})}function q1(Y,X){return new VX({check:"less_than",...y(X),value:Y,inclusive:!0})}function H9(Y,X){return new BX({check:"greater_than",...y(X),value:Y,inclusive:!1})}function j1(Y,X){return new BX({check:"greater_than",...y(X),value:Y,inclusive:!0})}function N9(Y,X){return new a5({check:"multiple_of",...y(X),value:Y})}function Z9(Y,X){return new e5({check:"max_length",...y(X),maximum:Y})}function lY(Y,X){return new YG({check:"min_length",...y(X),minimum:Y})}function V9(Y,X){return new XG({check:"length_equals",...y(X),length:Y})}function PX(Y,X){return new JG({check:"string_format",format:"regex",...y(X),pattern:Y})}function MX(Y){return new QG({check:"string_format",format:"lowercase",...y(Y)})}function EX(Y){return new GG({check:"string_format",format:"uppercase",...y(Y)})}function wX(Y,X){return new $G({check:"string_format",format:"includes",...y(X),includes:Y})}function AX(Y,X){return new WG({check:"string_format",format:"starts_with",...y(X),prefix:Y})}function TX(Y,X){return new KG({check:"string_format",format:"ends_with",...y(X),suffix:Y})}function SY(Y){return new zG({check:"overwrite",tx:Y})}function RX(Y){return SY((X)=>X.normalize(Y))}function CX(){return SY((Y)=>Y.trim())}function IX(){return SY((Y)=>Y.toLowerCase())}function _X(){return SY((Y)=>Y.toUpperCase())}function i$(Y,X,J){return new Y({type:"array",element:X,...y(J)})}function o$(Y,X,J){let Q=y(J);return Q.abort??(Q.abort=!0),new Y({type:"custom",check:"custom",fn:X,...Q})}function n$(Y,X,J){return new Y({type:"custom",check:"custom",fn:X,...y(J)})}function r$(Y){let X=GL((J)=>{return J.addIssue=(Q)=>{if(typeof Q==="string")J.issues.push(pY(Q,J.value,X._zod.def));else{let G=Q;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=J.value),G.inst??(G.inst=X),G.continue??(G.continue=!X._zod.def.abort),J.issues.push(pY(G))}},Y(J.value,J)});return X}function GL(Y,X){let J=new q0({check:"custom",...y(X)});return J._zod.check=Y,J}class SX{constructor(Y){this.counter=0,this.metadataRegistry=Y?.metadata??_Y,this.target=Y?.target??"draft-2020-12",this.unrepresentable=Y?.unrepresentable??"throw",this.override=Y?.override??(()=>{}),this.io=Y?.io??"output",this.seen=new Map}process(Y,X={path:[],schemaPath:[]}){var J;let Q=Y._zod.def,G={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},$=this.seen.get(Y);if($){if($.count++,X.schemaPath.includes(Y))$.cycle=X.path;return $.schema}let W={schema:{},count:1,cycle:void 0,path:X.path};this.seen.set(Y,W);let z=Y._zod.toJSONSchema?.();if(z)W.schema=z;else{let H={...X,schemaPath:[...X.schemaPath,Y],path:X.path},B=Y._zod.parent;if(B)W.ref=B,this.process(B,H),this.seen.get(B).isParent=!0;else{let V=W.schema;switch(Q.type){case"string":{let Z=V;Z.type="string";let{minimum:j,maximum:O,format:C,patterns:R,contentEncoding:D}=Y._zod.bag;if(typeof j==="number")Z.minLength=j;if(typeof O==="number")Z.maxLength=O;if(C){if(Z.format=G[C]??C,Z.format==="")delete Z.format}if(D)Z.contentEncoding=D;if(R&&R.size>0){let E=[...R];if(E.length===1)Z.pattern=E[0].source;else if(E.length>1)W.schema.allOf=[...E.map((T)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:T.source}))]}break}case"number":{let Z=V,{minimum:j,maximum:O,format:C,multipleOf:R,exclusiveMaximum:D,exclusiveMinimum:E}=Y._zod.bag;if(typeof C==="string"&&C.includes("int"))Z.type="integer";else Z.type="number";if(typeof E==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")Z.minimum=E,Z.exclusiveMinimum=!0;else Z.exclusiveMinimum=E;if(typeof j==="number"){if(Z.minimum=j,typeof E==="number"&&this.target!=="draft-4")if(E>=j)delete Z.minimum;else delete Z.exclusiveMinimum}if(typeof D==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")Z.maximum=D,Z.exclusiveMaximum=!0;else Z.exclusiveMaximum=D;if(typeof O==="number"){if(Z.maximum=O,typeof D==="number"&&this.target!=="draft-4")if(D<=O)delete Z.maximum;else delete Z.exclusiveMaximum}if(typeof R==="number")Z.multipleOf=R;break}case"boolean":{let Z=V;Z.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")V.type="string",V.nullable=!0,V.enum=[null];else V.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":{V.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let Z=V,{minimum:j,maximum:O}=Y._zod.bag;if(typeof j==="number")Z.minItems=j;if(typeof O==="number")Z.maxItems=O;Z.type="array",Z.items=this.process(Q.element,{...H,path:[...H.path,"items"]});break}case"object":{let Z=V;Z.type="object",Z.properties={};let j=Q.shape;for(let R in j)Z.properties[R]=this.process(j[R],{...H,path:[...H.path,"properties",R]});let O=new Set(Object.keys(j)),C=new Set([...O].filter((R)=>{let D=Q.shape[R]._zod;if(this.io==="input")return D.optin===void 0;else return D.optout===void 0}));if(C.size>0)Z.required=Array.from(C);if(Q.catchall?._zod.def.type==="never")Z.additionalProperties=!1;else if(!Q.catchall){if(this.io==="output")Z.additionalProperties=!1}else if(Q.catchall)Z.additionalProperties=this.process(Q.catchall,{...H,path:[...H.path,"additionalProperties"]});break}case"union":{let Z=V,j=Q.options.map((O,C)=>this.process(O,{...H,path:[...H.path,"anyOf",C]}));Z.anyOf=j;break}case"intersection":{let Z=V,j=this.process(Q.left,{...H,path:[...H.path,"allOf",0]}),O=this.process(Q.right,{...H,path:[...H.path,"allOf",1]}),C=(D)=>("allOf"in D)&&Object.keys(D).length===1,R=[...C(j)?j.allOf:[j],...C(O)?O.allOf:[O]];Z.allOf=R;break}case"tuple":{let Z=V;Z.type="array";let j=this.target==="draft-2020-12"?"prefixItems":"items",O=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",C=Q.items.map((T,g)=>this.process(T,{...H,path:[...H.path,j,g]})),R=Q.rest?this.process(Q.rest,{...H,path:[...H.path,O,...this.target==="openapi-3.0"?[Q.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(Z.prefixItems=C,R)Z.items=R}else if(this.target==="openapi-3.0"){if(Z.items={anyOf:C},R)Z.items.anyOf.push(R);if(Z.minItems=C.length,!R)Z.maxItems=C.length}else if(Z.items=C,R)Z.additionalItems=R;let{minimum:D,maximum:E}=Y._zod.bag;if(typeof D==="number")Z.minItems=D;if(typeof E==="number")Z.maxItems=E;break}case"record":{let Z=V;if(Z.type="object",this.target==="draft-7"||this.target==="draft-2020-12")Z.propertyNames=this.process(Q.keyType,{...H,path:[...H.path,"propertyNames"]});Z.additionalProperties=this.process(Q.valueType,{...H,path:[...H.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 Z=V,j=H1(Q.entries);if(j.every((O)=>typeof O==="number"))Z.type="number";if(j.every((O)=>typeof O==="string"))Z.type="string";Z.enum=j;break}case"literal":{let Z=V,j=[];for(let O of Q.values)if(O===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof O==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else j.push(Number(O));else j.push(O);if(j.length===0);else if(j.length===1){let O=j[0];if(Z.type=O===null?"null":typeof O,this.target==="draft-4"||this.target==="openapi-3.0")Z.enum=[O];else Z.const=O}else{if(j.every((O)=>typeof O==="number"))Z.type="number";if(j.every((O)=>typeof O==="string"))Z.type="string";if(j.every((O)=>typeof O==="boolean"))Z.type="string";if(j.every((O)=>O===null))Z.type="null";Z.enum=j}break}case"file":{let Z=V,j={type:"string",format:"binary",contentEncoding:"binary"},{minimum:O,maximum:C,mime:R}=Y._zod.bag;if(O!==void 0)j.minLength=O;if(C!==void 0)j.maxLength=C;if(R)if(R.length===1)j.contentMediaType=R[0],Object.assign(Z,j);else Z.anyOf=R.map((D)=>{return{...j,contentMediaType:D}});else Object.assign(Z,j);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let Z=this.process(Q.innerType,H);if(this.target==="openapi-3.0")W.ref=Q.innerType,V.nullable=!0;else V.anyOf=[Z,{type:"null"}];break}case"nonoptional":{this.process(Q.innerType,H),W.ref=Q.innerType;break}case"success":{let Z=V;Z.type="boolean";break}case"default":{this.process(Q.innerType,H),W.ref=Q.innerType,V.default=JSON.parse(JSON.stringify(Q.defaultValue));break}case"prefault":{if(this.process(Q.innerType,H),W.ref=Q.innerType,this.io==="input")V._prefault=JSON.parse(JSON.stringify(Q.defaultValue));break}case"catch":{this.process(Q.innerType,H),W.ref=Q.innerType;let Z;try{Z=Q.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}V.default=Z;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let Z=V,j=Y._zod.pattern;if(!j)throw Error("Pattern not found in template literal");Z.type="string",Z.pattern=j.source;break}case"pipe":{let Z=this.io==="input"?Q.in._zod.def.type==="transform"?Q.out:Q.in:Q.out;this.process(Z,H),W.ref=Z;break}case"readonly":{this.process(Q.innerType,H),W.ref=Q.innerType,V.readOnly=!0;break}case"promise":{this.process(Q.innerType,H),W.ref=Q.innerType;break}case"optional":{this.process(Q.innerType,H),W.ref=Q.innerType;break}case"lazy":{let Z=Y._zod.innerType;this.process(Z,H),W.ref=Z;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"&&N0(Y))delete W.schema.examples,delete W.schema.default;if(this.io==="input"&&W.schema._prefault)(J=W.schema).default??(J.default=W.schema._prefault);return delete W.schema._prefault,this.seen.get(Y).schema}emit(Y,X){let J={cycles:X?.cycles??"ref",reused:X?.reused??"inline",external:X?.external??void 0},Q=this.seen.get(Y);if(!Q)throw Error("Unprocessed schema. This is a bug in Zod.");let G=(U)=>{let H=this.target==="draft-2020-12"?"$defs":"definitions";if(J.external){let j=J.external.registry.get(U[0])?.id,O=J.external.uri??((R)=>R);if(j)return{ref:O(j)};let C=U[1].defId??U[1].schema.id??`schema${this.counter++}`;return U[1].defId=C,{defId:C,ref:`${O("__shared")}#/${H}/${C}`}}if(U[1]===Q)return{ref:"#"};let V=`${"#"}/${H}/`,Z=U[1].schema.id??`__schema${this.counter++}`;return{defId:Z,ref:V+Z}},$=(U)=>{if(U[1].schema.$ref)return;let H=U[1],{ref:B,defId:V}=G(U);if(H.def={...H.schema},V)H.defId=V;let Z=H.schema;for(let j in Z)delete Z[j];Z.$ref=B};if(J.cycles==="throw")for(let U of this.seen.entries()){let H=U[1];if(H.cycle)throw Error(`Cycle detected: #/${H.cycle?.join("/")}/<root>
186
91
 
187
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let L of this.seen.entries()){let V=L[1];if(Y===L[0]){G(L);continue}if(J.external){let K=J.external.registry.get(L[0])?.id;if(Y!==L[0]&&K){G(L);continue}}if(this.metadataRegistry.get(L[0])?.id){G(L);continue}if(V.cycle){G(L);continue}if(V.count>1){if(J.reused==="ref"){G(L);continue}}}let W=(L,V)=>{let B=this.seen.get(L),K=B.def??B.schema,N={...K};if(B.ref===null)return;let O=B.ref;if(B.ref=null,O){W(O,V);let j=this.seen.get(O).schema;if(j.$ref&&(V.target==="draft-7"||V.target==="draft-4"||V.target==="openapi-3.0"))K.allOf=K.allOf??[],K.allOf.push(j);else Object.assign(K,j),Object.assign(K,N)}if(!B.isParent)this.override({zodSchema:L,jsonSchema:K,path:B.path??[]})};for(let L of[...this.seen.entries()].reverse())W(L[0],{target:this.target});let U={};if(this.target==="draft-2020-12")U.$schema="https://json-schema.org/draft/2020-12/schema";else if(this.target==="draft-7")U.$schema="http://json-schema.org/draft-07/schema#";else if(this.target==="draft-4")U.$schema="http://json-schema.org/draft-04/schema#";else if(this.target==="openapi-3.0");else console.warn(`Invalid target: ${this.target}`);if(J.external?.uri){let L=J.external.registry.get(Y)?.id;if(!L)throw Error("Schema is missing an `id` property");U.$id=J.external.uri(L)}Object.assign(U,Q.def);let H=J.external?.defs??{};for(let L of this.seen.entries()){let V=L[1];if(V.def&&V.defId)H[V.defId]=V.def}if(J.external);else if(Object.keys(H).length>0)if(this.target==="draft-2020-12")U.$defs=H;else U.definitions=H;try{return JSON.parse(JSON.stringify(U))}catch(L){throw Error("Error converting schema to JSON.")}}}function i5(Y,X){if(Y instanceof aY){let Q=new x9(X),$={};for(let U of Y._idmap.entries()){let[H,L]=U;Q.process(L)}let G={},W={registry:Y,uri:X?.uri,defs:$};for(let U of Y._idmap.entries()){let[H,L]=U;G[H]=Q.emit(L,{...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 x9(X);return J.process(Y),J.emit(Y,X)}function L0(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 L0($.element,J);case"object":{for(let G in $.shape)if(L0($.shape[G],J))return!0;return!1}case"union":{for(let G of $.options)if(L0(G,J))return!0;return!1}case"intersection":return L0($.left,J)||L0($.right,J);case"tuple":{for(let G of $.items)if(L0(G,J))return!0;if($.rest&&L0($.rest,J))return!0;return!1}case"record":return L0($.keyType,J)||L0($.valueType,J);case"map":return L0($.keyType,J)||L0($.valueType,J);case"set":return L0($.valueType,J);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return L0($.innerType,J);case"lazy":return L0($.getter(),J);case"default":return L0($.innerType,J);case"prefault":return L0($.innerType,J);case"custom":return!1;case"transform":return!0;case"pipe":return L0($.in,J)||L0($.out,J);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${$.type}`)}var OH=q("ZodISODateTime",(Y,X)=>{TG.init(Y,X),t.init(Y,X)});function n5(Y){return k5(OH,Y)}var FH=q("ZodISODate",(Y,X)=>{RG.init(Y,X),t.init(Y,X)});function o5(Y){return b5(FH,Y)}var qH=q("ZodISOTime",(Y,X)=>{_G.init(Y,X),t.init(Y,X)});function r5(Y){return x5(qH,Y)}var jH=q("ZodISODuration",(Y,X)=>{CG.init(Y,X),t.init(Y,X)});function s5(Y){return v5(jH,Y)}var a5=(Y,X)=>{lY.init(Y,X),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(J)=>W$(Y,J)},flatten:{value:(J)=>G$(Y,J)},addIssue:{value:(J)=>{Y.issues.push(J),Y.message=JSON.stringify(Y.issues,u1,2)}},addIssues:{value:(J)=>{Y.issues.push(...J),Y.message=JSON.stringify(Y.issues,u1,2)}},isEmpty:{get(){return Y.issues.length===0}}})},AO=q("ZodError",a5),_0=q("ZodError",a5,{Parent:Error});var t5=dY(_0),e5=iY(_0),Y7=zY(_0),$8=UY(_0),X7=L$(_0),J7=H$(_0),Q7=N$(_0),$7=V$(_0),G7=Z$(_0),W7=K$(_0),z7=B$(_0),U7=O$(_0);var e=q("ZodType",(Y,X)=>{return o.init(Y,X),Y.def=X,Y.type=X.type,Object.defineProperty(Y,"_def",{value:X}),Y.check=(...J)=>{return Y.clone({...X,checks:[...X.checks??[],...J.map((Q)=>typeof Q==="function"?{_zod:{check:Q,def:{check:"custom"},onattach:[]}}:Q)]})},Y.clone=(J,Q)=>x0(Y,J,Q),Y.brand=()=>Y,Y.register=(J,Q)=>{return J.add(Y,Q),Y},Y.parse=(J,Q)=>t5(Y,J,Q,{callee:Y.parse}),Y.safeParse=(J,Q)=>Y7(Y,J,Q),Y.parseAsync=async(J,Q)=>e5(Y,J,Q,{callee:Y.parseAsync}),Y.safeParseAsync=async(J,Q)=>$8(Y,J,Q),Y.spa=Y.safeParseAsync,Y.encode=(J,Q)=>X7(Y,J,Q),Y.decode=(J,Q)=>J7(Y,J,Q),Y.encodeAsync=async(J,Q)=>Q7(Y,J,Q),Y.decodeAsync=async(J,Q)=>$7(Y,J,Q),Y.safeEncode=(J,Q)=>G7(Y,J,Q),Y.safeDecode=(J,Q)=>W7(Y,J,Q),Y.safeEncodeAsync=async(J,Q)=>z7(Y,J,Q),Y.safeDecodeAsync=async(J,Q)=>U7(Y,J,Q),Y.refine=(J,Q)=>Y.check(VN(J,Q)),Y.superRefine=(J)=>Y.check(ZN(J)),Y.overwrite=(J)=>Y.check(C1(J)),Y.optional=()=>N7(Y),Y.nullable=()=>V7(Y),Y.nullish=()=>N7(V7(Y)),Y.nonoptional=(J)=>GN(Y,J),Y.array=()=>g9(Y),Y.or=(J)=>y9([Y,J]),Y.and=(J)=>rH(Y,J),Y.transform=(J)=>Z7(Y,eH(J)),Y.default=(J)=>JN(Y,J),Y.prefault=(J)=>$N(Y,J),Y.catch=(J)=>zN(Y,J),Y.pipe=(J)=>Z7(Y,J),Y.readonly=()=>HN(Y),Y.describe=(J)=>{let Q=Y.clone();return _1.add(Q,{description:J}),Q},Object.defineProperty(Y,"description",{get(){return _1.get(Y)?.description},configurable:!0}),Y.meta=(...J)=>{if(J.length===0)return _1.get(Y);let Q=Y.clone();return _1.add(Q,J[0]),Q},Y.isOptional=()=>Y.safeParse(void 0).success,Y.isNullable=()=>Y.safeParse(null).success,Y}),K7=q("_ZodString",(Y,X)=>{sY.init(Y,X),e.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(A9(...Q)),Y.includes=(...Q)=>Y.check(R9(...Q)),Y.startsWith=(...Q)=>Y.check(_9(...Q)),Y.endsWith=(...Q)=>Y.check(C9(...Q)),Y.min=(...Q)=>Y.check(d1(...Q)),Y.max=(...Q)=>Y.check(X8(...Q)),Y.length=(...Q)=>Y.check(J8(...Q)),Y.nonempty=(...Q)=>Y.check(d1(1,...Q)),Y.lowercase=(Q)=>Y.check(w9(Q)),Y.uppercase=(Q)=>Y.check(T9(Q)),Y.trim=()=>Y.check(S9()),Y.normalize=(...Q)=>Y.check(I9(...Q)),Y.toLowerCase=()=>Y.check(k9()),Y.toUpperCase=()=>Y.check(b9())}),EH=q("ZodString",(Y,X)=>{sY.init(Y,X),K7.init(Y,X),Y.email=(J)=>Y.check(N5(AH,J)),Y.url=(J)=>Y.check(O5(wH,J)),Y.jwt=(J)=>Y.check(S5(mH,J)),Y.emoji=(J)=>Y.check(F5(TH,J)),Y.guid=(J)=>Y.check(E9(L7,J)),Y.uuid=(J)=>Y.check(V5(G8,J)),Y.uuidv4=(J)=>Y.check(Z5(G8,J)),Y.uuidv6=(J)=>Y.check(K5(G8,J)),Y.uuidv7=(J)=>Y.check(B5(G8,J)),Y.nanoid=(J)=>Y.check(q5(RH,J)),Y.guid=(J)=>Y.check(E9(L7,J)),Y.cuid=(J)=>Y.check(j5(_H,J)),Y.cuid2=(J)=>Y.check(D5(CH,J)),Y.ulid=(J)=>Y.check(P5(IH,J)),Y.base64=(J)=>Y.check(_5(gH,J)),Y.base64url=(J)=>Y.check(C5(yH,J)),Y.xid=(J)=>Y.check(M5(SH,J)),Y.ksuid=(J)=>Y.check(E5(kH,J)),Y.ipv4=(J)=>Y.check(A5(bH,J)),Y.ipv6=(J)=>Y.check(w5(xH,J)),Y.cidrv4=(J)=>Y.check(T5(vH,J)),Y.cidrv6=(J)=>Y.check(R5(hH,J)),Y.e164=(J)=>Y.check(I5(fH,J)),Y.datetime=(J)=>Y.check(n5(J)),Y.date=(J)=>Y.check(o5(J)),Y.time=(J)=>Y.check(r5(J)),Y.duration=(J)=>Y.check(s5(J))});function B7(Y){return H5(EH,Y)}var t=q("ZodStringFormat",(Y,X)=>{s.init(Y,X),K7.init(Y,X)}),AH=q("ZodEmail",(Y,X)=>{FG.init(Y,X),t.init(Y,X)});var L7=q("ZodGUID",(Y,X)=>{BG.init(Y,X),t.init(Y,X)});var G8=q("ZodUUID",(Y,X)=>{OG.init(Y,X),t.init(Y,X)});var wH=q("ZodURL",(Y,X)=>{qG.init(Y,X),t.init(Y,X)});var TH=q("ZodEmoji",(Y,X)=>{jG.init(Y,X),t.init(Y,X)});var RH=q("ZodNanoID",(Y,X)=>{DG.init(Y,X),t.init(Y,X)});var _H=q("ZodCUID",(Y,X)=>{PG.init(Y,X),t.init(Y,X)});var CH=q("ZodCUID2",(Y,X)=>{MG.init(Y,X),t.init(Y,X)});var IH=q("ZodULID",(Y,X)=>{EG.init(Y,X),t.init(Y,X)});var SH=q("ZodXID",(Y,X)=>{AG.init(Y,X),t.init(Y,X)});var kH=q("ZodKSUID",(Y,X)=>{wG.init(Y,X),t.init(Y,X)});var bH=q("ZodIPv4",(Y,X)=>{IG.init(Y,X),t.init(Y,X)});var xH=q("ZodIPv6",(Y,X)=>{SG.init(Y,X),t.init(Y,X)});var vH=q("ZodCIDRv4",(Y,X)=>{kG.init(Y,X),t.init(Y,X)});var hH=q("ZodCIDRv6",(Y,X)=>{bG.init(Y,X),t.init(Y,X)});var gH=q("ZodBase64",(Y,X)=>{vG.init(Y,X),t.init(Y,X)});var yH=q("ZodBase64URL",(Y,X)=>{hG.init(Y,X),t.init(Y,X)});var fH=q("ZodE164",(Y,X)=>{gG.init(Y,X),t.init(Y,X)});var mH=q("ZodJWT",(Y,X)=>{yG.init(Y,X),t.init(Y,X)});var O7=q("ZodNumber",(Y,X)=>{P9.init(Y,X),e.init(Y,X),Y.gt=(Q,$)=>Y.check(eY(Q,$)),Y.gte=(Q,$)=>Y.check(NY(Q,$)),Y.min=(Q,$)=>Y.check(NY(Q,$)),Y.lt=(Q,$)=>Y.check(tY(Q,$)),Y.lte=(Q,$)=>Y.check(HY(Q,$)),Y.max=(Q,$)=>Y.check(HY(Q,$)),Y.int=(Q)=>Y.check(H7(Q)),Y.safe=(Q)=>Y.check(H7(Q)),Y.positive=(Q)=>Y.check(eY(0,Q)),Y.nonnegative=(Q)=>Y.check(NY(0,Q)),Y.negative=(Q)=>Y.check(tY(0,Q)),Y.nonpositive=(Q)=>Y.check(HY(0,Q)),Y.multipleOf=(Q,$)=>Y.check(Y8(Q,$)),Y.step=(Q,$)=>Y.check(Y8(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 F7(Y){return h5(O7,Y)}var cH=q("ZodNumberFormat",(Y,X)=>{fG.init(Y,X),O7.init(Y,X)});function H7(Y){return g5(cH,Y)}var uH=q("ZodBoolean",(Y,X)=>{mG.init(Y,X),e.init(Y,X)});function q7(Y){return y5(uH,Y)}var pH=q("ZodNull",(Y,X)=>{cG.init(Y,X),e.init(Y,X)});function j7(Y){return f5(pH,Y)}var lH=q("ZodUnknown",(Y,X)=>{uG.init(Y,X),e.init(Y,X)});function VY(){return m5(lH)}var dH=q("ZodNever",(Y,X)=>{pG.init(Y,X),e.init(Y,X)});function h9(Y){return c5(dH,Y)}var iH=q("ZodArray",(Y,X)=>{lG.init(Y,X),e.init(Y,X),Y.element=X.element,Y.min=(J,Q)=>Y.check(d1(J,Q)),Y.nonempty=(J)=>Y.check(d1(1,J)),Y.max=(J,Q)=>Y.check(X8(J,Q)),Y.length=(J,Q)=>Y.check(J8(J,Q)),Y.unwrap=()=>Y.element});function g9(Y,X){return u5(iH,Y,X)}var D7=q("ZodObject",(Y,X)=>{nG.init(Y,X),e.init(Y,X),m.defineLazy(Y,"shape",()=>X.shape),Y.keyof=()=>f9(Object.keys(Y._zod.def.shape)),Y.catchall=(J)=>Y.clone({...Y._zod.def,catchall:J}),Y.passthrough=()=>Y.clone({...Y._zod.def,catchall:VY()}),Y.loose=()=>Y.clone({...Y._zod.def,catchall:VY()}),Y.strict=()=>Y.clone({...Y._zod.def,catchall:h9()}),Y.strip=()=>Y.clone({...Y._zod.def,catchall:void 0}),Y.extend=(J)=>{return m.extend(Y,J)},Y.safeExtend=(J)=>{return m.safeExtend(Y,J)},Y.merge=(J)=>m.merge(Y,J),Y.pick=(J)=>m.pick(Y,J),Y.omit=(J)=>m.omit(Y,J),Y.partial=(...J)=>m.partial(R7,Y,J[0]),Y.required=(...J)=>m.required(_7,Y,J[0])});function P7(Y,X){let J={type:"object",get shape(){return m.assignProp(this,"shape",Y?m.objectClone(Y):{}),this.shape},...m.normalizeParams(X)};return new D7(J)}function M7(Y,X){return new D7({type:"object",get shape(){return m.assignProp(this,"shape",m.objectClone(Y)),this.shape},catchall:VY(),...m.normalizeParams(X)})}var E7=q("ZodUnion",(Y,X)=>{M9.init(Y,X),e.init(Y,X),Y.options=X.options});function y9(Y,X){return new E7({type:"union",options:Y,...m.normalizeParams(X)})}var nH=q("ZodDiscriminatedUnion",(Y,X)=>{E7.init(Y,X),oG.init(Y,X)});function A7(Y,X,J){return new nH({type:"union",options:X,discriminator:Y,...m.normalizeParams(J)})}var oH=q("ZodIntersection",(Y,X)=>{rG.init(Y,X),e.init(Y,X)});function rH(Y,X){return new oH({type:"intersection",left:Y,right:X})}var sH=q("ZodRecord",(Y,X)=>{sG.init(Y,X),e.init(Y,X),Y.keyType=X.keyType,Y.valueType=X.valueType});function w7(Y,X,J){return new sH({type:"record",keyType:Y,valueType:X,...m.normalizeParams(J)})}var v9=q("ZodEnum",(Y,X)=>{aG.init(Y,X),e.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 v9({...X,checks:[],...m.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 v9({...X,checks:[],...m.normalizeParams($),entries:G})}});function f9(Y,X){let J=Array.isArray(Y)?Object.fromEntries(Y.map((Q)=>[Q,Q])):Y;return new v9({type:"enum",entries:J,...m.normalizeParams(X)})}var aH=q("ZodLiteral",(Y,X)=>{tG.init(Y,X),e.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 T7(Y,X){return new aH({type:"literal",values:Array.isArray(Y)?Y:[Y],...m.normalizeParams(X)})}var tH=q("ZodTransform",(Y,X)=>{eG.init(Y,X),e.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new XY(Y.constructor.name);J.addIssue=(G)=>{if(typeof G==="string")J.issues.push(m.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(m.issue(W))}};let $=X.transform(J.value,J);if($ instanceof Promise)return $.then((G)=>{return J.value=G,J});return J.value=$,J}});function eH(Y){return new tH({type:"transform",transform:Y})}var R7=q("ZodOptional",(Y,X)=>{Y5.init(Y,X),e.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function N7(Y){return new R7({type:"optional",innerType:Y})}var YN=q("ZodNullable",(Y,X)=>{X5.init(Y,X),e.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function V7(Y){return new YN({type:"nullable",innerType:Y})}var XN=q("ZodDefault",(Y,X)=>{J5.init(Y,X),e.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function JN(Y,X){return new XN({type:"default",innerType:Y,get defaultValue(){return typeof X==="function"?X():m.shallowClone(X)}})}var QN=q("ZodPrefault",(Y,X)=>{Q5.init(Y,X),e.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function $N(Y,X){return new QN({type:"prefault",innerType:Y,get defaultValue(){return typeof X==="function"?X():m.shallowClone(X)}})}var _7=q("ZodNonOptional",(Y,X)=>{$5.init(Y,X),e.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function GN(Y,X){return new _7({type:"nonoptional",innerType:Y,...m.normalizeParams(X)})}var WN=q("ZodCatch",(Y,X)=>{G5.init(Y,X),e.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function zN(Y,X){return new WN({type:"catch",innerType:Y,catchValue:typeof X==="function"?X:()=>X})}var UN=q("ZodPipe",(Y,X)=>{W5.init(Y,X),e.init(Y,X),Y.in=X.in,Y.out=X.out});function Z7(Y,X){return new UN({type:"pipe",in:Y,out:X})}var LN=q("ZodReadonly",(Y,X)=>{z5.init(Y,X),e.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function HN(Y){return new LN({type:"readonly",innerType:Y})}var NN=q("ZodLazy",(Y,X)=>{U5.init(Y,X),e.init(Y,X),Y.unwrap=()=>Y._zod.def.getter()});function C7(Y){return new NN({type:"lazy",getter:Y})}var m9=q("ZodCustom",(Y,X)=>{L5.init(Y,X),e.init(Y,X)});function I7(Y,X){return p5(m9,Y??(()=>!0),X)}function VN(Y,X={}){return l5(m9,Y,X)}function ZN(Y){return d5(Y)}function S7(Y,X={error:`Input not instance of ${Y.name}`}){let J=new m9({type:"custom",check:"custom",fn:(Q)=>Q instanceof Y,abort:!0,...m.normalizeParams(X)});return J._zod.bag.Class=Y,J}function c7(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 KN(Y){if(Y==null)return{};let X={};if(Y instanceof Headers)Y.forEach((J,Q)=>{X[Q.toLowerCase()]=J});else{if(!Array.isArray(Y))Y=Object.entries(Y);for(let[J,Q]of Y)if(Q!=null)X[J.toLowerCase()]=Q}return X}function i1(Y,...X){let J=new Headers(KN(Y)),Q=J.get("user-agent")||"";return J.set("user-agent",[Q,...X].filter(Boolean).join(" ")),Object.fromEntries(J.entries())}var BN=[{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]}],NF=[...BN,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];var ON=12,FN=131072,VF=FN+ON;async function W8(Y){var X;try{await((X=Y.body)==null?void 0:X.cancel())}catch(J){}}var u7="AI_DownloadError",p7=`vercel.ai.error.${u7}`,qN=Symbol.for(p7),k7,b7,j0=class extends(b7=D,k7=qN,b7){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:u7,message:$,cause:Q});this[k7]=!0,this.url=Y,this.statusCode=X,this.statusText=J}static isInstance(Y){return D.hasMarker(Y,p7)}};function jN(Y=globalThis){return Y.window!=null}function x7(Y,X){try{return new URL(Y).origin===new URL(X).origin}catch(J){return!1}}function DN(Y){let X;try{X=new URL(Y)}catch(Q){throw new j0({url:Y,message:`Invalid URL: ${Y}`})}if(X.protocol==="data:")return;if(X.protocol!=="http:"&&X.protocol!=="https:")throw new j0({url:Y,message:`URL scheme must be http, https, or data, got ${X.protocol}`});let J=X.hostname.toLowerCase().replace(/\.+$/,"");if(!J)throw new j0({url:Y,message:"URL must have a hostname"});if(J==="localhost"||J.endsWith(".local")||J.endsWith(".localhost"))throw new j0({url:Y,message:`URL with hostname ${J} is not allowed`});if(J.startsWith("[")&&J.endsWith("]")){let Q=J.slice(1,-1);if(l7(Q))throw new j0({url:Y,message:`URL with IPv6 address ${J} is not allowed`});return}if(i9(J)){if(n9(J))throw new j0({url:Y,message:`URL with IP address ${J} is not allowed`});return}}function PN({address:Y,family:X,hostname:J}){if(X===4?!i9(Y)||n9(Y):X===6?l7(Y):!0)throw new j0({url:J,message:`Hostname ${J} resolved to disallowed IP address ${Y}`})}function i9(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 n9(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 MN(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=[],H=W.split(":");for(let L=0;L<H.length;L++){let V=H[L];if(V.includes(".")){if(L!==H.length-1||!i9(V))return null;let[B,K,N,O]=V.split(".").map(Number);U.push(B<<8|K,N<<8|O);continue}if(!/^[0-9a-f]{1,4}$/.test(V))return null;U.push(parseInt(V,16))}return U},G=$(Q[0]);if(G===null)return null;if(Q.length===2){let W=$(Q[1]);if(W===null)return null;let U=8-G.length-W.length;if(U<0)return null;return[...G,...Array(U).fill(0),...W]}return G.length===8?G:null}function l7(Y){let X=MN(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 n9(`${$}.${G}.${W}.${U}`)}return!1}function EN(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:H}of G)PN({address:U,family:H,hostname:X});if(J.all===!0)Q(null,G);else Q(null,W.address,W.family)}catch(W){Q(W instanceof Error?W:Error(String(W)))}})}}var c9,d7=globalThis.fetch,AN=RN(d7);function wN(){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 TN(){if(!wN()||!AN||globalThis.fetch!==d7)return globalThis.fetch;return c9!=null?c9:c9=Promise.resolve().then(_N)}function RN(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 _N(){let{createRequire:Y}=v7("node:module"),{lookup:X}=v7("node:dns"),{Agent:J,fetch:Q}=Y(i7())("undici"),$=new J({connect:{lookup:EN(X)}});return(G,W)=>Q(G,{...W,dispatcher:$})}function v7(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 i7(){let Y=Error.prepareStackTrace;try{Error.prepareStackTrace=($,G)=>G;let X=Error("Capture current module path");Error.captureStackTrace(X,i7);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 CN=["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 IN(Y){let X=new Headers(Y);for(let J of CN)X.delete(J);return X}var SN=10,kN=new Set([301,302,303,307,308]);async function n7({url:Y,headers:X,abortSignal:J,maxRedirects:Q=SN,fetch:$,trustedOrigin:G}){let W=X===void 0?void 0:IN(X),U=(L)=>{let V={signal:J,redirect:L};if(W!==void 0)V.headers=new Headers(W);return V},H=Y;for(let L=0;L<=Q;L++){let V=G!==void 0&&x7(H,G);if(!V)DN(H);let B=$!=null?$:V?globalThis.fetch:await TN(),K=await B(H,U("manual"));if(K.type==="opaqueredirect"){if(!jN())throw new j0({url:Y,message:`Redirect from ${H} could not be validated and was blocked`});return await B(H,U("follow"))}let N=K.headers.get("location");if(kN.has(K.status)&&N){await W8(K);let O=new URL(N,H).toString();if(W!==void 0&&!x7(O,H)){let j=W.get("user-agent");W=new Headers(j==null?void 0:{"user-agent":j})}H=O;continue}return K}throw new j0({url:Y,message:`Too many redirects (max ${Q})`})}var o9=2147483648;async function o7({response:Y,url:X,maxBytes:J=o9}){let Q=Y.headers.get("content-length");if(Q!=null){let V=parseInt(Q,10);if(!isNaN(V)&&V>J)throw await W8(Y),new j0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes (Content-Length: ${V}).`})}let $=Y.body;if($==null)return new Uint8Array(0);let G=$.getReader(),W=[],U=0;try{while(!0){let{done:V,value:B}=await G.read();if(V)break;if(U+=B.length,U>J)throw new j0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes.`});W.push(B)}}finally{try{await G.cancel()}catch(V){}finally{G.releaseLock()}}let H=new Uint8Array(U),L=0;for(let V of W)H.set(V,L),L+=V.length;return H}var z0=({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 TQ({argument:"separator",message:`The separator "${Q}" must not be part of the alphabet "${J}".`});return()=>`${Y}${Q}${$()}`},BF=z0();function r7(Y){var X,J;return(J=(X=globalThis.Buffer)==null?void 0:X.isBuffer(Y))!=null?J:!1}var bN=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,xN=/"(?: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 h7(Y){let X=JSON.parse(Y);if(X===null||typeof X!=="object")return X;if(bN.test(Y)===!1&&xN.test(Y)===!1)return X;return vN(X)}function vN(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 hN(Y){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(J){return h7(Y)}try{return h7(Y)}finally{Error.stackTraceLimit=X}}function r9(Y){if(Y.type==="object"||Array.isArray(Y.type)&&Y.type.includes("object")){let{additionalProperties:J}=Y;Y.additionalProperties=J!=null&&typeof J!=="boolean"?K1(J):!1;let{properties:Q}=Y;if(Q!=null)for(let $ of Object.keys(Q))Q[$]=K1(Q[$])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(K1):K1(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(K1);if(Y.allOf!=null)Y.allOf=Y.allOf.map(K1);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(K1);let{definitions:X}=Y;if(X!=null)for(let J of Object.keys(X))X[J]=K1(X[J]);return Y}function K1(Y){if(typeof Y==="boolean")return Y;return r9(Y)}var gN=Symbol("Let zodToJsonSchema decide on which parser to use"),g7={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"},yN=(Y)=>typeof Y==="string"?{...g7,name:Y}:{...g7,...Y};function C0(){return{}}function fN(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 mN(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 cN(){return{type:"boolean"}}function s7(Y,X){return i(Y.type._def,X)}var uN=(Y,X)=>{return i(Y.innerType._def,X)};function a7(Y,X,J){let Q=J!=null?J:X.dateStrategy;if(Array.isArray(Q))return{anyOf:Q.map(($)=>a7(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 pN(Y)}}var pN=(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 lN(Y,X){return{...i(Y.innerType._def,X),default:Y.defaultValue()}}function dN(Y,X){return X.effectStrategy==="input"?i(Y.schema._def,X):C0()}function iN(Y){return{type:"string",enum:Array.from(Y.values)}}var nN=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function oN(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(nN($))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 rN(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 u9=void 0,h0={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(u9===void 0)u9=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return u9},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 t7(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":g0(J,"email",Q.message,X);break;case"format:idn-email":g0(J,"idn-email",Q.message,X);break;case"pattern:zod":q0(J,h0.email,Q.message,X);break}break;case"url":g0(J,"uri",Q.message,X);break;case"uuid":g0(J,"uuid",Q.message,X);break;case"regex":q0(J,Q.regex,Q.message,X);break;case"cuid":q0(J,h0.cuid,Q.message,X);break;case"cuid2":q0(J,h0.cuid2,Q.message,X);break;case"startsWith":q0(J,RegExp(`^${p9(Q.value,X)}`),Q.message,X);break;case"endsWith":q0(J,RegExp(`${p9(Q.value,X)}$`),Q.message,X);break;case"datetime":g0(J,"date-time",Q.message,X);break;case"date":g0(J,"date",Q.message,X);break;case"time":g0(J,"time",Q.message,X);break;case"duration":g0(J,"duration",Q.message,X);break;case"length":J.minLength=typeof J.minLength==="number"?Math.max(J.minLength,Q.value):Q.value,J.maxLength=typeof J.maxLength==="number"?Math.min(J.maxLength,Q.value):Q.value;break;case"includes":{q0(J,RegExp(p9(Q.value,X)),Q.message,X);break}case"ip":{if(Q.version!=="v6")g0(J,"ipv4",Q.message,X);if(Q.version!=="v4")g0(J,"ipv6",Q.message,X);break}case"base64url":q0(J,h0.base64url,Q.message,X);break;case"jwt":q0(J,h0.jwt,Q.message,X);break;case"cidr":{if(Q.version!=="v6")q0(J,h0.ipv4Cidr,Q.message,X);if(Q.version!=="v4")q0(J,h0.ipv6Cidr,Q.message,X);break}case"emoji":q0(J,h0.emoji(),Q.message,X);break;case"ulid":{q0(J,h0.ulid,Q.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{g0(J,"binary",Q.message,X);break}case"contentEncoding:base64":{J.contentEncoding="base64";break}case"pattern:zod":{q0(J,h0.base64,Q.message,X);break}}break}case"nanoid":q0(J,h0.nanoid,Q.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return J}function p9(Y,X){return X.patternStrategy==="escape"?aN(Y):Y}var sN=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function aN(Y){let X="";for(let J=0;J<Y.length;J++){if(!sN.has(Y[J]))X+="\\";X+=Y[J]}return X}function g0(Y,X,J,Q){var $;if(Y.format||(($=Y.anyOf)==null?void 0:$.some((G)=>G.format))){if(!Y.anyOf)Y.anyOf=[];if(Y.format)Y.anyOf.push({format:Y.format}),delete Y.format;Y.anyOf.push({format:X,...J&&Q.errorMessages&&{errorMessage:{format:J}}})}else Y.format=X}function q0(Y,X,J,Q){var $;if(Y.pattern||(($=Y.allOf)==null?void 0:$.some((G)=>G.pattern))){if(!Y.allOf)Y.allOf=[];if(Y.pattern)Y.allOf.push({pattern:Y.pattern}),delete Y.pattern;Y.allOf.push({pattern:y7(X,Q),...J&&Q.errorMessages&&{errorMessage:{pattern:J}}})}else Y.pattern=y7(X,Q)}function y7(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,H=!1;for(let L=0;L<$.length;L++){if(W){G+=$[L],W=!1;continue}if(Q.i){if(U){if($[L].match(/[a-z]/)){if(H)G+=$[L],G+=`${$[L-2]}-${$[L]}`.toUpperCase(),H=!1;else if($[L+1]==="-"&&((J=$[L+2])==null?void 0:J.match(/[a-z]/)))G+=$[L],H=!0;else G+=`${$[L]}${$[L].toUpperCase()}`;continue}}else if($[L].match(/[a-z]/)){G+=`[${$[L]}${$[L].toUpperCase()}]`;continue}}if(Q.m){if($[L]==="^"){G+=`(^|(?<=[\r
188
- ]))`;continue}else if($[L]==="$"){G+=`($|(?=[\r
189
- ]))`;continue}}if(Q.s&&$[L]==="."){G+=U?`${$[L]}\r
190
- `:`[${$[L]}\r
191
- ]`;continue}if(G+=$[L],$[L]==="\\")W=!0;else if(U&&$[L]==="]")U=!1;else if(!U&&$[L]==="[")U=!0}try{new RegExp(G)}catch(L){return console.warn(`Could not convert regex pattern at ${X.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Y.source}return G}function e7(Y,X){var J,Q,$,G,W,U;let H={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:L,...V}=t7(Y.keyType._def,X);return{...H,propertyNames:V}}else if(((G=Y.keyType)==null?void 0:G._def.typeName)==="ZodEnum")return{...H,propertyNames:{enum:Y.keyType._def.values}};else if(((W=Y.keyType)==null?void 0:W._def.typeName)==="ZodBranded"&&Y.keyType._def.type._def.typeName==="ZodString"&&((U=Y.keyType._def.type._def.checks)==null?void 0:U.length)){let{type:L,...V}=s7(Y.keyType._def,X);return{...H,propertyNames:V}}return H}function tN(Y,X){if(X.mapStrategy==="record")return e7(Y,X);let J=i(Y.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||C0(),Q=i(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||C0();return{type:"array",maxItems:125,items:{type:"array",items:[J,Q],minItems:2,maxItems:2}}}function eN(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 Y6(){return{not:C0()}}function X6(){return{type:"null"}}var l9={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function J6(Y,X){let J=Y.options instanceof Map?Array.from(Y.options.values()):Y.options;if(J.every((Q)=>(Q._def.typeName in l9)&&(!Q._def.checks||!Q._def.checks.length))){let Q=J.reduce(($,G)=>{let W=l9[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 Q6(Y,X)}var Q6=(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 $6(Y,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Y.innerType._def.typeName)&&(!Y.innerType._def.checks||!Y.innerType._def.checks.length))return{type:[l9[Y.innerType._def.typeName],"null"]};let J=i(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return J&&{anyOf:[J,{type:"null"}]}}function G6(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 W6(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 H=U6(U),L=i(U._def,{...X,currentPath:[...X.currentPath,"properties",W],propertyPath:[...X.currentPath,"properties",W]});if(L===void 0)continue;if(J.properties[W]=L,!H)Q.push(W)}if(Q.length)J.required=Q;let G=z6(Y,X);if(G!==void 0)J.additionalProperties=G;return J}function z6(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 U6(Y){try{return Y.isOptional()}catch(X){return!0}}var L6=(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:C0()},Q]}:C0()},H6=(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 N6(Y,X){return i(Y.type._def,X)}function V6(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 Z6(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 K6(){return{not:C0()}}function B6(){return C0()}var O6=(Y,X)=>{return i(Y.innerType._def,X)},F6=(Y,X,J)=>{switch(X){case"ZodString":return t7(Y,J);case"ZodNumber":return G6(Y);case"ZodObject":return W6(Y,J);case"ZodBigInt":return mN(Y);case"ZodBoolean":return cN();case"ZodDate":return a7(Y,J);case"ZodUndefined":return K6();case"ZodNull":return X6();case"ZodArray":return fN(Y,J);case"ZodUnion":case"ZodDiscriminatedUnion":return J6(Y,J);case"ZodIntersection":return oN(Y,J);case"ZodTuple":return Z6(Y,J);case"ZodRecord":return e7(Y,J);case"ZodLiteral":return rN(Y);case"ZodEnum":return iN(Y);case"ZodNativeEnum":return eN(Y);case"ZodNullable":return $6(Y,J);case"ZodOptional":return L6(Y,J);case"ZodMap":return tN(Y,J);case"ZodSet":return V6(Y,J);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return N6(Y,J);case"ZodNaN":case"ZodNever":return Y6();case"ZodEffects":return dN(Y,J);case"ZodAny":return C0();case"ZodUnknown":return B6();case"ZodDefault":return lN(Y,J);case"ZodBranded":return s7(Y,J);case"ZodReadonly":return O6(Y,J);case"ZodCatch":return uN(Y,J);case"ZodPipeline":return H6(Y,J);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Q)=>{return})(X)}},q6=(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 H=(Q=X.override)==null?void 0:Q.call(X,Y,X,$,J);if(H!==gN)return H}if($&&!J){let H=j6($,X);if(H!==void 0)return H}let G={def:Y,path:X.currentPath,jsonSchema:void 0};X.seen.set(Y,G);let W=F6(Y,Y.typeName,X),U=typeof W==="function"?i(W(),X):W;if(U)D6(Y,X,U);if(X.postProcess){let H=X.postProcess(U,Y,X);return G.jsonSchema=U,H}return G.jsonSchema=U,U}var j6=(Y,X)=>{switch(X.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:q6(X.currentPath,Y.path)};case"none":case"seen":{if(Y.path.length<X.currentPath.length&&Y.path.every((J,Q)=>X.currentPath[Q]===J))return console.warn(`Recursive reference detected at ${X.currentPath.join("/")}! Defaulting to any`),C0();return X.$refStrategy==="seen"?C0():void 0}}},D6=(Y,X,J)=>{if(Y.description)J.description=Y.description;return J},P6=(Y)=>{let X=yN(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}]))}},M6=(Y,X)=>{var J;let Q=P6(X),$=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((L,[V,B])=>{var K;return{...L,[V]:(K=i(B._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,V]},!0))!=null?K:C0()}},{}):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:C0(),U=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if(U!==void 0)W.title=U;let H=G===void 0?$?{...W,[Q.definitionPath]:$}:W:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,G].join("/"),[Q.definitionPath]:{...$,[G]:W}};return H.$schema="http://json-schema.org/draft-07/schema#",H},d9=Symbol.for("vercel.ai.schema");function z8(Y){let X;return()=>{if(X==null)X=Y();return X}}function U8(Y,{validate:X}={}){return{[d9]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:X}}function E6(Y){return typeof Y==="object"&&Y!==null&&d9 in Y&&Y[d9]===!0&&"jsonSchema"in Y&&"validate"in Y}function L8(Y){return Y==null?U8({type:"object",properties:{},additionalProperties:!1}):E6(Y)?Y:("~standard"in Y)?Y["~standard"].vendor==="zod"?ZY(Y):A6(Y):Y()}function A6(Y){return U8(()=>{if(!w6(Y))throw Error(`Standard schema vendor '${Y["~standard"].vendor}' does not support JSON Schema conversion.`);return r9(Y["~standard"].jsonSchema.input({target:"draft-07"}))},{validate:async(X)=>{let J=await Y["~standard"].validate(X);return"value"in J?{success:!0,value:J.value}:{success:!1,error:new p0({value:X,cause:J.issues})}}})}function w6(Y){return Y["~standard"].jsonSchema!=null}function T6(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return U8(()=>M6(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 R6(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return U8(()=>r9(i5(Y,{target:"draft-7",io:"input",reused:Q?"ref":"inline"})),{validate:async($)=>{let G=await $8(Y,$);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function _6(Y){return"_zod"in Y}function ZY(Y,X){if(_6(Y))return R6(Y,X);else return T6(Y,X)}async function n1({value:Y,schema:X,context:J}){let Q=L8(X);try{if(Q.validate==null)return{success:!0,value:Y,rawValue:Y};let $=await Q.validate(Y);if($.success)return{success:!0,value:$.value,rawValue:Y};return{success:!1,error:p0.wrap({value:Y,cause:$.error,context:J}),rawValue:Y}}catch($){return{success:!1,error:p0.wrap({value:Y,cause:$,context:J}),rawValue:Y}}}async function B1({text:Y,schema:X}){try{let J=hN(Y);if(X==null)return{success:!0,value:J,rawValue:J};return await n1({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 s9(Y){if(typeof Y==="function")Y=Y();return Promise.resolve(Y)}var YW="AI_SerializationError",XW=`vercel.ai.error.${YW}`,C6=Symbol.for(XW),f7,m7,MF=class extends(m7=D,f7=C6,m7){constructor({message:Y="Failed to serialize value.",cause:X}={}){super({name:YW,message:Y,cause:X});this[f7]=!0}static isInstance(Y){return D.hasMarker(Y,XW)}};var k6=Object.defineProperty,b6=(Y,X)=>{for(var J in X)k6(Y,J,{get:X[J],enumerable:!0})},sW="AI_InvalidArgumentError",aW=`vercel.ai.error.${sW}`,x6=Symbol.for(aW),JW,QW,bF=class extends(QW=D,JW=x6,QW){constructor({parameter:Y,value:X,message:J}){super({name:sW,message:`Invalid argument for parameter ${Y}: ${J}`});this[JW]=!0,this.parameter=Y,this.value=X}static isInstance(Y){return D.hasMarker(Y,aW)}},tW="AI_InvalidStreamPartError",eW=`vercel.ai.error.${tW}`,v6=Symbol.for(eW),$W,GW,vF=class extends(GW=D,$W=v6,GW){constructor({chunk:Y,message:X}){super({name:tW,message:X});this[$W]=!0,this.chunk=Y}static isInstance(Y){return D.hasMarker(Y,eW)}},Y2="AI_InvalidToolApprovalError",X2=`vercel.ai.error.${Y2}`,h6=Symbol.for(X2),WW,zW,gF=class extends(zW=D,WW=h6,zW){constructor({approvalId:Y}){super({name:Y2,message:`Tool approval response references unknown approvalId: "${Y}". No matching tool-approval-request found in message history.`});this[WW]=!0,this.approvalId=Y}static isInstance(Y){return D.hasMarker(Y,X2)}},J2="AI_InvalidToolApprovalSignatureError",Q2=`vercel.ai.error.${J2}`,g6=Symbol.for(Q2),UW,LW,fF=class extends(LW=D,UW=g6,LW){constructor({approvalId:Y,toolCallId:X,reason:J}){super({name:J2,message:`Tool approval signature verification failed for approval "${Y}" (tool call "${X}"): ${J}`});this[UW]=!0,this.approvalId=Y,this.toolCallId=X}static isInstance(Y){return D.hasMarker(Y,Q2)}},$2="AI_InvalidToolInputError",G2=`vercel.ai.error.${$2}`,y6=Symbol.for(G2),HW,NW,cF=class extends(NW=D,HW=y6,NW){constructor({toolInput:Y,toolName:X,cause:J,message:Q=`Invalid input for tool ${X}: ${T1(J)}`}){super({name:$2,message:Q,cause:J});this[HW]=!0,this.toolInput=Y,this.toolName=X}static isInstance(Y){return D.hasMarker(Y,G2)}},W2="AI_ToolCallNotFoundForApprovalError",z2=`vercel.ai.error.${W2}`,f6=Symbol.for(z2),VW,ZW,pF=class extends(ZW=D,VW=f6,ZW){constructor({toolCallId:Y,approvalId:X}){super({name:W2,message:`Tool call "${Y}" not found for approval request "${X}".`});this[VW]=!0,this.toolCallId=Y,this.approvalId=X}static isInstance(Y){return D.hasMarker(Y,z2)}},U2="AI_MissingToolResultsError",L2=`vercel.ai.error.${U2}`,m6=Symbol.for(L2),KW,BW,dF=class extends(BW=D,KW=m6,BW){constructor({toolCallIds:Y}){super({name:U2,message:`Tool result${Y.length>1?"s are":" is"} missing for tool call${Y.length>1?"s":""} ${Y.join(", ")}.`});this[KW]=!0,this.toolCallIds=Y}static isInstance(Y){return D.hasMarker(Y,L2)}},H2="AI_NoImageGeneratedError",N2=`vercel.ai.error.${H2}`,c6=Symbol.for(N2),OW,FW,nF=class extends(FW=D,OW=c6,FW){constructor({message:Y="No image generated.",cause:X,responses:J}){super({name:H2,message:Y,cause:X});this[OW]=!0,this.responses=J}static isInstance(Y){return D.hasMarker(Y,N2)}},V2="AI_NoObjectGeneratedError",Z2=`vercel.ai.error.${V2}`,u6=Symbol.for(Z2),qW,jW,O1=class extends(jW=D,qW=u6,jW){constructor({message:Y="No object generated.",cause:X,text:J,response:Q,usage:$,finishReason:G}){super({name:V2,message:Y,cause:X});this[qW]=!0,this.text=J,this.response=Q,this.usage=$,this.finishReason=G}static isInstance(Y){return D.hasMarker(Y,Z2)}},K2="AI_NoOutputGeneratedError",B2=`vercel.ai.error.${K2}`,p6=Symbol.for(B2),DW,PW,sF=class extends(PW=D,DW=p6,PW){constructor({message:Y="No output generated.",cause:X}={}){super({name:K2,message:Y,cause:X});this[DW]=!0}static isInstance(Y){return D.hasMarker(Y,B2)}},O2="AI_NoSpeechGeneratedError",F2=`vercel.ai.error.${O2}`,l6=Symbol.for(F2),MW,EW,tF=class extends(EW=D,MW=l6,EW){constructor(Y){super({name:O2,message:"No speech audio generated."});this[MW]=!0,this.responses=Y.responses}static isInstance(Y){return D.hasMarker(Y,F2)}},q2="AI_NoTranscriptGeneratedError",j2=`vercel.ai.error.${q2}`,d6=Symbol.for(j2),AW,wW,Yq=class extends(wW=D,AW=d6,wW){constructor(Y){super({name:q2,message:"No transcript generated."});this[AW]=!0,this.responses=Y.responses}static isInstance(Y){return D.hasMarker(Y,j2)}},D2="AI_NoTranslationGeneratedError",P2=`vercel.ai.error.${D2}`,i6=Symbol.for(P2),TW,RW,Jq=class extends(RW=D,TW=i6,RW){constructor(Y){super({name:D2,message:"No translation generated."});this[TW]=!0,this.response=Y.response}static isInstance(Y){return D.hasMarker(Y,P2)}},a9="AI_NoVideoGeneratedError",M2=`vercel.ai.error.${a9}`,n6=Symbol.for(M2),_W,CW,$q=class extends(CW=D,_W=n6,CW){constructor({message:Y="No video generated.",cause:X,responses:J}){super({name:a9,message:Y,cause:X});this[_W]=!0,this.responses=J}static isInstance(Y){return D.hasMarker(Y,M2)}static isNoVideoGeneratedError(Y){return Y instanceof Error&&Y.name===a9&&typeof Y.responses<"u"?!0:!1}toJSON(){return{name:this.name,message:this.message,stack:this.stack,cause:this.cause,responses:this.responses}}},E2="AI_NoSuchToolError",A2=`vercel.ai.error.${E2}`,o6=Symbol.for(A2),IW,SW,Wq=class extends(SW=D,IW=o6,SW){constructor({toolName:Y,availableTools:X=void 0,message:J=`Model tried to call unavailable tool '${Y}'. ${X===void 0?"No tools are available.":`Available tools: ${X.join(", ")}.`}`}){super({name:E2,message:J});this[IW]=!0,this.toolName=Y,this.availableTools=X}static isInstance(Y){return D.hasMarker(Y,A2)}},w2="AI_StreamProviderError",T2=`vercel.ai.error.${w2}`,r6=Symbol.for(T2),kW,bW,Uq=class extends(bW=D,kW=r6,bW){constructor({message:Y,type:X,code:J,statusCode:Q,isRetryable:$=s6(Q),data:G,cause:W}){super({name:w2,message:Y,cause:W});this[kW]=!0,this.type=X,this.code=J,this.statusCode=Q,this.isRetryable=$,this.data=G}static isInstance(Y){return D.hasMarker(Y,T2)}};function s6(Y){return Y!=null&&(Y===408||Y===409||Y===429||Y>=500)}var R2="AI_ToolCallRepairError",_2=`vercel.ai.error.${R2}`,a6=Symbol.for(_2),xW,vW,Hq=class extends(vW=D,xW=a6,vW){constructor({cause:Y,originalError:X,message:J=`Error repairing tool call: ${T1(Y)}`}){super({name:R2,message:J,cause:Y});this[xW]=!0,this.originalError=X}static isInstance(Y){return D.hasMarker(Y,_2)}},C2="AI_ToolChoiceViolationError",I2=`vercel.ai.error.${C2}`,t6=Symbol.for(I2),hW,gW,Vq=class extends(gW=D,hW=t6,gW){constructor({toolChoice:Y,finishReason:X,provider:J,modelId:Q,content:$,message:G=Y.type==="required"?"Model response did not contain a tool call even though tool choice was required.":`Model response did not contain a call to the required tool '${Y.toolName}'.`}){super({name:C2,message:G});this[hW]=!0,this.toolChoice=Y,this.finishReason=X,this.provider=J,this.modelId=Q,this.content=$}static isInstance(Y){return D.hasMarker(Y,I2)}};var S2="AI_UIMessageStreamError",k2=`vercel.ai.error.${S2}`,e6=Symbol.for(k2),yW,fW,Kq=class extends(fW=D,yW=e6,fW){constructor({chunkType:Y,chunkId:X,message:J}){super({name:S2,message:J});this[yW]=!0,this.chunkType=Y,this.chunkId=X}static isInstance(Y){return D.hasMarker(Y,k2)}},b2="AI_InvalidDataContentError",x2=`vercel.ai.error.${b2}`,YV=Symbol.for(x2),mW,cW,Oq=class extends(cW=D,mW=YV,cW){constructor({content:Y,cause:X,message:J=`Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof Y}.`}){super({name:b2,message:J,cause:X});this[mW]=!0,this.content=Y}static isInstance(Y){return D.hasMarker(Y,x2)}},v2="AI_InvalidMessageRoleError",h2=`vercel.ai.error.${v2}`,XV=Symbol.for(h2),uW,pW,qq=class extends(pW=D,uW=XV,pW){constructor({role:Y,message:X=`Invalid message role: '${Y}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:v2,message:X});this[uW]=!0,this.role=Y}static isInstance(Y){return D.hasMarker(Y,h2)}},g2="AI_MessageConversionError",y2=`vercel.ai.error.${g2}`,JV=Symbol.for(y2),lW,dW,Dq=class extends(dW=D,lW=JV,dW){constructor({originalMessage:Y,message:X}){super({name:g2,message:X});this[lW]=!0,this.originalMessage=Y}static isInstance(Y){return D.hasMarker(Y,y2)}},f2="AI_RetryError",m2=`vercel.ai.error.${f2}`,QV=Symbol.for(m2),iW,nW,Mq=class extends(nW=D,iW=QV,nW){constructor({message:Y,reason:X,errors:J}){super({name:f2,message:Y});this[iW]=!0,this.reason=X,this.errors=J,this.lastError=J[J.length-1]}static isInstance(Y){return D.hasMarker(Y,m2)}};var $V="7.0.90",GV=async({url:Y,maxBytes:X,abortSignal:J})=>{var Q;let $=Y.toString();try{let G=i1({},`ai-sdk/${$V}`,c7()),W=await n7({url:$,headers:G,abortSignal:J});if(!W.ok)throw await W8(W),new j0({url:$,statusCode:W.status,statusText:W.statusText});return{data:await o7({response:W,url:$,maxBytes:X!=null?X:o9}),mediaType:(Q=W.headers.get("content-type"))!=null?Q:void 0}}catch(G){if(j0.isInstance(G))throw G;throw new j0({url:$,cause:G})}};var z={array:g9,boolean:q7,custom:I7,discriminatedUnion:A7,enum:f9,instanceof:S7,lazy:C7,literal:T7,looseObject:M7,never:h9,null:j7,number:F7,object:P7,record:w7,string:B7,union:y9,unknown:VY},I1=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),I1.optional()),z.array(I1)])),R=z.record(z.string(),z.record(z.string(),I1.optional())),BY=z.union([z.string(),z.instanceof(Uint8Array),z.instanceof(ArrayBuffer),z.custom(r7,{message:"Must be a Buffer"})]),t9=z.record(z.string(),z.string()),c2=z.object({type:z.literal("text"),text:z.string(),providerOptions:R.optional()}),WV=z.object({type:z.literal("image"),image:z.union([BY,z.instanceof(URL),t9]),mediaType:z.string().optional(),providerOptions:R.optional()}),u2=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:BY}),z.object({type:z.literal("url"),url:z.instanceof(URL)}),z.object({type:z.literal("reference"),reference:t9}),z.object({type:z.literal("text"),text:z.string()})]),zV=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:BY}),z.object({type:z.literal("url"),url:z.instanceof(URL)})]),p2=z.object({type:z.literal("file"),data:z.union([u2,BY,z.instanceof(URL),t9]),filename:z.string().optional(),mediaType:z.string(),providerOptions:R.optional()}),UV=z.object({type:z.literal("reasoning"),text:z.string(),providerOptions:R.optional()}),LV=z.object({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerOptions:R.optional()}),HV=z.object({type:z.literal("reasoning-file"),data:z.union([zV,BY,z.instanceof(URL)]),mediaType:z.string(),providerOptions:R.optional()}),NV=z.object({type:z.literal("tool-call"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerOptions:R.optional(),providerExecuted:z.boolean().optional()}),VV=z.discriminatedUnion("type",[z.object({type:z.literal("text"),value:z.string(),providerOptions:R.optional()}),z.object({type:z.literal("json"),value:I1,providerOptions:R.optional()}),z.object({type:z.literal("execution-denied"),reason:z.string().optional(),providerOptions:R.optional()}),z.object({type:z.literal("error-text"),value:z.string(),providerOptions:R.optional()}),z.object({type:z.literal("error-json"),value:I1,providerOptions:R.optional()}),z.object({type:z.literal("content"),value:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),providerOptions:R.optional()}),z.object({type:z.literal("file"),data:u2,mediaType:z.string(),filename:z.string().optional(),providerOptions:R.optional()}),z.object({type:z.literal("file-data"),data:z.string(),mediaType:z.string(),filename:z.string().optional(),providerOptions:R.optional()}),z.object({type:z.literal("file-url"),url:z.string(),mediaType:z.string().optional(),providerOptions:R.optional()}),z.object({type:z.literal("file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:R.optional()}),z.object({type:z.literal("file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:R.optional()}),z.object({type:z.literal("image-data"),data:z.string(),mediaType:z.string(),providerOptions:R.optional()}),z.object({type:z.literal("image-url"),url:z.string(),providerOptions:R.optional()}),z.object({type:z.literal("image-file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:R.optional()}),z.object({type:z.literal("image-file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:R.optional()}),z.object({type:z.literal("custom"),providerOptions:R.optional()})]))})]),l2=z.object({type:z.literal("tool-result"),toolCallId:z.string(),toolName:z.string(),output:VV,providerOptions:R.optional()}),ZV=z.object({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string(),reason:z.string().optional()}),KV=z.object({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional()}),BV=z.object({role:z.literal("system"),content:z.string(),providerOptions:R.optional()}),OV=z.object({role:z.literal("user"),content:z.union([z.string(),z.array(z.union([c2,WV,p2]))]),providerOptions:R.optional()}),FV=z.object({role:z.literal("assistant"),content:z.union([z.string(),z.array(z.union([c2,LV,p2,UV,HV,NV,l2,ZV]))]),providerOptions:R.optional()}),qV=z.object({role:z.literal("tool"),content:z.array(z.union([l2,KV])),providerOptions:R.optional()}),Tq=z.union([BV,OV,FV,qV]);var jV={};b6(jV,{array:()=>EV,choice:()=>AV,json:()=>wV,object:()=>MV,text:()=>PV});function DV(Y){let X=["ROOT"],J=-1,Q=null,$=0;function G(V){return V>="0"&&V<="9"||V>="A"&&V<="F"||V>="a"&&V<="f"}function W(V,B,K){switch(V){case'"':{J=B,X.pop(),X.push(K),X.push("INSIDE_STRING");break}case"f":case"t":case"n":{J=B,Q=B,X.pop(),X.push(K),X.push("INSIDE_LITERAL");break}case"-":{X.pop(),X.push(K),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=B,X.pop(),X.push(K),X.push("INSIDE_NUMBER");break}case"{":{J=B,X.pop(),X.push(K),X.push("INSIDE_OBJECT_START");break}case"[":{J=B,X.pop(),X.push(K),X.push("INSIDE_ARRAY_START");break}}}function U(V,B){switch(V){case",":{X.pop(),X.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{J=B,X.pop();break}}}function H(V,B){switch(V){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=B,X.pop();break}}}for(let V=0;V<Y.length;V++){let B=Y[V];switch(X[X.length-1]){case"ROOT":W(B,V,"FINISH");break;case"INSIDE_OBJECT_START":{switch(B){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}case"}":{J=V,X.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(B){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(B){case'"':{X.pop(),X.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(B){case":":{X.pop(),X.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{W(B,V,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{U(B,V);break}case"INSIDE_STRING":{switch(B){case'"':{X.pop(),J=V;break}case"\\":{X.push("INSIDE_STRING_ESCAPE");break}default:J=V}break}case"INSIDE_ARRAY_START":{switch(B){case"]":{J=V,X.pop();break}default:{J=V,W(B,V,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(B){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=V,X.pop();break}default:{J=V;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{W(B,V,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{if(X.pop(),B==="u")$=0,X.push("INSIDE_STRING_UNICODE_ESCAPE");else J=V;break}case"INSIDE_STRING_UNICODE_ESCAPE":{if(G(B)){if($++,$===4)X.pop(),J=V}break}case"INSIDE_NUMBER":{switch(B){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=V;break}case"e":case"E":case"-":case".":break;case",":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")H(B,V);if(X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")U(B,V);break}case"}":{if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")U(B,V);break}case"]":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")H(B,V);break}default:{X.pop();break}}break}case"INSIDE_LITERAL":{let N=Y.substring(Q,V+1);if(!"false".startsWith(N)&&!"true".startsWith(N)&&!"null".startsWith(N)){if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")U(B,V);else if(X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")H(B,V)}else J=V;break}}}let L=Y.slice(0,J+1);for(let V=X.length-1;V>=0;V--)switch(X[V]){case"INSIDE_STRING":{L+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{L+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{L+="]";break}case"INSIDE_LITERAL":{let K=Y.substring(Q,Y.length);if("true".startsWith(K))L+="true".slice(K.length);else if("false".startsWith(K))L+="false".slice(K.length);else if("null".startsWith(K))L+="null".slice(K.length)}}return L}async function H8(Y){if(Y===void 0)return{value:void 0,state:"undefined-input"};let X=await B1({text:Y});if(X.success)return{value:X.value,state:"successful-parse"};if(X=await B1({text:DV(Y)}),X.success)return{value:X.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var PV=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:Y}){return Y},async parsePartialOutput({text:Y}){return{partial:Y}},createElementStreamTransform(){return}}),MV=({schema:Y,name:X,description:J})=>{let Q=L8(Y);return{name:"object",responseFormat:s9(Q.jsonSchema).then(($)=>({type:"json",schema:$,...X!=null&&{name:X},...J!=null&&{description:J}})),async parseCompleteOutput({text:$},G){let W=await B1({text:$});if(!W.success)throw new O1({message:"No object generated: could not parse the response.",cause:W.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let U=await n1({value:W.value,schema:Q});if(!U.success)throw new O1({message:"No object generated: response did not match schema.",cause:U.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});return U.value},async parsePartialOutput({text:$}){let G=await H8($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:G.value}}},createElementStreamTransform(){return}}},EV=({element:Y,name:X,description:J})=>{let Q=L8(Y);return{name:"array",responseFormat:s9(Q.jsonSchema).then(($)=>{let{$schema:G,definitions:W,$defs:U,...H}=$;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",...W!=null&&{definitions:W},...U!=null&&{$defs:U},type:"object",properties:{elements:{type:"array",items:H}},required:["elements"],additionalProperties:!1},...X!=null&&{name:X},...J!=null&&{description:J}}}),async parseCompleteOutput({text:$},G){let W=await B1({text:$});if(!W.success)throw new O1({message:"No object generated: could not parse the response.",cause:W.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let U=W.value;if(U==null||typeof U!=="object"||!("elements"in U)||!Array.isArray(U.elements))throw new O1({message:"No object generated: response did not match schema.",cause:new p0({value:U,cause:"response must be an object with an elements array"}),text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let H=[];for(let L of U.elements){let V=await n1({value:L,schema:Q});if(!V.success)throw new O1({message:"No object generated: response did not match schema.",cause:V.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});H.push(V.value)}return H},async parsePartialOutput({text:$}){let G=await H8($);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,H=[];for(let L of U){let V=await n1({value:L,schema:Q});if(V.success)H.push(V.value)}return{partial:H}}}},createElementStreamTransform(){let $=0;return new TransformStream({transform({partialOutput:G},W){if(G!=null)for(;$<G.length;$++)W.enqueue(G[$])}})}}},AV=({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 B1({text:Q});if(!G.success)throw new O1({message:"No object generated: could not parse the response.",cause:G.error,text:Q,response:$.response,usage:$.usage,finishReason:$.finishReason});let W=G.value;if(W==null||typeof W!=="object"||!("result"in W)||typeof W.result!=="string"||!Y.includes(W.result))throw new O1({message:"No object generated: response did not match schema.",cause:new p0({value:W,cause:"response must be an object that contains a choice value."}),text:Q,response:$.response,usage:$.usage,finishReason:$.finishReason});return W.result},async parsePartialOutput({text:Q}){let $=await H8(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}}},wV=({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 B1({text:J});if(!$.success)throw new O1({message:"No object generated: could not parse the response.",cause:$.error,text:J,response:Q.response,usage:Q.usage,finishReason:Q.finishReason});return $.value},async parsePartialOutput({text:J}){let Q=await H8(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 Iq=z0({prefix:"aitxt",size:24}),Sq=z0({prefix:"call",size:24});var bq=class extends TransformStream{constructor(){super({transform(Y,X){X.enqueue(`data: ${JSON.stringify(Y)}
92
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let U of this.seen.entries()){let H=U[1];if(Y===U[0]){$(U);continue}if(J.external){let V=J.external.registry.get(U[0])?.id;if(Y!==U[0]&&V){$(U);continue}}if(this.metadataRegistry.get(U[0])?.id){$(U);continue}if(H.cycle){$(U);continue}if(H.count>1){if(J.reused==="ref"){$(U);continue}}}let W=(U,H)=>{let B=this.seen.get(U),V=B.def??B.schema,Z={...V};if(B.ref===null)return;let j=B.ref;if(B.ref=null,j){W(j,H);let O=this.seen.get(j).schema;if(O.$ref&&(H.target==="draft-7"||H.target==="draft-4"||H.target==="openapi-3.0"))V.allOf=V.allOf??[],V.allOf.push(O);else Object.assign(V,O),Object.assign(V,Z)}if(!B.isParent)this.override({zodSchema:U,jsonSchema:V,path:B.path??[]})};for(let U of[...this.seen.entries()].reverse())W(U[0],{target:this.target});let z={};if(this.target==="draft-2020-12")z.$schema="https://json-schema.org/draft/2020-12/schema";else if(this.target==="draft-7")z.$schema="http://json-schema.org/draft-07/schema#";else if(this.target==="draft-4")z.$schema="http://json-schema.org/draft-04/schema#";else if(this.target==="openapi-3.0");else console.warn(`Invalid target: ${this.target}`);if(J.external?.uri){let U=J.external.registry.get(Y)?.id;if(!U)throw Error("Schema is missing an `id` property");z.$id=J.external.uri(U)}Object.assign(z,Q.def);let L=J.external?.defs??{};for(let U of this.seen.entries()){let H=U[1];if(H.def&&H.defId)L[H.defId]=H.def}if(J.external);else if(Object.keys(L).length>0)if(this.target==="draft-2020-12")z.$defs=L;else z.definitions=L;try{return JSON.parse(JSON.stringify(z))}catch(U){throw Error("Error converting schema to JSON.")}}}function s$(Y,X){if(Y instanceof U9){let Q=new SX(X),G={};for(let z of Y._idmap.entries()){let[L,U]=z;Q.process(U)}let $={},W={registry:Y,uri:X?.uri,defs:G};for(let z of Y._idmap.entries()){let[L,U]=z;$[L]=Q.emit(U,{...X,external:W})}if(Object.keys(G).length>0){let z=Q.target==="draft-2020-12"?"$defs":"definitions";$.__shared={[z]:G}}return{schemas:$}}let J=new SX(X);return J.process(Y),J.emit(Y,X)}function N0(Y,X){let J=X??{seen:new Set};if(J.seen.has(Y))return!1;J.seen.add(Y);let G=Y._zod.def;switch(G.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return N0(G.element,J);case"object":{for(let $ in G.shape)if(N0(G.shape[$],J))return!0;return!1}case"union":{for(let $ of G.options)if(N0($,J))return!0;return!1}case"intersection":return N0(G.left,J)||N0(G.right,J);case"tuple":{for(let $ of G.items)if(N0($,J))return!0;if(G.rest&&N0(G.rest,J))return!0;return!1}case"record":return N0(G.keyType,J)||N0(G.valueType,J);case"map":return N0(G.keyType,J)||N0(G.valueType,J);case"set":return N0(G.valueType,J);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return N0(G.innerType,J);case"lazy":return N0(G.getter(),J);case"default":return N0(G.innerType,J);case"prefault":return N0(G.innerType,J);case"custom":return!1;case"transform":return!0;case"pipe":return N0(G.in,J)||N0(G.out,J);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${G.type}`)}var LL=q("ZodISODateTime",(Y,X)=>{_G.init(Y,X),e.init(Y,X)});function a$(Y){return h$(LL,Y)}var HL=q("ZodISODate",(Y,X)=>{SG.init(Y,X),e.init(Y,X)});function t$(Y){return g$(HL,Y)}var NL=q("ZodISOTime",(Y,X)=>{kG.init(Y,X),e.init(Y,X)});function e$(Y){return y$(NL,Y)}var ZL=q("ZodISODuration",(Y,X)=>{xG.init(Y,X),e.init(Y,X)});function Y2(Y){return f$(ZL,Y)}var X2=(Y,X)=>{J9.init(Y,X),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(J)=>L5(Y,J)},flatten:{value:(J)=>U5(Y,J)},addIssue:{value:(J)=>{Y.issues.push(J),Y.message=JSON.stringify(Y.issues,cY,2)}},addIssues:{value:(J)=>{Y.issues.push(...J),Y.message=JSON.stringify(Y.issues,cY,2)}},isEmpty:{get(){return Y.issues.length===0}}})},mO=q("ZodError",X2),x0=q("ZodError",X2,{Parent:Error});var J2=Q9(x0),Q2=G9(x0),G2=B1(x0),F9=F1(x0),$2=Z5(x0),W2=V5(x0),K2=B5(x0),z2=F5(x0),U2=O5(x0),L2=q5(x0),H2=j5(x0),N2=D5(x0);var Y0=q("ZodType",(Y,X)=>{return a.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)=>y0(Y,J,Q),Y.brand=()=>Y,Y.register=(J,Q)=>{return J.add(Y,Q),Y},Y.parse=(J,Q)=>J2(Y,J,Q,{callee:Y.parse}),Y.safeParse=(J,Q)=>G2(Y,J,Q),Y.parseAsync=async(J,Q)=>Q2(Y,J,Q,{callee:Y.parseAsync}),Y.safeParseAsync=async(J,Q)=>F9(Y,J,Q),Y.spa=Y.safeParseAsync,Y.encode=(J,Q)=>$2(Y,J,Q),Y.decode=(J,Q)=>W2(Y,J,Q),Y.encodeAsync=async(J,Q)=>K2(Y,J,Q),Y.decodeAsync=async(J,Q)=>z2(Y,J,Q),Y.safeEncode=(J,Q)=>U2(Y,J,Q),Y.safeDecode=(J,Q)=>L2(Y,J,Q),Y.safeEncodeAsync=async(J,Q)=>H2(Y,J,Q),Y.safeDecodeAsync=async(J,Q)=>N2(Y,J,Q),Y.refine=(J,Q)=>Y.check(WH(J,Q)),Y.superRefine=(J)=>Y.check(KH(J)),Y.overwrite=(J)=>Y.check(SY(J)),Y.optional=()=>B2(Y),Y.nullable=()=>F2(Y),Y.nullish=()=>B2(F2(Y)),Y.nonoptional=(J)=>eL(Y,J),Y.array=()=>bX(Y),Y.or=(J)=>vX([Y,J]),Y.and=(J)=>pL(Y,J),Y.transform=(J)=>O2(Y,oL(J)),Y.default=(J)=>sL(Y,J),Y.prefault=(J)=>tL(Y,J),Y.catch=(J)=>XH(Y,J),Y.pipe=(J)=>O2(Y,J),Y.readonly=()=>GH(Y),Y.describe=(J)=>{let Q=Y.clone();return _Y.add(Q,{description:J}),Q},Object.defineProperty(Y,"description",{get(){return _Y.get(Y)?.description},configurable:!0}),Y.meta=(...J)=>{if(J.length===0)return _Y.get(Y);let Q=Y.clone();return _Y.add(Q,J[0]),Q},Y.isOptional=()=>Y.safeParse(void 0).success,Y.isNullable=()=>Y.safeParse(null).success,Y}),q2=q("_ZodString",(Y,X)=>{z9.init(Y,X),Y0.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(PX(...Q)),Y.includes=(...Q)=>Y.check(wX(...Q)),Y.startsWith=(...Q)=>Y.check(AX(...Q)),Y.endsWith=(...Q)=>Y.check(TX(...Q)),Y.min=(...Q)=>Y.check(lY(...Q)),Y.max=(...Q)=>Y.check(Z9(...Q)),Y.length=(...Q)=>Y.check(V9(...Q)),Y.nonempty=(...Q)=>Y.check(lY(1,...Q)),Y.lowercase=(Q)=>Y.check(MX(Q)),Y.uppercase=(Q)=>Y.check(EX(Q)),Y.trim=()=>Y.check(CX()),Y.normalize=(...Q)=>Y.check(RX(...Q)),Y.toLowerCase=()=>Y.check(IX()),Y.toUpperCase=()=>Y.check(_X())}),OL=q("ZodString",(Y,X)=>{z9.init(Y,X),q2.init(Y,X),Y.email=(J)=>Y.check(B$(qL,J)),Y.url=(J)=>Y.check(D$(jL,J)),Y.jwt=(J)=>Y.check(v$(bL,J)),Y.emoji=(J)=>Y.check(P$(DL,J)),Y.guid=(J)=>Y.check(DX(Z2,J)),Y.uuid=(J)=>Y.check(F$(O9,J)),Y.uuidv4=(J)=>Y.check(O$(O9,J)),Y.uuidv6=(J)=>Y.check(q$(O9,J)),Y.uuidv7=(J)=>Y.check(j$(O9,J)),Y.nanoid=(J)=>Y.check(M$(PL,J)),Y.guid=(J)=>Y.check(DX(Z2,J)),Y.cuid=(J)=>Y.check(E$(ML,J)),Y.cuid2=(J)=>Y.check(w$(EL,J)),Y.ulid=(J)=>Y.check(A$(wL,J)),Y.base64=(J)=>Y.check(k$(SL,J)),Y.base64url=(J)=>Y.check(x$(kL,J)),Y.xid=(J)=>Y.check(T$(AL,J)),Y.ksuid=(J)=>Y.check(R$(TL,J)),Y.ipv4=(J)=>Y.check(C$(RL,J)),Y.ipv6=(J)=>Y.check(I$(CL,J)),Y.cidrv4=(J)=>Y.check(_$(IL,J)),Y.cidrv6=(J)=>Y.check(S$(_L,J)),Y.e164=(J)=>Y.check(b$(xL,J)),Y.datetime=(J)=>Y.check(a$(J)),Y.date=(J)=>Y.check(t$(J)),Y.time=(J)=>Y.check(e$(J)),Y.duration=(J)=>Y.check(Y2(J))});function j2(Y){return V$(OL,Y)}var e=q("ZodStringFormat",(Y,X)=>{t.init(Y,X),q2.init(Y,X)}),qL=q("ZodEmail",(Y,X)=>{PG.init(Y,X),e.init(Y,X)});var Z2=q("ZodGUID",(Y,X)=>{jG.init(Y,X),e.init(Y,X)});var O9=q("ZodUUID",(Y,X)=>{DG.init(Y,X),e.init(Y,X)});var jL=q("ZodURL",(Y,X)=>{MG.init(Y,X),e.init(Y,X)});var DL=q("ZodEmoji",(Y,X)=>{EG.init(Y,X),e.init(Y,X)});var PL=q("ZodNanoID",(Y,X)=>{wG.init(Y,X),e.init(Y,X)});var ML=q("ZodCUID",(Y,X)=>{AG.init(Y,X),e.init(Y,X)});var EL=q("ZodCUID2",(Y,X)=>{TG.init(Y,X),e.init(Y,X)});var wL=q("ZodULID",(Y,X)=>{RG.init(Y,X),e.init(Y,X)});var AL=q("ZodXID",(Y,X)=>{CG.init(Y,X),e.init(Y,X)});var TL=q("ZodKSUID",(Y,X)=>{IG.init(Y,X),e.init(Y,X)});var RL=q("ZodIPv4",(Y,X)=>{bG.init(Y,X),e.init(Y,X)});var CL=q("ZodIPv6",(Y,X)=>{vG.init(Y,X),e.init(Y,X)});var IL=q("ZodCIDRv4",(Y,X)=>{hG.init(Y,X),e.init(Y,X)});var _L=q("ZodCIDRv6",(Y,X)=>{gG.init(Y,X),e.init(Y,X)});var SL=q("ZodBase64",(Y,X)=>{fG.init(Y,X),e.init(Y,X)});var kL=q("ZodBase64URL",(Y,X)=>{mG.init(Y,X),e.init(Y,X)});var xL=q("ZodE164",(Y,X)=>{cG.init(Y,X),e.init(Y,X)});var bL=q("ZodJWT",(Y,X)=>{uG.init(Y,X),e.init(Y,X)});var D2=q("ZodNumber",(Y,X)=>{qX.init(Y,X),Y0.init(Y,X),Y.gt=(Q,G)=>Y.check(H9(Q,G)),Y.gte=(Q,G)=>Y.check(j1(Q,G)),Y.min=(Q,G)=>Y.check(j1(Q,G)),Y.lt=(Q,G)=>Y.check(L9(Q,G)),Y.lte=(Q,G)=>Y.check(q1(Q,G)),Y.max=(Q,G)=>Y.check(q1(Q,G)),Y.int=(Q)=>Y.check(V2(Q)),Y.safe=(Q)=>Y.check(V2(Q)),Y.positive=(Q)=>Y.check(H9(0,Q)),Y.nonnegative=(Q)=>Y.check(j1(0,Q)),Y.negative=(Q)=>Y.check(L9(0,Q)),Y.nonpositive=(Q)=>Y.check(q1(0,Q)),Y.multipleOf=(Q,G)=>Y.check(N9(Q,G)),Y.step=(Q,G)=>Y.check(N9(Q,G)),Y.finite=()=>Y;let J=Y._zod.bag;Y.minValue=Math.max(J.minimum??Number.NEGATIVE_INFINITY,J.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Y.maxValue=Math.min(J.maximum??Number.POSITIVE_INFINITY,J.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Y.isInt=(J.format??"").includes("int")||Number.isSafeInteger(J.multipleOf??0.5),Y.isFinite=!0,Y.format=J.format??null});function P2(Y){return m$(D2,Y)}var vL=q("ZodNumberFormat",(Y,X)=>{pG.init(Y,X),D2.init(Y,X)});function V2(Y){return c$(vL,Y)}var hL=q("ZodBoolean",(Y,X)=>{lG.init(Y,X),Y0.init(Y,X)});function M2(Y){return u$(hL,Y)}var gL=q("ZodNull",(Y,X)=>{dG.init(Y,X),Y0.init(Y,X)});function E2(Y){return p$(gL,Y)}var yL=q("ZodUnknown",(Y,X)=>{iG.init(Y,X),Y0.init(Y,X)});function D1(){return l$(yL)}var fL=q("ZodNever",(Y,X)=>{oG.init(Y,X),Y0.init(Y,X)});function xX(Y){return d$(fL,Y)}var mL=q("ZodArray",(Y,X)=>{nG.init(Y,X),Y0.init(Y,X),Y.element=X.element,Y.min=(J,Q)=>Y.check(lY(J,Q)),Y.nonempty=(J)=>Y.check(lY(1,J)),Y.max=(J,Q)=>Y.check(Z9(J,Q)),Y.length=(J,Q)=>Y.check(V9(J,Q)),Y.unwrap=()=>Y.element});function bX(Y,X){return i$(mL,Y,X)}var w2=q("ZodObject",(Y,X)=>{aG.init(Y,X),Y0.init(Y,X),d.defineLazy(Y,"shape",()=>X.shape),Y.keyof=()=>hX(Object.keys(Y._zod.def.shape)),Y.catchall=(J)=>Y.clone({...Y._zod.def,catchall:J}),Y.passthrough=()=>Y.clone({...Y._zod.def,catchall:D1()}),Y.loose=()=>Y.clone({...Y._zod.def,catchall:D1()}),Y.strict=()=>Y.clone({...Y._zod.def,catchall:xX()}),Y.strip=()=>Y.clone({...Y._zod.def,catchall:void 0}),Y.extend=(J)=>{return d.extend(Y,J)},Y.safeExtend=(J)=>{return d.safeExtend(Y,J)},Y.merge=(J)=>d.merge(Y,J),Y.pick=(J)=>d.pick(Y,J),Y.omit=(J)=>d.omit(Y,J),Y.partial=(...J)=>d.partial(S2,Y,J[0]),Y.required=(...J)=>d.required(k2,Y,J[0])});function A2(Y,X){let J={type:"object",get shape(){return d.assignProp(this,"shape",Y?d.objectClone(Y):{}),this.shape},...d.normalizeParams(X)};return new w2(J)}function T2(Y,X){return new w2({type:"object",get shape(){return d.assignProp(this,"shape",d.objectClone(Y)),this.shape},catchall:D1(),...d.normalizeParams(X)})}var R2=q("ZodUnion",(Y,X)=>{jX.init(Y,X),Y0.init(Y,X),Y.options=X.options});function vX(Y,X){return new R2({type:"union",options:Y,...d.normalizeParams(X)})}var cL=q("ZodDiscriminatedUnion",(Y,X)=>{R2.init(Y,X),tG.init(Y,X)});function C2(Y,X,J){return new cL({type:"union",options:X,discriminator:Y,...d.normalizeParams(J)})}var uL=q("ZodIntersection",(Y,X)=>{eG.init(Y,X),Y0.init(Y,X)});function pL(Y,X){return new uL({type:"intersection",left:Y,right:X})}var lL=q("ZodRecord",(Y,X)=>{Y$.init(Y,X),Y0.init(Y,X),Y.keyType=X.keyType,Y.valueType=X.valueType});function I2(Y,X,J){return new lL({type:"record",keyType:Y,valueType:X,...d.normalizeParams(J)})}var kX=q("ZodEnum",(Y,X)=>{X$.init(Y,X),Y0.init(Y,X),Y.enum=X.entries,Y.options=Object.values(X.entries);let J=new Set(Object.keys(X.entries));Y.extract=(Q,G)=>{let $={};for(let W of Q)if(J.has(W))$[W]=X.entries[W];else throw Error(`Key ${W} not found in enum`);return new kX({...X,checks:[],...d.normalizeParams(G),entries:$})},Y.exclude=(Q,G)=>{let $={...X.entries};for(let W of Q)if(J.has(W))delete $[W];else throw Error(`Key ${W} not found in enum`);return new kX({...X,checks:[],...d.normalizeParams(G),entries:$})}});function hX(Y,X){let J=Array.isArray(Y)?Object.fromEntries(Y.map((Q)=>[Q,Q])):Y;return new kX({type:"enum",entries:J,...d.normalizeParams(X)})}var dL=q("ZodLiteral",(Y,X)=>{J$.init(Y,X),Y0.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 _2(Y,X){return new dL({type:"literal",values:Array.isArray(Y)?Y:[Y],...d.normalizeParams(X)})}var iL=q("ZodTransform",(Y,X)=>{Q$.init(Y,X),Y0.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new U1(Y.constructor.name);J.addIssue=($)=>{if(typeof $==="string")J.issues.push(d.issue($,J.value,X));else{let W=$;if(W.fatal)W.continue=!1;W.code??(W.code="custom"),W.input??(W.input=J.value),W.inst??(W.inst=Y),J.issues.push(d.issue(W))}};let G=X.transform(J.value,J);if(G instanceof Promise)return G.then(($)=>{return J.value=$,J});return J.value=G,J}});function oL(Y){return new iL({type:"transform",transform:Y})}var S2=q("ZodOptional",(Y,X)=>{G$.init(Y,X),Y0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function B2(Y){return new S2({type:"optional",innerType:Y})}var nL=q("ZodNullable",(Y,X)=>{$$.init(Y,X),Y0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function F2(Y){return new nL({type:"nullable",innerType:Y})}var rL=q("ZodDefault",(Y,X)=>{W$.init(Y,X),Y0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function sL(Y,X){return new rL({type:"default",innerType:Y,get defaultValue(){return typeof X==="function"?X():d.shallowClone(X)}})}var aL=q("ZodPrefault",(Y,X)=>{K$.init(Y,X),Y0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function tL(Y,X){return new aL({type:"prefault",innerType:Y,get defaultValue(){return typeof X==="function"?X():d.shallowClone(X)}})}var k2=q("ZodNonOptional",(Y,X)=>{z$.init(Y,X),Y0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function eL(Y,X){return new k2({type:"nonoptional",innerType:Y,...d.normalizeParams(X)})}var YH=q("ZodCatch",(Y,X)=>{U$.init(Y,X),Y0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function XH(Y,X){return new YH({type:"catch",innerType:Y,catchValue:typeof X==="function"?X:()=>X})}var JH=q("ZodPipe",(Y,X)=>{L$.init(Y,X),Y0.init(Y,X),Y.in=X.in,Y.out=X.out});function O2(Y,X){return new JH({type:"pipe",in:Y,out:X})}var QH=q("ZodReadonly",(Y,X)=>{H$.init(Y,X),Y0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function GH(Y){return new QH({type:"readonly",innerType:Y})}var $H=q("ZodLazy",(Y,X)=>{N$.init(Y,X),Y0.init(Y,X),Y.unwrap=()=>Y._zod.def.getter()});function x2(Y){return new $H({type:"lazy",getter:Y})}var gX=q("ZodCustom",(Y,X)=>{Z$.init(Y,X),Y0.init(Y,X)});function b2(Y,X){return o$(gX,Y??(()=>!0),X)}function WH(Y,X={}){return n$(gX,Y,X)}function KH(Y){return r$(Y)}function v2(Y,X={error:`Input not instance of ${Y.name}`}){let J=new gX({type:"custom",check:"custom",fn:(Q)=>Q instanceof Y,abort:!0,...d.normalizeParams(X)});return J._zod.bag.Class=Y,J}function d2(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 zH(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 dY(Y,...X){let J=new Headers(zH(Y)),Q=J.get("user-agent")||"";return J.set("user-agent",[Q,...X].filter(Boolean).join(" ")),Object.fromEntries(J.entries())}var UH=[{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]}],Rq=[...UH,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];var LH=12,HH=131072,Cq=HH+LH;async function q9(Y){var X;try{await((X=Y.body)==null?void 0:X.cancel())}catch(J){}}var i2="AI_DownloadError",o2=`vercel.ai.error.${i2}`,NH=Symbol.for(o2),h2,g2,A0=class extends(g2=P,h2=NH,g2){constructor({url:Y,statusCode:X,statusText:J,cause:Q,message:G=Q==null?`Failed to download ${Y}: ${X} ${J}`:`Failed to download ${Y}: ${Q}`}){super({name:i2,message:G,cause:Q});this[h2]=!0,this.url=Y,this.statusCode=X,this.statusText=J}static isInstance(Y){return P.hasMarker(Y,o2)}};function ZH(Y=globalThis){return Y.window!=null}function y2(Y,X){try{return new URL(Y).origin===new URL(X).origin}catch(J){return!1}}function VH(Y){let X;try{X=new URL(Y)}catch(Q){throw new A0({url:Y,message:`Invalid URL: ${Y}`})}if(X.protocol==="data:")return;if(X.protocol!=="http:"&&X.protocol!=="https:")throw new A0({url:Y,message:`URL scheme must be http, https, or data, got ${X.protocol}`});let J=X.hostname.toLowerCase().replace(/\.+$/,"");if(!J)throw new A0({url:Y,message:"URL must have a hostname"});if(J==="localhost"||J.endsWith(".local")||J.endsWith(".localhost"))throw new A0({url:Y,message:`URL with hostname ${J} is not allowed`});if(J.startsWith("[")&&J.endsWith("]")){let Q=J.slice(1,-1);if(n2(Q))throw new A0({url:Y,message:`URL with IPv6 address ${J} is not allowed`});return}if(pX(J)){if(lX(J))throw new A0({url:Y,message:`URL with IP address ${J} is not allowed`});return}}function BH({address:Y,family:X,hostname:J}){if(X===4?!pX(Y)||lX(Y):X===6?n2(Y):!0)throw new A0({url:J,message:`Hostname ${J} resolved to disallowed IP address ${Y}`})}function pX(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 lX(Y){let X=Y.split(".").map(Number),[J,Q,G]=X;if(J===0)return!0;if(J===10)return!0;if(J===100&&Q>=64&&Q<=127)return!0;if(J===127)return!0;if(J===169&&Q===254)return!0;if(J===172&&Q>=16&&Q<=31)return!0;if(J===192&&Q===0&&G===0)return!0;if(J===192&&Q===0&&G===2)return!0;if(J===192&&Q===168)return!0;if(J===198&&(Q===18||Q===19))return!0;if(J===198&&Q===51&&G===100)return!0;if(J===203&&Q===0&&G===113)return!0;if(J>=224)return!0;return!1}function FH(Y){let X=Y.toLowerCase(),J=X.indexOf("%");if(J!==-1)X=X.slice(0,J);let Q=X.split("::");if(Q.length>2)return null;let G=(W)=>{if(W==="")return[];let z=[],L=W.split(":");for(let U=0;U<L.length;U++){let H=L[U];if(H.includes(".")){if(U!==L.length-1||!pX(H))return null;let[B,V,Z,j]=H.split(".").map(Number);z.push(B<<8|V,Z<<8|j);continue}if(!/^[0-9a-f]{1,4}$/.test(H))return null;z.push(parseInt(H,16))}return z},$=G(Q[0]);if($===null)return null;if(Q.length===2){let W=G(Q[1]);if(W===null)return null;let z=8-$.length-W.length;if(z<0)return null;return[...$,...Array(z).fill(0),...W]}return $.length===8?$:null}function n2(Y){let X=FH(Y);if(X===null)return!0;let J=(G)=>X.slice(0,G).every(($)=>$===0);if(J(7)&&(X[7]===0||X[7]===1))return!0;if((X[0]&65024)===64512)return!0;if((X[0]&65472)===65152)return!0;if((X[0]&65472)===65216)return!0;if((X[0]&65280)===65280)return!0;if(X[0]===8193&&X[1]===3512)return!0;if(X[0]===16383&&(X[1]&61440)===0)return!0;if(J(6)||J(5)&&X[5]===65535||J(4)&&X[4]===65535&&X[5]===0||X[0]===100&&X[1]===65435&&X[2]===0&&X[3]===0&&X[4]===0&&X[5]===0||X[0]===100&&X[1]===65435&&X[2]===1){let G=X[6]>>8&255,$=X[6]&255,W=X[7]>>8&255,z=X[7]&255;return lX(`${G}.${$}.${W}.${z}`)}return!1}function OH(Y){return(X,J,Q)=>{Y(X,{...J,all:!0},(G,$)=>{if(G){Q(G);return}try{let[W]=$;if(W==null)throw Error(`Hostname ${X} did not resolve to an address`);for(let{address:z,family:L}of $)BH({address:z,family:L,hostname:X});if(J.all===!0)Q(null,$);else Q(null,W.address,W.family)}catch(W){Q(W instanceof Error?W:Error(String(W)))}})}}var yX,r2=globalThis.fetch,qH=PH(r2);function jH(){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 DH(){if(!jH()||!qH||globalThis.fetch!==r2)return globalThis.fetch;return yX!=null?yX:yX=Promise.resolve().then(MH)}function PH(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 MH(){let{createRequire:Y}=f2("node:module"),{lookup:X}=f2("node:dns"),{Agent:J,fetch:Q}=Y(s2())("undici"),G=new J({connect:{lookup:OH(X)}});return($,W)=>Q($,{...W,dispatcher:G})}function f2(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 s2(){let Y=Error.prepareStackTrace;try{Error.prepareStackTrace=(G,$)=>$;let X=Error("Capture current module path");Error.captureStackTrace(X,s2);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 EH=["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 wH(Y){let X=new Headers(Y);for(let J of EH)X.delete(J);return X}var AH=10,TH=new Set([301,302,303,307,308]);async function RH(Y){return Y==null||Y===globalThis.fetch?await DH():Y}async function a2({url:Y,headers:X,abortSignal:J,maxRedirects:Q=AH,fetch:G,trustedOrigin:$}){var W;let z=X===void 0?void 0:wH(X),L=(H)=>{let B={signal:J,redirect:H};if(z!==void 0)B.headers=new Headers(z);return B},U=Y;for(let H=0;H<=Q;H++){let B=$!==void 0&&y2(U,$);if(!B)VH(U);let V=B&&G!=null?G:B?globalThis.fetch:await RH(G),Z=await V(U,L("manual"));if(Z.type==="opaqueredirect"){if(!ZH())throw new A0({url:Y,message:`Redirect from ${U} could not be validated and was blocked`});return await V(U,L("follow"))}let j=(W=Z.headers)==null?void 0:W.get("location");if(TH.has(Z.status)&&j){await q9(Z);let O=new URL(j,U).toString();if(z!==void 0&&!y2(O,U)){let C=z.get("user-agent");z=new Headers(C==null?void 0:{"user-agent":C})}U=O;continue}return Z}throw new A0({url:Y,message:`Too many redirects (max ${Q})`})}var dX=2147483648;async function t2({response:Y,url:X,maxBytes:J=dX}){let Q=Y.headers.get("content-length");if(Q!=null){let H=parseInt(Q,10);if(!isNaN(H)&&H>J)throw await q9(Y),new A0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes (Content-Length: ${H}).`})}let G=Y.body;if(G==null)return new Uint8Array(0);let $=G.getReader(),W=[],z=0;try{while(!0){let{done:H,value:B}=await $.read();if(H)break;if(z+=B.length,z>J)throw new A0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes.`});W.push(B)}}finally{try{await $.cancel()}catch(H){}finally{$.releaseLock()}}let L=new Uint8Array(z),U=0;for(let H of W)L.set(H,U),U+=H.length;return L}var z0=({prefix:Y,size:X=16,alphabet:J="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:Q="-"}={})=>{let G=()=>{let $=J.length,W=Array(X);for(let z=0;z<X;z++)W[z]=J[Math.random()*$|0];return W.join("")};if(Y==null)return G;if(J.includes(Q))throw new _Q({argument:"separator",message:`The separator "${Q}" must not be part of the alphabet "${J}".`});return()=>`${Y}${Q}${G()}`},Sq=z0();function e2(Y){var X,J;return(J=(X=globalThis.Buffer)==null?void 0:X.isBuffer(Y))!=null?J:!1}var CH=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,IH=/"(?: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 m2(Y){let X=JSON.parse(Y);if(X===null||typeof X!=="object")return X;if(CH.test(Y)===!1&&IH.test(Y)===!1)return X;return _H(X)}function _H(Y){let X=[Y];while(X.length){let J=X;X=[];for(let Q of J){if(Object.prototype.hasOwnProperty.call(Q,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(Q,"constructor")&&Q.constructor!==null&&typeof Q.constructor==="object"&&Object.prototype.hasOwnProperty.call(Q.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let G in Q){let $=Q[G];if($&&typeof $==="object")X.push($)}}}return Y}function SH(Y){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(J){return m2(Y)}try{return m2(Y)}finally{Error.stackTraceLimit=X}}function iX(Y){if(Y.type==="object"||Array.isArray(Y.type)&&Y.type.includes("object")){let{additionalProperties:J}=Y;Y.additionalProperties=J!=null&&typeof J!=="boolean"?OY(J):!1;let{properties:Q}=Y;if(Q!=null)for(let G of Object.keys(Q))Q[G]=OY(Q[G])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(OY):OY(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(OY);if(Y.allOf!=null)Y.allOf=Y.allOf.map(OY);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(OY);let{definitions:X}=Y;if(X!=null)for(let J of Object.keys(X))X[J]=OY(X[J]);return Y}function OY(Y){if(typeof Y==="boolean")return Y;return iX(Y)}var kH=Symbol("Let zodToJsonSchema decide on which parser to use"),c2={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"},xH=(Y)=>typeof Y==="string"?{...c2,name:Y}:{...c2,...Y};function b0(){return{}}function bH(Y,X){var J,Q,G;let $={type:"array"};if(((J=Y.type)==null?void 0:J._def)&&((G=(Q=Y.type)==null?void 0:Q._def)==null?void 0:G.typeName)!=="ZodAny")$.items=r(Y.type._def,{...X,currentPath:[...X.currentPath,"items"]});if(Y.minLength)$.minItems=Y.minLength.value;if(Y.maxLength)$.maxItems=Y.maxLength.value;if(Y.exactLength)$.minItems=Y.exactLength.value,$.maxItems=Y.exactLength.value;return $}function vH(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 hH(){return{type:"boolean"}}function Y7(Y,X){return r(Y.type._def,X)}var gH=(Y,X)=>{return r(Y.innerType._def,X)};function X7(Y,X,J){let Q=J!=null?J:X.dateStrategy;if(Array.isArray(Q))return{anyOf:Q.map((G)=>X7(Y,X,G))};switch(Q){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return yH(Y)}}var yH=(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 fH(Y,X){return{...r(Y.innerType._def,X),default:Y.defaultValue()}}function mH(Y,X){return X.effectStrategy==="input"?r(Y.schema._def,X):b0()}function cH(Y){return{type:"string",enum:Array.from(Y.values)}}var uH=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function pH(Y,X){let J=[r(Y.left._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),r(Y.right._def,{...X,currentPath:[...X.currentPath,"allOf","1"]})].filter((G)=>!!G),Q=[];return J.forEach((G)=>{if(uH(G))Q.push(...G.allOf);else{let $=G;if("additionalProperties"in G&&G.additionalProperties===!1){let{additionalProperties:W,...z}=G;$=z}Q.push($)}}),Q.length?{allOf:Q}:void 0}function lH(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 fX=void 0,m0={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(fX===void 0)fX=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return fX},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 J7(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":c0(J,"email",Q.message,X);break;case"format:idn-email":c0(J,"idn-email",Q.message,X);break;case"pattern:zod":w0(J,m0.email,Q.message,X);break}break;case"url":c0(J,"uri",Q.message,X);break;case"uuid":c0(J,"uuid",Q.message,X);break;case"regex":w0(J,Q.regex,Q.message,X);break;case"cuid":w0(J,m0.cuid,Q.message,X);break;case"cuid2":w0(J,m0.cuid2,Q.message,X);break;case"startsWith":w0(J,RegExp(`^${mX(Q.value,X)}`),Q.message,X);break;case"endsWith":w0(J,RegExp(`${mX(Q.value,X)}$`),Q.message,X);break;case"datetime":c0(J,"date-time",Q.message,X);break;case"date":c0(J,"date",Q.message,X);break;case"time":c0(J,"time",Q.message,X);break;case"duration":c0(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":{w0(J,RegExp(mX(Q.value,X)),Q.message,X);break}case"ip":{if(Q.version!=="v6")c0(J,"ipv4",Q.message,X);if(Q.version!=="v4")c0(J,"ipv6",Q.message,X);break}case"base64url":w0(J,m0.base64url,Q.message,X);break;case"jwt":w0(J,m0.jwt,Q.message,X);break;case"cidr":{if(Q.version!=="v6")w0(J,m0.ipv4Cidr,Q.message,X);if(Q.version!=="v4")w0(J,m0.ipv6Cidr,Q.message,X);break}case"emoji":w0(J,m0.emoji(),Q.message,X);break;case"ulid":{w0(J,m0.ulid,Q.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{c0(J,"binary",Q.message,X);break}case"contentEncoding:base64":{J.contentEncoding="base64";break}case"pattern:zod":{w0(J,m0.base64,Q.message,X);break}}break}case"nanoid":w0(J,m0.nanoid,Q.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return J}function mX(Y,X){return X.patternStrategy==="escape"?iH(Y):Y}var dH=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function iH(Y){let X="";for(let J=0;J<Y.length;J++){if(!dH.has(Y[J]))X+="\\";X+=Y[J]}return X}function c0(Y,X,J,Q){var G;if(Y.format||((G=Y.anyOf)==null?void 0:G.some(($)=>$.format))){if(!Y.anyOf)Y.anyOf=[];if(Y.format)Y.anyOf.push({format:Y.format}),delete Y.format;Y.anyOf.push({format:X,...J&&Q.errorMessages&&{errorMessage:{format:J}}})}else Y.format=X}function w0(Y,X,J,Q){var G;if(Y.pattern||((G=Y.allOf)==null?void 0:G.some(($)=>$.pattern))){if(!Y.allOf)Y.allOf=[];if(Y.pattern)Y.allOf.push({pattern:Y.pattern}),delete Y.pattern;Y.allOf.push({pattern:u2(X,Q),...J&&Q.errorMessages&&{errorMessage:{pattern:J}}})}else Y.pattern=u2(X,Q)}function u2(Y,X){var J;if(!X.applyRegexFlags||!Y.flags)return Y.source;let Q={i:Y.flags.includes("i"),m:Y.flags.includes("m"),s:Y.flags.includes("s")},G=Q.i?Y.source.toLowerCase():Y.source,$="",W=!1,z=!1,L=!1;for(let U=0;U<G.length;U++){if(W){$+=G[U],W=!1;continue}if(Q.i){if(z){if(G[U].match(/[a-z]/)){if(L)$+=G[U],$+=`${G[U-2]}-${G[U]}`.toUpperCase(),L=!1;else if(G[U+1]==="-"&&((J=G[U+2])==null?void 0:J.match(/[a-z]/)))$+=G[U],L=!0;else $+=`${G[U]}${G[U].toUpperCase()}`;continue}}else if(G[U].match(/[a-z]/)){$+=`[${G[U]}${G[U].toUpperCase()}]`;continue}}if(Q.m){if(G[U]==="^"){$+=`(^|(?<=[\r
93
+ ]))`;continue}else if(G[U]==="$"){$+=`($|(?=[\r
94
+ ]))`;continue}}if(Q.s&&G[U]==="."){$+=z?`${G[U]}\r
95
+ `:`[${G[U]}\r
96
+ ]`;continue}if($+=G[U],G[U]==="\\")W=!0;else if(z&&G[U]==="]")z=!1;else if(!z&&G[U]==="[")z=!0}try{new RegExp($)}catch(U){return console.warn(`Could not convert regex pattern at ${X.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Y.source}return $}function Q7(Y,X){var J,Q,G,$,W,z;let L={type:"object",additionalProperties:(J=r(Y.valueType._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]}))!=null?J:X.allowedAdditionalProperties};if(((Q=Y.keyType)==null?void 0:Q._def.typeName)==="ZodString"&&((G=Y.keyType._def.checks)==null?void 0:G.length)){let{type:U,...H}=J7(Y.keyType._def,X);return{...L,propertyNames:H}}else if((($=Y.keyType)==null?void 0:$._def.typeName)==="ZodEnum")return{...L,propertyNames:{enum:Y.keyType._def.values}};else if(((W=Y.keyType)==null?void 0:W._def.typeName)==="ZodBranded"&&Y.keyType._def.type._def.typeName==="ZodString"&&((z=Y.keyType._def.type._def.checks)==null?void 0:z.length)){let{type:U,...H}=Y7(Y.keyType._def,X);return{...L,propertyNames:H}}return L}function oH(Y,X){if(X.mapStrategy==="record")return Q7(Y,X);let J=r(Y.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||b0(),Q=r(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||b0();return{type:"array",maxItems:125,items:{type:"array",items:[J,Q],minItems:2,maxItems:2}}}function nH(Y){let X=Y.values,Q=Object.keys(Y.values).filter(($)=>{return typeof X[X[$]]!=="number"}).map(($)=>X[$]),G=Array.from(new Set(Q.map(($)=>typeof $)));return{type:G.length===1?G[0]==="string"?"string":"number":["string","number"],enum:Q}}function rH(){return{not:b0()}}function sH(){return{type:"null"}}var cX={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function aH(Y,X){let J=Y.options instanceof Map?Array.from(Y.options.values()):Y.options;if(J.every((Q)=>(Q._def.typeName in cX)&&(!Q._def.checks||!Q._def.checks.length))){let Q=J.reduce((G,$)=>{let W=cX[$._def.typeName];return W&&!G.includes(W)?[...G,W]:G},[]);return{type:Q.length>1?Q:Q[0]}}else if(J.every((Q)=>Q._def.typeName==="ZodLiteral"&&!Q.description)){let Q=J.reduce((G,$)=>{let W=typeof $._def.value;switch(W){case"string":case"number":case"boolean":return[...G,W];case"bigint":return[...G,"integer"];case"object":if($._def.value===null)return[...G,"null"];case"symbol":case"undefined":case"function":default:return G}},[]);if(Q.length===J.length){let G=Q.filter(($,W,z)=>z.indexOf($)===W);return{type:G.length>1?G:G[0],enum:J.reduce(($,W)=>{return $.includes(W._def.value)?$:[...$,W._def.value]},[])}}}else if(J.every((Q)=>Q._def.typeName==="ZodEnum"))return{type:"string",enum:J.reduce((Q,G)=>[...Q,...G._def.values.filter(($)=>!Q.includes($))],[])};return tH(Y,X)}var tH=(Y,X)=>{let J=(Y.options instanceof Map?Array.from(Y.options.values()):Y.options).map((Q,G)=>r(Q._def,{...X,currentPath:[...X.currentPath,"anyOf",`${G}`]})).filter((Q)=>!!Q&&(!X.strictUnions||typeof Q==="object"&&Object.keys(Q).length>0));return J.length?{anyOf:J}:void 0};function eH(Y,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Y.innerType._def.typeName)&&(!Y.innerType._def.checks||!Y.innerType._def.checks.length))return{type:[cX[Y.innerType._def.typeName],"null"]};let J=r(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return J&&{anyOf:[J,{type:"null"}]}}function YN(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 XN(Y,X){let J={type:"object",properties:{}},Q=[],G=Y.shape();for(let W in G){let z=G[W];if(z===void 0||z._def===void 0)continue;let L=QN(z),U=r(z._def,{...X,currentPath:[...X.currentPath,"properties",W],propertyPath:[...X.currentPath,"properties",W]});if(U===void 0)continue;if(J.properties[W]=U,!L)Q.push(W)}if(Q.length)J.required=Q;let $=JN(Y,X);if($!==void 0)J.additionalProperties=$;return J}function JN(Y,X){if(Y.catchall._def.typeName!=="ZodNever")return r(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 QN(Y){try{return Y.isOptional()}catch(X){return!0}}var GN=(Y,X)=>{var J;if(X.currentPath.toString()===((J=X.propertyPath)==null?void 0:J.toString()))return r(Y.innerType._def,X);let Q=r(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return Q?{anyOf:[{not:b0()},Q]}:b0()},$N=(Y,X)=>{if(X.pipeStrategy==="input")return r(Y.in._def,X);else if(X.pipeStrategy==="output")return r(Y.out._def,X);let J=r(Y.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),Q=r(Y.out._def,{...X,currentPath:[...X.currentPath,"allOf",J?"1":"0"]});return{allOf:[J,Q].filter((G)=>G!==void 0)}};function WN(Y,X){return r(Y.type._def,X)}function KN(Y,X){let Q={type:"array",uniqueItems:!0,items:r(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 zN(Y,X){if(Y.rest)return{type:"array",minItems:Y.items.length,items:Y.items.map((J,Q)=>r(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[]),additionalItems:r(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)=>r(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[])}}function UN(){return{not:b0()}}function LN(){return b0()}var HN=(Y,X)=>{return r(Y.innerType._def,X)},NN=(Y,X,J)=>{switch(X){case"ZodString":return J7(Y,J);case"ZodNumber":return YN(Y);case"ZodObject":return XN(Y,J);case"ZodBigInt":return vH(Y);case"ZodBoolean":return hH();case"ZodDate":return X7(Y,J);case"ZodUndefined":return UN();case"ZodNull":return sH();case"ZodArray":return bH(Y,J);case"ZodUnion":case"ZodDiscriminatedUnion":return aH(Y,J);case"ZodIntersection":return pH(Y,J);case"ZodTuple":return zN(Y,J);case"ZodRecord":return Q7(Y,J);case"ZodLiteral":return lH(Y);case"ZodEnum":return cH(Y);case"ZodNativeEnum":return nH(Y);case"ZodNullable":return eH(Y,J);case"ZodOptional":return GN(Y,J);case"ZodMap":return oH(Y,J);case"ZodSet":return KN(Y,J);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return WN(Y,J);case"ZodNaN":case"ZodNever":return rH();case"ZodEffects":return mH(Y,J);case"ZodAny":return b0();case"ZodUnknown":return LN();case"ZodDefault":return fH(Y,J);case"ZodBranded":return Y7(Y,J);case"ZodReadonly":return HN(Y,J);case"ZodCatch":return gH(Y,J);case"ZodPipeline":return $N(Y,J);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Q)=>{return})(X)}},ZN=(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 r(Y,X,J=!1){var Q;let G=X.seen.get(Y);if(X.override){let L=(Q=X.override)==null?void 0:Q.call(X,Y,X,G,J);if(L!==kH)return L}if(G&&!J){let L=VN(G,X);if(L!==void 0)return L}let $={def:Y,path:X.currentPath,jsonSchema:void 0};X.seen.set(Y,$);let W=NN(Y,Y.typeName,X),z=typeof W==="function"?r(W(),X):W;if(z)BN(Y,X,z);if(X.postProcess){let L=X.postProcess(z,Y,X);return $.jsonSchema=z,L}return $.jsonSchema=z,z}var VN=(Y,X)=>{switch(X.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:ZN(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`),b0();return X.$refStrategy==="seen"?b0():void 0}}},BN=(Y,X,J)=>{if(Y.description)J.description=Y.description;return J},FN=(Y)=>{let X=xH(Y),J=X.name!==void 0?[...X.basePath,X.definitionPath,X.name]:X.basePath;return{...X,currentPath:J,propertyPath:void 0,seen:new Map(Object.entries(X.definitions).map(([Q,G])=>[G._def,{def:G._def,path:[...X.basePath,X.definitionPath,Q],jsonSchema:void 0}]))}},ON=(Y,X)=>{var J;let Q=FN(X),G=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((U,[H,B])=>{var V;return{...U,[H]:(V=r(B._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,H]},!0))!=null?V:b0()}},{}):void 0,$=typeof X==="string"?X:(X==null?void 0:X.nameStrategy)==="title"?void 0:X==null?void 0:X.name,W=(J=r(Y._def,$===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,$]},!1))!=null?J:b0(),z=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if(z!==void 0)W.title=z;let L=$===void 0?G?{...W,[Q.definitionPath]:G}:W:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,$].join("/"),[Q.definitionPath]:{...G,[$]:W}};return L.$schema="http://json-schema.org/draft-07/schema#",L},uX=Symbol.for("vercel.ai.schema");function j9(Y){let X;return()=>{if(X==null)X=Y();return X}}function D9(Y,{validate:X}={}){return{[uX]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:X}}function qN(Y){return typeof Y==="object"&&Y!==null&&uX in Y&&Y[uX]===!0&&"jsonSchema"in Y&&"validate"in Y}function P9(Y){return Y==null?D9({type:"object",properties:{},additionalProperties:!1}):qN(Y)?Y:("~standard"in Y)?Y["~standard"].vendor==="zod"?P1(Y):jN(Y):Y()}function jN(Y){return D9(()=>{if(!DN(Y))throw Error(`Standard schema vendor '${Y["~standard"].vendor}' does not support JSON Schema conversion.`);return iX(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 h0({value:X,cause:J.issues})}}})}function DN(Y){return Y["~standard"].jsonSchema!=null}function PN(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return D9(()=>ON(Y,{$refStrategy:Q?"root":"none"}),{validate:async(G)=>{let $=await Y.safeParseAsync(G);return $.success?{success:!0,value:$.data}:{success:!1,error:$.error}}})}function MN(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return D9(()=>iX(s$(Y,{target:"draft-7",io:"input",reused:Q?"ref":"inline"})),{validate:async(G)=>{let $=await F9(Y,G);return $.success?{success:!0,value:$.data}:{success:!1,error:$.error}}})}function EN(Y){return"_zod"in Y}function P1(Y,X){if(EN(Y))return MN(Y,X);else return PN(Y,X)}async function iY({value:Y,schema:X,context:J}){let Q=P9(X);try{if(Q.validate==null)return{success:!0,value:Y,rawValue:Y};let G=await Q.validate(Y);if(G.success)return{success:!0,value:G.value,rawValue:Y};return{success:!1,error:h0.wrap({value:Y,cause:G.error,context:J}),rawValue:Y}}catch(G){return{success:!1,error:h0.wrap({value:Y,cause:G,context:J}),rawValue:Y}}}async function qY({text:Y,schema:X}){try{let J=SH(Y);if(X==null)return{success:!0,value:J,rawValue:J};return await iY({value:J,schema:X})}catch(J){return{success:!1,error:t1.isInstance(J)?J:new t1({text:Y,cause:J}),rawValue:void 0}}}async function oX(Y){if(typeof Y==="function")Y=Y();return Promise.resolve(Y)}var G7="AI_SerializationError",$7=`vercel.ai.error.${G7}`,wN=Symbol.for($7),p2,l2,yq=class extends(l2=P,p2=wN,l2){constructor({message:Y="Failed to serialize value.",cause:X}={}){super({name:G7,message:Y,cause:X});this[p2]=!0}static isInstance(Y){return P.hasMarker(Y,$7)}};var RN=Object.defineProperty,CN=(Y,X)=>{for(var J in X)RN(Y,J,{get:X[J],enumerable:!0})},JW="AI_InvalidArgumentError",QW=`vercel.ai.error.${JW}`,IN=Symbol.for(QW),W7,K7,nX=class extends(K7=P,W7=IN,K7){constructor({parameter:Y,value:X,message:J}){super({name:JW,message:`Invalid argument for parameter ${Y}: ${J}`});this[W7]=!0,this.parameter=Y,this.value=X}static isInstance(Y){return P.hasMarker(Y,QW)}},GW="AI_InvalidStreamPartError",$W=`vercel.ai.error.${GW}`,_N=Symbol.for($W),z7,U7,sq=class extends(U7=P,z7=_N,U7){constructor({chunk:Y,message:X}){super({name:GW,message:X});this[z7]=!0,this.chunk=Y}static isInstance(Y){return P.hasMarker(Y,$W)}},WW="AI_InvalidToolApprovalError",KW=`vercel.ai.error.${WW}`,SN=Symbol.for(KW),L7,H7,tq=class extends(H7=P,L7=SN,H7){constructor({approvalId:Y}){super({name:WW,message:`Tool approval response references unknown approvalId: "${Y}". No matching tool-approval-request found in message history.`});this[L7]=!0,this.approvalId=Y}static isInstance(Y){return P.hasMarker(Y,KW)}},zW="AI_InvalidToolApprovalSignatureError",UW=`vercel.ai.error.${zW}`,kN=Symbol.for(UW),N7,Z7,Yj=class extends(Z7=P,N7=kN,Z7){constructor({approvalId:Y,toolCallId:X,reason:J}){super({name:zW,message:`Tool approval signature verification failed for approval "${Y}" (tool call "${X}"): ${J}`});this[N7]=!0,this.approvalId=Y,this.toolCallId=X}static isInstance(Y){return P.hasMarker(Y,UW)}},LW="AI_InvalidToolInputError",HW=`vercel.ai.error.${LW}`,xN=Symbol.for(HW),V7,B7,Jj=class extends(B7=P,V7=xN,B7){constructor({toolInput:Y,toolName:X,cause:J,message:Q=`Invalid input for tool ${X}: ${CY(J)}`}){super({name:LW,message:Q,cause:J});this[V7]=!0,this.toolInput=Y,this.toolName=X}static isInstance(Y){return P.hasMarker(Y,HW)}},NW="AI_ToolCallNotFoundForApprovalError",ZW=`vercel.ai.error.${NW}`,bN=Symbol.for(ZW),F7,O7,Gj=class extends(O7=P,F7=bN,O7){constructor({toolCallId:Y,approvalId:X}){super({name:NW,message:`Tool call "${Y}" not found for approval request "${X}".`});this[F7]=!0,this.toolCallId=Y,this.approvalId=X}static isInstance(Y){return P.hasMarker(Y,ZW)}},VW="AI_MissingToolResultsError",BW=`vercel.ai.error.${VW}`,vN=Symbol.for(BW),q7,j7,Wj=class extends(j7=P,q7=vN,j7){constructor({toolCallIds:Y}){super({name:VW,message:`Tool result${Y.length>1?"s are":" is"} missing for tool call${Y.length>1?"s":""} ${Y.join(", ")}.`});this[q7]=!0,this.toolCallIds=Y}static isInstance(Y){return P.hasMarker(Y,BW)}},FW="AI_NoImageGeneratedError",OW=`vercel.ai.error.${FW}`,hN=Symbol.for(OW),D7,P7,zj=class extends(P7=P,D7=hN,P7){constructor({message:Y="No image generated.",cause:X,calls:J,responses:Q}){super({name:FW,message:Y,cause:X});this[D7]=!0,this.calls=J,this.responses=Q}static isInstance(Y){return P.hasMarker(Y,OW)}},qW="AI_NoObjectGeneratedError",jW=`vercel.ai.error.${qW}`,gN=Symbol.for(jW),M7,E7,GY=class extends(E7=P,M7=gN,E7){constructor({message:Y="No object generated.",cause:X,text:J,response:Q,usage:G,finishReason:$}){super({name:qW,message:Y,cause:X});this[M7]=!0,this.text=J,this.response=Q,this.usage=G,this.finishReason=$}static isInstance(Y){return P.hasMarker(Y,jW)}},DW="AI_NoOutputGeneratedError",PW=`vercel.ai.error.${DW}`,yN=Symbol.for(PW),w7,A7,Hj=class extends(A7=P,w7=yN,A7){constructor({message:Y="No output generated.",cause:X}={}){super({name:DW,message:Y,cause:X});this[w7]=!0}static isInstance(Y){return P.hasMarker(Y,PW)}},MW="AI_NoSpeechGeneratedError",EW=`vercel.ai.error.${MW}`,fN=Symbol.for(EW),T7,R7,Zj=class extends(R7=P,T7=fN,R7){constructor(Y){super({name:MW,message:"No speech audio generated."});this[T7]=!0,this.responses=Y.responses}static isInstance(Y){return P.hasMarker(Y,EW)}},wW="AI_NoTranscriptGeneratedError",AW=`vercel.ai.error.${wW}`,mN=Symbol.for(AW),C7,I7,Bj=class extends(I7=P,C7=mN,I7){constructor(Y){super({name:wW,message:"No transcript generated."});this[C7]=!0,this.responses=Y.responses}static isInstance(Y){return P.hasMarker(Y,AW)}},TW="AI_NoTranslationGeneratedError",RW=`vercel.ai.error.${TW}`,cN=Symbol.for(RW),_7,S7,Oj=class extends(S7=P,_7=cN,S7){constructor(Y){super({name:TW,message:"No translation generated."});this[_7]=!0,this.response=Y.response}static isInstance(Y){return P.hasMarker(Y,RW)}},rX="AI_NoVideoGeneratedError",CW=`vercel.ai.error.${rX}`,uN=Symbol.for(CW),k7,x7,jj=class extends(x7=P,k7=uN,x7){constructor({message:Y="No video generated.",cause:X,responses:J}){super({name:rX,message:Y,cause:X});this[k7]=!0,this.responses=J}static isInstance(Y){return P.hasMarker(Y,CW)}static isNoVideoGeneratedError(Y){return Y instanceof Error&&Y.name===rX&&typeof Y.responses<"u"?!0:!1}toJSON(){return{name:this.name,message:this.message,stack:this.stack,cause:this.cause,responses:this.responses}}},IW="AI_NoSuchToolError",_W=`vercel.ai.error.${IW}`,pN=Symbol.for(_W),b7,v7,Pj=class extends(v7=P,b7=pN,v7){constructor({toolName:Y,availableTools:X=void 0,message:J=`Model tried to call unavailable tool '${Y}'. ${X===void 0?"No tools are available.":`Available tools: ${X.join(", ")}.`}`}){super({name:IW,message:J});this[b7]=!0,this.toolName=Y,this.availableTools=X}static isInstance(Y){return P.hasMarker(Y,_W)}},SW="AI_StreamProviderError",kW=`vercel.ai.error.${SW}`,lN=Symbol.for(kW),h7,g7,Ej=class extends(g7=P,h7=lN,g7){constructor({message:Y,type:X,code:J,statusCode:Q,isRetryable:G=dN(Q),data:$,cause:W}){super({name:SW,message:Y,cause:W});this[h7]=!0,this.type=X,this.code=J,this.statusCode=Q,this.isRetryable=G,this.data=$}static isInstance(Y){return P.hasMarker(Y,kW)}};function dN(Y){return Y!=null&&(Y===408||Y===409||Y===429||Y>=500)}var xW="AI_ToolCallRepairError",bW=`vercel.ai.error.${xW}`,iN=Symbol.for(bW),y7,f7,Aj=class extends(f7=P,y7=iN,f7){constructor({cause:Y,originalError:X,message:J=`Error repairing tool call: ${CY(Y)}`}){super({name:xW,message:J,cause:Y});this[y7]=!0,this.originalError=X}static isInstance(Y){return P.hasMarker(Y,bW)}},vW="AI_ToolChoiceViolationError",hW=`vercel.ai.error.${vW}`,oN=Symbol.for(hW),m7,c7,Rj=class extends(c7=P,m7=oN,c7){constructor({toolChoice:Y,finishReason:X,provider:J,modelId:Q,content:G,message:$=Y.type==="required"?"Model response did not contain a tool call even though tool choice was required.":`Model response did not contain a call to the required tool '${Y.toolName}'.`}){super({name:vW,message:$});this[m7]=!0,this.toolChoice=Y,this.finishReason=X,this.provider=J,this.modelId=Q,this.content=G}static isInstance(Y){return P.hasMarker(Y,hW)}};var gW="AI_UIMessageStreamError",yW=`vercel.ai.error.${gW}`,nN=Symbol.for(yW),u7,p7,Ij=class extends(p7=P,u7=nN,p7){constructor({chunkType:Y,chunkId:X,message:J}){super({name:gW,message:J});this[u7]=!0,this.chunkType=Y,this.chunkId=X}static isInstance(Y){return P.hasMarker(Y,yW)}},fW="AI_InvalidDataContentError",mW=`vercel.ai.error.${fW}`,rN=Symbol.for(mW),l7,d7,Sj=class extends(d7=P,l7=rN,d7){constructor({content:Y,cause:X,message:J=`Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof Y}.`}){super({name:fW,message:J,cause:X});this[l7]=!0,this.content=Y}static isInstance(Y){return P.hasMarker(Y,mW)}},cW="AI_InvalidMessageRoleError",uW=`vercel.ai.error.${cW}`,sN=Symbol.for(uW),i7,o7,xj=class extends(o7=P,i7=sN,o7){constructor({role:Y,message:X=`Invalid message role: '${Y}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:cW,message:X});this[i7]=!0,this.role=Y}static isInstance(Y){return P.hasMarker(Y,uW)}},pW="AI_MessageConversionError",lW=`vercel.ai.error.${pW}`,aN=Symbol.for(lW),n7,r7,vj=class extends(r7=P,n7=aN,r7){constructor({originalMessage:Y,message:X}){super({name:pW,message:X});this[n7]=!0,this.originalMessage=Y}static isInstance(Y){return P.hasMarker(Y,lW)}},dW="AI_RetryError",iW=`vercel.ai.error.${dW}`,tN=Symbol.for(iW),s7,a7,gj=class extends(a7=P,s7=tN,a7){constructor({message:Y,reason:X,errors:J}){super({name:dW,message:Y});this[s7]=!0,this.reason=X,this.errors=J,this.lastError=J[J.length-1]}static isInstance(Y){return P.hasMarker(Y,iW)}};var eN="7.0.102",YZ=async({url:Y,maxBytes:X,abortSignal:J})=>{var Q;let G=Y.toString();try{let $=dY({},`ai-sdk/${eN}`,d2()),W=await a2({url:G,headers:$,abortSignal:J});if(!W.ok)throw await q9(W),new A0({url:G,statusCode:W.status,statusText:W.statusText});return{data:await t2({response:W,url:G,maxBytes:X!=null?X:dX}),mediaType:(Q=W.headers.get("content-type"))!=null?Q:void 0}}catch($){if(A0.isInstance($))throw $;throw new A0({url:G,cause:$})}};var K={array:bX,boolean:M2,custom:b2,discriminatedUnion:C2,enum:hX,instanceof:v2,lazy:x2,literal:_2,looseObject:T2,never:xX,null:E2,number:P2,object:A2,record:I2,string:j2,union:vX,unknown:D1},kY=K.lazy(()=>K.union([K.null(),K.string(),K.number(),K.boolean(),K.record(K.string(),kY.optional()),K.array(kY)])),_=K.record(K.string(),K.record(K.string(),kY.optional())),E1=K.union([K.string(),K.instanceof(Uint8Array),K.instanceof(ArrayBuffer),K.custom(e2,{message:"Must be a Buffer"})]),sX=K.record(K.string(),K.string()),oW=K.object({type:K.literal("text"),text:K.string(),providerOptions:_.optional()}),XZ=K.object({type:K.literal("image"),image:K.union([E1,K.instanceof(URL),sX]),mediaType:K.string().optional(),providerOptions:_.optional()}),nW=K.discriminatedUnion("type",[K.object({type:K.literal("data"),data:E1}),K.object({type:K.literal("url"),url:K.instanceof(URL)}),K.object({type:K.literal("reference"),reference:sX}),K.object({type:K.literal("text"),text:K.string()})]),JZ=K.discriminatedUnion("type",[K.object({type:K.literal("data"),data:E1}),K.object({type:K.literal("url"),url:K.instanceof(URL)})]),rW=K.object({type:K.literal("file"),data:K.union([nW,E1,K.instanceof(URL),sX]),filename:K.string().optional(),mediaType:K.string(),providerOptions:_.optional()}),QZ=K.object({type:K.literal("reasoning"),text:K.string(),providerOptions:_.optional()}),GZ=K.object({type:K.literal("custom"),kind:K.string().transform((Y)=>Y),providerOptions:_.optional()}),$Z=K.object({type:K.literal("reasoning-file"),data:K.union([JZ,E1,K.instanceof(URL)]),mediaType:K.string(),providerOptions:_.optional()}),WZ=K.object({type:K.literal("tool-call"),toolCallId:K.string(),toolName:K.string(),input:K.unknown(),providerOptions:_.optional(),providerExecuted:K.boolean().optional()}),KZ=K.discriminatedUnion("type",[K.object({type:K.literal("text"),value:K.string(),providerOptions:_.optional()}),K.object({type:K.literal("json"),value:kY,providerOptions:_.optional()}),K.object({type:K.literal("execution-denied"),reason:K.string().optional(),providerOptions:_.optional()}),K.object({type:K.literal("error-text"),value:K.string(),providerOptions:_.optional()}),K.object({type:K.literal("error-json"),value:kY,providerOptions:_.optional()}),K.object({type:K.literal("content"),value:K.array(K.union([K.object({type:K.literal("text"),text:K.string(),providerOptions:_.optional()}),K.object({type:K.literal("file"),data:nW,mediaType:K.string(),filename:K.string().optional(),providerOptions:_.optional()}),K.object({type:K.literal("file-data"),data:K.string(),mediaType:K.string(),filename:K.string().optional(),providerOptions:_.optional()}),K.object({type:K.literal("file-url"),url:K.string(),mediaType:K.string().optional(),providerOptions:_.optional()}),K.object({type:K.literal("file-id"),fileId:K.union([K.string(),K.record(K.string(),K.string())]),providerOptions:_.optional()}),K.object({type:K.literal("file-reference"),providerReference:K.record(K.string(),K.string()),providerOptions:_.optional()}),K.object({type:K.literal("image-data"),data:K.string(),mediaType:K.string(),providerOptions:_.optional()}),K.object({type:K.literal("image-url"),url:K.string(),providerOptions:_.optional()}),K.object({type:K.literal("image-file-id"),fileId:K.union([K.string(),K.record(K.string(),K.string())]),providerOptions:_.optional()}),K.object({type:K.literal("image-file-reference"),providerReference:K.record(K.string(),K.string()),providerOptions:_.optional()}),K.object({type:K.literal("custom"),providerOptions:_.optional()})]))})]),sW=K.object({type:K.literal("tool-result"),toolCallId:K.string(),toolName:K.string(),output:KZ,providerOptions:_.optional()}),zZ=K.object({type:K.literal("tool-approval-request"),approvalId:K.string(),toolCallId:K.string(),reason:K.string().optional()}),UZ=K.object({type:K.literal("tool-approval-response"),approvalId:K.string(),approved:K.boolean(),reason:K.string().optional()}),LZ=K.object({role:K.literal("system"),content:K.string(),providerOptions:_.optional()}),HZ=K.object({role:K.literal("user"),content:K.union([K.string(),K.array(K.union([oW,XZ,rW]))]),providerOptions:_.optional()}),NZ=K.object({role:K.literal("assistant"),content:K.union([K.string(),K.array(K.union([oW,GZ,rW,QZ,$Z,WZ,sW,zZ]))]),providerOptions:_.optional()}),ZZ=K.object({role:K.literal("tool"),content:K.array(K.union([sW,UZ])),providerOptions:_.optional()}),cj=K.union([LZ,HZ,NZ,ZZ]);var VZ={};CN(VZ,{array:()=>qZ,choice:()=>jZ,json:()=>DZ,object:()=>OZ,text:()=>FZ});function BZ(Y){let X=["ROOT"],J=-1,Q=null,G=0;function $(H){return H>="0"&&H<="9"||H>="A"&&H<="F"||H>="a"&&H<="f"}function W(H,B,V){switch(H){case'"':{J=B,X.pop(),X.push(V),X.push("INSIDE_STRING");break}case"f":case"t":case"n":{J=B,Q=B,X.pop(),X.push(V),X.push("INSIDE_LITERAL");break}case"-":{X.pop(),X.push(V),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=B,X.pop(),X.push(V),X.push("INSIDE_NUMBER");break}case"{":{J=B,X.pop(),X.push(V),X.push("INSIDE_OBJECT_START");break}case"[":{J=B,X.pop(),X.push(V),X.push("INSIDE_ARRAY_START");break}}}function z(H,B){switch(H){case",":{X.pop(),X.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{J=B,X.pop();break}}}function L(H,B){switch(H){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=B,X.pop();break}}}for(let H=0;H<Y.length;H++){let B=Y[H];switch(X[X.length-1]){case"ROOT":W(B,H,"FINISH");break;case"INSIDE_OBJECT_START":{switch(B){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}case"}":{J=H,X.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(B){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(B){case'"':{X.pop(),X.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(B){case":":{X.pop(),X.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{W(B,H,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{z(B,H);break}case"INSIDE_STRING":{switch(B){case'"':{X.pop(),J=H;break}case"\\":{X.push("INSIDE_STRING_ESCAPE");break}default:J=H}break}case"INSIDE_ARRAY_START":{switch(B){case"]":{J=H,X.pop();break}default:{J=H,W(B,H,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(B){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=H,X.pop();break}default:{J=H;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{W(B,H,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{if(X.pop(),B==="u")G=0,X.push("INSIDE_STRING_UNICODE_ESCAPE");else J=H;break}case"INSIDE_STRING_UNICODE_ESCAPE":{if($(B)){if(G++,G===4)X.pop(),J=H}break}case"INSIDE_NUMBER":{switch(B){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=H;break}case"e":case"E":case"-":case".":break;case",":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")L(B,H);if(X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")z(B,H);break}case"}":{if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")z(B,H);break}case"]":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")L(B,H);break}default:{X.pop();break}}break}case"INSIDE_LITERAL":{let Z=Y.substring(Q,H+1);if(!"false".startsWith(Z)&&!"true".startsWith(Z)&&!"null".startsWith(Z)){if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")z(B,H);else if(X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")L(B,H)}else J=H;break}}}let U=Y.slice(0,J+1);for(let H=X.length-1;H>=0;H--)switch(X[H]){case"INSIDE_STRING":{U+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{U+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{U+="]";break}case"INSIDE_LITERAL":{let V=Y.substring(Q,Y.length);if("true".startsWith(V))U+="true".slice(V.length);else if("false".startsWith(V))U+="false".slice(V.length);else if("null".startsWith(V))U+="null".slice(V.length)}}return U}async function M9(Y){if(Y===void 0)return{value:void 0,state:"undefined-input"};let X=await qY({text:Y});if(X.success)return{value:X.value,state:"successful-parse"};if(X=await qY({text:BZ(Y)}),X.success)return{value:X.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var FZ=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:Y}){return Y},async parsePartialOutput({text:Y}){return{partial:Y}},createElementStreamTransform(){return}}),OZ=({schema:Y,name:X,description:J})=>{let Q=P9(Y);return{name:"object",responseFormat:oX(Q.jsonSchema).then((G)=>({type:"json",schema:G,...X!=null&&{name:X},...J!=null&&{description:J}})),async parseCompleteOutput({text:G},$){let W=await qY({text:G});if(!W.success)throw new GY({message:"No object generated: could not parse the response.",cause:W.error,text:G,response:$.response,usage:$.usage,finishReason:$.finishReason});let z=await iY({value:W.value,schema:Q});if(!z.success)throw new GY({message:"No object generated: response did not match schema.",cause:z.error,text:G,response:$.response,usage:$.usage,finishReason:$.finishReason});return z.value},async parsePartialOutput({text:G}){let $=await M9(G);switch($.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:$.value}}},createElementStreamTransform(){return}}},qZ=({element:Y,minItems:X,maxItems:J,name:Q,description:G})=>{if(t7({name:"minItems",value:X}),t7({name:"maxItems",value:J}),X!=null&&J!=null&&X>J)throw new nX({parameter:"minItems",value:X,message:"minItems must be less than or equal to maxItems"});let $=P9(Y);return{name:"array",responseFormat:oX($.jsonSchema).then((W)=>{let{$schema:z,definitions:L,$defs:U,...H}=W;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",...L!=null&&{definitions:L},...U!=null&&{$defs:U},type:"object",properties:{elements:{type:"array",items:H,...X!=null&&{minItems:X},...J!=null&&{maxItems:J}}},required:["elements"],additionalProperties:!1},...Q!=null&&{name:Q},...G!=null&&{description:G}}}),async parseCompleteOutput({text:W},z){let L=await qY({text:W});if(!L.success)throw new GY({message:"No object generated: could not parse the response.",cause:L.error,text:W,response:z.response,usage:z.usage,finishReason:z.finishReason});let U=L.value;if(U==null||typeof U!=="object"||!("elements"in U)||!Array.isArray(U.elements))throw new GY({message:"No object generated: response did not match schema.",cause:new h0({value:U,cause:"response must be an object with an elements array"}),text:W,response:z.response,usage:z.usage,finishReason:z.finishReason});let H=e7({value:U.elements,minItems:X,maxItems:J});if(H!=null)throw new GY({message:"No object generated: response did not match schema.",cause:H,text:W,response:z.response,usage:z.usage,finishReason:z.finishReason});let B=[];for(let V of U.elements){let Z=await iY({value:V,schema:$});if(!Z.success)throw new GY({message:"No object generated: response did not match schema.",cause:Z.error,text:W,response:z.response,usage:z.usage,finishReason:z.finishReason});B.push(Z.value)}return B},async parsePartialOutput({text:W}){let z=await M9(W);switch(z.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let L=z.value;if(L==null||typeof L!=="object"||!("elements"in L)||!Array.isArray(L.elements))return;let U=z.state==="repaired-parse"&&L.elements.length>0?L.elements.slice(0,-1):L.elements,H=[];for(let B of U){let V=await iY({value:B,schema:$});if(V.success)H.push(V.value)}return{partial:H}}}},createElementStreamTransform(){let W=0;return new TransformStream({transform({partialOutput:z},L){if(z!=null)for(;W<z.length;W++){if(J!=null&&W>=J){L.error(e7({value:z,maxItems:J}));return}L.enqueue(z[W])}}})}}};function t7({name:Y,value:X}){if(X==null)return;if(!Number.isInteger(X))throw new nX({parameter:Y,value:X,message:`${Y} must be an integer`});if(X<0)throw new nX({parameter:Y,value:X,message:`${Y} must be greater than or equal to 0`})}function e7({value:Y,minItems:X,maxItems:J}){if(X!=null&&Y.length<X)return new h0({value:Y,cause:`elements array must contain at least ${X} items`});if(J!=null&&Y.length>J)return new h0({value:Y,cause:`elements array must contain at most ${J} items`});return}var jZ=({options:Y,name:X,description:J})=>{return{name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:Y}},required:["result"],additionalProperties:!1},...X!=null&&{name:X},...J!=null&&{description:J}}),async parseCompleteOutput({text:Q},G){let $=await qY({text:Q});if(!$.success)throw new GY({message:"No object generated: could not parse the response.",cause:$.error,text:Q,response:G.response,usage:G.usage,finishReason:G.finishReason});let W=$.value;if(W==null||typeof W!=="object"||!("result"in W)||typeof W.result!=="string"||!Y.includes(W.result))throw new GY({message:"No object generated: response did not match schema.",cause:new h0({value:W,cause:"response must be an object that contains a choice value."}),text:Q,response:G.response,usage:G.usage,finishReason:G.finishReason});return W.result},async parsePartialOutput({text:Q}){let G=await M9(Q);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let $=G.value;if($==null||typeof $!=="object"||!("result"in $)||typeof $.result!=="string")return;let W=Y.filter((z)=>z.startsWith($.result));if(G.state==="successful-parse")return W.includes($.result)?{partial:$.result}:void 0;else return W.length===1?{partial:W[0]}:void 0}}},createElementStreamTransform(){return}}},DZ=({name:Y,description:X}={})=>{return{name:"json",responseFormat:Promise.resolve({type:"json",...Y!=null&&{name:Y},...X!=null&&{description:X}}),async parseCompleteOutput({text:J},Q){let G=await qY({text:J});if(!G.success)throw new GY({message:"No object generated: could not parse the response.",cause:G.error,text:J,response:Q.response,usage:Q.usage,finishReason:Q.finishReason});return G.value},async parsePartialOutput({text:J}){let Q=await M9(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 dj=z0({prefix:"aitxt",size:24}),ij=z0({prefix:"call",size:24});var nj=class extends TransformStream{constructor(){super({transform(Y,X){X.enqueue(`data: ${JSON.stringify(Y)}
192
97
 
193
98
  `)},flush(Y){Y.enqueue(`data: [DONE]
194
99
 
195
- `)}})}};var KY=z.record(z.string(),I1.optional()),vq=z8(()=>ZY(z.union([z.looseObject({type:z.literal("text-start"),id:z.string(),providerMetadata:R.optional()}),z.looseObject({type:z.literal("text-delta"),id:z.string(),delta:z.string(),providerMetadata:R.optional()}),z.looseObject({type:z.literal("text-end"),id:z.string(),providerMetadata:R.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:R.optional(),toolMetadata:KY.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:R.optional(),toolMetadata:KY.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:R.optional(),toolMetadata:KY.optional(),dynamic:z.boolean().optional(),errorText:z.string(),title:z.string().optional()}),z.looseObject({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string(),approvalDescriptor:z.unknown().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}),z.looseObject({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional(),providerExecuted:z.boolean().optional(),providerMetadata:R.optional()}),z.looseObject({type:z.literal("tool-output-available"),toolCallId:z.string(),output:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:R.optional(),toolMetadata:KY.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:R.optional(),toolMetadata:KY.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:R.optional()}),z.looseObject({type:z.literal("reasoning-delta"),id:z.string(),delta:z.string(),providerMetadata:R.optional()}),z.looseObject({type:z.literal("reasoning-end"),id:z.string(),providerMetadata:R.optional()}),z.looseObject({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerMetadata:R.optional()}),z.looseObject({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:R.optional()}),z.looseObject({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:R.optional()}),z.looseObject({type:z.literal("file"),url:z.string(),mediaType:z.string(),providerMetadata:R.optional()}),z.looseObject({type:z.literal("reasoning-file"),url:z.string(),mediaType:z.string(),providerMetadata:R.optional()}),z.looseObject({type:z.custom((Y)=>typeof Y==="string"&&Y.startsWith("data-"),{message:'Type must start with "data-"'}),id:z.string().optional(),data:z.unknown(),transient:z.boolean().optional()}),z.looseObject({type:z.literal("start-step")}),z.looseObject({type:z.literal("finish-step")}),z.looseObject({type:z.literal("reset-step")}),z.looseObject({type:z.literal("start"),messageId:z.string().optional(),messageMetadata:z.unknown().optional()}),z.looseObject({type:z.literal("finish"),finishReason:z.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:z.unknown().optional()}),z.looseObject({type:z.literal("abort"),reason:z.string().optional()}),z.looseObject({type:z.literal("message-metadata"),messageMetadata:z.unknown()})])));var gq=z0({prefix:"aitxt",size:24}),yq=z0({prefix:"call",size:24});var fq=z0({prefix:"aitxt",size:24}),mq=z0({prefix:"call",size:24});var A0=z.record(z.string(),I1.optional()),TV=z.record(z.string(),z.string());var uq=z8(()=>ZY(z.array(z.object({id:z.string(),role:z.enum(["system","user","assistant"]),metadata:z.unknown().optional(),parts:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:R.optional()}),z.object({type:z.literal("reasoning"),id:z.string().optional(),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:R.optional()}),z.object({type:z.literal("custom"),kind:z.string(),providerMetadata:R.optional()}),z.object({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:R.optional()}),z.object({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:R.optional()}),z.object({type:z.literal("file"),mediaType:z.string(),filename:z.string().optional(),url:z.string(),providerReference:TV.optional(),providerMetadata:R.optional()}),z.object({type:z.literal("reasoning-file"),mediaType:z.string(),url:z.string(),providerMetadata:R.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:A0.optional(),state:z.literal("input-streaming"),input:z.unknown().optional(),providerExecuted:z.boolean().optional(),callProviderMetadata:R.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:A0.optional(),state:z.literal("input-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:R.optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:A0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:R.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.never().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:A0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:R.optional(),approval:z.object({id:z.string(),approved:z.boolean(),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:A0.optional(),state:z.literal("output-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:R.optional(),resultProviderMetadata:R.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:A0.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:R.optional(),resultProviderMetadata:R.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:A0.optional(),state:z.literal("output-denied"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:R.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:A0.optional(),state:z.literal("input-streaming"),providerExecuted:z.boolean().optional(),callProviderMetadata:R.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:A0.optional(),state:z.literal("input-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:R.optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:A0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:R.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.never().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:A0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:R.optional(),approval:z.object({id:z.string(),approved:z.boolean(),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:A0.optional(),state:z.literal("output-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:R.optional(),resultProviderMetadata:R.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:A0.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:R.optional(),resultProviderMetadata:R.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:A0.optional(),state:z.literal("output-denied"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:R.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})})]))}).superRefine((Y,X)=>{if(Y.role!=="assistant"&&Y.parts.length===0)X.addIssue({origin:"array",code:"too_small",minimum:1,inclusive:!0,input:Y.parts,path:["parts"],message:"Message must contain at least one part"})})).nonempty("Messages array must not be empty")));var lq=z0({prefix:"call",size:24});var iq=z0({prefix:"call",size:24});var oq=z0({prefix:"aiobj",size:24});function d2(Y){return({url:X,abortSignal:J})=>GV({url:X,maxBytes:Y==null?void 0:Y.maxBytes,abortSignal:J})}var sq=z0({prefix:"aiobj",size:24});var aq=d2();var i2="AI_NoSuchProviderError",n2=`vercel.ai.error.${i2}`,RV=Symbol.for(n2),oW,rW,eq=class extends(rW=W9,oW=RV,rW){constructor({modelId:Y,modelType:X,providerId:J,availableProviders:Q,message:$=`No such provider: ${J} (available providers: ${Q.join()})`}){super({errorName:i2,modelId:Y,modelType:X,message:$});this[oW]=!0,this.providerId=J,this.availableProviders=Q}static isInstance(Y){return D.hasMarker(Y,n2)}};var Xj=z0({prefix:"call",size:24});var Jj=d2();class w0 extends YY{name="ProviderResponseStreamError";constructor(Y,X){super({message:Y,url:"",requestBodyValues:void 0,cause:X?.cause,isRetryable:X?.retryable??!0})}}var B0={};U9(B0,{toWebSocketUrl:()=>dV,streamResponsesWebSocket:()=>sV,parseRateLimitSignal:()=>FY,normalizeHeaders:()=>iV,markOversizedFrame:()=>G4,isUpgradeFailure:()=>nV,isOversizedFrame:()=>oV,isAbortError:()=>JX,connectResponsesWebSocket:()=>rV,PROTOCOL_HEADER:()=>J4,OpenAIWebSocket:()=>B0});function OY(Y){let X=Number(Y.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(X)?X:void 0}function N8(Y,X,J=!1){let $=Buffer.from(Y.slice(0,X)).toString("latin1").split(`\r
196
- `),G=$[0]??"",W=OY(G);if(W===void 0||W===101)return;let U=Object.fromEntries($.slice(1).flatMap((N)=>{let O=N.indexOf(":");return O===-1?[]:[[N.slice(0,O).trim().toLowerCase(),N.slice(O+1).trim()]]})),H=Y.slice(X+4),L=U["content-length"],V=Number(L);if(!J&&(L===void 0||Number.isFinite(V)&&H.length<V))return;let B=Buffer.from(H).toString("utf8"),K=(()=>{try{let N=JSON.parse(B);return C(N)?N:void 0}catch{return}})();return{message:`WS upgrade failed: ${G}`,status:W,status_code:W,headers:U,body:B,...C(K?.error)?{error:K.error}:{}}}var _V="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",o2=["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 e9{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];writeQueue=[];constructor(Y,X,J){this.url=Y,this.sessionID=J?.sessionID,this.connect(Y,X)}addEventListener(Y,X,J){this.listeners[Y]?.add(X)}removeEventListener(Y,X){this.listeners[Y]?.delete(X)}peerClose;closeEmitted=!1;emitClose(Y,X){if(this.closeEmitted)return;this.closeEmitted=!0,this.emit("close",{code:Y,reason:X})}emit(Y,X){for(let J of[...this.listeners[Y]??[]])try{J(X)}catch{}}async connect(Y,X){let J=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),Q=J.hostname,$=J.port?Number(J.port):J.protocol==="https:"?443:80,G=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),U=Buffer.from(W).toString("base64"),H=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(U+_V));this.expectedAccept=Buffer.from(new Uint8Array(H)).toString("base64");let L={};for(let[K,N]of Object.entries(X))L[K.toLowerCase()]=N;let V=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${U}`];for(let K of o2)if(L[K]!==void 0)V.push(`${CV(K)}: ${L[K]}`);for(let[K,N]of Object.entries(X))if(!o2.includes(K.toLowerCase())&&K.toLowerCase()!=="content-length")V.push(`${K}: ${N}`);let B=`${V.join(`\r
100
+ `)}})}};var M1=K.record(K.string(),kY.optional()),sj=j9(()=>P1(K.union([K.looseObject({type:K.literal("text-start"),id:K.string(),providerMetadata:_.optional()}),K.looseObject({type:K.literal("text-delta"),id:K.string(),delta:K.string(),providerMetadata:_.optional()}),K.looseObject({type:K.literal("text-end"),id:K.string(),providerMetadata:_.optional()}),K.looseObject({type:K.literal("error"),errorText:K.string()}),K.looseObject({type:K.literal("tool-input-start"),toolCallId:K.string(),toolName:K.string(),providerExecuted:K.boolean().optional(),providerMetadata:_.optional(),toolMetadata:M1.optional(),dynamic:K.boolean().optional(),title:K.string().optional()}),K.looseObject({type:K.literal("tool-input-delta"),toolCallId:K.string(),inputTextDelta:K.string()}),K.looseObject({type:K.literal("tool-input-available"),toolCallId:K.string(),toolName:K.string(),input:K.unknown(),providerExecuted:K.boolean().optional(),providerMetadata:_.optional(),toolMetadata:M1.optional(),dynamic:K.boolean().optional(),title:K.string().optional()}),K.looseObject({type:K.literal("tool-input-error"),toolCallId:K.string(),toolName:K.string(),input:K.unknown(),providerExecuted:K.boolean().optional(),providerMetadata:_.optional(),toolMetadata:M1.optional(),dynamic:K.boolean().optional(),errorText:K.string(),title:K.string().optional()}),K.looseObject({type:K.literal("tool-approval-request"),approvalId:K.string(),toolCallId:K.string(),approvalDescriptor:K.unknown().optional(),reason:K.string().optional(),isAutomatic:K.boolean().optional(),signature:K.string().optional()}),K.looseObject({type:K.literal("tool-approval-response"),approvalId:K.string(),approved:K.boolean(),reason:K.string().optional(),providerExecuted:K.boolean().optional(),providerMetadata:_.optional()}),K.looseObject({type:K.literal("tool-output-available"),toolCallId:K.string(),output:K.unknown(),providerExecuted:K.boolean().optional(),providerMetadata:_.optional(),toolMetadata:M1.optional(),dynamic:K.boolean().optional(),preliminary:K.boolean().optional()}),K.looseObject({type:K.literal("tool-output-error"),toolCallId:K.string(),errorText:K.string(),providerExecuted:K.boolean().optional(),providerMetadata:_.optional(),toolMetadata:M1.optional(),dynamic:K.boolean().optional()}),K.looseObject({type:K.literal("tool-output-denied"),toolCallId:K.string()}),K.looseObject({type:K.literal("reasoning-start"),id:K.string(),providerMetadata:_.optional()}),K.looseObject({type:K.literal("reasoning-delta"),id:K.string(),delta:K.string(),providerMetadata:_.optional()}),K.looseObject({type:K.literal("reasoning-end"),id:K.string(),providerMetadata:_.optional()}),K.looseObject({type:K.literal("custom"),kind:K.string().transform((Y)=>Y),providerMetadata:_.optional()}),K.looseObject({type:K.literal("source-url"),sourceId:K.string(),url:K.string(),title:K.string().optional(),providerMetadata:_.optional()}),K.looseObject({type:K.literal("source-document"),sourceId:K.string(),mediaType:K.string(),title:K.string(),filename:K.string().optional(),providerMetadata:_.optional()}),K.looseObject({type:K.literal("file"),url:K.string(),mediaType:K.string(),providerMetadata:_.optional()}),K.looseObject({type:K.literal("reasoning-file"),url:K.string(),mediaType:K.string(),providerMetadata:_.optional()}),K.looseObject({type:K.custom((Y)=>typeof Y==="string"&&Y.startsWith("data-"),{message:'Type must start with "data-"'}),id:K.string().optional(),data:K.unknown(),transient:K.boolean().optional()}),K.looseObject({type:K.literal("start-step")}),K.looseObject({type:K.literal("finish-step")}),K.looseObject({type:K.literal("reset-step")}),K.looseObject({type:K.literal("start"),messageId:K.string().optional(),messageMetadata:K.unknown().optional()}),K.looseObject({type:K.literal("finish"),finishReason:K.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:K.unknown().optional()}),K.looseObject({type:K.literal("abort"),reason:K.string().optional()}),K.looseObject({type:K.literal("message-metadata"),messageMetadata:K.unknown()})])));var tj=z0({prefix:"aitxt",size:24}),ej=z0({prefix:"call",size:24});var Y6=z0({prefix:"aitxt",size:24}),X6=z0({prefix:"call",size:24});var I0=K.record(K.string(),kY.optional()),PZ=K.record(K.string(),K.string());var Q6=j9(()=>P1(K.array(K.object({id:K.string(),role:K.enum(["system","user","assistant"]),metadata:K.unknown().optional(),parts:K.array(K.union([K.object({type:K.literal("text"),text:K.string(),state:K.enum(["streaming","done"]).optional(),providerMetadata:_.optional()}),K.object({type:K.literal("reasoning"),id:K.string().optional(),text:K.string(),state:K.enum(["streaming","done"]).optional(),providerMetadata:_.optional()}),K.object({type:K.literal("custom"),kind:K.string(),providerMetadata:_.optional()}),K.object({type:K.literal("source-url"),sourceId:K.string(),url:K.string(),title:K.string().optional(),providerMetadata:_.optional()}),K.object({type:K.literal("source-document"),sourceId:K.string(),mediaType:K.string(),title:K.string(),filename:K.string().optional(),providerMetadata:_.optional()}),K.object({type:K.literal("file"),mediaType:K.string(),filename:K.string().optional(),url:K.string(),providerReference:PZ.optional(),providerMetadata:_.optional()}),K.object({type:K.literal("reasoning-file"),mediaType:K.string(),url:K.string(),providerMetadata:_.optional()}),K.object({type:K.literal("step-start")}),K.object({type:K.string().startsWith("data-"),id:K.string().optional(),data:K.unknown()}),K.object({type:K.literal("dynamic-tool"),toolName:K.string(),toolCallId:K.string(),title:K.string().optional(),toolMetadata:I0.optional(),state:K.literal("input-streaming"),input:K.unknown().optional(),providerExecuted:K.boolean().optional(),callProviderMetadata:_.optional(),output:K.never().optional(),errorText:K.never().optional(),approval:K.never().optional()}),K.object({type:K.literal("dynamic-tool"),toolName:K.string(),toolCallId:K.string(),title:K.string().optional(),toolMetadata:I0.optional(),state:K.literal("input-available"),input:K.unknown(),providerExecuted:K.boolean().optional(),output:K.never().optional(),errorText:K.never().optional(),callProviderMetadata:_.optional(),approval:K.never().optional()}),K.object({type:K.literal("dynamic-tool"),toolName:K.string(),toolCallId:K.string(),title:K.string().optional(),toolMetadata:I0.optional(),state:K.literal("approval-requested"),input:K.unknown(),providerExecuted:K.boolean().optional(),output:K.never().optional(),errorText:K.never().optional(),callProviderMetadata:_.optional(),approval:K.object({id:K.string(),approved:K.never().optional(),descriptor:K.unknown().optional(),requestReason:K.string().optional(),reason:K.never().optional(),isAutomatic:K.boolean().optional(),signature:K.string().optional()})}),K.object({type:K.literal("dynamic-tool"),toolName:K.string(),toolCallId:K.string(),title:K.string().optional(),toolMetadata:I0.optional(),state:K.literal("approval-responded"),input:K.unknown(),providerExecuted:K.boolean().optional(),output:K.never().optional(),errorText:K.never().optional(),callProviderMetadata:_.optional(),approval:K.object({id:K.string(),approved:K.boolean(),descriptor:K.unknown().optional(),requestReason:K.string().optional(),reason:K.string().optional(),isAutomatic:K.boolean().optional(),signature:K.string().optional()})}),K.object({type:K.literal("dynamic-tool"),toolName:K.string(),toolCallId:K.string(),title:K.string().optional(),toolMetadata:I0.optional(),state:K.literal("output-available"),input:K.unknown(),providerExecuted:K.boolean().optional(),output:K.unknown(),errorText:K.never().optional(),callProviderMetadata:_.optional(),resultProviderMetadata:_.optional(),preliminary:K.boolean().optional(),approval:K.object({id:K.string(),approved:K.literal(!0),descriptor:K.unknown().optional(),requestReason:K.string().optional(),reason:K.string().optional(),isAutomatic:K.boolean().optional(),signature:K.string().optional()}).optional()}),K.object({type:K.literal("dynamic-tool"),toolName:K.string(),toolCallId:K.string(),title:K.string().optional(),toolMetadata:I0.optional(),state:K.literal("output-error"),input:K.unknown().optional(),rawInput:K.unknown().optional(),providerExecuted:K.boolean().optional(),output:K.never().optional(),errorText:K.string(),callProviderMetadata:_.optional(),resultProviderMetadata:_.optional(),approval:K.object({id:K.string(),approved:K.literal(!0),descriptor:K.unknown().optional(),requestReason:K.string().optional(),reason:K.string().optional(),isAutomatic:K.boolean().optional(),signature:K.string().optional()}).optional()}),K.object({type:K.literal("dynamic-tool"),toolName:K.string(),toolCallId:K.string(),title:K.string().optional(),toolMetadata:I0.optional(),state:K.literal("output-denied"),input:K.unknown(),providerExecuted:K.boolean().optional(),output:K.never().optional(),errorText:K.never().optional(),callProviderMetadata:_.optional(),approval:K.object({id:K.string(),approved:K.literal(!1),descriptor:K.unknown().optional(),requestReason:K.string().optional(),reason:K.string().optional(),isAutomatic:K.boolean().optional(),signature:K.string().optional()})}),K.object({type:K.string().startsWith("tool-"),toolCallId:K.string(),title:K.string().optional(),toolMetadata:I0.optional(),state:K.literal("input-streaming"),providerExecuted:K.boolean().optional(),callProviderMetadata:_.optional(),input:K.unknown().optional(),output:K.never().optional(),errorText:K.never().optional(),approval:K.never().optional()}),K.object({type:K.string().startsWith("tool-"),toolCallId:K.string(),title:K.string().optional(),toolMetadata:I0.optional(),state:K.literal("input-available"),providerExecuted:K.boolean().optional(),input:K.unknown(),output:K.never().optional(),errorText:K.never().optional(),callProviderMetadata:_.optional(),approval:K.never().optional()}),K.object({type:K.string().startsWith("tool-"),toolCallId:K.string(),title:K.string().optional(),toolMetadata:I0.optional(),state:K.literal("approval-requested"),input:K.unknown(),providerExecuted:K.boolean().optional(),output:K.never().optional(),errorText:K.never().optional(),callProviderMetadata:_.optional(),approval:K.object({id:K.string(),approved:K.never().optional(),descriptor:K.unknown().optional(),requestReason:K.string().optional(),reason:K.never().optional(),isAutomatic:K.boolean().optional(),signature:K.string().optional()})}),K.object({type:K.string().startsWith("tool-"),toolCallId:K.string(),title:K.string().optional(),toolMetadata:I0.optional(),state:K.literal("approval-responded"),input:K.unknown(),providerExecuted:K.boolean().optional(),output:K.never().optional(),errorText:K.never().optional(),callProviderMetadata:_.optional(),approval:K.object({id:K.string(),approved:K.boolean(),descriptor:K.unknown().optional(),requestReason:K.string().optional(),reason:K.string().optional(),isAutomatic:K.boolean().optional(),signature:K.string().optional()})}),K.object({type:K.string().startsWith("tool-"),toolCallId:K.string(),title:K.string().optional(),toolMetadata:I0.optional(),state:K.literal("output-available"),providerExecuted:K.boolean().optional(),input:K.unknown(),output:K.unknown(),errorText:K.never().optional(),callProviderMetadata:_.optional(),resultProviderMetadata:_.optional(),preliminary:K.boolean().optional(),approval:K.object({id:K.string(),approved:K.literal(!0),descriptor:K.unknown().optional(),requestReason:K.string().optional(),reason:K.string().optional(),isAutomatic:K.boolean().optional(),signature:K.string().optional()}).optional()}),K.object({type:K.string().startsWith("tool-"),toolCallId:K.string(),title:K.string().optional(),toolMetadata:I0.optional(),state:K.literal("output-error"),providerExecuted:K.boolean().optional(),input:K.unknown().optional(),rawInput:K.unknown().optional(),output:K.never().optional(),errorText:K.string(),callProviderMetadata:_.optional(),resultProviderMetadata:_.optional(),approval:K.object({id:K.string(),approved:K.literal(!0),descriptor:K.unknown().optional(),requestReason:K.string().optional(),reason:K.string().optional(),isAutomatic:K.boolean().optional(),signature:K.string().optional()}).optional()}),K.object({type:K.string().startsWith("tool-"),toolCallId:K.string(),title:K.string().optional(),toolMetadata:I0.optional(),state:K.literal("output-denied"),providerExecuted:K.boolean().optional(),input:K.unknown(),output:K.never().optional(),errorText:K.never().optional(),callProviderMetadata:_.optional(),approval:K.object({id:K.string(),approved:K.literal(!1),descriptor:K.unknown().optional(),requestReason:K.string().optional(),reason:K.string().optional(),isAutomatic:K.boolean().optional(),signature:K.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 $6=z0({prefix:"call",size:24});var K6=z0({prefix:"call",size:24});var U6=z0({prefix:"aiobj",size:24});function aW(Y){return({url:X,abortSignal:J})=>YZ({url:X,maxBytes:Y==null?void 0:Y.maxBytes,abortSignal:J})}var H6=z0({prefix:"aiobj",size:24});var N6=aW();var Z6=K.object({token:K.string().refine((Y)=>Y.trim().length>0),url:K.string().refine((Y)=>{try{let X=new URL(Y);return(X.protocol==="ws:"||X.protocol==="wss:")&&X.hostname!==""}catch(X){return!1}}),expiresAt:K.number().positive().max(Number.MAX_SAFE_INTEGER).optional(),tools:K.array(K.object({type:K.literal("function"),name:K.string().min(1),description:K.string().optional(),parameters:K.record(K.string(),K.unknown())})).optional()});var tW="AI_NoSuchProviderError",eW=`vercel.ai.error.${tW}`,MZ=Symbol.for(eW),YW,XW,B6=class extends(XW=QX,YW=MZ,XW){constructor({modelId:Y,modelType:X,providerId:J,availableProviders:Q,message:G=`No such provider: ${J} (available providers: ${Q.join()})`}){super({errorName:tW,modelId:Y,modelType:X,message:G});this[YW]=!0,this.providerId=J,this.availableProviders=Q}static isInstance(Y){return P.hasMarker(Y,eW)}};var O6=z0({prefix:"call",size:24});var q6=aW();class _0 extends z1{name="ProviderResponseStreamError";constructor(Y,X){super({message:Y,url:"",requestBodyValues:void 0,cause:X?.cause,isRetryable:X?.retryable??!0})}}var P0={};$X(P0,{toWebSocketUrl:()=>mZ,streamResponsesWebSocket:()=>dZ,parseRateLimitSignal:()=>A1,normalizeHeaders:()=>cZ,markOversizedFrame:()=>L4,isUpgradeFailure:()=>uZ,isOversizedFrame:()=>pZ,isAbortError:()=>Y8,connectResponsesWebSocket:()=>lZ,TERMINAL_AFTER_OUTPUT_MESSAGE:()=>N4,PROTOCOL_HEADER:()=>K4,OpenAIWebSocket:()=>P0,OVERSIZED_FRAME_MESSAGE:()=>Z4});function w1(Y){let X=Number(Y.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(X)?X:void 0}function E9(Y,X,J=!1){let G=Buffer.from(Y.slice(0,X)).toString("latin1").split(`\r
101
+ `),$=G[0]??"",W=w1($);if(W===void 0||W===101)return;let z=Object.fromEntries(G.slice(1).flatMap((Z)=>{let j=Z.indexOf(":");return j===-1?[]:[[Z.slice(0,j).trim().toLowerCase(),Z.slice(j+1).trim()]]})),L=Y.slice(X+4),U=z["content-length"],H=Number(U);if(!J&&(U===void 0||Number.isFinite(H)&&L.length<H))return;let B=Buffer.from(L).toString("utf8"),V=(()=>{try{let Z=JSON.parse(B);return k(Z)?Z:void 0}catch{return}})();return{message:`WS upgrade failed: ${$}`,status:W,status_code:W,headers:z,body:B,...k(V?.error)?{error:V.error}:{}}}var EZ="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",Y4=["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 aX{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];writeQueue=[];constructor(Y,X,J){this.url=Y,this.sessionID=J?.sessionID,this.connect(Y,X)}addEventListener(Y,X,J){this.listeners[Y]?.add(X)}removeEventListener(Y,X){this.listeners[Y]?.delete(X)}peerClose;closeEmitted=!1;emitClose(Y,X){if(this.closeEmitted)return;this.closeEmitted=!0,this.emit("close",{code:Y,reason:X})}emit(Y,X){for(let J of[...this.listeners[Y]??[]])try{J(X)}catch{}}async connect(Y,X){let J=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),Q=J.hostname,G=J.port?Number(J.port):J.protocol==="https:"?443:80,$=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),z=Buffer.from(W).toString("base64"),L=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(z+EZ));this.expectedAccept=Buffer.from(new Uint8Array(L)).toString("base64");let U={};for(let[V,Z]of Object.entries(X))U[V.toLowerCase()]=Z;let H=[`GET ${$} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${z}`];for(let V of Y4)if(U[V]!==void 0)H.push(`${wZ(V)}: ${U[V]}`);for(let[V,Z]of Object.entries(X))if(!Y4.includes(V.toLowerCase())&&V.toLowerCase()!=="content-length")H.push(`${V}: ${Z}`);let B=`${H.join(`\r
197
102
  `)}\r
198
103
  \r
199
- `;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let K=globalThis.Bun?.connect;if(!K)throw Error("Bun.connect is not available");this.socket=await K({hostname:Q,port:$,tls:J.protocol==="https:"?{serverName:Q}:void 0,socket:{open:(N)=>{this.socket=N,this.enqueueWrite(new TextEncoder().encode(B))},data:(N,O)=>this.onData(O),drain:()=>this.flushWrites(),error:(N,O)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let j=O instanceof Error?O.message:String(O);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.emitClose(this.peerClose?.code??1006,this.peerClose?.reason??"socket closed")}}})}catch(K){this.readyState=3;let N=K instanceof Error?K.message:String(K);this.log("connect_exception",{message:N}),this.emit("error",{message:N})}}onData(Y){if(this.rxBuffer=IV(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
104
+ `;try{this.log("connect_start",{host:Q,port:G,tls:J.protocol==="https:"});let V=globalThis.Bun?.connect;if(!V)throw Error("Bun.connect is not available");this.socket=await V({hostname:Q,port:G,tls:J.protocol==="https:"?{serverName:Q}:void 0,socket:{open:(Z)=>{this.socket=Z,this.enqueueWrite(new TextEncoder().encode(B))},data:(Z,j)=>this.onData(j),drain:()=>this.flushWrites(),error:(Z,j)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let O=j instanceof Error?j.message:String(j);this.log("socket_error",{message:O}),this.emit("error",{message:O})},close:()=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close"),this.emitClose(this.peerClose?.code??1006,this.peerClose?.reason??"socket closed")}}})}catch(V){this.readyState=3;let Z=V instanceof Error?V.message:String(V);this.log("connect_exception",{message:Z}),this.emit("error",{message:Z})}}onData(Y){if(this.rxBuffer=AZ(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
200
105
  \r
201
- `);if(J===-1)return;let Q=X.slice(0,J),$=Q.split(`\r
202
- `)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=OY($);if(W!==101){if(W===void 0){this.readyState=3;try{this.socket?.end()}catch{}this.log("upgrade_failed",{statusLine:$}),this.emit("error",{message:`WS upgrade failed: ${$}`});return}if(!this.emitRejectedUpgrade())return;try{this.socket?.end()}catch{}return}if(!G||G[1]!==this.expectedAccept){this.readyState=3;try{this.socket?.end()}catch{}this.log("accept_mismatch",{statusLine:$}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(J+4),this.log("open",{statusLine:$}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let X=Buffer.from(this.rxBuffer).indexOf(`\r
106
+ `);if(J===-1)return;let Q=X.slice(0,J),G=Q.split(`\r
107
+ `)[0]??"",$=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=w1(G);if(W!==101){if(W===void 0){this.readyState=3;try{this.socket?.end()}catch{}this.log("upgrade_failed",{statusLine:G}),this.emit("error",{message:`WS upgrade failed: ${G}`});return}if(!this.emitRejectedUpgrade())return;try{this.socket?.end()}catch{}return}if(!$||$[1]!==this.expectedAccept){this.readyState=3;try{this.socket?.end()}catch{}this.log("accept_mismatch",{statusLine:G}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(J+4),this.log("open",{statusLine:G}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let X=Buffer.from(this.rxBuffer).indexOf(`\r
203
108
  \r
204
- `);if(X===-1)return!1;let J=N8(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 L=0;L<8;L++)W=W*256+Y[2+L];U=10}if(G)U+=4;if(Y.length<U+W)return;let H=Y.slice(U,U+W);this.rxBuffer=Y.slice(U+W),this.handleFrame(Q,$,H)}}handleFrame(Y,X,J){if(X===9){this.writeFrame(10,J);return}if(X===10)return;if(X===8){let $=1005,G="";if(J.length>=2)$=J[0]<<8|J[1],G=Buffer.from(J.slice(2)).toString("utf-8");this.readyState=3,this.peerClose={code:$,reason:G};try{this.socket?.end()}catch{}this.log("close_frame",{code:$,reason:G}),this.emitClose($,G);return}if(X===1||X===2)this.fragOpcode=X,this.fragChunks=[J];else if(X===0)this.fragChunks.push(J);if(!Y)return;let Q=SV(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let $=Buffer.from(Q).toString("utf-8");this.emit("message",{data:$})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),$;if(J<126)$=[128|Y,128|J];else if(J<65536)$=[128|Y,254,J>>8&255,J&255];else{$=[128|Y,255];for(let U=7;U>=0;U--)$.push(J/2**(8*U)&255)}let G=new Uint8Array(J);for(let U=0;U<J;U++)G[U]=X[U]^Q[U%4];let W=new Uint8Array($.length+4+J);W.set($,0),W.set(Q,$.length),W.set(G,$.length+4);try{this.enqueueWrite(W)}catch{}}enqueueWrite(Y){this.writeQueue.push(Y),this.flushWrites()}flushWrites(){let Y=this.socket;if(!Y)return;while(this.writeQueue.length>0){let X=this.writeQueue[0],J=Y.write(X);if(J<X.length){this.writeQueue[0]=X.slice(J),this.log("write_backpressure",{written:J,remaining:X.length-J});return}this.writeQueue.shift()}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return e0({component:"raw-ws-bun",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function CV(Y){return Y}function IV(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function SV(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 kV}from"node:net";import{connect as bV}from"node:tls";var xV="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",r2=["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 YX{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];constructor(Y,X,J){this.url=Y,this.sessionID=J?.sessionID,this.connect(Y,X)}addEventListener(Y,X,J){this.listeners[Y]?.add(X)}removeEventListener(Y,X){this.listeners[Y]?.delete(X)}peerClose;closeEmitted=!1;emitClose(Y,X){if(this.closeEmitted)return;this.closeEmitted=!0,this.emit("close",{code:Y,reason:X})}emit(Y,X){for(let J of[...this.listeners[Y]??[]])try{J(X)}catch{}}async connect(Y,X){let J=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),Q=J.hostname,$=J.port?Number(J.port):J.protocol==="https:"?443:80,G=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),U=Buffer.from(W).toString("base64"),H=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(U+xV));this.expectedAccept=Buffer.from(new Uint8Array(H)).toString("base64");let L={};for(let[K,N]of Object.entries(X))L[K.toLowerCase()]=N;let V=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${U}`];for(let K of r2)if(L[K]!==void 0)V.push(`${vV(K)}: ${L[K]}`);for(let[K,N]of Object.entries(X))if(!r2.includes(K.toLowerCase())&&K.toLowerCase()!=="content-length")V.push(`${K}: ${N}`);let B=`${V.join(`\r
109
+ `);if(X===-1)return!1;let J=E9(this.rxBuffer,X,Y);if(!J)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:J.status,partial:Y}),this.emit("error",J),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let X=Y[0],J=Y[1],Q=(X&128)!==0,G=X&15,$=(J&128)!==0,W=J&127,z=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],z=4}else if(W===127){if(Y.length<10)return;W=0;for(let U=0;U<8;U++)W=W*256+Y[2+U];z=10}if($)z+=4;if(Y.length<z+W)return;let L=Y.slice(z,z+W);this.rxBuffer=Y.slice(z+W),this.handleFrame(Q,G,L)}}handleFrame(Y,X,J){if(X===9){this.writeFrame(10,J);return}if(X===10)return;if(X===8){let G=1005,$="";if(J.length>=2)G=J[0]<<8|J[1],$=Buffer.from(J.slice(2)).toString("utf-8");this.readyState=3,this.peerClose={code:G,reason:$};try{this.socket?.end()}catch{}this.log("close_frame",{code:G,reason:$}),this.emitClose(G,$);return}if(X===1||X===2)this.fragOpcode=X,this.fragChunks=[J];else if(X===0)this.fragChunks.push(J);if(!Y)return;let Q=TZ(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let G=Buffer.from(Q).toString("utf-8");this.emit("message",{data:G})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),G;if(J<126)G=[128|Y,128|J];else if(J<65536)G=[128|Y,254,J>>8&255,J&255];else{G=[128|Y,255];for(let z=7;z>=0;z--)G.push(J/2**(8*z)&255)}let $=new Uint8Array(J);for(let z=0;z<J;z++)$[z]=X[z]^Q[z%4];let W=new Uint8Array(G.length+4+J);W.set(G,0),W.set(Q,G.length),W.set($,G.length+4);try{this.enqueueWrite(W)}catch{}}enqueueWrite(Y){this.writeQueue.push(Y),this.flushWrites()}flushWrites(){let Y=this.socket;if(!Y)return;while(this.writeQueue.length>0){let X=this.writeQueue[0],J=Y.write(X);if(J<X.length){this.writeQueue[0]=X.slice(J),this.log("write_backpressure",{written:J,remaining:X.length-J});return}this.writeQueue.shift()}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return e0({component:"raw-ws-bun",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function wZ(Y){return Y}function AZ(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function TZ(Y){let X=0;for(let G of Y)X+=G.length;let J=new Uint8Array(X),Q=0;for(let G of Y)J.set(G,Q),Q+=G.length;return J}import{connect as RZ}from"node:net";import{connect as CZ}from"node:tls";var IZ="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",X4=["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 tX{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];constructor(Y,X,J){this.url=Y,this.sessionID=J?.sessionID,this.connect(Y,X)}addEventListener(Y,X,J){this.listeners[Y]?.add(X)}removeEventListener(Y,X){this.listeners[Y]?.delete(X)}peerClose;closeEmitted=!1;emitClose(Y,X){if(this.closeEmitted)return;this.closeEmitted=!0,this.emit("close",{code:Y,reason:X})}emit(Y,X){for(let J of[...this.listeners[Y]??[]])try{J(X)}catch{}}async connect(Y,X){let J=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),Q=J.hostname,G=J.port?Number(J.port):J.protocol==="https:"?443:80,$=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),z=Buffer.from(W).toString("base64"),L=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(z+IZ));this.expectedAccept=Buffer.from(new Uint8Array(L)).toString("base64");let U={};for(let[V,Z]of Object.entries(X))U[V.toLowerCase()]=Z;let H=[`GET ${$} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${z}`];for(let V of X4)if(U[V]!==void 0)H.push(`${_Z(V)}: ${U[V]}`);for(let[V,Z]of Object.entries(X))if(!X4.includes(V.toLowerCase())&&V.toLowerCase()!=="content-length")H.push(`${V}: ${Z}`);let B=`${H.join(`\r
205
110
  `)}\r
206
111
  \r
207
- `;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let K=()=>{this.socket?.write(B)},N=J.protocol==="https:"?bV({host:Q,port:$,servername:Q},K):kV({host:Q,port:$},K);this.socket=N,N.on("data",(O)=>{this.onData(typeof O==="string"?Buffer.from(O,"binary"):O)}),N.on("error",(O)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let j=O instanceof Error?O.message:String(O);this.log("socket_error",{message:j}),this.emit("error",{message:j})}),N.on("close",(O)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close",{hadError:O}),this.emitClose(this.peerClose?.code??1006,this.peerClose?.reason??"socket closed")})}catch(K){this.readyState=3,this.log("connect_exception",{message:K instanceof Error?K.message:String(K)}),this.emit("error",{message:K instanceof Error?K.message:String(K)})}}onData(Y){if(this.rxBuffer=hV(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
112
+ `;try{this.log("connect_start",{host:Q,port:G,tls:J.protocol==="https:"});let V=()=>{this.socket?.write(B)},Z=J.protocol==="https:"?CZ({host:Q,port:G,servername:Q},V):RZ({host:Q,port:G},V);this.socket=Z,Z.on("data",(j)=>{this.onData(typeof j==="string"?Buffer.from(j,"binary"):j)}),Z.on("error",(j)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let O=j instanceof Error?j.message:String(j);this.log("socket_error",{message:O}),this.emit("error",{message:O})}),Z.on("close",(j)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close",{hadError:j}),this.emitClose(this.peerClose?.code??1006,this.peerClose?.reason??"socket closed")})}catch(V){this.readyState=3,this.log("connect_exception",{message:V instanceof Error?V.message:String(V)}),this.emit("error",{message:V instanceof Error?V.message:String(V)})}}onData(Y){if(this.rxBuffer=SZ(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
208
113
  \r
209
- `);if(J===-1)return;let Q=X.slice(0,J),$=Q.split(`\r
210
- `)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=OY($);if(W!==101){if(W===void 0){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:$}),this.emit("error",{message:`WS upgrade failed: ${$}`});return}if(!this.emitRejectedUpgrade())return;this.socket?.destroy?.();return}if(!G||G[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:$}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(J+4),this.log("open",{statusLine:$}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let X=Buffer.from(this.rxBuffer).indexOf(`\r
114
+ `);if(J===-1)return;let Q=X.slice(0,J),G=Q.split(`\r
115
+ `)[0]??"",$=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=w1(G);if(W!==101){if(W===void 0){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:G}),this.emit("error",{message:`WS upgrade failed: ${G}`});return}if(!this.emitRejectedUpgrade())return;this.socket?.destroy?.();return}if(!$||$[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:G}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(J+4),this.log("open",{statusLine:G}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let X=Buffer.from(this.rxBuffer).indexOf(`\r
211
116
  \r
212
- `);if(X===-1)return!1;let J=N8(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 L=0;L<8;L++)W=W*256+Y[2+L];U=10}if(G)U+=4;if(Y.length<U+W)return;let H=Y.slice(U,U+W);this.rxBuffer=Y.slice(U+W),this.handleFrame(Q,$,H)}}handleFrame(Y,X,J){if(X===9){this.writeFrame(10,J);return}if(X===10)return;if(X===8){let $=1005,G="";if(J.length>=2)$=J[0]<<8|J[1],G=Buffer.from(J.slice(2)).toString("utf-8");this.readyState=3,this.peerClose={code:$,reason:G};try{this.socket?.end()}catch{}this.log("close_frame",{code:$,reason:G}),this.emitClose($,G);return}if(X===1||X===2)this.fragOpcode=X,this.fragChunks=[J];else if(X===0)this.fragChunks.push(J);if(!Y)return;let Q=gV(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let $=Buffer.from(Q).toString("utf-8");this.emit("message",{data:$})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),$;if(J<126)$=[128|Y,128|J];else if(J<65536)$=[128|Y,254,J>>8&255,J&255];else{$=[128|Y,255];for(let U=7;U>=0;U--)$.push(J/2**(8*U)&255)}let G=new Uint8Array(J);for(let U=0;U<J;U++)G[U]=X[U]^Q[U%4];let W=new Uint8Array($.length+4+J);W.set($,0),W.set(Q,$.length),W.set(G,$.length+4);try{this.socket?.write(W)}catch{}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return e0({component:"raw-ws-node",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function vV(Y){return Y}function hV(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function gV(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 yV(){return typeof globalThis.Bun?.connect==="function"}var s2=yV()?e9:YX;function V8(Y){return process.env[Y]??process.env[Y.toLowerCase()]}function fV(Y){let X=V8("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 mV(Y){let X=new URL(Y);if(fV(X))return;if(X.protocol==="http:")return V8("HTTP_PROXY");if(X.protocol==="https:")return V8("HTTPS_PROXY")??V8("HTTP_PROXY");return}var a2={getProxyForUrl:mV};var cV=N0("quota"),t2=N0("transport"),J4="responses_websockets=2026-02-06",e2=["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"],uV=new Set([z1,"x-opencode-title"]);function pV(Y){let X=new Map;for(let Q of Object.keys(Y))X.set(Q.toLowerCase(),Q);let J={};for(let Q of e2){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(!e2.includes(Q.toLowerCase()))J[Q]=$;return J}function lV(Y){let X={};for(let[J,Q]of Object.entries(Y)){if(uV.has(J.toLowerCase()))continue;X[J]=Q}return X}function dV(Y){return Y.replace(/^http/,"ws")}function iV(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 JX(Y){return Y instanceof DOMException&&Y.name==="AbortError"}var Q4=new WeakSet;function nV(Y){return typeof Y==="object"&&Y!==null&&Q4.has(Y)}var $4=new WeakSet;function oV(Y){return typeof Y==="object"&&Y!==null&&$4.has(Y)}function G4(Y){return $4.add(Y),Y}function Y4(Y,X){let J=Error(Y,X===void 0?void 0:{cause:X});return Q4.add(J),J}function rV(Y){return new Promise((X,J)=>{if(Y.signal?.aborted){J(XX(Y.signal));return}let Q={...Y.headers,"openai-beta":Y.headers["openai-beta"]??J4},$=Q[z1]??Q["session-id"];delete Q["content-length"],Q=pV(lV(Q));let G=typeof Bun>"u"?void 0:a2.getProxyForUrl(Y.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),W=!0,U=Y.rawWebSocket?new s2(Y.url,Q,{sessionID:$}):new globalThis.WebSocket(Y.url,{headers:Q,...G?{proxy:G}:{},perMessageDeflate:W}),H=Y.timeout?setTimeout(()=>{L(),U.close(),J(Error("WebSocket connect timed out"))},Y.timeout):void 0;function L(){if(H)clearTimeout(H);U.removeEventListener("open",V),U.removeEventListener("error",B),U.removeEventListener("close",K),Y.signal?.removeEventListener("abort",N)}function V(){L(),X(U)}function B(O){L(),J(Y4(t0(O),O))}function K(O){L(),J(Y4(z4("WebSocket closed before open",O.code,O.reason)))}function N(){L(),U.close(),J(XX(Y.signal))}U.addEventListener("open",V,{once:!0}),U.addEventListener("error",B,{once:!0}),U.addEventListener("close",K,{once:!0}),Y.signal?.addEventListener("abort",N,{once:!0})})}function sV(Y){let X=new TextEncoder,J=Y.socket,Q,$=()=>{},G=!1,W=0,U=!1,H=!1,L,V=new Set;function B(){if(L)clearTimeout(L);$(),Y.signal?.removeEventListener("abort",u)}function K(w=J){w.close()}function N(){B(),Q?.enqueue(X.encode(`data: [DONE]
117
+ `);if(X===-1)return!1;let J=E9(this.rxBuffer,X,Y);if(!J)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:J.status,partial:Y}),this.emit("error",J),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let X=Y[0],J=Y[1],Q=(X&128)!==0,G=X&15,$=(J&128)!==0,W=J&127,z=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],z=4}else if(W===127){if(Y.length<10)return;W=0;for(let U=0;U<8;U++)W=W*256+Y[2+U];z=10}if($)z+=4;if(Y.length<z+W)return;let L=Y.slice(z,z+W);this.rxBuffer=Y.slice(z+W),this.handleFrame(Q,G,L)}}handleFrame(Y,X,J){if(X===9){this.writeFrame(10,J);return}if(X===10)return;if(X===8){let G=1005,$="";if(J.length>=2)G=J[0]<<8|J[1],$=Buffer.from(J.slice(2)).toString("utf-8");this.readyState=3,this.peerClose={code:G,reason:$};try{this.socket?.end()}catch{}this.log("close_frame",{code:G,reason:$}),this.emitClose(G,$);return}if(X===1||X===2)this.fragOpcode=X,this.fragChunks=[J];else if(X===0)this.fragChunks.push(J);if(!Y)return;let Q=kZ(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let G=Buffer.from(Q).toString("utf-8");this.emit("message",{data:G})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),G;if(J<126)G=[128|Y,128|J];else if(J<65536)G=[128|Y,254,J>>8&255,J&255];else{G=[128|Y,255];for(let z=7;z>=0;z--)G.push(J/2**(8*z)&255)}let $=new Uint8Array(J);for(let z=0;z<J;z++)$[z]=X[z]^Q[z%4];let W=new Uint8Array(G.length+4+J);W.set(G,0),W.set(Q,G.length),W.set($,G.length+4);try{this.socket?.write(W)}catch{}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return e0({component:"raw-ws-node",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function _Z(Y){return Y}function SZ(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function kZ(Y){let X=0;for(let G of Y)X+=G.length;let J=new Uint8Array(X),Q=0;for(let G of Y)J.set(G,Q),Q+=G.length;return J}function xZ(){return typeof globalThis.Bun?.connect==="function"}var J4=xZ()?aX:tX;function w9(Y){return process.env[Y]??process.env[Y.toLowerCase()]}function bZ(Y){let X=w9("NO_PROXY");if(!X)return!1;let J=Y.hostname.toLowerCase(),Q=X.split(",").map((G)=>G.trim().toLowerCase()).filter(Boolean);for(let G of Q){if(G==="*")return!0;if(G.startsWith(".")){if(J===G.slice(1)||J.endsWith(G))return!0}else if(J===G||J.endsWith(`.${G}`))return!0}return!1}function vZ(Y){let X=new URL(Y);if(bZ(X))return;if(X.protocol==="http:")return w9("HTTP_PROXY");if(X.protocol==="https:")return w9("HTTPS_PROXY")??w9("HTTP_PROXY");return}var Q4={getProxyForUrl:vZ};var hZ=D0("quota"),A9=D0("transport"),K4="responses_websockets=2026-02-06",G4=["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"],gZ=new Set([LY,"x-opencode-title"]);function yZ(Y){let X=new Map;for(let Q of Object.keys(Y))X.set(Q.toLowerCase(),Q);let J={};for(let Q of G4){let G=X.get(Q),$=G===void 0?void 0:Y[G];if(G!==void 0&&$!==void 0)J[G]=$}for(let[Q,G]of Object.entries(Y))if(!G4.includes(Q.toLowerCase()))J[Q]=G;return J}function fZ(Y){let X={};for(let[J,Q]of Object.entries(Y)){if(gZ.has(J.toLowerCase()))continue;X[J]=Q}return X}function mZ(Y){return Y.replace(/^http/,"ws")}function cZ(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 Y8(Y){return Y instanceof DOMException&&Y.name==="AbortError"}var z4=new WeakSet;function uZ(Y){return typeof Y==="object"&&Y!==null&&z4.has(Y)}var U4=new WeakSet;function pZ(Y){return typeof Y==="object"&&Y!==null&&U4.has(Y)}function L4(Y){return U4.add(Y),Y}function $4(Y,X){let J=Error(Y,X===void 0?void 0:{cause:X});return z4.add(J),J}function lZ(Y){return new Promise((X,J)=>{if(Y.signal?.aborted){J(eX(Y.signal));return}let Q={...Y.headers,"openai-beta":Y.headers["openai-beta"]??K4},G=Q[LY]??Q["session-id"];delete Q["content-length"],Q=yZ(fZ(Q));let $=typeof Bun>"u"?void 0:Q4.getProxyForUrl(Y.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),W=!0,z=Y.rawWebSocket?new J4(Y.url,Q,{sessionID:G}):new globalThis.WebSocket(Y.url,{headers:Q,...$?{proxy:$}:{},perMessageDeflate:W}),L=Y.timeout?setTimeout(()=>{U(),z.close(),J(Error("WebSocket connect timed out"))},Y.timeout):void 0;function U(){if(L)clearTimeout(L);z.removeEventListener("open",H),z.removeEventListener("error",B),z.removeEventListener("close",V),Y.signal?.removeEventListener("abort",Z)}function H(){U(),X(z)}function B(j){U(),J($4(T1(j),j))}function V(j){U(),J($4(V4("WebSocket closed before open",j.code,j.reason)))}function Z(){U(),z.close(),J(eX(Y.signal))}z.addEventListener("open",H,{once:!0}),z.addEventListener("error",B,{once:!0}),z.addEventListener("close",V,{once:!0}),Y.signal?.addEventListener("abort",Z,{once:!0})})}function dZ(Y){let X=new TextEncoder,J=Y.socket,Q,G=()=>{},$=!1,W=0,z=!1,L=!1,U,H=[],B=12,V=typeof Y.body.previous_response_id==="string"?Y.body.previous_response_id:void 0,Z=typeof Y.body.prompt_cache_key==="string"?Y.body.prompt_cache_key:void 0,j={sessionID:Y.sessionID,codexSessionID:Z},O,C=0,R,D=new Set;function E(){if(U)clearTimeout(U);G(),Y.signal?.removeEventListener("abort",K0)}function T(w=J){w.close()}function g(){E(),Q?.enqueue(X.encode(`data: [DONE]
213
118
 
214
- `)),Q?.close()}function O(w){A(w,w)}function j(w){if(H){let J0=`${w.message} (not retried: output already emitted)`;t2.warn("stream failed after output; not retried",{reason:w.message,emittedOutput:!0}),A(Error(J0,{cause:w}),new w0(J0,{cause:w}));return}t2.warn("stream failed before output; retryable",{reason:w.message,emittedOutput:!1}),O(w)}function A(w,J0){if(G)return;G=!0,B(),Y.onConnectionInvalid?.(J0),Q?.error(w)}function x(w){if(G)return;if(!Y.idleTimeout)return;if(L)clearTimeout(L);L=setTimeout(()=>j(new w0(w)),Y.idleTimeout)}async function E(w){if(G)return;if(typeof w.data!=="string"){j(new w0("Unexpected binary WebSocket frame"));return}let J0=w.data,c=(()=>{try{let l=JSON.parse(J0);return typeof l==="object"&&l!==null?l:void 0}catch{return}})();if(c?.type==="codex.rate_limits"){cV.debug("codex.rate_limits frame received",{pid:process.pid}),x("idle timeout waiting for websocket");let l=X4(c);Y.onQuota?.(l);return}let n=!H?FY(c):void 0;if(n&&c){G=!0,B(),Y.onRateLimitReached?.(n.window,n.resetAt),Y.onTerminal?.(c),Y.onFirstEvent?.(),Q?.error(new w0(`OpenAI account rate limit reached at admission (${n.window})`));return}if(c?.type==="error"&&Y.onRetryableTerminal){if($(),L)clearTimeout(L);L=void 0;try{let l=await Y.onRetryableTerminal(c);if(G){if(l)K(l);return}if(l){Y0(l);return}}catch(l){j(new w0(l instanceof Error?l.message:String(l),{cause:l}));return}}let I0=XZ(c,J0);if(I0&&c){if(!U)Y.onFirstEvent?.(I0);G=!0,B(),Y.onTerminal?.(c);let l=new YY({message:I0.message,url:J.url,requestBodyValues:Y.body,statusCode:I0.status,responseHeaders:I0.headers,responseBody:I0.body});Q?.error(H?Error(l.message,{cause:l}):l);return}if(C(c)&&c.type==="response.failed"){let l=C(c.response)?c.response.failed:void 0,h=C(l)?l.rate_limit_reached_type:void 0;if(typeof h==="string"){if(G=!0,B(),Y.onRateLimitReached?.(h),Y.onTerminal?.(c),!H)Y.onFirstEvent?.(),Q?.error(new w0(`OpenAI account rate limit reached mid-stream (${h})`));else N();return}}if(c)aV(c,Y.sessionID),eV(c,V);let $0=c?X9(c):c;if(!$0){if(!U)Y.onFirstEvent?.();x("idle timeout waiting for websocket");return}let q1=$0===c?J0:JSON.stringify($0);if(!U)Y.onFirstEvent?.();if(Q?.enqueue(X.encode(`${q1.split(/\r?\n/).map((l)=>`data: ${l}`).join(`
119
+ `)),Q?.close()}function u(w){T0(w,w)}function l(w){let p={...j,openingFrameTypes:H,responseID:O,previousResponseID:V,hasContinuation:V!==void 0,framesSinceCreated:C,msSinceLastFrame:R===void 0?void 0:Date.now()-R};if(L){let f=N4;A9.warn("stream failed after output; not retried",{reason:w.message,emittedOutput:!0,...p}),T0(Error(f,{cause:w}),new _0(f,{cause:w}));return}A9.warn("stream failed before output; retryable",{reason:w.message,emittedOutput:!1,...p}),u(w)}function T0(w,p){if($)return;$=!0,E(),Y.onConnectionInvalid?.(p),Q?.error(w)}function Q0(w){if($)return;if(!Y.idleTimeout)return;if(U)clearTimeout(U);U=setTimeout(()=>l(new _0(w)),Y.idleTimeout)}async function c(w){if($)return;if(typeof w.data!=="string"){l(new _0("Unexpected binary WebSocket frame"));return}let p=w.data,f=(()=>{try{let n=JSON.parse(p);return typeof n==="object"&&n!==null?n:void 0}catch{return}})();if(f?.type==="codex.rate_limits"){hZ.debug("codex.rate_limits frame received",{pid:process.pid}),Q0("idle timeout waiting for websocket");let n=W4(f);Y.onQuota?.(n);return}let U0=!L?A1(f):void 0;if(U0&&f){$=!0,E(),Y.onRateLimitReached?.(U0.window,U0.resetAt),Y.onTerminal?.(f),Y.onFirstEvent?.(),Q?.error(new _0(`OpenAI account rate limit reached at admission (${U0.window})`));return}if(f?.type==="error"&&Y.onRetryableTerminal){if(G(),U)clearTimeout(U);U=void 0;try{let n=await Y.onRetryableTerminal(f);if($){if(n)T(n);return}if(n){r0(n);return}}catch(n){l(new _0(n instanceof Error?n.message:String(n),{cause:n}));return}}let u0=sZ(f,p);if(u0&&f){if(!z)Y.onFirstEvent?.(u0);$=!0,E(),Y.onTerminal?.(f);let n=new z1({message:u0.message,url:J.url,requestBodyValues:Y.body,statusCode:u0.status,responseHeaders:u0.headers,responseBody:u0.body});Q?.error(L?Error(n.message,{cause:n}):n);return}if(k(f)&&f.type==="response.failed"){let n=k(f.response)?f.response.failed:void 0,R0=k(n)?n.rate_limit_reached_type:void 0;if(typeof R0==="string"){if($=!0,E(),Y.onRateLimitReached?.(R0),Y.onTerminal?.(f),!L)Y.onFirstEvent?.(),Q?.error(new _0(`OpenAI account rate limit reached mid-stream (${R0})`));else g();return}}if(f)iZ(f,Y.sessionID),nZ(f,D);let $0=f?t9(f):f;if(!$0){if(!z)Y.onFirstEvent?.();Q0("idle timeout waiting for websocket");return}let WY=$0===f?p:JSON.stringify($0);if(!z)Y.onFirstEvent?.();if(Q?.enqueue(X.encode(`${WY.split(/\r?\n/).map((n)=>`data: ${n}`).join(`
215
120
  `)}
216
121
 
217
- `)),U=!0,$0.type!=="response.created"&&$0.type!=="response.in_progress")H=!0;if(x("idle timeout waiting for websocket"),!$0)return;if($0.type==="response.completed"||$0.type==="response.done"){G=!0,YZ($0,V),Y.onComplete?.($0,V),Y.onTerminal?.($0),N();return}if($0.type==="response.failed"||$0.type==="response.incomplete"||$0.type==="error")G=!0,Y.onTerminal?.($0),N()}function k(w){j(new w0(t0(w),{cause:w}))}function y(w){if(G)return;let J0=w.code===1009,c=new w0(z4("WebSocket closed before response.completed",w.code,w.reason,J0?W:void 0),{retryable:!J0});j(J0?G4(c):c)}function u(){let w=XX(Y.signal);if(G)return;G=!0,B(),K(),Y.onAbort?.(w),Q?.error(w)}function P0(w){if(G)return;G=!0,B(),K(),Y.onAbort?.(JZ(w))}function Y0(w){$(),J=w,J.addEventListener("message",E),J.addEventListener("error",k,{once:!0}),J.addEventListener("close",y,{once:!0}),$=()=>{J.removeEventListener("message",E),J.removeEventListener("error",k),J.removeEventListener("close",y)};let{background:J0,...c}=Y.body;x("idle timeout sending websocket request");try{let n=JSON.stringify({type:"response.create",...c});W=n.length,J.send(n),x("idle timeout waiting for websocket")}catch(n){if(G)return;O(new w0(n instanceof Error?n.message:String(n),{cause:n}))}}return new Response(new ReadableStream({start(w){if(Q=w,Y.signal?.addEventListener("abort",u,{once:!0}),Y.signal?.aborted){u();return}Y0(J)},cancel(w){P0(w)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function aV(Y,X){if(!tV(Y))return;await e0({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 tV(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 eV(Y,X){if(Y.type!=="response.output_item.done")return;if(!C(Y.item))return;W4(Y.item,X)}function YZ(Y,X){let J=Y.response;if(!C(J)||!Array.isArray(J.output))return;for(let Q of J.output)if(C(Q))W4(Q,X)}function W4(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 XZ(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 FY(Y){if(typeof Y==="string")try{return FY(JSON.parse(Y))}catch{return}if(!C(Y))return;let X=FY(Y.cause);if(X)return X;let J=FY(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,H=typeof W==="number"&&Number.isFinite(W)&&W>0?W*1000:typeof U==="number"&&Number.isFinite(U)&&U>0?Date.now()+U*1000:void 0;return{window:$??"primary",resetAt:H}}function JZ(Y){if(JX(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function XX(Y){let X=Y?.reason;if(JX(X))return X;if(QZ(X))return X;return new DOMException(X instanceof Error?X.message:"Aborted","AbortError")}function QZ(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function z4(Y,X,J,Q){let $=[`code ${X}`];if(X===1009)$.push("message too big");if(J.length>0)$.push(J.toString());if(Q!==void 0&&Q>0)$.push(`request was ${$Z(Q)}`);return`${Y} (${$.join(": ")})`}function $Z(Y){if(Y>=1048576)return`${(Y/1048576).toFixed(1)} MB`;if(Y>=1024)return`${Math.round(Y/1024)} KB`;return`${Y} B`}var $X="x-opencode-title",Z8="x-openai-auth-quota-account",QX=new Set([$X,z1,Z8,"x-opencode-session"]),WZ=15000,zZ=300000,UZ=3300000,U4="websocket_connection_limit_reached";function LZ(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 GZ("sha256").update(Q).digest("hex").slice(0,12)}function HZ(Y){let X=Y?.httpFetch??globalThis.fetch,J=new Map,Q=Y?.connectTimeout??WZ,$=Y?.idleTimeout??zZ,G=Y?.maxConnectionAge??UZ,W=Y?.streamRetries??5,U=Y?.firstEventGraceMs??250,H=Y?.rawWebSocket??!1,L=Y?.onQuota,V=Y?.onRateLimitReached,B=setInterval(()=>j(),Math.min($,60000));if(typeof B==="object"&&"unref"in B&&typeof B.unref==="function")B.unref();function K(E,k,y){if(!k||!y)return y;GX(E,L4(k));let u=new Headers(y.headers),P0=u.get("x-codex-turn-metadata");if(!P0)return y;let Y0=F4(P0,E.turnID,E.turnStartedAt);if(!Y0)return y;return u.set("x-codex-turn-metadata",Y0),{...y,headers:u}}async function N(E,k){let y=E instanceof URL?E.toString():typeof E==="string"?E:E.url,u=B0.normalizeHeaders(k?.headers),P0=D4(k),Y0=yY(P0);if(k?.method!=="POST"||!new URL(y).pathname.endsWith("/responses"))return X(E,Y0);let w=(()=>{try{if(typeof k?.body!=="string")return;let r=JSON.parse(k.body);return typeof r==="object"&&r!==null?r:void 0}catch{return}})();if(!w?.stream)return X(E,Y0);if(u[$X]==="true")return X(E,Y0);let J0=u[z1]??u["x-session-affinity"]??u["session-id"],c=J0;if(!J0)return X(E,Y0);let n=B0.normalizeHeaders(P0?.headers),I0=LZ(n),$0=`${J0}:${I0}:conversation`,q1=typeof u[Z8]==="string"?u[Z8]:void 0,l=V?(r,O0)=>V(r,q1,O0):void 0,h=J.get($0)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};if(J.set($0,h),h.fallback)return X(E,K(h,w,Y0));if(h.busy)return X(E,K(h,w,Y0));h.busy=!0,h.lastUsedAt=Date.now();try{let r=L4(w),O0=B0.normalizeHeaders(P0?.headers),F8=typeof O0.authorization==="string"&&O0.authorization.startsWith("Bearer ")?O0.authorization.slice(7):"",k1=typeof O0["chatgpt-account-id"]==="string"?O0["chatgpt-account-id"]:void 0,AY=L?(a)=>L(a,F8,q1,k1):void 0,n0=!h.socket&&!h.continuation?jZ(O0):O0;if(h.socket=await KZ(h,Y?.url??y,n0,Q,G,H,k?.signal),EZ(h,r))await BZ(h,r,$,{signal:k?.signal??void 0,sessionID:c,url:Y?.url??y,headers:P0?.headers,onRateLimitReached:l});let G1=()=>{},o0=()=>{},j1=new Promise((a,S0)=>{G1=a,o0=S0}),q8=MZ(h,r),r0=qY(O4(h,q8,r)),M0=typeof r0.previous_response_id==="string";await f1({sessionID:c,transport:"websocket",phase:"main",bodyText:JSON.stringify(r0),url:Y?.url??y,method:P0?.method,headers:P0?.headers});let y0=B0.streamResponsesWebSocket({socket:h.socket,body:r0,sessionID:c??void 0,idleTimeout:$,signal:k?.signal??void 0,onQuota:AY,onRateLimitReached:l,onFirstEvent:(a)=>G1(a??!0),onComplete:(a,S0)=>{let j8=V4(a);e0({component:"ws-pool",event:"main_completed",sessionID:c,responseID:N4(a),usage:j8}),B4(h,r,a,S0,M0)},onTerminal:(a)=>{if(h.busy=!1,h.lastUsedAt=Date.now(),h.streamFailures=0,a.type!=="response.completed"&&a.type!=="response.done")h.continuation=void 0,$1(h)},onConnectionInvalid:(a)=>{if(h.busy=!1,h.lastUsedAt=Date.now(),B0.isOversizedFrame(a))h.fallback=!0;if(!h.fallback)O(h);h.continuation=void 0,$1(h),G1(!1)},onAbort:(a)=>{h.busy=!1,h.lastUsedAt=Date.now(),h.streamFailures=0,h.continuation=void 0,$1(h),o0(a)},onRetryableTerminal:async(a)=>{let S0=H4(a);if(!S0)return;throw h.fallback=!0,S0}}),f0=await NZ(j1,U);if(f0!==!1){if(f0===!0||f0.status<200||f0.status>599)return y0;return new Response(f0.body,{status:f0.status,headers:{"content-type":"application/json",...f0.headers}})}let b1=()=>X(E,K(h,w,Y0));if(!h.fallback)return VZ(y0,b1);return b1()}catch(r){if(h.busy=!1,h.lastUsedAt=Date.now(),B0.isAbortError(r))throw h.streamFailures=0,h.continuation=void 0,$1(h),r;let O0=B0.parseRateLimitSignal(r);if(O0)l?.(O0.window,O0.resetAt);if(B0.isUpgradeFailure(r)&&!H)h.fallback=!0;if(O(h),h.continuation=void 0,$1(h),h.fallback)return X(E,K(h,w,Y0));return ZZ(new w0(r instanceof Error?r.message:String(r),{cause:r}))}}function O(E){if(E.streamFailures++,E.streamFailures>W)E.fallback=!0}function j(){let E=Date.now();for(let[k,y]of J){if(y.busy)continue;if(E-y.lastUsedAt<$)continue;$1(y),J.delete(k)}}function A(){clearInterval(B);for(let E of J.values())$1(E);J.clear()}function x(E){let k=`${E}:`;for(let[y,u]of J){if(!y.startsWith(k))continue;$1(u),J.delete(y)}}return Object.assign(N,{close:A,remove:x})}function H4(Y){if(Y.type!=="error"||!C(Y.error)||Y.error.code!==U4)return;return Error(typeof Y.error.message==="string"?Y.error.message:U4)}async function NZ(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 VZ(Y,X){let J=Y.body;if(!J)return Y;let Q=!1,$=new ReadableStream({async start(G){let W=J.getReader(),U=async(H)=>{while(!0){let{done:L,value:V}=await H.read();if(L)return;if(V&&V.length>0)Q=!0,G.enqueue(V)}};try{await U(W),G.close()}catch(H){if(Q||!B0.isOversizedFrame(H)){G.error(H);return}try{let L=await X();if(!L.ok){G.error(new w0(`HTTP fallback after an oversized WebSocket frame failed with ${L.status}`));return}if(L.body)await U(L.body.getReader());G.close()}catch(L){G.error(L)}}},cancel(G){J.cancel(G)}});return new Response($,{status:Y.status,headers:Y.headers})}function ZZ(Y){return new Response(new ReadableStream({start(X){X.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function KZ(Y,X,J,Q,$,G,W){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<$)return Y.socket;$1(Y);let U=await B0.connectResponsesWebSocket({url:B0.toWebSocketUrl(X),headers:J,timeout:Q,rawWebSocket:G,signal:W??void 0});return Y.connectedAt=Date.now(),U}function $1(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function BZ(Y,X,J,Q){if(!Y.socket||!Array.isArray(X.input)||X.input.length===0)return;let $=FZ(X);await f1({sessionID:Q.sessionID,transport:"websocket",phase:"prewarm",bodyText:JSON.stringify($),url:Q.url,method:"POST",headers:Q.headers});let G=B0.streamResponsesWebSocket({socket:Y.socket,body:$,sessionID:Q.sessionID,idleTimeout:J,signal:Q.signal,onRateLimitReached:Q.onRateLimitReached,onComplete:(W,U)=>{e0({component:"ws-pool",event:"prewarm_completed",sessionID:Q.sessionID,responseID:N4(W),usage:V4(W)}),B4(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=H4(W);if(!U)return;throw Y.fallback=!0,U}});await OZ(G)}function N4(Y){let X=Y.response;if(!C(X))return;return typeof X.id==="string"?X.id:void 0}function V4(Y){let X=Y.response;if(!C(X))return;return C(X.usage)?X.usage:void 0}async function OZ(Y){let X=Y.body?.getReader();if(!X)return;while(!0)if((await X.read()).done)return}function FZ(Y){return qY({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:qZ(Y.client_metadata)})}function Z4(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 qZ(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":Z4(X),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function jZ(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":Z4(J)}}catch{return Y}}var K4=["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 L4(Y){let X={...Y};if(Array.isArray(Y.input))X.input=Y.input.map(DZ);return X}function qY(Y){let X={};for(let J of K4)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 DZ(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 B4(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 H of Q)U.add(H);Y.continuation={responseID:W,input:X.input,signature:WX(X),finalizedCallIds:U}}function GX(Y,X,J=X){let Q=Array.isArray(X.input)?X.input:[],$=Array.isArray(J.input)?J.input:Q,G=WX(J),W=Y.turnInput&&Y.turnSignature===G?PZ(Y.turnInput,$):void 0,U=W===void 0?Q:$.slice(W);if(U.length>0&&U.some(q4)||!Y.turnID)Y.turnID=w1(),Y.turnStartedAt=Date.now();Y.turnInput=$.slice(),Y.turnSignature=G}function O4(Y,X,J=X){GX(Y,X,J);let Q=X.client_metadata;if(!C(Q)||typeof Q["x-codex-turn-metadata"]!=="string")return X;let $=F4(Q["x-codex-turn-metadata"],Y.turnID,Y.turnStartedAt);if(!$)return X;return{...X,client_metadata:{...Q,"x-codex-turn-metadata":$}}}function F4(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 PZ(Y,X){if(Y.length>X.length)return;for(let J=0;J<Y.length;J++)if(Y1(Y[J])!==Y1(X[J]))return;return Y.length}function MZ(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!J||!Y.continuation)return X;if(Y.continuation.signature!==WX(X))return Y.continuation=void 0,X;if(!j4(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),$=AZ(Q,Y.continuation.finalizedCallIds);if($.length===0)return X;return{...X,previous_response_id:Y.continuation.responseID,input:$}}function EZ(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!Y.continuation)return!0;if(!J)return!1;if(!j4(Y.continuation.input,J))return!0;return J.slice(Y.continuation.input.length).some(q4)}function q4(Y){if(!C(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function AZ(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 WX(Y){return Y1(wZ(Object.fromEntries(Object.entries(Y).filter(([X])=>X!=="input"&&X!=="stream"&&X!=="background"&&X!=="previous_response_id"&&X!=="generate"))))}function wZ(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 j4(Y,X){if(Y.length>=X.length)return!1;for(let J=0;J<Y.length;J++)if(Y1(Y[J])!==Y1(X[J]))return!1;return!0}function D4(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let X=new Headers(Y.headers);for(let J of QX)X.delete(J);return{...Y,headers:X}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((X)=>!QX.has(X[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([X])=>!QX.has(X.toLowerCase())))}}var kZ=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),bZ=new Set(["gpt-5.6","gpt-6"]),xZ=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-6-astra"]),vZ="opencode-oauth-dummy-key",hZ="terminal_resize_reflow",HX="0.153.0",gZ=`codex_exec/${HX} (Debian 12.0.0; aarch64) unknown (codex_exec; ${HX})`,yZ="seccomp",fZ="main-refresh",mZ=120000,cZ=90000,uZ=4000,P4=50,M4=3,pZ=25,lZ=60000,dZ="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",E4=!1,A4=N0("models"),w4=!1,T4=!1;class VX extends Error{code="OPENAI_AUTH_PERSIST_FAILED";constructor(Y){super("OpenAI OAuth token refreshed but could not be persisted; re-login required",{cause:Y});this.name="AuthPersistError"}}class d0 extends Error{code;constructor(Y,X){super(X);this.name="ResetTargetResolutionError",this.code=Y}}function R4(Y,X,J,Q){let $=(J?.refresh?.refreshBeforeExpiryMinutes??240)*60000;return!Y||!X||X-Q<=$}function iZ(Y){return async(X)=>{if(X==="main"){let U=await Y.loadAccounts(Y.accountStoragePath),H=await Y.getAuth();if(H.type!=="oauth")throw new d0("non_oauth_account","Main OpenAI account is not authenticated with OAuth.");if(R4(H.access,H.expires,U,Y.now()))H={type:"oauth",...await Y.refreshMainWithLease()};if(!H.access)throw new d0("token_unavailable","Main OpenAI account has no usable access token.");let L=o1(H.access),V=L?r1(L):void 0,B=await Y.loadAccounts(Y.accountStoragePath);return{accountKey:X,label:"Main account",accessToken:H.access,chatgptAccountId:V??B?.mainAccountId}}let J=await Y.loadAccounts(Y.accountStoragePath),Q=J?.accounts.find((U)=>U.id===X);if(!J||!Q)throw new d0("unknown_account",`Fallback account ${X} was not found.`);if(Q.enabled===!1)throw new d0("disabled_account",`Fallback account ${X} is disabled.`);if(!i0(Q))throw new d0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);let $=Q;if(R4($.access,$.expires,J,Y.now()))$=await Y.refreshFallbackAccount($,J);if(!$.access)throw new d0("token_unavailable",`Fallback account ${X} has no usable access token.`);let G=await Y.loadAccounts(Y.accountStoragePath),W=G?.accounts.find((U)=>U.id===X);if(!G||!W)throw new d0("unknown_account",`Fallback account ${X} was not found.`);if(W.enabled===!1)throw new d0("disabled_account",`Fallback account ${X} is disabled.`);if(!i0(W))throw new d0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);return{accountKey:X,label:$.label??X,accessToken:$.access,chatgptAccountId:W.accountId}}}function nZ(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function UX(Y){return Y instanceof VX}function _4(){throw Error(dZ)}function oZ(Y){return Math.floor(Math.random()*Y)}function rZ(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 sZ(Y,X,J){let Q=Y.get(X);if(Q)return Q;let $=w1(),G={threadID:$,turnID:w1(),windowID:`${$}:0`};return Y.set(X,G),J?.(),G}function Wz(){return SZ(IY(),"openai-auth-sessions.json")}function aZ(){let Y=new Map;try{let X=JSON.parse(RZ(Wz(),"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:w1(),windowID:`${Q.threadID}:0`})}}catch{}return Y}function tZ(Y){let X=Wz(),J=`${X}.tmp-${process.pid}`;try{TZ(IY(),{recursive:!0});let Q={version:1,sessions:Object.fromEntries([...Y.entries()].map(([$,G])=>[$,{threadID:G.threadID}]))};IZ(J,`${JSON.stringify(Q,null,2)}
218
- `,"utf8"),_Z(J,X)}catch{}}function C4(Y,X){return C(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===X}function eZ(Y,X){if(Y.length>X.length)return!1;for(let J=0;J<Y.length;J++)if(Y1(Y[J])!==Y1(X[J]))return!1;return!0}function YK(Y,X){if(!Y.input)return X.length>0;if(!eZ(Y.input,X))return!0;return X.slice(Y.input.length).some((Q)=>C4(Q,"user")||C4(Q,"developer"))}function XK(Y,X){let J=Array.isArray(X?.input)?X.input:void 0;if(J&&(YK(Y,J)||!Y.turnID))Y.turnID=w1(),Y.turnStartedAt=Date.now();else if(!Y.turnStartedAt)Y.turnStartedAt=Date.now();if(J)Y.input=J}function JK(Y){if(!Y.metadata)return{init:Y.init};let X=rZ(Y.init?.body);if(!Y.websocket)XK(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:yZ,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",hZ),Y.headers.set("x-codex-turn-metadata",J),Y.headers.set("user-agent",gZ),Y.headers.set("version",HX),Y.dumpSessionID)Y.headers.set(z1,Y.dumpSessionID);let Q=X;if(!Q)return{init:Y.init};let $=Y.responsesLite&&typeof Q.model==="string"&&xZ.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(NK);if(LK(Q),HK(Q),RJ(Q),GK(Q),zK(Q,Y.metadata),$)UK(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 QK(Y,X){return Y.find((J)=>J.enabled!==!1&&i0(J)&&(J.id===X||J.accountId===X))}function I4(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 K8(Y,X){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:X}}function zz(Y,X,J=Date.now(),Q=X.mainAccountId){let $=Y.getMain(),G=$?.quota;return{main:{quota:G?{...G,checkedAt:$.checkedAt,primary:K8(G.primary,$.checkedAt),secondary:K8(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),H=U?.quota;return{id:W.id,label:W.label,accountId:U?.accountId??W.accountId,quota:H?{...H,checkedAt:U.checkedAt,primary:K8(H.primary,U.checkedAt),secondary:K8(H.secondary,U.checkedAt)}:null,killed:!1,enabled:!0,...H?.resetCreditsAvailable!==void 0?{resetCredits:H.resetCreditsAvailable}:{}}}),route:X.routing?.mode??"main-first",lastUpdated:J}}function mD(Y,X,J,Q=Date.now()){return{...zz(Y,X,Q),activeId:J}}function S4(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 $K(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 k4(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}function GK(Y){if(!E0().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 NX(Y){if(Array.isArray(Y)){for(let X of Y)NX(X);return}if(!C(Y))return;if(Y.type==="input_image")delete Y.detail;for(let X of Object.values(Y))NX(X)}var WK=new Set(["gpt-6-astra"]);function zK(Y,X){let J=typeof Y.model==="string"?Y.model:"";if(!WK.has(J))return;let Q=C(Y.reasoning)?Y.reasoning:void 0,$=typeof Q?.effort==="string"?Q.effort:void 0;if(!$)return;if(X.pinnedEffort===void 0){X.pinnedEffort=$;return}if($===X.pinnedEffort)return;let G=Array.isArray(Y.input)?Y.input:void 0;if(!G||G.length===0)return;Y.reasoning={...Q,effort:X.pinnedEffort},G.splice(G.length-1,0,{type:"configuration_update",reasoning:{effort:$}})}function UK(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:[];NX(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 LK(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(C(X)&&X.type==="function"&&X.name==="web_search"))}function HK(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 NK(Y){if(!C(Y))return Y;if(Y.type!=="function")return Y;let X=C(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:H,...L}=Y.parameters;return L})():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 VK(Y,X={}){let J=X.codexApiEndpoint??E0().codexApiEndpoint,Q=crypto.randomUUID(),$=aZ(),G=()=>tZ($),W=!1,U=[],H=null,L=null,V,B=new f8;async function K(N,O){let j=Y.client.session;if(typeof j?.promptAsync==="function"){let A=await vJ(Y.client,N),x={noReply:!0,parts:[{type:"text",text:O,ignored:!0}]};if(A?.agent)x.agent=A.agent;if(A?.model)x.model=A.model;if(A?.variant)x.variant=A.variant;await j.promptAsync({path:{id:N},body:x});return}}return{async dispose(){B.stop();for(let N of U)N.close();if(U.length=0,L){await L.stop().catch(()=>{});let N=globalThis;if(N.__openaiAuthRpcServer===L)N.__openaiAuthRpcServer=void 0;L=null}},async event(N){if(N.event.type!=="session.deleted")return;let O=N.event.properties.info,j=$.get(O.id);if(j)H?.cacheKeepManager?.remove(j.threadID);if($.delete(O.id))G();if(V){let A=(await D0(W0()))?.accounts;await Jz(O.id,A,V)}for(let A of U)A.remove(O.id)},provider:{id:"openai",async models(N,O){if(O.auth?.type!=="oauth")return N.models;let j=await D0(W0()),A=!j||i4(j),x=A?null:await SJ();if(!A&&x&&!w4)w4=!0,A4.debug("restoring OAuth model costs from models.dev catalog");if(!A&&!x&&!T4)T4=!0,A4.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(N.models).filter(([,E])=>{if(E.options.reasoningMode==="pro")return!1;if(kZ.has(E.api.id))return!0;if(bZ.has(E.api.id))return!1;let y=E.api.id.match(/^gpt-(\d+(?:\.\d+)?)/)?.[1];return y?parseFloat(y)>5.4:!1}).map(([E,k])=>[E,{...k,cost:A?{input:0,output:0,cache:{read:0,write:0}}:x?.[k.api.id]??x?.[E]??k.cost,limit:k.id.includes("gpt-5.5")?{context:400000,input:272000,output:128000}:k.id.includes("gpt-6-astra")?{context:872000,input:744000,output:128000}:k.id.includes("gpt-5.6")?{context:372000,input:244000,output:128000}:k.limit}]))}},tool:{web_search:wJ},auth:{provider:"openai",async loader(N){let O=await N();if(O.type!=="oauth")return{};await o4({type:"oauth",access:O.access??"",refresh:O.refresh??"",expires:O.expires??0},W0());let j=await D0(W0()).catch((Z)=>{let F=W0();throw Error(`OpenAI auth store at ${F} is corrupt or unreadable: ${Z instanceof Error?Z.message:String(Z)}. Fix or remove it to continue.`,{cause:Z})}),A;async function x(){let Z=W0();try{let F=CZ(Z);if(A?.path===Z&&A.mtimeMs===F.mtimeMs&&A.size===F.size)return A.storage;let P=await D0(Z);return A={path:Z,mtimeMs:F.mtimeMs,size:F.size,storage:P},P}catch{return A=void 0,D0(Z)}}function E(){A=void 0}if(j&&O.access){let Z=B8({id_token:"",access_token:O.access,refresh_token:O.refresh??""});if(Z&&Z!==j.mainAccountId)await G0((F)=>{return F.mainAccountId=Z,F},W0()),j.mainAccountId=Z,E()}let k=j?.logging?.level;if(k&&typeof k==="string")xY(k);let y=N0("transport"),u=N0("quota"),P0=N0("refresh"),Y0=N0("accounts");y.info("codex auth loader ready",{codexApiEndpoint:J,transport:E0().rawWebSocket?"raw-websocket":E0().webSockets?"websocket":"http",webSearch:E0().webSearch});let w=new d4({storage:j,fetchQuotaFn:void 0}),J0,c=0,n=new r4({refreshFn:(Z)=>S1({refreshToken:Z.refreshToken,fetchImpl:Z.fetchImpl,now:Z.now}),quotaManager:w,onFallbackStorageChanged:E});if(j&&j.accounts.length>0)n.startBackgroundRefresh();let I0=N0("cachekeep"),$0=j?.cachekeep?.enabled===!0,q1=j?.cachekeep?.subagents===!0,l=j?.cachekeep?.sustain===!0,h=zJ(j),r;async function O0(Z){await new Promise((F)=>setTimeout(F,Z))}async function F8(Z){let F;for(let P=1;P<=M4;P++)try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:Z.refresh,access:Z.access,expires:Z.expires}});return}catch(_){if(F=_,P<M4)await O0(pZ*P)}throw new VX(F)}async function k1(Z){await G0((F)=>{return F.refresh=F.refresh??{},Z(F),F},W0()),E()}async function AY(Z){let F=Date.now()+uZ;while(Date.now()<F){await new Promise((b)=>setTimeout(b,P4+oZ(P4)));let P=await N();if(P.type!=="oauth"||!P.access)continue;if((P.access!==Z.access||P.refresh!==Z.refresh||(P.expires??0)>(Z.expires??0)+60000)&&(!P.expires||P.expires>Date.now()))return P0.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:P.expires?P.expires-Date.now():void 0}),{access:P.access,refresh:P.refresh??Z.refresh??"",expires:P.expires??0}}return null}async function n0(){if(!r)r=(async()=>{let Z=await N();if(Z.type!=="oauth")throw Error("not oauth");if(!Z.refresh)throw Error("Token refresh failed: missing refresh token");let F=b4(Z.refresh),P=await D0(W0()),_=P?.refresh?.mainLastRefreshError;if(_&&vY(_,Z.refresh,Date.now()))throw Error(hY(_,Date.now()));if(P?.refresh?.mainRefreshLeaseUntil&&P.refresh.mainRefreshLeaseUntil>Date.now()&&P.refresh.mainRefreshLeaseTokenHash===F){let S=await AY(Z);if(S)return S;throw Error("Codex OAuth refresh is already in progress")}let b=await gY({name:fZ,ttlMs:mZ,path:W0(),renew:!0});if(!b){let S=await AY(Z);if(S)return S;throw Error("Codex OAuth refresh is already in progress")}let I=crypto.randomUUID(),T=F;try{await k1((f)=>{f.refresh=f.refresh??{},f.refresh.mainRefreshLeaseId=I,f.refresh.mainRefreshLeaseUntil=Date.now()+cZ,f.refresh.mainRefreshLeaseTokenHash=F});let S=await D0(W0());if(S?.refresh?.mainRefreshLeaseId!==I||S.refresh.mainRefreshLeaseTokenHash!==F)throw Error("Codex OAuth refresh is already in progress");let M=await S1({refreshToken:Z.refresh,fetchImpl:fetch,now:Date.now});return await F8(M),await k1((f)=>{if(f.refresh=f.refresh??{},f.refresh.mainLastRefreshError=void 0,f.refresh.mainRefreshLeaseId===I)f.refresh.mainRefreshLeaseId=void 0,f.refresh.mainRefreshLeaseUntil=void 0,f.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),T=void 0,M}catch(S){if(Z.refresh&&!UX(S))await k1((M)=>{M.refresh=M.refresh??{},M.refresh.mainLastRefreshError=x4({error:S,now:Date.now(),refreshToken:Z.refresh??"",previous:M.refresh.mainLastRefreshError})}).catch(()=>{});throw S}finally{if(T)await k1((S)=>{if(S.refresh?.mainRefreshLeaseId===I&&S.refresh.mainRefreshLeaseTokenHash===T)S.refresh.mainRefreshLeaseId=void 0,S.refresh.mainRefreshLeaseUntil=void 0,S.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await b.release().catch(()=>{})}})().finally(()=>{r=void 0});return r}let G1=globalThis;G1.__openaiAuthCacheKeepManager?.stop();let o0=new l8({fetchImpl:fetch,getMainToken:async()=>{let Z=await N();if(Z.type!=="oauth")throw Error("not oauth");if(!Z.access||(Z.expires??0)<Date.now())try{return(await n0()).access}catch(F){if(UX(F))throw F;if(Z.access)return Z.access;throw Error("main token refresh failed")}return Z.access},refreshFallback:async(Z)=>{let F=await x(),P=F?QK(F.accounts,Z):void 0;if(!P)throw Error(`fallback account ${Z} not found`);let _=await n.refreshAccount(P,F??{version:1,accounts:[P]});if(!_.access)throw Error(`no access token for ${Z}`);return _.access},codexResponsesUrl:J,logger:I0,now:Date.now,getWindow:()=>h,getSustain:()=>l});G1.__openaiAuthCacheKeepManager=o0;async function j1(Z,F,P,_,b=!1){if(Object.keys(Z).length===0&&!b)return;let I=Date.now(),T=Z,S={quota:T,refreshAfter:I+300000,checkedAt:I},M;if(P&&P!=="main"){let v=F?o1(F):null,Q0=v?r1(v):void 0,F0=w.peekFallbackForPolicy(P)?.quota,m0=I4(T,F0);S={...S,quota:m0},w.setFallback(P,S,F,b,Q0)}else{if(M=_,!M&&F){let F0=o1(F);M=F0?r1(F0):void 0}if(M&&J0&&M!==J0){u.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:M,currentMainIdentity:J0});return}let v=w.peekMainForPolicy(M)?.quota,Q0=I4(T,v);S={...S,quota:Q0},w.setMain(F,S,M,b)}u.debug("quota pushed",{pid:process.pid,accountId:P??"main",snapshot:S.quota});let f=await x();await y0(w,f,P&&P!=="main"?f?.mainAccountId:M)}function q8(Z,F,P){let _=Z==="main"?w.peekMainForPolicy()?.quota:w.peekFallbackForPolicy(Z)?.quota;return l4(_,F,Date.now(),lZ,P)}let r0=X.experimentalWebSockets?F1.createWebSocketFetch({httpFetch:fetch,rawWebSocket:E0().rawWebSocket,onQuota:(Z,F,P,_)=>{j1(Z,F,P,!P||P==="main"?_:void 0,!0)},onRateLimitReached:(Z,F,P)=>{if(!F)u.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:Z});let _=F??"main",b=q8(_,Z,P);w.markRateLimited(_,b),u.debug("mid-stream rate limit mark",{pid:process.pid,accountId:_,window:Z})}}):void 0;if(r0)U.push(r0),W=!0;let M0=s4();V=M0;async function y0(Z,F,P=F?.mainAccountId){if(!F)return;await Yz(zz(Z,F,Date.now(),P),M0)}async function f0(Z,F,P,_,b){let I={activeId:P,route:_,updatedAt:Date.now()};if(Z){if(await O8({sessionId:Z,...I},b,M0),F&&F!==Z){if(_==="sticky-balanced"){let T=(await A1(M0)).stickyAssignments?.[EY(F)]?.accountId,S=b===void 0||T==="main"||b.some((M)=>M.enabled!==!1&&M.id===T);if(!T||!S)return;await O8({sessionId:F,activeId:T,route:_,updatedAt:Date.now()},b,M0);return}await O8({sessionId:F,...I},b,M0)}return}await Xz(I,M0)}H={accountStoragePath:W0(),quotaManager:w,loadAccounts:D0,client:Y.client,resolveResetTarget:iZ({getAuth:N,refreshMainWithLease:n0,refreshFallbackAccount:(Z,F)=>n.refreshAccount(Z,F),loadAccounts:D0,accountStoragePath:W0(),now:Date.now}),...nZ(),cacheKeepManager:o0,setCacheKeepEnabled:(Z)=>{$0=Z},setCacheKeepSubagents:(Z)=>{q1=Z},setCacheKeepSustain:(Z)=>{l=Z},setCacheKeepWindow:(Z)=>{h=Z},clearStickyRouting:(Z)=>$z(Z,M0),getStickyRouting:async(Z)=>e4(await A1(M0),Z),refreshSidebar:async()=>{let Z=await D0(W0());await y0(w,Z)},refreshAllQuota:async()=>h1({getAuth:N,codexRefreshFn:S1,refreshMainWithLease:n0,fallbackManager:n,quotaManager:w,loadAccounts:D0,writeSidebarState:y0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:W0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:i0,whamFn:W1}),refreshResetTargetQuota:async(Z)=>{return(await h1({getAuth:N,codexRefreshFn:S1,refreshMainWithLease:n0,fallbackManager:n,quotaManager:w,loadAccounts:D0,writeSidebarState:y0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:W0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:i0,whamFn:W1,respectBackoff:!1},{accountKey:Z})).find((P)=>P.account===Z)??{account:Z,ok:!1,error:"targeted quota refresh returned no result"}}};let b1=null;if(Y.directory){let Z=await Gz(Y.directory),F=globalThis;if(F.__openaiAuthRpcServer)await F.__openaiAuthRpcServer.stop().catch(()=>{}),F.__openaiAuthRpcServer=void 0;try{b1=await uJ({dir:Z.dir,secureDir:Z.secureDir,sweepRoot:Z.sweepRoot,drain:gJ,apply:async(P)=>{let _={...H,sessionId:P.sessionId},b=await g8(P.command,P.arguments,_);return{text:b.text,knobs:b.knobs}}}),F.__openaiAuthRpcServer=b1,L=b1}catch{}}async function a(Z,F,P,_,b="main"){let I=S4(Z,F);if(I.delete("x-api-key"),I.delete("api-key"),I.set("authorization",`Bearer ${P}`),_)I.set("ChatGPT-Account-Id",_);I.set(F1.QUOTA_ACCOUNT_HEADER,b);let T=k4(I),S=T?sZ($,T,G):void 0,M=Z instanceof URL?Z:new URL(typeof Z==="string"?Z:Z.url),f=M.pathname.includes("/v1/responses")||M.pathname.includes("/chat/completions")?new URL(J):M,Q0=JK({init:{...F,headers:I},headers:I,metadata:S,installationID:Q,websocket:Boolean(r0&&M.pathname.endsWith("/responses")),responsesLite:X.responsesLite??!1,dumpSessionID:T}).init,F0=$0,m0=new Headers(Q0?.headers),U0=WJ({enabled:F0,includeSubagents:q1,headers:m0,body:Q0?.body});if(F0)I0.trace("cachekeep headers",{pid:process.pid,hasParent:m0.has("x-parent-session-id"),sessionKey:U0?.sessionKey,captured:Boolean(U0),affinity:m0.get("x-session-affinity"),opencodeSession:m0.get("x-opencode-session"),sessionId:m0.get("session-id")});if(r0&&M.pathname.endsWith("/responses")){if(y.debug("WS transport",{pid:process.pid,pathname:M.pathname,accountId:b}),U0)o0.track(U0.sessionKey,U0.bodyText,b,_,U0.replayHeaders,U0.isSubagent);return r0(f,Q0)}let K0=F1.withoutInternalHeaders(Q0);if(typeof K0?.body!=="string")return fetch(f,K0);if(U0)o0.track(U0.sessionKey,U0.bodyText,b,_,U0.replayHeaders,U0.isSubagent);y.debug("HTTP transport",{pid:process.pid,pathname:M.pathname,accountId:b});try{let k0=await fetch(f,K0);return await f1({sessionID:T,transport:"http",phase:"http",bodyText:K0.body,accountId:b,url:f.toString(),method:K0.method,headers:K0.headers,status:k0.status}),TJ(k0)}catch(k0){throw await f1({sessionID:T,transport:"http",phase:"http",bodyText:K0.body,accountId:b,url:f.toString(),method:K0.method,headers:K0.headers,error:k0 instanceof Error?k0.message:String(k0)}),k0}}function S0(Z,F){if((F?.method??(Z instanceof Request?Z.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof F?.body!=="string")return!1;try{let _=Z instanceof URL?Z.toString():typeof Z==="string"?Z:Z.url;return new URL(_).pathname.endsWith("/responses")}catch{return!1}}function j8(Z){return w.peekMainForPolicy(Z)?.quota}function ZX(Z,F){for(let P of[Z?.primary?.checkedAt,Z?.secondary?.checkedAt,Z?.checkedAt,F])if(typeof P==="number"&&Number.isFinite(P))return P;return}function s1(Z,F,P,_,b){let I=ZX(Z,F),T=ZX(P),S=_===b&&P!=null&&(Z===void 0||T!==void 0&&(I===void 0||T>I));return{quota:S?P:Z,quotaCheckedAt:S?T:I,source:S?"file":"memory"}}function KX(Z,F,P,_,b){let I=Z?.quota,T=s1(I,Z?.checkedAt,F,_,b),S=T.source,M=T.quota;if(!t4(M,P))return{exhausted:!1};let f=a4(M,P);if(!f)return{exhausted:!1};return{exhausted:!0,source:S,...f}}function BX(Z,F){u.debug("admission skip: exhausted account",{accountId:Z,source:F.source,resetsAt:F.resetsAt})}function Uz(Z,F="killswitch",P){let _=Date.now(),b=w.getMain()?.quota,I=(Z?.accounts??[]).filter((v)=>v.enabled!==!1&&i0(v)).map((v)=>({accountId:v.id,quota:w.getFallback(v.id)?.quota})),T=n4(b,I,_,Z);if(F==="quota-exhausted"&&P!==void 0)T=Math.max(1,Math.ceil((P-_)/1000));else if(F==="mid-stream-rate-limit"&&P!==void 0){let v=Math.max(1,Math.ceil((P-_)/1000));T=Math.min(T,v)}let S=Math.floor(T/60),M=T%60,f=F==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${S}m ${M}s.`:F==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${S}m ${M}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${S}m ${M}s.`;return new Response(JSON.stringify({error:{message:f,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(T)}})}function OX(Z){let F=Z?.resetCreditsAvailable;return typeof F==="number"&&Number.isFinite(F)?F:void 0}async function Lz(Z){let F=PY(Z.storage),P=Date.now(),_=w.peekMainForPolicy(Z.mainAccountIdentity),b=s1(_?.quota,_?.checkedAt,Z.sidebarState.main.quota,Z.sidebarState.main.mainAccountId,Z.mainAccountIdentity),I=F?MY(_?.quota,Z.storage,void 0,P):void 0,T=[{accountId:"main",wireAccountId:Z.mainAccountIdentity,access:Z.primaryAccess,keepwarmAccountKey:"main",quota:b.quota,quotaCheckedAt:b.quotaCheckedAt,reservePercent:LX(Z.storage),configuredOrder:0,resetCreditsApplicable:OX(b.quota),killswitchPasses:I}],S=await n.getUsableFallbackAccounts(Z.storage);for(let M of S){if(!M.access)continue;let f=Z.sidebarState.fallbacks.find((m0)=>m0.id===M.id),v=w.peekFallbackForPolicy(M.id,M.accountId),Q0=s1(v?.quota,v?.checkedAt,f?.quota,f?.accountId,M.accountId),F0=F?MY(v?.quota,Z.storage,M.id,P):void 0;T.push({accountId:M.id,wireAccountId:M.accountId,access:M.access,keepwarmAccountKey:M.id,fallback:M,quota:Q0.quota,quotaCheckedAt:Q0.quotaCheckedAt,reservePercent:LX(Z.storage,M.id),configuredOrder:T.length,resetCreditsApplicable:OX(Q0.quota),killswitchPasses:F0})}return T}function FX(Z,F,P,_,b){let I=PY(b)?Z.killswitchPasses:void 0;if(Z.accountId==="main"){let f=w.peekMainForPolicy(Z.wireAccountId),v=s1(f?.quota,f?.checkedAt,F.main.quota,F.main.mainAccountId,Z.wireAccountId);return n8({quota:v.quota,quotaCheckedAt:v.quotaCheckedAt,status:P,now:_,killswitchPasses:I})}let T=F.fallbacks.find((f)=>f.id===Z.accountId),S=w.peekFallbackForPolicy(Z.accountId,Z.wireAccountId),M=s1(S?.quota,S?.checkedAt,T?.quota,T?.accountId,Z.wireAccountId);return n8({quota:M.quota,quotaCheckedAt:M.quotaCheckedAt,status:P,now:_,killswitchPasses:I})}function Hz(Z){return Z.accountId==="main"?"main":Z.keepwarmAccountKey}function qX(Z){return w.isRateLimited(Hz(Z))}async function D8(Z){let F=Z.candidates.filter((M)=>!qX(M)),P=new Map(F.map((M)=>[M.accountId,M])),_=Object.fromEntries(F.map((M)=>[M.accountId,M.quotaCheckedAt])),b=Object.fromEntries(F.map((M)=>[M.accountId,M.wireAccountId])),I=new Set(Z.excludeAccountIds),T,S=await Qz({sessionId:Z.sessionId,requestBytes:Z.requestBytes,now:Z.now,validPinnedAccountIds:[...P.keys()],excludeAccountIds:Z.excludeAccountIds,quotaCheckedAtByAccount:_,wireAccountIdByAccount:b,choose:(M)=>{let f=F.filter((Q0)=>!I.has(Q0.accountId));if(f.length===0)return;let v=KJ({candidates:f,pendingBytes:M,requestBytes:Z.requestBytes,now:Z.now,onEmptyWeightedSet:()=>{Y0.debug("sticky routing: no fresh weighted candidates; using configured order")}});if(!v)return;return T={accountId:v.accountId,source:v.source,pendingBytes:M.get(v.accountId)??0},v}},M0);if(T&&S?.accountId===T.accountId)Y0.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:EY(Z.sessionId),accountId:T.accountId,source:T.source,requestBytes:Z.requestBytes,pendingBytes:T.pendingBytes});return S?P.get(S.accountId):void 0}async function Nz(Z,F){let P=await n.getUsableFallbackAccounts(Z),_=[];for(let v of P)if(v.access)_.push({access:v.access,accountId:v.accountId,keepwarmAccountKey:v.id,quotaAccountId:v.id,fallback:v});let b=_.filter((v)=>!w.isRateLimited(v.quotaAccountId)),I=PY(Z)?b.filter((v)=>MY(w.peekFallbackForPolicy(v.quotaAccountId,v.accountId)?.quota,Z,v.quotaAccountId,Date.now())):b,T=new Map(F.fallbacks.map((v)=>[v.id,{quota:v.quota,accountId:v.accountId}])),S=[],M=[],f=Date.now();for(let v of I){let Q0=T.get(v.quotaAccountId),F0=KX(w.peekFallbackForPolicy(v.quotaAccountId,v.accountId),Q0?.quota,f,Q0?.accountId,v.accountId);if(F0.exhausted)M.push({candidate:v,decision:F0});else S.push(v)}return{current:I,retained:S,skipped:M}}function jX(Z,F){if(Z.retained.length===0&&!F)return Z.current;for(let{candidate:P,decision:_}of Z.skipped)BX(P.quotaAccountId,_);return Z.retained}async function DX(Z,F){try{let P=g1(Z.headers);await j1(P,F.access,F.quotaAccountId,void 0,jY(Z.headers))}catch{}}async function Vz(Z,F,P,_){for(let b of _){let I;try{I=await a(Z,F,b.access,b.accountId,b.keepwarmAccountKey)}catch(T){if(T instanceof DOMException&&T.name==="AbortError")throw T;if(F?.signal?.aborted)throw T;throw Y0.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:b.quotaAccountId}),T}if(!DY(I.status,P))return n.markUsed(b.fallback),{response:I,accessToken:b.access,quotaAccountId:b.quotaAccountId,activeId:b.keepwarmAccountKey};await DX(I,b),I.body?.cancel().catch(()=>{})}return}async function Zz(Z,F,P,_,b){if(!S0(Z,F))return{response:P};if(!b.length)return{response:P};let I=P,T;for(let S of b){let M;try{M=await a(Z,F,S.access,S.accountId,S.keepwarmAccountKey)}catch(f){if(f instanceof DOMException&&f.name==="AbortError")throw f;if(F?.signal?.aborted)throw f;return Y0.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:S.quotaAccountId}),{response:I,...T}}if(I.body?.cancel().catch(()=>{}),I=M,T={accessToken:S.access,accountId:S.quotaAccountId},!DY(M.status,_))return n.markUsed(S.fallback),{response:M,...T};await DX(M,S)}return{response:I,...T}}if(!E4){if(E4=!0,j){let Z=[];for(let F of j.accounts)if(i0(F))Z.push(F);w.seedFallbacksFromAccounts(Z)}y0(w,j).catch(()=>{}),h1({getAuth:N,codexRefreshFn:S1,refreshMainWithLease:n0,fallbackManager:n,quotaManager:w,loadAccounts:D0,writeSidebarState:y0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:W0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:i0,whamFn:W1,respectBackoff:!0}).catch((Z)=>u.warn("boot quota seed failed",{pid:process.pid,error:t0(Z)}))}return B.start(async()=>{let F=(await XJ({getAuth:N,codexRefreshFn:S1,refreshMainWithLease:n0,fallbackManager:n,quotaManager:w,loadAccounts:D0,writeSidebarState:(P,_)=>B.isStopped()?Promise.resolve():y0(P,_),client:Y.client,fetchImpl:fetch,now:Date.now,configPath:W0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:i0,whamFn:W1,readSidebarState:()=>A1(M0)})).filter((P)=>!P.ok);if(F.length>0)u.warn("background quota refresh completed with failures",{pid:process.pid,failures:F})},(Z)=>{u.warn("background quota refresh failed",{pid:process.pid,error:Z instanceof Error?Z.message:String(Z)})}),{apiKey:vZ,async fetch(Z,F){let P=S4(Z,F),_=k4(P),b=P.get("x-parent-session-id")?.trim()||void 0,I=await x(),T=await N(),S=++c;if(T.type!=="oauth")return fetch(Z,F);F=await $K(Z,F);let M=T.access??"";if(!T.access||(T.expires??0)<Date.now()){P0.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(T.access),expiresInMs:T.expires?T.expires-Date.now():void 0});try{let X0=await n0();T.access=X0.access,T.refresh=X0.refresh,T.expires=X0.expires}catch(X0){if(UX(X0))throw X0}}M=T.access??"";let v=T.accountId??(M?r1(o1(M)??{}):void 0);if(S===c)J0=v;let Q0=I?.routing?.mode??"main-first",F0,U0=await(()=>{return F0??=A1(M0),F0})();if(Q0==="sticky-balanced"&&_&&S0(Z,F)&&typeof F?.body==="string"){let X0=Buffer.byteLength(F.body,"utf8"),V0=await Lz({storage:I,sidebarState:U0,primaryAccess:M,mainAccountIdentity:v}),H0=await D8({sessionId:_,requestBytes:X0,candidates:V0,now:Date.now()});if(H0){let RX=qX(H0)?{action:"migrate",reason:"exhausted"}:FX(H0,U0,void 0,Date.now(),I);if(RX.action==="migrate"){let T0=await D8({sessionId:_,requestBytes:X0,candidates:V0,excludeAccountIds:[H0.accountId],now:Date.now()});if(T0)Y0.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:EY(_),fromAccountId:H0.accountId,toAccountId:T0.accountId,reason:RX.reason}),H0=T0}let c0=await a(Z,F,H0.access,H0.wireAccountId,H0.keepwarmAccountKey),_X=async(T0,D1)=>{try{let Kz=g1(T0.headers);await j1(Kz,D1.access,D1.accountId==="main"?void 0:D1.accountId,D1.accountId==="main"?D1.wireAccountId:void 0,jY(T0.headers))}catch{}};await _X(c0,H0);let CX=FX(H0,U0,c0.status,Date.now(),I);if((c0.status===401||c0.status===403||c0.status===429)&&CX.action==="migrate"){let T0=await D8({sessionId:_,requestBytes:X0,candidates:V0,excludeAccountIds:[H0.accountId],now:Date.now()});if(T0){Y0.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:EY(_),fromAccountId:H0.accountId,toAccountId:T0.accountId,reason:CX.reason});let D1=c0;c0=await a(Z,F,T0.access,T0.wireAccountId,T0.keepwarmAccountKey),D1.body?.cancel().catch(()=>{}),H0=T0,await _X(c0,H0)}}if(H0.fallback&&!DY(c0.status,I))n.markUsed(H0.fallback);return await f0(_,b,H0.accountId,Q0,I?.accounts).catch(()=>{}),c0}}let K0=KX(w.peekMainForPolicy(v),U0.main.quota,Date.now(),U0.main.mainAccountId,v),k0=PY(I)&&!MY(j8(v),I,void 0,Date.now()),wY=w.isRateLimited("main"),PX,P8=()=>{return PX??=Nz(I,U0),PX},s0,x1,MX=!1,TY;if(Q0==="fallback-first"&&S0(Z,F)){MX=!0;let X0=await P8();TY=jX(X0,!k0&&!wY&&!K0.exhausted);let V0=await Vz(Z,F,I,TY);if(V0)s0=V0.response,x1={accessToken:V0.accessToken,accountId:V0.quotaAccountId,activeId:V0.activeId}}if(!s0){let X0=K0.exhausted&&S0(Z,F)&&(await P8()).retained.length>0;if(k0||wY||X0){let V0=k0?"killswitch":wY?"mid-stream-rate-limit":"quota-exhausted";if(V0==="quota-exhausted"&&K0.exhausted)BX("main",K0);Y0.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:V0}),s0=Uz(I,V0,V0==="quota-exhausted"&&K0.exhausted?K0.resetAtMs:wY?w.rateLimitedUntil("main"):void 0)}else s0=await a(Z,F,M,v,"main")}let EX=Boolean(x1),a1=s0,AX=x1?.accessToken??M,wX=x1?.accountId,TX=x1?.activeId??"main";if(!x1&&!MX&&DY(s0.status,I)){Y0.debug("reactive fallback triggered",{pid:process.pid,status:s0.status}),TY??=jX(await P8(),!1);let X0=await Zz(Z,F,s0,I,TY),V0=X0.response;if(V0!==s0){if(EX=!0,a1=V0,AX=X0.accessToken??M,wX=X0.accountId,X0.accountId)TX=X0.accountId}}try{let X0=g1(a1.headers);if(EX)await j1(X0,AX,wX,void 0,jY(a1.headers));else await j1(X0,M,void 0,v,jY(a1.headers))}catch{}return await f0(_,b,TX,Q0,I?.accounts).catch(()=>{}),a1},async dispose(){if(B.stop(),o0.stop(),G1.__openaiAuthCacheKeepManager===o0)G1.__openaiAuthCacheKeepManager=void 0;if(n.stopBackgroundRefresh(),L){await L.stop().catch(()=>{});let Z=globalThis;if(Z.__openaiAuthRpcServer===L)Z.__openaiAuthRpcServer=void 0;L=null}}}},methods:[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:async()=>{let{redirectUri:N}=await m4(),O=await g4(),j=h4(crypto.getRandomValues(new Uint8Array(32)).buffer),A=y4(N,O,j),x=c4(O,j);return{url:A,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let E=await x,k=B8(E);return{type:"success",refresh:E.refresh_token,access:E.access_token,expires:Date.now()+(E.expires_in??3600)*1000,accountId:k}}finally{f4(j)}}}}},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:async()=>{let{deviceData:N,url:O,instructions:j}=await u4();return{url:O,instructions:j,method:"auto",async callback(){try{let A=await p4(N);return{type:"success",refresh:A.refresh_token,access:A.access_token,expires:Date.now()+(A.expires_in??3600)*1000,accountId:B8(A)}}catch{return{type:"failed"}}}}}},{label:"Manually enter API Key",type:"api"}]},"chat.headers":async(N,O)=>{if(N.model.providerID!=="openai")return;if(O.headers.originator="opencode",O.headers["User-Agent"]=`${v4} (${zX.platform()} ${zX.release()}; ${zX.arch()})`,O.headers["session-id"]=N.sessionID,W&&N.agent==="title")O.headers[F1.TITLE_HEADER]="true"},"chat.params":async(N,O)=>{if(N.model.providerID!=="openai")return;O.maxOutputTokens=void 0},config:async(N)=>{N.command={...N.command??{},[I8]:{template:I8,description:"Show current OpenAI Codex OAuth quota usage for all accounts."},[S8]:{template:S8,description:"Manage OpenAI accounts — add, switch, remove, or reorder."},[k8]:{template:k8,description:"Show or change OpenAI account routing between main-first, fallback-first, and sticky-balanced."},[b8]:{template:b8,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."},[x8]:{template:x8,description:"Show or toggle OpenAI Codex request dump capture for debugging."},[v8]:{template:v8,description:"Show or change the plugin log level (error, warn, info, debug, trace)."},[h8]:{template:h8,description:"Keep Codex prompt cache alive during idle by shadow-replaying the last request."},[E1]:{template:E1,description:"Spend one reset credit on an exhausted Codex account."}}},"command.execute.before":async(N)=>{if(!eX.includes(N.command))return;if(!H)await K(N.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),_4();let O=N.command,j={...H,sessionId:N.sessionID,notify:(x)=>{$9(x,N.sessionID)}},A=await g8(O,N.arguments,j);if(yJ(N.sessionID))$9(A,N.sessionID);else await K(N.sessionID,A.text);_4()}}}var ZK=async(Y)=>{let X=E0();return VK(Y,{codexApiEndpoint:X.codexApiEndpoint,experimentalWebSockets:X.webSockets,responsesLite:X.responsesLite})},cD={id:"cortexkit-openai-auth",server:ZK};export{k4 as resolveSidebarSessionId,o1 as parseJwtClaims,I4 as mergePushedQuotaMetadata,QK as findCachekeepFallbackAccount,r1 as extractAccountIdFromClaims,cD as default,iZ as createResetTargetResolver,mD as buildSidebarState,zz as buildSidebarMachineState,nZ as buildResetRedemptionDeps,d0 as ResetTargetResolutionError,ZK as OpenAIAuthPlugin,mZ as MAIN_REFRESH_LOCK_TTL_MS,cZ as MAIN_REFRESH_LEASE_TTL_MS,VK as CodexAuthPlugin,VX as AuthPersistError};
122
+ `)),z=!0,R=Date.now(),O!==void 0)C++;if(H.length<B)H.push(String($0.type));if($0.type==="response.created")O=eZ($0),A9.debug("response created",{...j,responseID:O,previousResponseID:V,hasContinuation:V!==void 0});if(!YV($0.type))L=!0;if(Q0("idle timeout waiting for websocket"),!$0)return;if($0.type==="response.completed"||$0.type==="response.done"){$=!0,rZ($0,D),Y.onComplete?.($0,D),Y.onTerminal?.($0),g();return}if($0.type==="response.failed"||$0.type==="response.incomplete"||$0.type==="error")$=!0,Y.onTerminal?.($0),g()}function S0(w){l(new _0(T1(w),{cause:w}))}function PY(w){if($)return;let p=w.code===1009,f=new _0(p?Z4:V4("WebSocket closed before response.completed",w.code,w.reason),{retryable:!p});if(p)A9.warn("websocket peer refused the request size",{...j,requestBytes:W,reason:w.reason.toString()});l(p?L4(f):f)}function K0(){let w=eX(Y.signal);if($)return;$=!0,E(),T(),Y.onAbort?.(w),Q?.error(w)}function MY(w){if($)return;$=!0,E(),T(),Y.onAbort?.(aZ(w))}function r0(w){G(),J=w,J.addEventListener("message",c),J.addEventListener("error",S0,{once:!0}),J.addEventListener("close",PY,{once:!0}),G=()=>{J.removeEventListener("message",c),J.removeEventListener("error",S0),J.removeEventListener("close",PY)};let{background:p,...f}=Y.body;Q0("idle timeout sending websocket request");try{let U0=JSON.stringify({type:"response.create",...f});W=U0.length,J.send(U0),Q0("idle timeout waiting for websocket")}catch(U0){if($)return;u(new _0(U0 instanceof Error?U0.message:String(U0),{cause:U0}))}}return new Response(new ReadableStream({start(w){if(Q=w,Y.signal?.addEventListener("abort",K0,{once:!0}),Y.signal?.aborted){K0();return}r0(J)},cancel(w){MY(w)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function iZ(Y,X){if(!oZ(Y))return;await e0({component:"ws",event:"provider_native_web_search_event",sessionID:X,serverEventType:Y.type,itemType:k(Y.item)?Y.item.type:void 0,serverEvent:Y})}function oZ(Y){if(typeof Y.type==="string"&&(Y.type.startsWith("response.web_search_call.")||Y.type.startsWith("response.web_search_preview_call.")))return!0;if(k(Y.item)&&typeof Y.item.type==="string")return Y.item.type==="web_search_call"||Y.item.type==="web_search_preview_call";return!1}function nZ(Y,X){if(Y.type!=="response.output_item.done")return;if(!k(Y.item))return;H4(Y.item,X)}function rZ(Y,X){let J=Y.response;if(!k(J)||!Array.isArray(J.output))return;for(let Q of J.output)if(k(Q))H4(Q,X)}function H4(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 sZ(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:k(Y.headers)?Object.fromEntries(Object.entries(Y.headers).flatMap(([Q,G])=>typeof G==="string"||typeof G==="number"||typeof G==="boolean"?[[Q,String(G)]]:[])):void 0,body:X,message:k(Y.error)&&typeof Y.error.message==="string"?Y.error.message:`${J}`}}function A1(Y){if(typeof Y==="string")try{return A1(JSON.parse(Y))}catch{return}if(!k(Y))return;let X=A1(Y.cause);if(X)return X;let J=A1(Y.body);if(J)return J;let Q=k(Y.error)?Y.error:Y,G=typeof Q.type==="string"?Q.type:void 0,$=Y.status??Y.status_code;if(G!=="usage_limit_reached"&&$!==429)return;let{resets_at:W,resets_in_seconds:z}=Q,L=typeof W==="number"&&Number.isFinite(W)&&W>0?W*1000:typeof z==="number"&&Number.isFinite(z)&&z>0?Date.now()+z*1000:void 0;return{window:G??"primary",resetAt:L}}function aZ(Y){if(Y8(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function eX(Y){let X=Y?.reason;if(Y8(X))return X;if(tZ(X))return X;return new DOMException(X instanceof Error?X.message:"Aborted","AbortError")}function tZ(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function eZ(Y){let X=Y.response;if(!k(X))return;return typeof X.id==="string"?X.id:void 0}function YV(Y){return Y==="response.created"||Y==="response.in_progress"||Y.startsWith("codex.")}var N4="The response ended early after part of it had already been shown. It was not sent again, because repeating it would duplicate that output and re-run any tools it had started. The transport log records what ended it.",Z4="The request was larger than the websocket would carry, so it was sent over HTTP instead. Resending it unchanged over the same socket cannot succeed. The transport log records the size.";function V4(Y,X,J){let Q=[`code ${X}`];if(J.length>0)Q.push(J.toString());return`${Y} (${Q.join(": ")})`}var J8="x-opencode-title",T9="x-openai-auth-quota-account",X8=new Set([J8,LY,T9,"x-opencode-session"]),JV=15000,QV=300000,GV=3300000,B4="websocket_connection_limit_reached";function $V(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 XV("sha256").update(Q).digest("hex").slice(0,12)}function WV(Y){let X=Y?.httpFetch??globalThis.fetch,J=new Map,Q=Y?.connectTimeout??JV,G=Y?.idleTimeout??QV,$=Y?.maxConnectionAge??GV,W=Y?.streamRetries??5,z=Y?.firstEventGraceMs??250,L=Y?.rawWebSocket??!1,U=Y?.onQuota,H=Y?.onRateLimitReached,B=setInterval(()=>O(),Math.min(G,60000));if(typeof B==="object"&&"unref"in B&&typeof B.unref==="function")B.unref();function V(D,E,T){if(!E||!T)return T;Q8(D,F4(E));let g=new Headers(T.headers),u=g.get("x-codex-turn-metadata");if(!u)return T;let l=w4(u,D.turnID,D.turnStartedAt);if(!l)return T;return g.set("x-codex-turn-metadata",l),{...T,headers:g}}async function Z(D,E){let T=D instanceof URL?D.toString():typeof D==="string"?D:D.url,g=P0.normalizeHeaders(E?.headers),u=R4(E),l=s1(u);if(E?.method!=="POST"||!new URL(T).pathname.endsWith("/responses"))return X(D,l);let T0=(()=>{try{if(typeof E?.body!=="string")return;let p=JSON.parse(E.body);return typeof p==="object"&&p!==null?p:void 0}catch{return}})();if(!T0?.stream)return X(D,l);if(g[J8]==="true")return X(D,l);let Q0=g[LY]??g["x-session-affinity"]??g["session-id"],c=Q0;if(!Q0)return X(D,l);let S0=P0.normalizeHeaders(u?.headers),PY=$V(S0),K0=`${Q0}:${PY}:conversation`,MY=typeof g[T9]==="string"?g[T9]:void 0,r0=H?(p,f)=>H(p,MY,f):void 0,w=J.get(K0)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};if(J.set(K0,w),w.fallback)return X(D,V(w,T0,l));if(w.busy)return X(D,V(w,T0,l));w.busy=!0,w.lastUsedAt=Date.now();try{let p=F4(T0),f=P0.normalizeHeaders(u?.headers),U0=typeof f.authorization==="string"&&f.authorization.startsWith("Bearer ")?f.authorization.slice(7):"",u0=typeof f["chatgpt-account-id"]==="string"?f["chatgpt-account-id"]:void 0,$0=U?(W0)=>U(W0,U0,MY,u0):void 0,WY=!w.socket&&!w.continuation?BV(f):f;if(w.socket=await LV(w,Y?.url??T,WY,Q,$,L,E?.signal),jV(w,p))await HV(w,p,G,{signal:E?.signal??void 0,sessionID:c,url:Y?.url??T,headers:u?.headers,onRateLimitReached:r0});let n=()=>{},R0=()=>{},bY=new Promise((W0,l0)=>{n=W0,R0=l0}),KY=qV(w,p),s0=R1(E4(w,KY,p)),I9=typeof s0.previous_response_id==="string";await yY({sessionID:c,transport:"websocket",phase:"main",bodyText:JSON.stringify(s0),url:Y?.url??T,method:u?.method,headers:u?.headers});let zY=P0.streamResponsesWebSocket({socket:w.socket,body:s0,sessionID:c??void 0,idleTimeout:G,signal:E?.signal??void 0,onQuota:$0,onRateLimitReached:r0,onFirstEvent:(W0)=>n(W0??!0),onComplete:(W0,l0)=>{let EY=j4(W0);e0({component:"ws-pool",event:"main_completed",sessionID:c,responseID:q4(W0),usage:EY}),M4(w,p,W0,l0,I9)},onTerminal:(W0)=>{if(w.busy=!1,w.lastUsedAt=Date.now(),w.streamFailures=0,W0.type!=="response.completed"&&W0.type!=="response.done")w.continuation=void 0,$Y(w)},onConnectionInvalid:(W0)=>{if(w.busy=!1,w.lastUsedAt=Date.now(),P0.isOversizedFrame(W0))w.fallback=!0;if(!w.fallback)j(w);w.continuation=void 0,$Y(w),n(!1)},onAbort:(W0)=>{w.busy=!1,w.lastUsedAt=Date.now(),w.streamFailures=0,w.continuation=void 0,$Y(w),R0(W0)},onRetryableTerminal:async(W0)=>{let l0=O4(W0);if(!l0)return;throw w.fallback=!0,l0}}),X0=await KV(bY,z);if(X0!==!1){if(X0===!0||X0.status<200||X0.status>599)return zY;return new Response(X0.body,{status:X0.status,headers:{"content-type":"application/json",...X0.headers}})}let p0=()=>X(D,V(w,T0,l));if(!w.fallback)return zV(zY,p0);return p0()}catch(p){if(w.busy=!1,w.lastUsedAt=Date.now(),P0.isAbortError(p))throw w.streamFailures=0,w.continuation=void 0,$Y(w),p;let f=P0.parseRateLimitSignal(p);if(f)r0?.(f.window,f.resetAt);if(P0.isUpgradeFailure(p)&&!L)w.fallback=!0;if(j(w),w.continuation=void 0,$Y(w),w.fallback)return X(D,V(w,T0,l));return UV(new _0(p instanceof Error?p.message:String(p),{cause:p}))}}function j(D){if(D.streamFailures++,D.streamFailures>W)D.fallback=!0}function O(){let D=Date.now();for(let[E,T]of J){if(T.busy)continue;if(D-T.lastUsedAt<G)continue;$Y(T),J.delete(E)}}function C(){clearInterval(B);for(let D of J.values())$Y(D);J.clear()}function R(D){let E=`${D}:`;for(let[T,g]of J){if(!T.startsWith(E))continue;$Y(g),J.delete(T)}}return Object.assign(Z,{close:C,remove:R})}function O4(Y){if(Y.type!=="error"||!k(Y.error)||Y.error.code!==B4)return;return Error(typeof Y.error.message==="string"?Y.error.message:B4)}async function KV(Y,X){if(X<=0)return!1;return new Promise((J,Q)=>{let G=setTimeout(()=>J(!1),X);Y.then(($)=>{clearTimeout(G),J($)},($)=>{clearTimeout(G),Q($)})})}function zV(Y,X){let J=Y.body;if(!J)return Y;let Q=!1,G=new ReadableStream({async start($){let W=J.getReader(),z=async(L)=>{while(!0){let{done:U,value:H}=await L.read();if(U)return;if(H&&H.length>0)Q=!0,$.enqueue(H)}};try{await z(W),$.close()}catch(L){if(Q||!P0.isOversizedFrame(L)){$.error(L);return}try{let U=await X();if(!U.ok){$.error(new _0(`HTTP fallback after an oversized WebSocket frame failed with ${U.status}`));return}if(U.body)await z(U.body.getReader());$.close()}catch(U){$.error(U)}}},cancel($){J.cancel($)}});return new Response(G,{status:Y.status,headers:Y.headers})}function UV(Y){return new Response(new ReadableStream({start(X){X.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function LV(Y,X,J,Q,G,$,W){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<G)return Y.socket;$Y(Y);let z=await P0.connectResponsesWebSocket({url:P0.toWebSocketUrl(X),headers:J,timeout:Q,rawWebSocket:$,signal:W??void 0});return Y.connectedAt=Date.now(),z}function $Y(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function HV(Y,X,J,Q){if(!Y.socket||!Array.isArray(X.input)||X.input.length===0)return;let G=ZV(X);await yY({sessionID:Q.sessionID,transport:"websocket",phase:"prewarm",bodyText:JSON.stringify(G),url:Q.url,method:"POST",headers:Q.headers});let $=P0.streamResponsesWebSocket({socket:Y.socket,body:G,sessionID:Q.sessionID,idleTimeout:J,signal:Q.signal,onRateLimitReached:Q.onRateLimitReached,onComplete:(W,z)=>{e0({component:"ws-pool",event:"prewarm_completed",sessionID:Q.sessionID,responseID:q4(W),usage:j4(W)}),M4(Y,G,W,z,!1)},onTerminal:(W)=>{if(W.type!=="response.completed"&&W.type!=="response.done")Y.continuation=void 0},onConnectionInvalid:()=>{Y.continuation=void 0},onAbort:()=>{Y.continuation=void 0},onRetryableTerminal:async(W)=>{let z=O4(W);if(!z)return;throw Y.fallback=!0,z}});await NV($)}function q4(Y){let X=Y.response;if(!k(X))return;return typeof X.id==="string"?X.id:void 0}function j4(Y){let X=Y.response;if(!k(X))return;return k(X.usage)?X.usage:void 0}async function NV(Y){let X=Y.body?.getReader();if(!X)return;while(!0)if((await X.read()).done)return}function ZV(Y){return R1({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:VV(Y.client_metadata)})}function D4(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 VV(Y){if(!k(Y))return Y;if(typeof Y["x-codex-turn-metadata"]!=="string")return Y;try{let X=JSON.parse(Y["x-codex-turn-metadata"]);if(!k(X))return Y;return{...Y,"x-codex-turn-metadata":D4(X),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function BV(Y){let X=Y["x-codex-turn-metadata"];if(!X)return Y;try{let J=JSON.parse(X);if(!k(J))return Y;return{...Y,"x-codex-turn-metadata":D4(J)}}catch{return Y}}var P4=["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 F4(Y){let X={...Y};if(Array.isArray(Y.input))X.input=Y.input.map(FV);return X}function R1(Y){let X={};for(let J of P4)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 FV(Y){if(!k(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 M4(Y,X,J,Q,G){let $=J.response,W=k($)&&typeof $.id==="string"?$.id:void 0;if(!W||!Array.isArray(X.input)){Y.continuation=void 0;return}let z=G?new Set(Y.continuation?.finalizedCallIds):new Set;for(let L of Q)z.add(L);Y.continuation={responseID:W,input:X.input,signature:G8(X),finalizedCallIds:z}}function Q8(Y,X,J=X){let Q=Array.isArray(X.input)?X.input:[],G=Array.isArray(J.input)?J.input:Q,$=G8(J),W=Y.turnInput&&Y.turnSignature===$?OV(Y.turnInput,G):void 0,z=W===void 0?Q:G.slice(W);if(z.length>0&&z.some(A4)||!Y.turnID)Y.turnID=RY(),Y.turnStartedAt=Date.now();Y.turnInput=G.slice(),Y.turnSignature=$}function E4(Y,X,J=X){Q8(Y,X,J);let Q=X.client_metadata;if(!k(Q)||typeof Q["x-codex-turn-metadata"]!=="string")return X;let G=w4(Q["x-codex-turn-metadata"],Y.turnID,Y.turnStartedAt);if(!G)return X;return{...X,client_metadata:{...Q,"x-codex-turn-metadata":G}}}function w4(Y,X,J){let Q;try{Q=JSON.parse(Y)}catch{return}if(!k(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 OV(Y,X){if(Y.length>X.length)return;for(let J=0;J<Y.length;J++)if(YY(Y[J])!==YY(X[J]))return;return Y.length}function qV(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!J||!Y.continuation)return X;if(Y.continuation.signature!==G8(X))return Y.continuation=void 0,X;if(!T4(Y.continuation.input,J))return Y.continuation=void 0,X;if(Y.continuation.input.length===0)return{...X,previous_response_id:Y.continuation.responseID};let Q=J.slice(Y.continuation.input.length),G=DV(Q,Y.continuation.finalizedCallIds);if(G.length===0)return X;return{...X,previous_response_id:Y.continuation.responseID,input:G}}function jV(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!Y.continuation)return!0;if(!J)return!1;if(!T4(Y.continuation.input,J))return!0;return J.slice(Y.continuation.input.length).some(A4)}function A4(Y){if(!k(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function DV(Y,X){return Y.filter((J)=>{if(!k(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 G8(Y){return YY(PV(Object.fromEntries(Object.entries(Y).filter(([X])=>X!=="input"&&X!=="stream"&&X!=="background"&&X!=="previous_response_id"&&X!=="generate"))))}function PV(Y){if(!k(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 T4(Y,X){if(Y.length>=X.length)return!1;for(let J=0;J<Y.length;J++)if(YY(Y[J])!==YY(X[J]))return!1;return!0}function R4(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let X=new Headers(Y.headers);for(let J of X8)X.delete(J);return{...Y,headers:X}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((X)=>!X8.has(X[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([X])=>!X8.has(X.toLowerCase())))}}var CV=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),IV=new Set(["gpt-5.6","gpt-6"]),_V=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-6-astra"]),SV="opencode-oauth-dummy-key",kV="terminal_resize_reflow",z8="0.153.0",xV=`codex_exec/${z8} (Debian 12.0.0; aarch64) unknown (codex_exec; ${z8})`,bV="seccomp",vV="main-refresh",hV=120000,gV=90000,yV=4000,C4=50,I4=3,fV=25,mV=60000,cV="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",_4=!1,S4=D0("models"),k4=!1,x4=!1;class L8 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 n0 extends Error{code;constructor(Y,X){super(X);this.name="ResetTargetResolutionError",this.code=Y}}function b4(Y,X,J,Q){let G=(J?.refresh?.refreshBeforeExpiryMinutes??240)*60000;return!Y||!X||X-Q<=G}function uV(Y){return async(X)=>{if(X==="main"){let z=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),L=await Y.getAuth();if(L.type!=="oauth")throw new n0("non_oauth_account","Main OpenAI account is not authenticated with OAuth.");if(b4(L.access,L.expires,z,Y.now()))L={type:"oauth",...await Y.refreshMainWithLease()};if(!L.access)throw new n0("token_unavailable","Main OpenAI account has no usable access token.");let U=oY(L.access),H=U?nY(U):void 0,B=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath});return{accountKey:X,label:"Main account",accessToken:L.access,chatgptAccountId:H??B?.mainAccountId}}let J=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),Q=J?.accounts.find((z)=>z.id===X);if(!J||!Q)throw new n0("unknown_account",`Fallback account ${X} was not found.`);if(Q.enabled===!1)throw new n0("disabled_account",`Fallback account ${X} is disabled.`);if(!V0(Q))throw new n0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);let G=Q;if(b4(G.access,G.expires,J,Y.now()))G=await Y.refreshFallbackAccount(G,J);if(!G.access)throw new n0("token_unavailable",`Fallback account ${X} has no usable access token.`);let $=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),W=$?.accounts.find((z)=>z.id===X);if(!$||!W)throw new n0("unknown_account",`Fallback account ${X} was not found.`);if(W.enabled===!1)throw new n0("disabled_account",`Fallback account ${X} is disabled.`);if(!V0(W))throw new n0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);return{accountKey:X,label:G.label??X,accessToken:G.access,chatgptAccountId:W.accountId}}}function pV(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function W8(Y){return Y instanceof L8}function v4(){throw Error(cV)}function lV(Y){return Math.floor(Math.random()*Y)}function dV(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 iV(Y,X,J){let Q=Y.get(X);if(Q)return Q;let G=RY(),$={threadID:G,turnID:RY(),windowID:`${G}:0`};return Y.set(X,$),J?.(),$}function $K(){return RV(f1(),"openai-auth-sessions.json")}function oV(){let Y=new Map;try{let X=JSON.parse(EV($K(),"utf8"));if(!k(X.sessions))return Y;for(let[J,Q]of Object.entries(X.sessions)){if(!k(Q)||typeof Q.threadID!=="string")continue;Y.set(J,{threadID:Q.threadID,turnID:RY(),windowID:`${Q.threadID}:0`})}}catch{}return Y}function nV(Y){let X=$K(),J=`${X}.tmp-${process.pid}`;try{MV(f1(),{recursive:!0});let Q={version:1,sessions:Object.fromEntries([...Y.entries()].map(([G,$])=>[G,{threadID:$.threadID}]))};TV(J,`${JSON.stringify(Q,null,2)}
123
+ `,"utf8"),wV(J,X)}catch{}}function h4(Y,X){return k(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===X}function rV(Y,X){if(Y.length>X.length)return!1;for(let J=0;J<Y.length;J++)if(YY(Y[J])!==YY(X[J]))return!1;return!0}function sV(Y,X){if(!Y.input)return X.length>0;if(!rV(Y.input,X))return!0;return X.slice(Y.input.length).some((Q)=>h4(Q,"user")||h4(Q,"developer"))}function aV(Y,X){let J=Array.isArray(X?.input)?X.input:void 0;if(J&&(sV(Y,J)||!Y.turnID))Y.turnID=RY(),Y.turnStartedAt=Date.now();else if(!Y.turnStartedAt)Y.turnStartedAt=Date.now();if(J)Y.input=J}function tV(Y){if(!Y.metadata)return{init:Y.init};let X=dV(Y.init?.body);if(!Y.websocket)aV(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:bV,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",kV),Y.headers.set("x-codex-turn-metadata",J),Y.headers.set("user-agent",xV),Y.headers.set("version",z8),Y.dumpSessionID)Y.headers.set(LY,Y.dumpSessionID);let Q=X;if(!Q)return{init:Y.init};let G=Y.responsesLite&&typeof Q.model==="string"&&_V.has(Q.model);if(G&&!Y.websocket)Y.headers.set("x-openai-internal-codex-responses-lite","true");if(Q.prompt_cache_key=Y.metadata.threadID,Q.parallel_tool_calls??=!0,Array.isArray(Q.tools))Q.tools=Q.tools.map(KB);if($B(Q),WB(Q),SJ(Q),XB(Q),QB(Q,Y.metadata),G)GB(Q);let $={...typeof Q.client_metadata==="object"&&Q.client_metadata!==null?Q.client_metadata:{},"x-codex-installation-id":Y.installationID,"x-codex-window-id":Y.metadata.windowID};if(Y.websocket){if($["x-codex-turn-metadata"]=J,$["x-codex-ws-stream-request-start-ms"]=String(Date.now()),G)$.ws_request_header_x_openai_internal_codex_responses_lite="true"}return Q.client_metadata=$,Y.headers.delete("content-length"),Y.headers.delete("Content-Length"),{init:{...Y.init,body:JSON.stringify(R1(Q))}}}function eV(Y,X){return Y.find((J)=>J.enabled!==!1&&V0(J)&&(J.id===X||J.accountId===X))}function g4(Y,X){if(!X)return Y;let J={...Y};for(let Q of["resetCreditsAvailable","resetCreditsApplicable"]){let G=X[Q];if(J[Q]===void 0&&G!==void 0)J[Q]=G}return J}function R9(Y,X){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:X}}function WK(Y,X,J=Date.now(),Q=X.mainAccountId){let G=Y.getMain(),$=G?.quota;return{main:{quota:$?{...$,checkedAt:G.checkedAt,primary:R9($.primary,G.checkedAt),secondary:R9($.secondary,G.checkedAt)}:null,...typeof Q==="string"?{mainAccountId:Q}:{},killed:!1,...$?.resetCreditsAvailable!==void 0?{resetCredits:$.resetCreditsAvailable}:{}},fallbacks:X.accounts.filter((W)=>W.enabled).map((W)=>{let z=Y.getFallback(W.id),L=z?.quota;return{id:W.id,label:W.label,accountId:z?.accountId??W.accountId,quota:L?{...L,checkedAt:z.checkedAt,primary:R9(L.primary,z.checkedAt),secondary:R9(L.secondary,z.checkedAt)}:null,killed:!1,enabled:!0,...L?.resetCreditsAvailable!==void 0?{resetCredits:L.resetCreditsAvailable}:{}}}),route:X.routing?.mode??"main-first",lastUpdated:J}}function nD(Y,X,J,Q=Date.now()){return{...WK(Y,X,Q),activeId:J}}function y4(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 YB(Y,X){if(!(Y instanceof Request))return X;let J=new Request(Y,X),Q=J.method.toUpperCase(),G=Q==="GET"||Q==="HEAD"||J.body===null?void 0:await J.text();return{method:J.method,headers:new Headers(J.headers),body:G,signal:J.signal,cache:J.cache,credentials:J.credentials,integrity:J.integrity,keepalive:J.keepalive,mode:J.mode,redirect:J.redirect,referrer:J.referrer,referrerPolicy:J.referrerPolicy}}function f4(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}function XB(Y){if(!C0().webSearch)return;if(!Array.isArray(Y.tools)||Y.tools.length===0)return;if(Y.tools.some((X)=>k(X)&&X.type==="web_search"))return;Y.tools=[...Y.tools,{type:"web_search",external_web_access:!1,search_content_types:["text","image"]}]}function U8(Y){if(Array.isArray(Y)){for(let X of Y)U8(X);return}if(!k(Y))return;if(Y.type==="input_image")delete Y.detail;for(let X of Object.values(Y))U8(X)}var JB=new Set(["gpt-6-astra"]);function QB(Y,X){let J=typeof Y.model==="string"?Y.model:"";if(!JB.has(J))return;let Q=k(Y.reasoning)?Y.reasoning:void 0,G=typeof Q?.effort==="string"?Q.effort:void 0;if(!G)return;if(X.pinnedEffort===void 0){X.pinnedEffort=G;return}if(G===X.pinnedEffort)return;let $=Array.isArray(Y.input)?Y.input:void 0;if(!$||$.length===0)return;Y.reasoning={...Q,effort:X.pinnedEffort},$.splice($.length-1,0,{type:"configuration_update",reasoning:{effort:G}})}function GB(Y){let X=k(Y.reasoning)?{...Y.reasoning}:{};X.context="all_turns",Y.reasoning=X,Y.parallel_tool_calls=!1;let J=Array.isArray(Y.input)?Y.input:[];U8(J);let G=[{type:"additional_tools",role:"developer",tools:Array.isArray(Y.tools)?Y.tools.filter(($)=>!(k($)&&$.type==="web_search")):[]}];if(typeof Y.instructions==="string"&&Y.instructions.length>0)G.push({type:"message",role:"developer",content:[{type:"input_text",text:Y.instructions}]});Y.input=[...G,...J],delete Y.tools,delete Y.instructions}function $B(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(k(X)&&X.type==="function"&&X.name==="web_search"))}function WB(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(k(X)&&X.type==="function"&&X.name==="websearch_web_search_exa"))}function KB(Y){if(!k(Y))return Y;if(Y.type!=="function")return Y;let X=k(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:L,...U}=Y.parameters;return U})():Y.parameters,{type:J,name:Q,description:G,strict:$,parameters:W,...z}=Y;return{type:J,name:Q,description:G,strict:$??!1,parameters:X,...z}}async function zB(Y,X={}){let J=X.codexApiEndpoint??C0().codexApiEndpoint,Q=crypto.randomUUID(),G=oV(),$=()=>nV(G),W=!1,z=[],L=null,U=null,H,B=new h9,V,Z=GJ({client:Y.client,getAuth:async()=>V?.(),fetchImpl:fetch});async function j(O,C){let R=Y.client.session;if(typeof R?.promptAsync==="function"){let D=await fJ(Y.client,O),E={noReply:!0,parts:[{type:"text",text:C,ignored:!0}]};if(D?.agent)E.agent=D.agent;if(D?.model)E.model=D.model;if(D?.variant)E.variant=D.variant;await R.promptAsync({path:{id:O},body:E});return}}return{async dispose(){B.stop();for(let O of z)O.close();if(z.length=0,U){await U.stop().catch(()=>{});let O=globalThis;if(O.__openaiAuthRpcServer===U)O.__openaiAuthRpcServer=void 0;U=null}},async event(O){if(O.event.type!=="session.deleted")return;let C=O.event.properties.info,R=G.get(C.id);if(R)L?.cacheKeepManager?.remove(R.threadID);if(G.delete(C.id))$();if(H){let D=(await O0(H0(s())))?.accounts;await XK(C.id,D,H)}for(let D of z)D.remove(C.id)},provider:{id:"openai",async models(O,C){if(C.auth?.type!=="oauth")return O.models;let R=await O0(H0(s())),D=!R||d4(R),E=D?null:await vJ();if(!D&&E&&!k4)k4=!0,S4.debug("restoring OAuth model costs from models.dev catalog");if(!D&&!E&&!x4)x4=!0,S4.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(O.models).filter(([,T])=>{if(T.options.reasoningMode==="pro")return!1;if(CV.has(T.api.id))return!0;if(IV.has(T.api.id))return!1;let u=T.api.id.match(/^gpt-(\d+(?:\.\d+)?)/)?.[1];return u?parseFloat(u)>5.4:!1}).map(([T,g])=>[T,{...g,cost:D?{input:0,output:0,cache:{read:0,write:0}}:E?.[g.api.id]??E?.[T]??g.cost,limit:g.id.includes("gpt-5.5")?{context:400000,input:272000,output:128000}:g.id.includes("gpt-6-astra")?{context:872000,input:744000,output:128000}:g.id.includes("gpt-5.6")?{context:372000,input:244000,output:128000}:g.limit}]))}},tool:{web_search:IJ},auth:{provider:"openai",async loader(O){V=O;let C=await O();if(C.type!=="oauth")return{};await o4({type:"oauth",access:C.access??"",refresh:C.refresh??"",expires:C.expires??0},H0(s()));let R=await O0(H0(s())).catch((N)=>{let F=s();throw Error(`OpenAI auth store at ${F} is corrupt or unreadable: ${N instanceof Error?N.message:String(N)}. Fix or remove it to continue.`,{cause:N})}),D;async function E(){let N=s();try{let F=AV(N);if(D?.path===N&&D.mtimeMs===F.mtimeMs&&D.size===F.size)return D.storage;let M=await O0(H0(N));return D={path:N,mtimeMs:F.mtimeMs,size:F.size,storage:M},M}catch{return D=void 0,O0(H0(N))}}function T(){D=void 0}if(R&&C.access){let N=tY({id_token:"",access_token:C.access,refresh_token:C.refresh??""});if(N&&N!==R.mainAccountId)await B0((F)=>{return F.mainAccountId=N,F},H0(s())),R.mainAccountId=N,T()}let g=R?.logging?.level;if(g&&typeof g==="string")n1(g);let u=D0("transport"),l=D0("quota"),T0=D0("refresh"),Q0=D0("accounts");u.info("codex auth loader ready",{codexApiEndpoint:J,transport:C0().rawWebSocket?"raw-websocket":C0().webSockets?"websocket":"http",webSearch:C0().webSearch});let c=new i1({storage:R,configPath:s(),fetchQuotaFn:void 0}),S0,PY=0,K0=new n4({paths:H0(s()),refreshFn:(N)=>xY({refreshToken:N.refreshToken,fetchImpl:N.fetchImpl,now:N.now}),quotaManager:c,onFallbackStorageChanged:T});if(R&&R.accounts.length>0)K0.startBackgroundRefresh();let MY=D0("cachekeep"),r0=R?.cachekeep?.enabled===!0,w=R?.cachekeep?.subagents===!0,p=R?.cachekeep?.sustain===!0,f=HJ(R),U0;async function u0(N){await new Promise((F)=>setTimeout(F,N))}async function $0(N){let F;for(let M=1;M<=I4;M++)try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:N.refresh,access:N.access,expires:N.expires}});return}catch(S){if(F=S,M<I4)await u0(fV*M)}throw new L8(F)}async function WY(N){await B0((F)=>{return F.refresh=F.refresh??{},N(F),F},H0(s())),T()}async function n(N){let F=Date.now()+yV;while(Date.now()<F){await new Promise((v)=>setTimeout(v,C4+lV(C4)));let M=await O();if(M.type!=="oauth"||!M.access)continue;if((M.access!==N.access||M.refresh!==N.refresh||(M.expires??0)>(N.expires??0)+60000)&&(!M.expires||M.expires>Date.now()))return T0.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:M.expires?M.expires-Date.now():void 0}),{access:M.access,refresh:M.refresh??N.refresh??"",expires:M.expires??0}}return null}async function R0(){if(!U0)U0=(async()=>{let N=await O();if(N.type!=="oauth")throw Error("not oauth");if(!N.refresh)throw Error("Token refresh failed: missing refresh token");let F=m4(N.refresh),M=await O0(H0(s())),S=M?.refresh?.mainLastRefreshError;if(S&&p1(S,N.refresh,Date.now()))throw Error(u4(S,Date.now()));if(M?.refresh?.mainRefreshLeaseUntil&&M.refresh.mainRefreshLeaseUntil>Date.now()&&M.refresh.mainRefreshLeaseTokenHash===F){let b=await n(N);if(b)return b;throw Error("Codex OAuth refresh is already in progress")}let v=await r1({name:vV,ttlMs:hV,path:s(),renew:!0});if(!v){let b=await n(N);if(b)return b;throw Error("Codex OAuth refresh is already in progress")}let x=crypto.randomUUID(),I=F;try{await WY((m)=>{m.refresh=m.refresh??{},m.refresh.mainRefreshLeaseId=x,m.refresh.mainRefreshLeaseUntil=Date.now()+gV,m.refresh.mainRefreshLeaseTokenHash=F});let b=await O0(H0(s()));if(b?.refresh?.mainRefreshLeaseId!==x||b.refresh.mainRefreshLeaseTokenHash!==F)throw Error("Codex OAuth refresh is already in progress");let A=await xY({refreshToken:N.refresh,fetchImpl:fetch,now:Date.now});return await $0(A),await WY((m)=>{if(m.refresh=m.refresh??{},m.refresh.mainLastRefreshError=void 0,m.refresh.mainRefreshLeaseId===x)m.refresh.mainRefreshLeaseId=void 0,m.refresh.mainRefreshLeaseUntil=void 0,m.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),I=void 0,A}catch(b){if(N.refresh&&!W8(b))await WY((A)=>{A.refresh=A.refresh??{},A.refresh.mainLastRefreshError=c4({error:b,now:Date.now(),refreshToken:N.refresh??"",previous:A.refresh.mainLastRefreshError})}).catch(()=>{});throw b}finally{if(I)await WY((b)=>{if(b.refresh?.mainRefreshLeaseId===x&&b.refresh.mainRefreshLeaseTokenHash===I)b.refresh.mainRefreshLeaseId=void 0,b.refresh.mainRefreshLeaseUntil=void 0,b.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await v.release().catch(()=>{})}})().finally(()=>{U0=void 0});return U0}let bY=globalThis;bY.__openaiAuthCacheKeepManager?.stop();let KY=new c9({fetchImpl:fetch,getMainToken:async()=>{let N=await O();if(N.type!=="oauth")throw Error("not oauth");if(!N.access||(N.expires??0)<Date.now())try{return(await R0()).access}catch(F){if(W8(F))throw F;if(N.access)return N.access;throw Error("main token refresh failed")}return N.access},refreshFallback:async(N)=>{let F=await E(),M=F?eV(F.accounts,N):void 0;if(!M)throw Error(`fallback account ${N} not found`);let S=await K0.refreshAccount(M,F??{version:1,accounts:[M]});if(!S.access)throw Error(`no access token for ${N}`);return S.access},codexResponsesUrl:J,logger:MY,now:Date.now,getWindow:()=>f,getSustain:()=>p});bY.__openaiAuthCacheKeepManager=KY;async function s0(N,F,M,S,v=!1){if(Object.keys(N).length===0&&!v)return;let x=Date.now(),I=N,b={quota:I,refreshAfter:x+300000,checkedAt:x},A;if(M&&M!=="main"){let h=F?oY(F):null,G0=h?nY(h):void 0,M0=c.peekFallbackForPolicy(M)?.quota,d0=g4(I,M0);b={...b,quota:d0},c.setFallback(M,b,F,v,G0)}else{if(A=S,!A&&F){let M0=oY(F);A=M0?nY(M0):void 0}if(A&&S0&&A!==S0){l.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:A,currentMainIdentity:S0});return}let h=c.peekMainForPolicy(A)?.quota,G0=g4(I,h);b={...b,quota:G0},c.setMain(F,b,A,v)}l.debug("quota pushed",{pid:process.pid,accountId:M??"main",snapshot:b.quota});let m=await E();await p0(c,m,M&&M!=="main"?m?.mainAccountId:A)}function I9(N,F,M){let S=N==="main"?c.peekMainForPolicy()?.quota:c.peekFallbackForPolicy(N)?.quota;return l4(S,F,Date.now(),mV,M)}let zY=X.experimentalWebSockets?jY.createWebSocketFetch({httpFetch:fetch,rawWebSocket:C0().rawWebSocket,onQuota:(N,F,M,S)=>{s0(N,F,M,!M||M==="main"?S:void 0,!0)},onRateLimitReached:(N,F,M)=>{if(!F)l.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:N});let S=F??"main",v=I9(S,N,M);c.markRateLimited(S,v),l.debug("mid-stream rate limit mark",{pid:process.pid,accountId:S,window:N})}}):void 0;if(zY)z.push(zY),W=!0;let X0=r4();H=X0;async function p0(N,F,M=F?.mainAccountId){if(!F)return;await e4(WK(N,F,Date.now(),M),X0)}async function W0(N,F,M,S,v){let x={activeId:M,route:S,updatedAt:Date.now()};if(N){if(await C9({sessionId:N,...x},v,X0),F&&F!==N){if(S==="sticky-balanced"){let I=(await DY(X0)).stickyAssignments?.[k1(F)]?.accountId,b=v===void 0||I==="main"||v.some((A)=>A.enabled!==!1&&A.id===I);if(!I||!b)return;await C9({sessionId:F,activeId:I,route:S,updatedAt:Date.now()},v,X0);return}await C9({sessionId:F,...x},v,X0)}return}await YK(x,X0)}L={accountStoragePath:s(),accountStatePath:u1(s()),packageVersion:aY,quotaManager:c,loadAccounts:O0,client:Y.client,resolveResetTarget:uV({getAuth:O,refreshMainWithLease:R0,refreshFallbackAccount:(N,F)=>K0.refreshAccount(N,F),loadAccounts:O0,accountStoragePath:s(),accountStatePath:u1(s()),now:Date.now}),...pV(),cacheKeepManager:KY,setCacheKeepEnabled:(N)=>{r0=N},setCacheKeepSubagents:(N)=>{w=N},setCacheKeepSustain:(N)=>{p=N},setCacheKeepWindow:(N)=>{f=N},clearStickyRouting:(N)=>QK(N,X0),getStickyRouting:async(N)=>t4(await DY(X0),N),refreshSidebar:async()=>{let N=await O0(H0(s()));await p0(c,N)},refreshAllQuota:async()=>UY({getAuth:O,codexRefreshFn:xY,refreshMainWithLease:R0,fallbackManager:K0,quotaManager:c,loadAccounts:O0,writeSidebarState:p0,client:Y.client,fetchImpl:fetch,now:Date.now,paths:H0(s()),readSidebarState:()=>DY(X0),storageMainAccountId:R?.mainAccountId,isOAuthAccountFn:V0,whamFn:AY}),refreshResetTargetQuota:async(N)=>{return(await UY({getAuth:O,codexRefreshFn:xY,refreshMainWithLease:R0,fallbackManager:K0,quotaManager:c,loadAccounts:O0,writeSidebarState:p0,client:Y.client,fetchImpl:fetch,now:Date.now,paths:H0(s()),readSidebarState:()=>DY(X0),storageMainAccountId:R?.mainAccountId,isOAuthAccountFn:V0,whamFn:AY,respectBackoff:!1},{accountKey:N})).find((M)=>M.account===N)??{account:N,ok:!1,error:"targeted quota refresh returned no result"}}};let l0=null;if(Y.directory){let N=await GK(Y.directory),F=globalThis;if(F.__openaiAuthRpcServer)await F.__openaiAuthRpcServer.stop().catch(()=>{}),F.__openaiAuthRpcServer=void 0;try{l0=await iJ({dir:N.dir,secureDir:N.secureDir,sweepRoot:N.sweepRoot,drain:cJ,apply:async(M)=>{let S={...L,sessionId:M.sessionId},v=await v9(M.command,M.arguments,S);return{text:v.text,knobs:v.knobs}}}),F.__openaiAuthRpcServer=l0,U=l0}catch{}}async function EY(N,F,M,S,v="main"){let x=y4(N,F);if(x.delete("x-api-key"),x.delete("api-key"),x.set("authorization",`Bearer ${M}`),S)x.set("ChatGPT-Account-Id",S);x.set(jY.QUOTA_ACCOUNT_HEADER,v);let I=f4(x),b=I?iV(G,I,$):void 0,A=N instanceof URL?N:new URL(typeof N==="string"?N:N.url),m=A.pathname.includes("/v1/responses")||A.pathname.includes("/chat/completions")?new URL(J):A,G0=tV({init:{...F,headers:x},headers:x,metadata:b,installationID:Q,websocket:Boolean(zY&&A.pathname.endsWith("/responses")),responsesLite:X.responsesLite??!1,dumpSessionID:I}).init,M0=r0,d0=new Headers(G0?.headers),L0=LJ({enabled:M0,includeSubagents:w,headers:d0,body:G0?.body});if(M0)MY.trace("cachekeep headers",{pid:process.pid,hasParent:d0.has("x-parent-session-id"),sessionKey:L0?.sessionKey,captured:Boolean(L0),affinity:d0.get("x-session-affinity"),opencodeSession:d0.get("x-opencode-session"),sessionId:d0.get("session-id")});if(zY&&A.pathname.endsWith("/responses")){if(u.debug("WS transport",{pid:process.pid,pathname:A.pathname,accountId:v}),L0)KY.track(L0.sessionKey,L0.bodyText,v,S,L0.replayHeaders,L0.isSubagent);return zY(m,G0)}let j0=jY.withoutInternalHeaders(G0);if(typeof j0?.body!=="string")return fetch(m,j0);if(L0)KY.track(L0.sessionKey,L0.bodyText,v,S,L0.replayHeaders,L0.isSubagent);u.debug("HTTP transport",{pid:process.pid,pathname:A.pathname,accountId:v});try{let g0=await fetch(m,j0);return await yY({sessionID:I,transport:"http",phase:"http",bodyText:j0.body,accountId:v,url:m.toString(),method:j0.method,headers:j0.headers,status:g0.status}),_J(g0)}catch(g0){throw await yY({sessionID:I,transport:"http",phase:"http",bodyText:j0.body,accountId:v,url:m.toString(),method:j0.method,headers:j0.headers,error:g0 instanceof Error?g0.message:String(g0)}),g0}}function x1(N,F){if((F?.method??(N instanceof Request?N.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof F?.body!=="string")return!1;try{let S=N instanceof URL?N.toString():typeof N==="string"?N:N.url;return new URL(S).pathname.endsWith("/responses")}catch{return!1}}function KK(N){return c.peekMainForPolicy(N)?.quota}function H8(N,F){for(let M of[N?.primary?.checkedAt,N?.secondary?.checkedAt,N?.checkedAt,F])if(typeof M==="number"&&Number.isFinite(M))return M;return}function rY(N,F,M,S,v){let x=H8(N,F),I=H8(M),b=S===v&&M!=null&&(N===void 0||I!==void 0&&(x===void 0||I>x));return{quota:b?M:N,quotaCheckedAt:b?I:x,source:b?"file":"memory"}}function N8(N,F,M,S,v){let x=N?.quota,I=rY(x,N?.checkedAt,F,S,v),b=I.source,A=I.quota;if(!a4(A,M))return{exhausted:!1};let m=s4(A,M);if(!m)return{exhausted:!1};return{exhausted:!0,source:b,...m}}function Z8(N,F){l.debug("admission skip: exhausted account",{accountId:N,source:F.source,resetsAt:F.resetsAt})}function zK(N,F="killswitch",M){let S=Date.now(),v=c.getMain()?.quota,x=(N?.accounts??[]).filter((h)=>h.enabled!==!1&&V0(h)).map((h)=>({accountId:h.id,quota:c.getFallback(h.id)?.quota})),I=i4(v,x,S,N);if(F==="quota-exhausted"&&M!==void 0)I=Math.max(1,Math.ceil((M-S)/1000));else if(F==="mid-stream-rate-limit"&&M!==void 0){let h=Math.max(1,Math.ceil((M-S)/1000));I=Math.min(I,h)}let b=Math.floor(I/60),A=I%60,m=F==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${b}m ${A}s.`:F==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${b}m ${A}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${b}m ${A}s.`;return new Response(JSON.stringify({error:{message:m,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(I)}})}function V8(N){let F=N?.resetCreditsAvailable;return typeof F==="number"&&Number.isFinite(F)?F:void 0}async function UK(N){let F=_1(N.storage),M=Date.now(),S=c.peekMainForPolicy(N.mainAccountIdentity),v=rY(S?.quota,S?.checkedAt,N.sidebarState.main.quota,N.sidebarState.main.mainAccountId,N.mainAccountIdentity),x=F?S1(S?.quota,N.storage,void 0,M):void 0,I=[{accountId:"main",wireAccountId:N.mainAccountIdentity,access:N.primaryAccess,keepwarmAccountKey:"main",quota:v.quota,quotaCheckedAt:v.quotaCheckedAt,reservePercent:K8(N.storage),configuredOrder:0,resetCreditsApplicable:V8(v.quota),killswitchPasses:x}],b=await K0.getUsableFallbackAccounts(N.storage);for(let A of b){if(!A.access)continue;let m=N.sidebarState.fallbacks.find((d0)=>d0.id===A.id),h=c.peekFallbackForPolicy(A.id,A.accountId),G0=rY(h?.quota,h?.checkedAt,m?.quota,m?.accountId,A.accountId),M0=F?S1(h?.quota,N.storage,A.id,M):void 0;I.push({accountId:A.id,wireAccountId:A.accountId,access:A.access,keepwarmAccountKey:A.id,fallback:A,quota:G0.quota,quotaCheckedAt:G0.quotaCheckedAt,reservePercent:K8(N.storage,A.id),configuredOrder:I.length,resetCreditsApplicable:V8(G0.quota),killswitchPasses:M0})}return I}function B8(N,F,M,S,v){let x=_1(v)?N.killswitchPasses:void 0;if(N.accountId==="main"){let m=c.peekMainForPolicy(N.wireAccountId),h=rY(m?.quota,m?.checkedAt,F.main.quota,F.main.mainAccountId,N.wireAccountId);return l9({quota:h.quota,quotaCheckedAt:h.quotaCheckedAt,status:M,now:S,killswitchPasses:x})}let I=F.fallbacks.find((m)=>m.id===N.accountId),b=c.peekFallbackForPolicy(N.accountId,N.wireAccountId),A=rY(b?.quota,b?.checkedAt,I?.quota,I?.accountId,N.wireAccountId);return l9({quota:A.quota,quotaCheckedAt:A.quotaCheckedAt,status:M,now:S,killswitchPasses:x})}function LK(N){return N.accountId==="main"?"main":N.keepwarmAccountKey}function F8(N){return c.isRateLimited(LK(N))}async function _9(N){let F=N.candidates.filter((A)=>!F8(A)),M=new Map(F.map((A)=>[A.accountId,A])),S=Object.fromEntries(F.map((A)=>[A.accountId,A.quotaCheckedAt])),v=Object.fromEntries(F.map((A)=>[A.accountId,A.wireAccountId])),x=new Set(N.excludeAccountIds),I,b=await JK({sessionId:N.sessionId,requestBytes:N.requestBytes,now:N.now,validPinnedAccountIds:[...M.keys()],excludeAccountIds:N.excludeAccountIds,quotaCheckedAtByAccount:S,wireAccountIdByAccount:v,choose:(A)=>{let m=F.filter((G0)=>!x.has(G0.accountId));if(m.length===0)return;let h=qJ({candidates:m,pendingBytes:A,requestBytes:N.requestBytes,now:N.now,onEmptyWeightedSet:()=>{Q0.debug("sticky routing: no fresh weighted candidates; using configured order")}});if(!h)return;return I={accountId:h.accountId,source:h.source,pendingBytes:A.get(h.accountId)??0},h}},X0);if(I&&b?.accountId===I.accountId)Q0.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:k1(N.sessionId),accountId:I.accountId,source:I.source,requestBytes:N.requestBytes,pendingBytes:I.pendingBytes});return b?M.get(b.accountId):void 0}async function HK(N,F){let M=await K0.getUsableFallbackAccounts(N),S=[];for(let h of M)if(h.access)S.push({access:h.access,accountId:h.accountId,keepwarmAccountKey:h.id,quotaAccountId:h.id,fallback:h});let v=S.filter((h)=>!c.isRateLimited(h.quotaAccountId)),x=_1(N)?v.filter((h)=>S1(c.peekFallbackForPolicy(h.quotaAccountId,h.accountId)?.quota,N,h.quotaAccountId,Date.now())):v,I=new Map(F.fallbacks.map((h)=>[h.id,{quota:h.quota,accountId:h.accountId}])),b=[],A=[],m=Date.now();for(let h of x){let G0=I.get(h.quotaAccountId),M0=N8(c.peekFallbackForPolicy(h.quotaAccountId,h.accountId),G0?.quota,m,G0?.accountId,h.accountId);if(M0.exhausted)A.push({candidate:h,decision:M0});else b.push(h)}return{current:x,retained:b,skipped:A}}function O8(N,F){if(N.retained.length===0&&!F)return N.current;for(let{candidate:M,decision:S}of N.skipped)Z8(M.quotaAccountId,S);return N.retained}async function q8(N,F){try{let M=hY(N.headers);await s0(M,F.access,F.quotaAccountId,void 0,C1(N.headers))}catch{}}async function NK(N,F,M,S){for(let v of S){let x;try{x=await EY(N,F,v.access,v.accountId,v.keepwarmAccountKey)}catch(I){if(I instanceof DOMException&&I.name==="AbortError")throw I;if(F?.signal?.aborted)throw I;throw Q0.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:v.quotaAccountId}),I}if(!I1(x.status,M))return K0.markUsed(v.fallback),{response:x,accessToken:v.access,quotaAccountId:v.quotaAccountId,activeId:v.keepwarmAccountKey};await q8(x,v),x.body?.cancel().catch(()=>{})}return}async function ZK(N,F,M,S,v){if(!x1(N,F))return{response:M};if(!v.length)return{response:M};let x=M,I;for(let b of v){let A;try{A=await EY(N,F,b.access,b.accountId,b.keepwarmAccountKey)}catch(m){if(m instanceof DOMException&&m.name==="AbortError")throw m;if(F?.signal?.aborted)throw m;return Q0.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:b.quotaAccountId}),{response:x,...I}}if(x.body?.cancel().catch(()=>{}),x=A,I={accessToken:b.access,accountId:b.quotaAccountId},!I1(A.status,S))return K0.markUsed(b.fallback),{response:A,...I};await q8(A,b)}return{response:x,...I}}if(!_4){if(_4=!0,R){let N=[];for(let F of R.accounts)if(V0(F))N.push(F);c.seedFallbacksFromAccounts(N)}p0(c,R).catch(()=>{}),UY({getAuth:O,codexRefreshFn:xY,refreshMainWithLease:R0,fallbackManager:K0,quotaManager:c,loadAccounts:O0,writeSidebarState:p0,client:Y.client,fetchImpl:fetch,now:Date.now,paths:H0(s()),readSidebarState:()=>DY(X0),storageMainAccountId:R?.mainAccountId,isOAuthAccountFn:V0,whamFn:AY,respectBackoff:!0}).catch((N)=>l.warn("boot quota seed failed",{pid:process.pid,error:T1(N)}))}return B.start(async()=>{let F=(await $J({getAuth:O,codexRefreshFn:xY,refreshMainWithLease:R0,fallbackManager:K0,quotaManager:c,loadAccounts:O0,writeSidebarState:(M,S)=>B.isStopped()?Promise.resolve():p0(M,S),client:Y.client,fetchImpl:fetch,now:Date.now,paths:H0(s()),storageMainAccountId:R?.mainAccountId,isOAuthAccountFn:V0,whamFn:AY,readSidebarState:()=>DY(X0)})).filter((M)=>!M.ok);if(F.length>0)l.warn("background quota refresh completed with failures",{pid:process.pid,failures:F})},(N)=>{l.warn("background quota refresh failed",{pid:process.pid,error:N instanceof Error?N.message:String(N)})}),{apiKey:SV,async fetch(N,F){let M=y4(N,F),S=f4(M),v=M.get("x-parent-session-id")?.trim()||void 0,x=await E(),I=await O(),b=++PY;if(I.type!=="oauth")return fetch(N,F);F=await YB(N,F);let A=I.access??"";if(!I.access||(I.expires??0)<Date.now()){T0.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(I.access),expiresInMs:I.expires?I.expires-Date.now():void 0});try{let J0=await R0();I.access=J0.access,I.refresh=J0.refresh,I.expires=J0.expires}catch(J0){if(W8(J0))throw J0}}A=I.access??"";let h=I.accountId??(A?nY(oY(A)??{}):void 0);if(b===PY)S0=h;let G0=x?.routing?.mode??"main-first",M0,L0=await(()=>{return M0??=DY(X0),M0})();if(G0==="sticky-balanced"&&S&&x1(N,F)&&typeof F?.body==="string"){let J0=Buffer.byteLength(F.body,"utf8"),F0=await UK({storage:x,sidebarState:L0,primaryAccess:A,mainAccountIdentity:h}),Z0=await _9({sessionId:S,requestBytes:J0,candidates:F0,now:Date.now()});if(Z0){let A8=F8(Z0)?{action:"migrate",reason:"exhausted"}:B8(Z0,L0,void 0,Date.now(),x);if(A8.action==="migrate"){let k0=await _9({sessionId:S,requestBytes:J0,candidates:F0,excludeAccountIds:[Z0.accountId],now:Date.now()});if(k0)Q0.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:k1(S),fromAccountId:Z0.accountId,toAccountId:k0.accountId,reason:A8.reason}),Z0=k0}let i0=await EY(N,F,Z0.access,Z0.wireAccountId,Z0.keepwarmAccountKey),T8=async(k0,wY)=>{try{let VK=hY(k0.headers);await s0(VK,wY.access,wY.accountId==="main"?void 0:wY.accountId,wY.accountId==="main"?wY.wireAccountId:void 0,C1(k0.headers))}catch{}};await T8(i0,Z0);let R8=B8(Z0,L0,i0.status,Date.now(),x);if((i0.status===401||i0.status===403||i0.status===429)&&R8.action==="migrate"){let k0=await _9({sessionId:S,requestBytes:J0,candidates:F0,excludeAccountIds:[Z0.accountId],now:Date.now()});if(k0){Q0.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:k1(S),fromAccountId:Z0.accountId,toAccountId:k0.accountId,reason:R8.reason});let wY=i0;i0=await EY(N,F,k0.access,k0.wireAccountId,k0.keepwarmAccountKey),wY.body?.cancel().catch(()=>{}),Z0=k0,await T8(i0,Z0)}}if(Z0.fallback&&!I1(i0.status,x))K0.markUsed(Z0.fallback);return await W0(S,v,Z0.accountId,G0,x?.accounts).catch(()=>{}),i0}}let j0=N8(c.peekMainForPolicy(h),L0.main.quota,Date.now(),L0.main.mainAccountId,h),g0=_1(x)&&!S1(KK(h),x,void 0,Date.now()),b1=c.isRateLimited("main"),j8,S9=()=>{return j8??=HK(x,L0),j8},a0,vY,D8=!1,v1;if(G0==="fallback-first"&&x1(N,F)){D8=!0;let J0=await S9();v1=O8(J0,!g0&&!b1&&!j0.exhausted);let F0=await NK(N,F,x,v1);if(F0)a0=F0.response,vY={accessToken:F0.accessToken,accountId:F0.quotaAccountId,activeId:F0.activeId}}if(!a0){let J0=j0.exhausted&&x1(N,F)&&(await S9()).retained.length>0;if(g0||b1||J0){let F0=g0?"killswitch":b1?"mid-stream-rate-limit":"quota-exhausted";if(F0==="quota-exhausted"&&j0.exhausted)Z8("main",j0);Q0.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:F0}),a0=zK(x,F0,F0==="quota-exhausted"&&j0.exhausted?j0.resetAtMs:b1?c.rateLimitedUntil("main"):void 0)}else a0=await EY(N,F,A,h,"main")}let P8=Boolean(vY),sY=a0,M8=vY?.accessToken??A,E8=vY?.accountId,w8=vY?.activeId??"main";if(!vY&&!D8&&I1(a0.status,x)){Q0.debug("reactive fallback triggered",{pid:process.pid,status:a0.status}),v1??=O8(await S9(),!1);let J0=await ZK(N,F,a0,x,v1),F0=J0.response;if(F0!==a0){if(P8=!0,sY=F0,M8=J0.accessToken??A,E8=J0.accountId,J0.accountId)w8=J0.accountId}}try{let J0=hY(sY.headers);if(P8)await s0(J0,M8,E8,void 0,C1(sY.headers));else await s0(J0,A,void 0,h,C1(sY.headers))}catch{}return await W0(S,v,w8,G0,x?.accounts).catch(()=>{}),sY},async dispose(){if(B.stop(),KY.stop(),bY.__openaiAuthCacheKeepManager===KY)bY.__openaiAuthCacheKeepManager=void 0;if(K0.stopBackgroundRefresh(),U){await U.stop().catch(()=>{});let N=globalThis;if(N.__openaiAuthRpcServer===U)N.__openaiAuthRpcServer=void 0;U=null}}}},methods:Z},"chat.headers":async(O,C)=>{if(O.model.providerID!=="openai")return;if(C.headers.originator="opencode",C.headers["User-Agent"]=`${p4(aY)} (${$8.platform()} ${$8.release()}; ${$8.arch()})`,C.headers["session-id"]=O.sessionID,W&&O.agent==="title")C.headers[jY.TITLE_HEADER]="true"},"chat.params":async(O,C)=>{if(O.model.providerID!=="openai")return;C.maxOutputTokens=void 0},config:async(O)=>{O.command={...O.command??{},[eY]:{template:eY,description:"Show current OpenAI Codex OAuth quota usage for all accounts."},[Y1]:{template:Y1,description:"Manage OpenAI accounts — add, switch, remove, or reorder."},[X1]:{template:X1,description:"Show or change OpenAI account routing between main-first, fallback-first, and sticky-balanced."},[J1]:{template:J1,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."},[Q1]:{template:Q1,description:"Show or toggle OpenAI Codex request dump capture for debugging."},[G1]:{template:G1,description:"Show or change the plugin log level (error, warn, info, debug, trace)."},[$1]:{template:$1,description:"Keep Codex prompt cache alive during idle by shadow-replaying the last request."},[W1]:{template:W1,description:"Spend one reset credit on an exhausted Codex account."}}},"command.execute.before":async(O)=>{if(!o1.includes(O.command))return;if(!L)await j(O.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),v4();let C=O.command,R={...L,sessionId:O.sessionID,notify:(E)=>{XX(E,O.sessionID)}},D=await v9(C,O.arguments,R);if(uJ(O.sessionID))XX(D,O.sessionID);else await j(O.sessionID,D.text);v4()}}}var UB=async(Y)=>{let X=C0();return zB(Y,{codexApiEndpoint:X.codexApiEndpoint,experimentalWebSockets:X.webSockets,responsesLite:X.responsesLite})},rD={id:"cortexkit-openai-auth",server:UB};export{f4 as resolveSidebarSessionId,oY as parseJwtClaims,g4 as mergePushedQuotaMetadata,eV as findCachekeepFallbackAccount,nY as extractAccountIdFromClaims,rD as default,uV as createResetTargetResolver,nD as buildSidebarState,WK as buildSidebarMachineState,pV as buildResetRedemptionDeps,n0 as ResetTargetResolutionError,UB as OpenAIAuthPlugin,hV as MAIN_REFRESH_LOCK_TTL_MS,gV as MAIN_REFRESH_LEASE_TTL_MS,zB as CodexAuthPlugin,L8 as AuthPersistError};