@cortexkit/opencode-openai-auth 0.7.2 → 0.9.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 (118) hide show
  1. package/README.md +9 -5
  2. package/dist/index-301y4qa1.js +2 -0
  3. package/dist/index-338z7171.js +211 -0
  4. package/dist/index-5y4vzdf8.js +2 -0
  5. package/dist/{index-zxqb5ydj.js → index-9ehhb051.js} +1 -1
  6. package/dist/{index-zg1x8sty.js → index-jwn4r3sw.js} +1 -1
  7. package/dist/{index-9jpc8yct.js → index-sdt2d2ra.js} +1 -1
  8. package/dist/index-w42s0g6m.js +2 -0
  9. package/dist/index.d.ts +213 -36
  10. package/dist/index.js +59 -154
  11. package/dist/internal-Y7QNVDJT.d.ts +908 -0
  12. package/dist/quota-normalize-3qffywcm.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 +7 -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-B98sERYt.d.ts +219 -0
  21. package/dist/sidebar-state.d.ts +2 -171
  22. package/dist/sidebar-state.js +1 -1
  23. package/dist/{token-bvp0y166.js → token-9823y0pc.js} +1 -1
  24. package/dist/token-util-ypgz7rge.js +1 -0
  25. package/dist/tui-preferences.d.ts +27 -26
  26. package/dist/tui-preferences.js +1 -1
  27. package/dist/tui.d.ts +42 -19
  28. package/package.json +8 -14
  29. package/src/tui/entry.mjs +2 -2
  30. package/src/tui-compiled/{core/account-paths.ts → raw/core-account-paths.ts} +29 -18
  31. package/src/tui-compiled/raw/core-custody-state.ts +243 -0
  32. package/src/tui-compiled/raw/logger.ts +53 -0
  33. package/src/tui-compiled/{rpc/port-file.ts → raw/rpc-port-file.ts} +1 -1
  34. package/src/tui-compiled/raw/rpc-protocol.ts +12 -0
  35. package/src/{rpc/rpc-client.ts → tui-compiled/raw/rpc-rpc-client.ts} +2 -2
  36. package/src/{sidebar-state.ts → tui-compiled/raw/sidebar-state.ts} +142 -13
  37. package/src/{tui/command-dialogs.tsx → tui-compiled/raw/tui-command-dialogs.tsx} +94 -44
  38. package/src/{tui.tsx → tui-compiled/raw/tui.tsx} +149 -28
  39. package/src/{core/account-paths.ts → tui-compiled/runtime/core-account-paths.ts} +29 -18
  40. package/src/tui-compiled/runtime/core-custody-state.ts +243 -0
  41. package/src/tui-compiled/runtime/logger.ts +53 -0
  42. package/src/{rpc/port-file.ts → tui-compiled/runtime/rpc-port-file.ts} +1 -1
  43. package/src/tui-compiled/runtime/rpc-protocol.ts +12 -0
  44. package/src/tui-compiled/{rpc/rpc-client.ts → runtime/rpc-rpc-client.ts} +2 -2
  45. package/src/tui-compiled/{sidebar-state.ts → runtime/sidebar-state.ts} +142 -13
  46. package/src/tui-compiled/{tui/command-dialogs.tsx → runtime/tui-command-dialogs.tsx} +73 -37
  47. package/src/tui-compiled/{tui.tsx → runtime/tui.tsx} +251 -153
  48. package/src/tui-compiled/shared/internal.ts +6 -0
  49. package/src/{logger.ts → tui-compiled/shared/logger.ts} +91 -23
  50. package/src/tui-compiled/shared/paths.ts +33 -0
  51. package/src/{core → tui-compiled/shared}/refresh-file-lock.ts +7 -4
  52. package/dist/cli.d.ts +0 -2
  53. package/dist/cli.js +0 -15
  54. package/dist/codex-http.d.ts +0 -3
  55. package/dist/commands.d.ts +0 -88
  56. package/dist/config.d.ts +0 -47
  57. package/dist/core/account-paths.d.ts +0 -25
  58. package/dist/core/accounts.d.ts +0 -330
  59. package/dist/core/atomic-write.d.ts +0 -1
  60. package/dist/core/background-quota-refresh.d.ts +0 -46
  61. package/dist/core/backoff.d.ts +0 -53
  62. package/dist/core/cachekeep.d.ts +0 -118
  63. package/dist/core/oauth.d.ts +0 -138
  64. package/dist/core/provider.d.ts +0 -70
  65. package/dist/core/quota-manager.d.ts +0 -192
  66. package/dist/core/refresh-all-quota.d.ts +0 -86
  67. package/dist/core/refresh-file-lock.d.ts +0 -12
  68. package/dist/core/reset-credits.d.ts +0 -116
  69. package/dist/core/sticky-routing.d.ts +0 -43
  70. package/dist/dump.d.ts +0 -20
  71. package/dist/hosted-web-search.d.ts +0 -5
  72. package/dist/index-87145jkw.js +0 -2
  73. package/dist/index-8f1200qx.js +0 -6
  74. package/dist/index-cfjed1st.js +0 -89
  75. package/dist/index-nrvjr97q.js +0 -3
  76. package/dist/index-qaggaze1.js +0 -2
  77. package/dist/index-sdcpzbnk.js +0 -2
  78. package/dist/logger.d.ts +0 -22
  79. package/dist/model-costs.d.ts +0 -29
  80. package/dist/prompt-context.d.ts +0 -19
  81. package/dist/quota-normalize-dvwtmy7f.js +0 -1
  82. package/dist/quota-normalize.d.ts +0 -43
  83. package/dist/raw-ws-bun.d.ts +0 -40
  84. package/dist/raw-ws-node.d.ts +0 -37
  85. package/dist/raw-ws-upgrade.d.ts +0 -2
  86. package/dist/raw-ws.d.ts +0 -3
  87. package/dist/response-stream-error.d.ts +0 -12
  88. package/dist/rpc/notifications.d.ts +0 -5
  89. package/dist/rpc/rpc-server.d.ts +0 -17
  90. package/dist/token-util-jcj7k7pa.js +0 -1
  91. package/dist/tui/command-dialogs.d.ts +0 -21
  92. package/dist/util/error.d.ts +0 -1
  93. package/dist/util/open-url.d.ts +0 -6
  94. package/dist/util/proxy-env.d.ts +0 -4
  95. package/dist/util/record.d.ts +0 -1
  96. package/dist/util/stable-json.d.ts +0 -1
  97. package/dist/util/uuid-v7.d.ts +0 -1
  98. package/dist/version.d.ts +0 -1
  99. package/dist/ws-pool.d.ts +0 -57
  100. package/dist/ws.d.ts +0 -71
  101. package/src/rpc/notifications.ts +0 -54
  102. package/src/rpc/protocol.ts +0 -33
  103. package/src/rpc/rpc-server.ts +0 -172
  104. package/src/tui-compiled/core/refresh-file-lock.ts +0 -381
  105. package/src/tui-compiled/logger.ts +0 -196
  106. package/src/tui-compiled/rpc/protocol.ts +0 -33
  107. package/src/util/error.ts +0 -9
  108. package/src/util/open-url.ts +0 -30
  109. package/src/util/proxy-env.ts +0 -42
  110. package/src/util/record.ts +0 -3
  111. package/src/util/stable-json.ts +0 -15
  112. package/src/util/uuid-v7.ts +0 -18
  113. /package/src/{rpc/rpc-dir.ts → tui-compiled/raw/rpc-rpc-dir.ts} +0 -0
  114. /package/src/tui-compiled/{tui-preferences.ts → raw/tui-preferences.ts} +0 -0
  115. /package/src/tui-compiled/{rpc/rpc-dir.ts → runtime/rpc-rpc-dir.ts} +0 -0
  116. /package/src/{tui-preferences.ts → tui-compiled/runtime/tui-preferences.ts} +0 -0
  117. /package/src/tui-compiled/{util → shared/util}/error.ts +0 -0
  118. /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 f1,e as PY,f as $4}from"./index-87145jkw.js";import{A as X1,B as b1,C as L1,D as r4,E as s4,F as r0,G as a4,H as A1,I as i0,J as Y8,K as D0,L as Q0,M as MY,N as EY,O as NJ,P as wY,Q as t4,R as e4,S as Yz,h as y4,i as f4,j as hY,k as gY,l as m4,m as c4,n as u4,o as s1,p as a1,q as O9,s as p4,t as l4,u as d4,v as i4,w as n4,x as o4,y as tJ,z as eJ}from"./index-cfjed1st.js";import{$ as R1,U as i9,X as AY,Y as Xz,da as Jz,ea as Qz,fa as $z,ka as Gz,la as j9,ma as Wz,na as zz,oa as Uz,pa as Lz}from"./index-sdcpzbnk.js";import{wa as yY}from"./index-8f1200qx.js";import{xa as u8,ya as p8}from"./index-qaggaze1.js";import{Aa as vY,Ba as t9,Ca as q8,Da as H0}from"./index-nrvjr97q.js";import{Ga as Hz}from"./index-zg1x8sty.js";import{Ja as LX}from"./index-zxqb5ydj.js";import{mkdirSync as kK,readFileSync as xK,renameSync as bK,statSync as vK,writeFileSync as hK}from"node:fs";import LJ from"node:os";import{join as gK}from"node:path";import{readFileSync as Dz}from"node:fs";import{homedir as Pz,tmpdir as Mz}from"node:os";import{join as _Y}from"node:path";var Ez="https://chatgpt.com/backend-api/codex/responses",wz="openai-auth.json",Y1={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 SY(){let Y=process.env[Y1.configDir]?.trim();if(Y)return Y;return _Y(process.env.XDG_CONFIG_HOME||_Y(Pz(),".config"),"opencode")}function $0(){return process.env[Y1.configFile]?.trim()||_Y(SY(),wz)}function Az(){try{let Y=JSON.parse(Dz($0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function kJ(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 CY(Y,X,J){let Q=kJ(Y);if(Q!==void 0)return Q;if(typeof X==="boolean")return X;return J}function Tz(){let Y=Az(),X=kJ(Y1.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:CY(Y1.webSockets,Y.webSockets,!1),rawWebSocket:CY(Y1.rawWebSocket,Y.rawWebSocket,!1),responsesLite:CY(Y1.responsesLite,Y.responsesLite,!1),dump:CY(Y1.dump,Q,!1),dumpDir:process.env[Y1.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():_Y(Mz(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[Y1.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():Ez)}}var IY;function E0(){if(!IY)IY=Tz();return IY}function E9(){return IY=void 0,E0()}var w9="/backend-api/wham/rate-limit-reset-credits",Rz=`https://chatgpt.com${w9}`,gJ=`${w9}/consume`,Cz=`https://chatgpt.com${gJ}`,Iz=300000,_z=60000,Sz=15000,kz=60000;class h0 extends Error{kind;cooldownUntil;constructor(Y,X,J){super(X);this.name="ResetRedemptionError",this.kind=Y,this.cooldownUntil=J}}class w1 extends Error{kind;status;constructor(Y,X,J){super(X);this.name="ResetCreditError",this.kind=Y,this.status=J}}function yJ(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 kY(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}function fJ(Y){if(!Y)return;return{...Y.inFlight?{inFlight:{...Y.inFlight}}:{},...Y.lastOutcome?{lastOutcome:{...Y.lastOutcome}}:{},...Y.cooldownUntil!==void 0?{cooldownUntil:Y.cooldownUntil}:{}}}function A9(Y){if(!kY(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 mJ(Y){return Boolean(Y&&Object.hasOwn(Y,"inFlight"))}function cJ(Y,X){return X-Y.startedAt<Iz}function xY(Y,X){if(!i0(X))return;return Y.reset?.[X]}function uJ(Y){if(!Y.reset)Y.reset=Object.create(null);return Y.reset}function pJ(Y,X,J){if(!i0(X))return;let Q=uJ(Y),$=Q[X]??{},G=$.lastOutcome;delete $.inFlight,$.lastOutcome={code:"ambiguous_local",at:J,...G?{previousOutcome:{code:G.code,at:G.at}}:{}},Q[X]=$}function lJ(Y,X){let J=fJ(Y),Q=A9(Y?.inFlight);if(mJ(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&&cJ(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 xz(Y,X){if(!i0(X))return{kind:"fresh",beforeState:void 0};let J=await Y.loadAccountsFn(Y.configPath);return lJ(J?xY(J,X):void 0,Y.now())}async function bz(Y,X){let J;if(await Y.mutateAccountsFn((Q)=>{let $=Y.now(),G=xY(Q,X);if(J=lJ(G,$),J.kind==="corrupt")pJ(Q,X,$);return Q},Y.configPath),!J)throw Error("corrupt reset state mutation did not run");return J}async function vz(Y,X,J){if(!i0(X))return{kind:"fresh",beforeState:void 0};let Q;if(await Y.mutateAccountsFn(($)=>{let G=Y.now(),W=xY($,X),U=fJ(W),H=A9(W?.inFlight);if(mJ(W)&&!H)return pJ($,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&&cJ(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=uJ($);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 hz(Y,X,J,Q){if(!i0(X))return;if(!C9(Q.kind))return;await Y.mutateAccountsFn(($)=>{let G=xY($,X),W=A9(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+kz;else delete G.cooldownUntil;return $},Y.configPath)}function YY(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 T9(Y,X,J){if(!(X||YY(Y.primary,J)||YY(Y.secondary,J)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function xJ(Y,X){let J=Y[X];if(J===void 0||J===null)return;return typeof J==="string"?J:null}function gz(Y){if(!kY(Y))return;let X=xJ(Y,"granted_at"),J=xJ(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 R9(Y,X,J){let Q;try{Q=await Y(Rz,{method:"GET",headers:yJ(X,w9,J),signal:AbortSignal.timeout(Sz)})}catch{throw new w1("http_error","reset credit list request failed")}if(!Q.ok)throw new w1("http_error",`reset credit list request failed: ${Q.status}`,Q.status);let $;try{$=await Q.json()}catch{throw new w1("invalid_response","reset credit list response was not valid JSON",Q.status)}if(!kY($))throw new w1("invalid_response","reset credit list response was not an object",Q.status);return{credits:(Array.isArray($.credits)?$.credits:[]).flatMap((W)=>{let U=gz(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(dJ).sort((X,J)=>Date.parse(X.expiresAt)-Date.parse(J.expiresAt))[0]}function dJ(Y){return Y.status==="available"&&Y.isSupportedByPlan&&Y.resetType==="codex_rate_limits"}function iJ(Y){return Y.filter(dJ).length}function C9(Y){return Y==="reset"||Y==="already_redeemed"||Y==="nothing_to_reset"||Y==="no_credit"}async function yz(Y,X,J,Q,$){let G;try{G=await Y(Cz,{method:"POST",headers:{...yJ(X,gJ,J),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:$,credit_id:Q}),signal:AbortSignal.timeout(_z)})}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||!kY(U)||!C9(U.code))return{kind:"ambiguous",raw:U};return{kind:U.code,raw:U}}function bJ(Y){if(Y.kind==="cooldown")throw new h0("cooldown_active","reset credit redemption is cooling down",Y.cooldownUntil);throw Error(`unexpected reset state decision: ${Y.kind}`)}function vJ(){throw new h0("expired_unreconciled","the previous reset attempt outcome is unknown")}function hJ(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 fz(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 nJ(Y,X){if(!i0(X.accountKey))throw new h0("invalid_account_key","the reset account key is reserved");let J=await Y.resolveTarget(X.accountKey);if(J.chatgptAccountId!==X.expectedChatgptAccountId)throw new h0("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let Q=J.accountKey==="main"?void 0:J.chatgptAccountId,$=await xz(Y,X.accountKey);if($.kind==="corrupt"){if($=await bz(Y,X.accountKey),$.kind==="corrupt")return hJ(J,$.beforeState)}if($.kind==="cooldown")bJ($);let G;if($.kind==="claim")G=$.claim;else if($.kind==="expired_unreconciled"){if(!X.retry)vJ();G=$.claim}else{if(X.retry)throw new h0("retry_without_inflight","there is no active reset credit redemption to retry");let[H,L]=await Promise.all([Y.fetchUsage(J),R9(Y.fetchImpl,J.accessToken,Q)]),V=T9(H,Y.hasActiveRateLimitMark(X.accountKey),Y.now());if(!V.ok)throw new h0("not_exhausted",V.reason);if(!bY(L.credits))throw new h0("no_eligible_credit","no eligible reset credit was returned");let B=await vz(Y,X.accountKey,L.credits);if(B.kind==="corrupt")return hJ(J,B.beforeState);if(B.kind==="cooldown")bJ(B);if(B.kind==="expired_unreconciled")vJ();if(B.kind!=="claim")throw new h0("no_eligible_credit","no eligible reset credit was available while claiming");G=B.claim}let W=await yz(Y.fetchImpl,J.accessToken,Q,G.inFlight.creditId,G.inFlight.redeemRequestId),U=!1;try{await hz(Y,X.accountKey,G.inFlight,W)}catch{U=C9(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.":fz(W),...U?{finalizeStateWriteFailed:!0}:{}}}function R(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var S9="openai-quota",k9="openai-account",x9="openai-routing",b9="openai-killswitch",v9="openai-dump",h9="openai-logging",g9="openai-cachekeep",T1="openai-reset",X8=["openai-quota","openai-account","openai-routing","openai-killswitch","openai-dump","openai-logging","openai-cachekeep","openai-reset"],i=H0("commands");function oJ(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 mz=900000;function rJ(Y,X){if(typeof Y!=="number"||!Number.isFinite(Y))return" (age unknown)";let J=X-Y;if(J<mz)return"";let Q=Math.floor(J/3600000);if(Q>=24)return` (${Math.floor(Q/24)}d old)`;if(Q>=1)return` (${Q}h old)`;return` (${Math.floor(J/60000)}m old)`}async function cz(Y){let X=await Y.refreshAllQuota?.(),J=Y.quotaManager.getMain(),Q=Date.now(),$=["## OpenAI Quota",""];if(J?.quota){let U=J.quota;$.push("### Main account");for(let 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)${rJ(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)${rJ(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 g1(Y){return{id:Y.id,type:Y.type??"oauth",enabled:Y.enabled,label:Y.label}}async function uz(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(g1)}}}if(J[0]==="remove"&&J[1]){let G=J[1],W=await Y8(X.accountStoragePath),U=W?W.has(G):!1,H=!1,L=await Q0((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(g1)}};return i.info("account removed",{id:G}),X.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Account Removed
6
-
7
- Removed account \`${G}\`.`,knobs:{accounts:L.accounts.map(g1)}}}if(J[0]==="order"&&J.length>=3){let G=!1,W=await Q0((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(g1)}};return i.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(g1)}}}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 eJ({label:U,headless:G}),B=X.notify,K=X.sessionId;if(V.then(async(N)=>{let F=!1;if(await Q0((q)=>{if(N.accountId&&q.mainAccountId&&N.accountId===q.mainAccountId)return F=!0,q;return tJ(q.accounts,N),q},X.accountStoragePath),F){i.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}i.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 F=N instanceof Error?N.message:String(N??"unknown error");i.warn("account add failed",{error:F,sessionId:K}),B?.({command:"openai-account",text:`## Add Failed
18
-
19
- Account add failed: ${F}`,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(g1)}}}async function pz(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),i.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 Q0((H)=>{return H.routing={...H.routing??{},mode:U},H},X.accountStoragePath),i.info("routing mode changed",{mode:U}),{command:"openai-routing",text:`## OpenAI Routing Updated
44
-
45
- Mode: \`${U}\`
46
- - ${oJ(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
- - ${oJ($)}${W}
54
-
55
- Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:$}}}async function lz(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"]??A1.primary,V=H.secondary??H["1w"]??A1.secondary;U.push(`| main | ≥ ${L}% | ≥ ${V}% |`);for(let B of $){let K=Q.accounts?.[B]??Q.main??{},N=K.primary??K["5h"]??A1.primary,F=K.secondary??K["1w"]??A1.secondary;U.push(`| ${B} | ≥ ${N}% | ≥ ${F}% |`)}}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:A1.primary,secondary:A1.secondary}};return await Q0((U)=>{return U.killswitch=W,U},X.accountStoragePath),i.info("killswitch enabled"),{command:"openai-killswitch",text:"## Killswitch Enabled",knobs:{config:W,accountIds:$}}}if(G[0]==="off"){let W={...Q,enabled:!1};return await Q0((U)=>{return U.killswitch=W,U},X.accountStoragePath),i.info("killswitch disabled"),{command:"openai-killswitch",text:"## Killswitch Disabled",knobs:{config:W,accountIds:$}}}if(G[0]==="set"&&G.length>1){let W={...Q,enabled:!0,accounts:{...Q.accounts??{}}};for(let U=1;U<G.length;U++){let 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 Q0((U)=>{return U.killswitch=W,U},X.accountStoragePath),i.info("killswitch thresholds updated",{count:G.length-1}),{command:"openai-killswitch",text:"## Killswitch Updated",knobs:{config:W,accountIds:$}}}return{command:"openai-killswitch",text:"Usage: `/openai-killswitch`, `/openai-killswitch on`, `/openai-killswitch off`, `/openai-killswitch set <acct>:<5h>,<1w> ...`",knobs:{config:Q,accountIds:$}}}async function dz(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
1
+ import{A as uK,B as cK,C as pK,D as lK,c as S9,e as bX,h as GY,i as gK,j as YY,m as n1,q as tQ,r as yK,s as fK,t as mK,y as zJ,z as NX}from"./index-5y4vzdf8.js";import{I as A5,J as T5}from"./index-w42s0g6m.js";import{$ as WQ,$a as w9,Aa as lJ,Ba as t9,Ca as HX,Da as TY,Ea as H1,Fa as kK,Ga as RY,Ha as V0,Ia as xK,Ja as m1,Ka as rJ,L as ZK,La as P0,M as LK,Ma as f1,N as HK,Na as VX,O as nJ,Oa as q0,P as TK,Pa as JY,Q as RK,Qa as QY,R as EY,Ra as WJ,S as CK,Sa as $Y,T as CQ,Ta as bK,U as E0,Ua as vK,V as y0,Va as b1,W as CY,Wa as M1,X as mX,Xa as hK,Y as Q5,Ya as h,Z as B0,Za as E9,_ as IK,_a as M9,aa as zQ,ab as A9,ba as Q1,bb as T9,ca as $1,cb as R9,da as Y9,db as C9,ea as KQ,eb as I9,fa as UQ,fb as _9,ga as ZQ,gb as PX,ha as LQ,hb as E1,ia as HQ,ja as VQ,ka as NQ,la as AY,ma as J9,na as h1,oa as r1,pa as _K,qa as V1,ra as k0,sa as VK,ta as e8,ua as KX,va as GJ,wa as NK,xa as SK,ya as YJ,za as pJ}from"./index-338z7171.js";import{kb as dK}from"./index-jwn4r3sw.js";import{mb as X9,nb as XY,ob as uz}from"./index-301y4qa1.js";import{sb as aX}from"./index-9ehhb051.js";import{mkdirSync as gq,readFileSync as iK,renameSync as yq,statSync as fq,writeFileSync as mq}from"node:fs";import UX from"node:os";import{join as KJ}from"node:path";import{execFileSync as _U}from"node:child_process";import{readFileSync as LU}from"node:fs";import{homedir as HU,tmpdir as VU}from"node:os";import{join as FY}from"node:path";var NU="https://chatgpt.com/backend-api/codex/responses",BU="openai-auth.json",L1={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 OY(){let Y=process.env[L1.configDir]?.trim();if(Y)return Y;return FY(process.env.XDG_CONFIG_HOME||FY(HU(),".config"),"opencode")}function e(){return process.env[L1.configFile]?.trim()||FY(OY(),BU)}function qU(){try{let Y=JSON.parse(LU(e(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function mJ(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 BY(Y,X,J){let Q=mJ(Y);if(Q!==void 0)return Q;if(typeof X==="boolean")return X;return J}function FU(){let Y=qU(),X=mJ(L1.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:BY(L1.webSockets,Y.webSockets,!1),rawWebSocket:BY(L1.rawWebSocket,Y.rawWebSocket,!1),responsesLite:BY(L1.responsesLite,Y.responsesLite,!1),dump:BY(L1.dump,Q,!1),dumpDir:process.env[L1.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():FY(VU(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[L1.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():NU)}}var qY;function g0(){if(!qY)qY=FU();return qY}function jX(){return qY=void 0,g0()}import{realpathSync as uJ}from"node:fs";import{homedir as OU}from"node:os";import{basename as jU,dirname as DU,join as DY,resolve as dJ}from"node:path";function PU(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return DY(process.env.XDG_CONFIG_HOME||DY(OU(),".config"),"opencode")}function iJ(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||DY(PU(),pJ)}function jY(Y,X){let J=dJ(Y);return X==="win32"||X==="darwin"?J.toLowerCase():J}function cJ(Y){try{return uJ.native(Y)}catch{try{return DY(uJ.native(DU(Y)),jU(Y))}catch{return}}}function EU(Y,X,J=process.platform){if(jY(Y,J)===jY(X,J))return!0;let Q=cJ(Y),$=cJ(X);return Q!==void 0&&$!==void 0&&jY(Q,J)===jY($,J)}function PY(Y=iJ()){let X=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(X){if(EU(Y,X))throw Error(`OPENCODE_OPENAI_AUTH_STATE_FILE resolves to the config path (${dJ(Y)}). Set OPENCODE_OPENAI_AUTH_STATE_FILE to a different file.`);return X}return lJ(Y)}function s(Y=iJ()){return{configPath:Y,statePath:PY(Y)}}var P9="0.9.0";import{readFile as MU}from"node:fs/promises";function oJ(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}async function sJ(Y){let X=await rJ(Y.configPath),J=[];try{let $=JSON.parse(await MU(Y.statePath,"utf8"));if(oJ($)){let G=$.accounts;if(oJ(G))J=Object.keys(G)}}catch($){if($.code!=="ENOENT")throw $}return{rosterIds:X?[...X]:[],stateIds:J,orphanStateIds:X?J.filter(($)=>!X.has($)):[]}}function DX(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 wU(Y,X){let J=Y.lastRefreshError;return EY(J,Y.refresh,X)&&J!==void 0&&J.nextRetryAt!==void 0&&J.nextRetryAt-J.checkedAt>=nJ}function aJ(Y){let X=[],J=[],Q=Y.now??Date.now(),$=DX(Y.storage),G=!1;if(!Y.auth)X.push({code:"auth-slot-missing",message:"OpenCode's OpenAI auth slot is missing."}),G=!0;else if(Y.auth.type!=="oauth")X.push({code:"auth-slot-not-oauth",message:"OpenCode's OpenAI auth slot is not OAuth."}),G=!0;else if($&&(!Y.auth.refresh||$.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."}),G=!0;if(G&&$){let Z={type:"restore-main-credential"};J.push(Z);let U=X.find((L)=>L.code==="auth-slot-missing"||L.code==="auth-slot-not-oauth"||L.code==="main-refresh-not-in-store");if(U)U.repair=Z}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((Z)=>Z.enabled!==!1))X.push({code:"no-enabled-accounts",message:"The account store has no enabled accounts."});for(let Z of W){if(!V0(Z))continue;if(!wU(Z,Q))continue;let U={type:"clear-refresh-backoff",accountId:Z.id};J.push(U),X.push({code:"armed-non-transient-refresh-backoff",accountId:Z.id,message:`Account ${Z.id} has an armed non-transient refresh backoff.`,repair:U})}let K=[...Y.orphanStateIds??[]];if(K.length>0){let Z={type:"prune-orphan-state-ids",ids:K};J.push(Z),X.push({code:"orphan-state-ids",message:`State contains ids absent from the config roster: ${K.join(", ")}.`,repair:Z})}return{findings:X,repairs:J}}function tJ(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 Y0={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 eJ(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 YQ(){return Boolean(process.stdin.isTTY)}var AU=50,XQ=`${String.fromCharCode(27)}\\[[0-9;]*m`,TU=new RegExp(XQ,"g"),RU=new RegExp(`^${XQ}`);function CU(Y){return Y.replace(TU,"")}function MY(Y,X){if(X<=0)return"";if(CU(Y).length<=X)return Y;let J=X>=3?"...":".".repeat(X),Q=Math.max(0,X-J.length),$="",G=0,W=0;while(G<Y.length&&W<Q){if(Y[G]==="\x1B"){let K=Y.slice(G).match(RU);if(K){$+=K[0],G+=K[0].length;continue}}$+=Y[G],G+=1,W+=1}return $.includes("\x1B[")?`${$}${Y0.reset}${J}`:$+J}function IU(Y){if(Y==="red")return Y0.red;if(Y==="cyan")return Y0.cyan;return""}async function wY(Y,X){if(!YQ())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,$=0,G=null,W=!1,K=0,Z=()=>{let U=Q.columns??80,L=Q.rows??24,F=K;if(X.clearScreen)Q.write(Y0.clearScreen+Y0.moveTo(1,1));else if(F>0)Q.write(Y0.up(F));let N=0,V=(E)=>{Q.write(`${Y0.clearLine}${E}
5
+ `),N+=1},j=X.subtitle?3:0,R=Math.max(1,Math.min(Y.length,L-(1+j+2)-1)),S=Math.max(0,Math.min($-Math.floor(R/2),Math.max(0,Y.length-R))),u=Y.slice(S,S+R);if(V(`${Y0.dim}┌ ${Y0.reset}${MY(X.message,Math.max(1,U-4))}`),X.subtitle)V(`${Y0.dim}│${Y0.reset}`),V(`${Y0.cyan}◆${Y0.reset} ${MY(X.subtitle,Math.max(1,U-4))}`),V("");for(let E=0;E<u.length;E++){let b=u[E];if(!b)continue;let f=S+E===$,o=IU(b.color),t=o?`${f?"":Y0.dim}${o}${b.label}${Y0.reset}`:f?b.label:`${Y0.dim}${b.label}${Y0.reset}`;t=MY(t,Math.max(1,U-8)),V(f?`${Y0.cyan}│${Y0.reset} ${Y0.green}●${Y0.reset} ${t}`:`${Y0.cyan}│${Y0.reset} ${Y0.dim}○${Y0.reset} ${t}`)}let I=u.length<Y.length?` (${S+1}-${S+u.length}/${Y.length})`:"";V(`${Y0.cyan}│${Y0.reset} ${Y0.dim}${MY(`Up/Down to select | Enter: confirm | Esc: back${I}`,Math.max(1,U-6))}${Y0.reset}`),V(`${Y0.cyan}└${Y0.reset}`);for(let E=N;E<F;E++)V("");K=N};return new Promise((U)=>{let L=J.isRaw??!1,F=()=>{if(W)return;if(W=!0,G)clearTimeout(G);J.removeListener("data",j);try{J.setRawMode(L),J.pause(),Q.write(Y0.show)}catch{}process.removeListener("SIGINT",V),process.removeListener("SIGTERM",V)},N=(R)=>{F(),U(R)},V=()=>N(null),j=(R)=>{if(G)clearTimeout(G),G=null;switch(eJ(R)){case"up":$=($-1+Y.length)%Y.length,Z();break;case"down":$=($+1)%Y.length,Z();break;case"enter":N(Y[$]?.value??null);break;case"escape":N(null);break;case"escape-start":G=setTimeout(()=>N(null),AU);break}};process.once("SIGINT",V),process.once("SIGTERM",V);try{J.setRawMode(!0)}catch{F(),U(null);return}J.resume(),Q.write(Y0.hide),Z(),J.on("data",j)})}var JQ=[{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"}],uF=JQ.map((Y)=>Y.label);async function QQ(){return await wY(JQ,{message:"OpenAI accounts",subtitle:"Select an account action",clearScreen:!0})??"cancel"}async function $Q(Y,X=!1){return await wY(X?[{label:"Yes",value:!0},{label:"No",value:!1}]:[{label:"No",value:!1},{label:"Yes",value:!0}],{message:Y})??!1}function SU(Y,X=process.platform,J=_U){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 kU(){return{url:"",instructions:"",method:"auto",callback:async()=>({type:"failed"})}}async function xU(){let{redirectUri:Y}=await ZQ(),X=await zQ(),J=WQ(crypto.getRandomValues(new Uint8Array(32)).buffer),Q=KQ(Y,X,J),$=LQ(X,J);return{url:Q,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let G=await $;return{type:"success",refresh:G.refresh_token,access:G.access_token,expires:Date.now()+(G.expires_in??3600)*1000,accountId:Y9(G)}}finally{UQ(J)}}}}async function bU(Y){let{deviceData:X,url:J,instructions:Q}=await HQ(Y);return{url:J,instructions:Q,method:"auto",async callback(){try{let $=await VQ(X,Y);return{type:"success",refresh:$.refresh_token,access:$.access_token,expires:Date.now()+($.expires_in??3600)*1000,accountId:Y9($)}}catch{return{type:"failed"}}}}}function GQ(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 BQ({client:Y,getAuth:X,getPaths:J=()=>s(e()),fetchImpl:Q=fetch,packageVersion:$=P9,dependencies:G}){let W={authorizeBrowser:G?.authorizeBrowser??xU,authorizeHeadless:G?.authorizeHeadless??(()=>bU($)),beginAccountLogin:G?.beginAccountLogin??AY,loadAccounts:G?.loadAccounts??P0,mutateAccounts:G?.mutateAccounts??q0,refreshAllQuota:G?.refreshAllQuota??E1,showAuthMenu:G?.showAuthMenu??QQ,confirm:G?.confirm??$Q,readStoreIds:G?.readStoreIds??sJ,openBrowser:G?.openBrowser??SU,now:G?.now??Date.now,custodyQuotaDeps:G?.custodyQuotaDeps??{}},K=async()=>await X?.().catch(()=>{return})??{type:"missing"},Z=async()=>{if((await K()).type!=="missing")return!0;return((await W.loadAccounts(J()))?.accounts.length??0)>0},U=async(I)=>{await Y.auth.set({path:{id:"openai"},body:{type:"oauth",...I}})},L=async()=>{let I=new AbortController,E=await W.beginAccountLogin({version:$,signal:I.signal});E.completion.catch(()=>{}),GQ(E);let b=!1;try{b=await W.openBrowser(E.url)!==!1}catch{b=!1}if(!b)I.abort(),console.log(`Could not open a browser. Switching to device authorization.
10
+ `),E=await W.beginAccountLogin({version:$,headless:!0}),GQ(E);return E.completion},F=async()=>{let I=await W.loadAccounts(J());if(f1(I)==="claustrum"){console.log("That account cannot be added while Claustrum mode is active. Run `/openai-account local` first.");return}let E=await L(),b=!1;if(await W.mutateAccounts((f)=>{if(E.accountId&&f.mainAccountId&&E.accountId===f.mainAccountId)return b=!0,f;return NQ(f.accounts,E),f},J()),b){console.log("That account is already the OpenCode main credential.");return}console.log(`Added fallback account ${E.id}.`)},N=async()=>{let I=await L();await U({refresh:I.refresh,access:I.access??"",expires:I.expires??0}),console.log("Updated the OpenCode main credential.")},V=async()=>{let I=J(),E=await W.loadAccounts(I),b=new RY({storage:E,configPath:I.configPath,fetchImpl:Q,now:W.now}),f={refreshAccount:async(W0)=>W0},o=async()=>{throw Error("No usable main access token for quota check")},t=async(W0)=>{let F0=await W.loadAccounts(W0);if(!F0)return null;return{...F0,accounts:F0.accounts.map((u0)=>V0(u0)?{...u0,lastRefreshError:void 0}:{...u0})}},N0=await W.refreshAllQuota({getAuth:K,codexRefreshFn:o,refreshMainWithLease:o,fallbackManager:f,quotaManager:b,loadAccounts:t,writeSidebarState:async()=>{},client:{auth:{set:async()=>{throw Error("Quota checks cannot write credentials")}}},fetchImpl:Q,now:W.now,paths:I,storageMainAccountId:E?.mainAccountId,isOAuthAccountFn:V0,whamFn:TY,respectBackoff:!1,readSidebarState:async()=>({main:{},fallbacks:[]}),...W.custodyQuotaDeps});vU(N0)},j=async()=>{let I=J(),[E,b,f]=await Promise.all([W.loadAccounts(I),W.readStoreIds(I),K()]),o=aJ({auth:f.type==="missing"?void 0:f,storage:E,orphanStateIds:b.orphanStateIds,now:W.now()});return console.log(tJ(o)),o},R=async()=>{let I=await j();if(I.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 b of I.repairs){if(b.type==="restore-main-credential"){let f=await W.loadAccounts(E),o=DX(f);if(!o)continue;await U({refresh:o.refresh,access:o.access??"",expires:o.expires??0});continue}if(b.type==="prune-orphan-state-ids"){await W.mutateAccounts((f)=>f,E);continue}await W.mutateAccounts((f)=>{let o=f.accounts.find((t)=>t.id===b.accountId&&V0(t));if(o)o.lastRefreshError=void 0;return f},E)}console.log(`Applied ${I.repairs.length} auth repair(s).`)},S=async()=>{if(!await W.confirm("Delete all fallback accounts?")){console.log("Delete cancelled.");return}let I=[];await W.mutateAccounts((E,b)=>{let f=new Set([...b?.rawRosterIds??[],...E.accounts.map((o)=>o.id)].filter((o)=>o!=="main"));return I.splice(0,I.length,...f),E.accounts=E.accounts.filter((o)=>o.id==="main"),E},J(),{allowDrop:I}),console.log("Deleted all fallback accounts.")},u=async(I)=>{switch(I){case"add-account":await F();break;case"auth-current":await N();break;case"check-quotas":await V();break;case"auth-doctor":await j();break;case"apply-repairs":await R();break;case"delete-all":await S();break;case"cancel":break}};return[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:async(I)=>{if(I&&await Z())return await u(await W.showAuthMenu()),kU();return W.authorizeBrowser()}},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:W.authorizeHeadless},{label:"Manually enter API Key",type:"api"}]}function vU(Y){for(let X of Y)console.log(X.ok?`${X.account}: quota refreshed`:`${X.account}: ${X.error??"quota refresh failed"}`)}var n0=B0("commands");function S0(Y){return{configPath:Y.accountStoragePath,statePath:Y.accountStatePath}}async function yU(Y,X){let J=await X.loadAccounts(S0(X))??{version:1,accounts:[]},Q=J.killswitch??{},$=(J.accounts??[]).filter((W)=>W.enabled!==!1).map((W)=>W.id),G=Y.trim().toLowerCase().split(/\s+/).filter(Boolean);if(G.length===0){let W=Q.enabled===!0,K=["## Killswitch","",`Status: **${W?"ON":"OFF"}**`];if(W){K.push(""),K.push("| Account | primary threshold | secondary threshold |"),K.push("| ------- | ------------ | ------------ |");let Z=Q.main??{},U=Z.primary??Z["5h"]??m1.primary,L=Z.secondary??Z["1w"]??m1.secondary;K.push(`| main | ≥ ${U}% | ≥ ${L}% |`);for(let F of $){let N=Q.accounts?.[F]??Q.main??{},V=N.primary??N["5h"]??m1.primary,j=N.secondary??N["1w"]??m1.secondary;K.push(`| ${F} | ≥ ${V}% | ≥ ${j}% |`)}}return K.push(""),K.push("Commands: `/openai-killswitch on` | `/openai-killswitch off` | `/openai-killswitch set <acct>:<5h>,<1w> ...`"),{command:"openai-killswitch",text:K.join(`
11
+ `),knobs:{config:Q,accountIds:$}}}if(G[0]==="on"){let W={...Q,enabled:!0,main:Q.main??{primary:m1.primary,secondary:m1.secondary}};return await q0((K)=>{return K.killswitch=W,K},S0(X)),n0.info("killswitch enabled"),{command:"openai-killswitch",text:"## Killswitch Enabled",knobs:{config:W,accountIds:$}}}if(G[0]==="off"){let W={...Q,enabled:!1};return await q0((K)=>{return K.killswitch=W,K},S0(X)),n0.info("killswitch disabled"),{command:"openai-killswitch",text:"## Killswitch Disabled",knobs:{config:W,accountIds:$}}}if(G[0]==="set"&&G.length>1){let W={...Q,enabled:!0,accounts:{...Q.accounts??{}}};for(let K=1;K<G.length;K++){let Z=G[K]?.match(/^([^:]+):(\d+),(\d+)$/);if(!Z)continue;let[,U,L,F]=Z,N={primary:Number.parseInt(L,10),secondary:Number.parseInt(F,10)};if(U==="main")W.main=N;else if(U==="all"){W.main=N;for(let V of $)W.accounts[V]=N}else W.accounts[U]=N}return await q0((K)=>{return K.killswitch=W,K},S0(X)),n0.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 fU(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),Q=g0(),$=Q.dump;if(J.length===0)return{command:"openai-dump",text:`## Request Dump
57
12
 
58
13
  - Enabled: ${$?"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 Q0((W)=>{return W.dump={...W.dump??{},enabled:!0},W},X.accountStoragePath);let G=E9();return i.info("request dump enabled"),{command:"openai-dump",text:`## Request Dump Enabled
16
+ Usage: \`/openai-dump on\` or \`/openai-dump off\``,knobs:{enabled:$}};if(J[0]==="on"){await q0((W)=>{return W.dump={...W.dump??{},enabled:!0},W},S0(X));let G=jX();return n0.info("request dump enabled"),{command:"openai-dump",text:`## Request Dump Enabled
62
17
 
63
18
  Dump directory: ${G.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 Q0((G)=>{return G.dump={...G.dump??{},enabled:!1},G},X.accountStoragePath),E9(),i.info("request dump disabled"),{command:"openai-dump",text:"## Request Dump Disabled",knobs:{enabled:!1}};return{command:"openai-dump",text:"Usage: `/openai-dump`, `/openai-dump on`, or `/openai-dump off`.",knobs:{enabled:$}}}async function iz(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 q0((G)=>{return G.dump={...G.dump??{},enabled:!1},G},S0(X)),jX(),n0.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 mU(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(S0(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((K)=>`\`${K}\``).join(", ")}
70
25
 
71
- Usage: \`/openai-logging <level>\``,knobs:{level:W}}}let $=J[0];if($&&Q.includes($)){let G=$;return vY(G),await Q0((W)=>{return W.logging={...W.logging??{},level:G},W},X.accountStoragePath),i.info("log level changed",{level:G}),{command:"openai-logging",text:`## Logging Updated
26
+ Usage: \`/openai-logging <level>\``,knobs:{level:W}}}let $=J[0];if($&&Q.includes($)){let G=$;return CY(G),await q0((W)=>{return W.logging={...W.logging??{},level:G},W},S0(X)),n0.info("log level changed",{level:G}),{command:"openai-logging",text:`## Logging Updated
72
27
 
73
28
  Level set to \`${G}\`.`,knobs:{level:G}}}return{command:"openai-logging",text:`## Invalid Level
74
29
 
75
- Valid levels: ${Q.map((G)=>`\`${G}\``).join(", ")}`,knobs:{level:"info"}}}function nz(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 oz(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((G)=>`\`${G}\``).join(", ")}`,knobs:{level:"info"}}}function uU(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 cU(Y,X){let J=X.cacheKeepManager,Q=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),$=await X.loadAccounts(S0(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,F=Math.ceil((K.cacheExpiresAt-U.generatedAt)/1000);V.push(`- \`${N}\` (${K.accountId??"main"}) — expires in ${F}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 K=J.status(),Z=K.window,U=Z?`${String(Z.startHour).padStart(2,"0")}-${String(Z.endHour).padStart(2,"0")}`:"always (no window)",L=["## Cachekeep","",`Status: **${G?"ON":"OFF"}**`,`Timer: **${K.running?"armed":"idle"}**`,`Subagent warming: **${$?.cachekeep?.subagents===!0?"ON":"OFF"}**`,`Idle policy: **sustain ${K.sustain?"ON":"OFF"} (main only)**`,`Window: **${U}**`];if(L.push(`Tracked sessions: **${K.tracked}**`),K.targets.length>0){L.push("");for(let N of K.targets){let V=N.sessionKey.length>12?`${N.sessionKey.slice(0,12)}…`:N.sessionKey,j=Math.ceil((N.cacheExpiresAt-K.generatedAt)/1000);L.push(`- \`${V}\` (${N.accountId??"main"}) — expires in ${j}s`+(N.lastWarmedAt?`, last warm ${Math.ceil((K.generatedAt-N.lastWarmedAt)/1000)}s ago`:"")+(N.backoffUntil&&N.backoffUntil>K.generatedAt?`, backoff ${Math.ceil((N.backoffUntil-K.generatedAt)/1000)}s`:""))}}L.push(""),L.push(`TTL: ${Math.round(K.ttlMs/1000)}s | Lead: ${Math.round(K.leadMs/1000)}s | Max idle warm: ${Math.round(K.maxIdleWarmMs/60000)}min`),L.push(""),L.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 F=Math.max(0,...K.targets.map((N)=>N.lastWarmedAt??0));return{command:"openai-cachekeep",text:L.join(`
33
+ `),knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:K.sustain,window:Z,running:K.running,tracked:K.tracked,lastWarmAt:F||void 0,generatedAt:K.generatedAt,maxIdleWarmMs:K.maxIdleWarmMs,maxSubagentIdleMs:K.maxSubagentIdleMs}}}if(Q[0]==="on"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
79
34
 
80
- Cannot start: manager not wired.`,knobs:{}};await Q0((L)=>{return L.cachekeep={...L.cachekeep??{},enabled:!0},L},X.accountStoragePath),i.info("cachekeep enabled"),X.setCacheKeepEnabled?.(!0),J.start();let U=J.status(),H=Math.max(0,...U.targets.map((L)=>L.lastWarmedAt??0));return{command:"openai-cachekeep",text:`## Cachekeep Enabled
35
+ Cannot start: manager not wired.`,knobs:{}};await q0((U)=>{return U.cachekeep={...U.cachekeep??{},enabled:!0},U},S0(X)),n0.info("cachekeep enabled"),X.setCacheKeepEnabled?.(!0),J.start();let K=J.status(),Z=Math.max(0,...K.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 Q0((U)=>{return U.cachekeep={...U.cachekeep??{},enabled:!1},U},X.accountStoragePath),i.info("cachekeep disabled"),X.setCacheKeepEnabled?.(!1),J?.stop(),{command:"openai-cachekeep",text:"## Cachekeep Disabled",knobs:{enabled:!1,sustain:$?.cachekeep?.sustain===!0,running:!1,tracked:0}};if(Q[0]==="sustain"){let U=Q[1];if(Q.length!==2||U!=="on"&&U!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep sustain on` | `/openai-cachekeep sustain off`",knobs:{}};let H=U==="on";await Q0((V)=>{return V.cachekeep={...V.cachekeep??{},sustain:H},V},X.accountStoragePath),i.info(`cachekeep sustain ${H?"enabled":"disabled"}`),X.setCacheKeepSustain?.(H);let L=J?.status();return{command:"openai-cachekeep",text:H?`## Cachekeep Sustain Enabled
37
+ TTL: ${Math.round(K.ttlMs/1000)}s | Max idle warm ${Math.round(K.maxIdleWarmMs/60000)}min`,knobs:{enabled:!0,subagents:$?.cachekeep?.subagents===!0,sustain:K.sustain,window:K.window,running:K.running,tracked:K.tracked,lastWarmAt:Z||void 0,generatedAt:K.generatedAt,maxIdleWarmMs:K.maxIdleWarmMs,maxSubagentIdleMs:K.maxSubagentIdleMs}}}if(Q[0]==="off")return await q0((K)=>{return K.cachekeep={...K.cachekeep??{},enabled:!1},K},S0(X)),n0.info("cachekeep disabled"),X.setCacheKeepEnabled?.(!1),J?.stop(),{command:"openai-cachekeep",text:"## Cachekeep Disabled",knobs:{enabled:!1,sustain:$?.cachekeep?.sustain===!0,running:!1,tracked:0}};if(Q[0]==="sustain"){let K=Q[1];if(Q.length!==2||K!=="on"&&K!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep sustain on` | `/openai-cachekeep sustain off`",knobs:{}};let Z=K==="on";await q0((L)=>{return L.cachekeep={...L.cachekeep??{},sustain:Z},L},S0(X)),n0.info(`cachekeep sustain ${Z?"enabled":"disabled"}`),X.setCacheKeepSustain?.(Z);let U=J?.status();return{command:"openai-cachekeep",text:Z?`## 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 Q0((V)=>{return V.cachekeep={...V.cachekeep??{},subagents:H},V},X.accountStoragePath),i.info(H?"cachekeep subagent warming enabled":"cachekeep subagent warming disabled"),X.setCacheKeepSubagents?.(H);let L=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Subagent Warming
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 Q0((L)=>{if(L.cachekeep)delete L.cachekeep.startHour,delete L.cachekeep.endHour;return L},X.accountStoragePath),X.setCacheKeepWindow?.(void 0),i.info("cachekeep window cleared");let H=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Cleared
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=nz(W);if(!U.ok)return{command:"openai-cachekeep",text:`## Cachekeep Window Invalid
93
-
94
- ${U.reason}`,knobs:{}};let{startHour:H,endHour:L}=U;await Q0((K)=>{return K.cachekeep={...K.cachekeep??{},startHour:H,endHour:L},K},X.accountStoragePath),X.setCacheKeepWindow?.({startHour:H,endHour:L}),i.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 J8(Y){let X=[Y.primary?.usedPercent,Y.secondary?.usedPercent].filter((J)=>J!==void 0);return X.length>0?Math.max(...X):void 0}function rz(Y,X){let J=[Y.primary,Y.secondary].filter(($)=>$!==void 0),Q=J.filter(($)=>YY($,X));return(Q.length>0?Q:J).sort(($,G)=>G.usedPercent-$.usedPercent)[0]?.resetsAt}function sz(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)=>!YY(Q,X))}function I9(Y){if(!Y)return;try{return decodeURIComponent(Y)}catch{return}}async function sJ(Y,X){try{let J=await X.resolveResetTarget(Y),Q=J.accountKey==="main"?void 0:J.chatgptAccountId,[$,G]=await Promise.all([L1({accessToken:J.accessToken,fetchImpl:X.fetchImpl,now:X.now,accountId:J.chatgptAccountId}),R9(X.fetchImpl,J.accessToken,Q)]),W=bY(G.credits),U=iJ(G.credits),H=G.availableCount??$.resetCreditsAvailable??(U>0?U:void 0),L=$.resetCreditsApplicable,V=T9($,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:J8($),resetTime:rz($,X.now()),availableCount:H,applicableAvailableCount:L,eligible:B===void 0,reason:B,selectedCreditId:W?.id,selectedCreditExpiresAt:W?.expiresAt}}catch(J){return i.warn("reset preview row failed",{accountKey:Y,error:J?.message??String(J)}),{accountKey:Y,label:Y==="main"?"Main account":Y,eligible:!1,reason:J?.message??String(J)}}}function az(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 aJ(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 I0(Y,X,J,Q={}){return{command:T1,text:J,knobs:{stage:"result",accountKey:Y,code:X,...Q}}}function tz(Y,X,J){if(X instanceof h0){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 I0(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 I0(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 w1)return I0(Y,X.kind,`## Reset credit
107
-
108
- No redemption was attempted: reset credit availability could not be loaded.
109
-
110
- Code: \`${X.kind}\``);return i.warn("reset command failed before a known result",{accountKey:Y,error:X?.message??String(X)}),I0(Y,"error",`## Reset credit
111
-
112
- The reset request failed before a known result: internal command failure — see plugin log.`)}async function ez(Y,X,J){let{accountKey:Q}=Y.target,$=Y.outcome.kind;if(Y.finalizeStateWriteFailed)return I0(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)i.warn("reset quota re-check failed",{accountKey:Q,error:W.error});let H=Q==="main"?X.quotaManager.getMain():X.quotaManager.getFallback(Q),L=W.ok&&sz(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 I0(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:J8(H?.quota??{}),remainingCredits:V})}if($==="ambiguous_local")return I0(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 I0(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 I0(Q,$,`## Reset credit result
43
+ Main-agent sessions again stop warming at the configured idle cap.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:Z,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 K=Q[1];if(!K||K!=="on"&&K!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off`",knobs:{}};let Z=K==="on";await q0((L)=>{return L.cachekeep={...L.cachekeep??{},subagents:Z},L},S0(X)),n0.info(Z?"cachekeep subagent warming enabled":"cachekeep subagent warming disabled"),X.setCacheKeepSubagents?.(Z);let U=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Subagent Warming
139
44
 
140
- Account: **${Y.target.label}** (\`${Q}\`)
45
+ Subagent warming: **${Z?"ON":"OFF"}**`,knobs:{enabled:G,subagents:Z,sustain:U?.sustain??$?.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 K=Q[1];if(K==="clear"||K==="off"){await q0((U)=>{if(U.cachekeep)delete U.cachekeep.startHour,delete U.cachekeep.endHour;return U},S0(X)),X.setCacheKeepWindow?.(void 0),n0.info("cachekeep window cleared");let Z=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:G,subagents:$?.cachekeep?.subagents===!0,sustain:Z?.sustain??$?.cachekeep?.sustain===!0,window:void 0,running:Z?.running??!1,tracked:Z?.tracked??0,generatedAt:Z?.generatedAt??Date.now(),maxIdleWarmMs:Z?.maxIdleWarmMs??3600000,maxSubagentIdleMs:Z?.maxSubagentIdleMs??1800000}}}return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep window clear`",knobs:{}}}let W=Q[0];if(W&&/^\d{1,2}-\d{1,2}$/.test(W)){let K=uU(W);if(!K.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 YU(Y,X){let J=[X.resolveResetTarget?void 0:"resolveResetTarget",X.fetchImpl?void 0:"fetchImpl",X.now?void 0:"now",X.randomUUID?void 0:"randomUUID",X.refreshResetTargetQuota?void 0:"refreshResetTargetQuota"].filter((W)=>W!==void 0);if(J.length>0)return i.warn("reset command dependencies unwired",{missingDeps:J}),{command:T1,text:`## Reset credit
49
+ ${K.reason}`,knobs:{}};let{startHour:Z,endHour:U}=K;await q0((N)=>{return N.cachekeep={...N.cachekeep??{},startHour:Z,endHour:U},N},S0(X)),X.setCacheKeepWindow?.({startHour:Z,endHour:U}),n0.info("cachekeep window set",{startHour:Z,endHour:U});let L=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)];i.debug("reset accounts stage requested",{accountKeys:U});let H=await Promise.all(U.map((L)=>sJ(L,Q)));return i.debug("reset accounts stage built",{rows:H.map((L)=>({accountKey:L.accountKey,eligible:L.eligible,reason:L.reason,usedPercent:L.usedPercent,availableCount:L.availableCount,applicableAvailableCount:L.applicableAvailableCount}))}),{command:T1,text:az(H),knobs:{stage:"accounts",accounts:H}}}if(G==="select"){let W=I9($[1]);if(!W||!i0(W)||$.length!==2)return I0("","invalid_command","Usage: `/openai-reset select <encodedAccountKey>`");let U=await sJ(W,Q);if(!U.eligible)return I0(W,"not_eligible",aJ(U));return{command:T1,text:aJ(U),knobs:{stage:"confirm",preview:U}}}if(G==="confirm"||G==="retry"){let W=I9($[1]),U=I9($[2]);if(!W||!i0(W)||!U||$.length!==3)return I0(W??"","invalid_command",`Usage: \`/openai-reset ${G} <encodedAccountKey> <encodedChatgptAccountId>\``);i.info("reset redemption decision",{accountKey:W,action:G}),i.debug("reset redemption identity binding",{accountKey:W,expectedChatgptAccountId:U});try{let H=await nJ({configPath:X.accountStoragePath,mutateAccountsFn:Q0,loadAccountsFn:X.loadAccounts,now:Q.now,randomUUID:Q.randomUUID,fetchImpl:Q.fetchImpl,resolveTarget:Q.resolveResetTarget,fetchUsage:(L)=>L1({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 i.info("reset redemption outcome",{accountKey:W,code:H.outcome.kind}),ez(H,Q,U)}catch(H){let L=tz(W,H,U);return i.info("reset redemption outcome",{accountKey:W,code:L.knobs.code}),L}}return I0("","invalid_command","Usage: `/openai-reset` | `/openai-reset select <encodedAccountKey>` | `/openai-reset confirm <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset retry <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset refresh`")}var XU=new Set(["access","refresh","apikey","authheader","password","secret"]);function JU(Y){let X=Y.toLowerCase().replace(/[-_]/g,"");if(XU.has(X))return!0;return X.endsWith("token")}function _9(Y,X,J){if(Array.isArray(Y))return Y.map(($,G)=>_9($,`${X}[${G}]`,J));if(!R(Y))return Y;let Q={};for(let[$,G]of Object.entries(Y)){if(JU($)){J.push(`${X}.${$}`);continue}Q[$]=_9(G,`${X}.${$}`,J)}return Q}async function y9(Y,X,J){let Q=await QU(Y,X,J),$=[],G=_9(Q.knobs,"knobs",$);if($.length>0)return i.warn("credential-shaped knob stripped before RPC",{command:Y,fields:$}),{...Q,knobs:G};return Q}async function QU(Y,X,J){switch(Y){case"openai-quota":return cz(J);case"openai-account":return uz(X,J);case"openai-routing":return pz(X,J);case"openai-killswitch":return lz(X,J);case"openai-dump":return dz(X,J);case"openai-logging":return iz(X,J);case"openai-cachekeep":return oz(X,J);case"openai-reset":return YU(X,J);default:throw Error(`unhandled command: ${Y}`)}}var f9=H0("quota");function $U(Y){return Y?.status===401}async function y1(Y,X={}){let J=Y.whamFn;if(!J)throw Error("whamFn is required for refreshAllQuota");let Q=[],$=Y.logger??f9,G=(N)=>{Q.push(N);let F={pid:process.pid,accountId:N.account,status:N.ok?"ok":"error",...N.error?{error:N.error}:{}};if(N.ok)$.debug("quota refresh succeeded",F);else $.warn("quota refresh failed",F)},W=Y.skipFresherThanMs,U=!1,H;if(W!==void 0)try{H=await(Y.readSidebarState??R1)()}catch{}let L=new Map(H?.fallbacks.map((N)=>[N.id,N])??[]),V=(...N)=>W!==void 0&&N.some((F)=>typeof F==="number"&&Number.isFinite(F)&&F<=Y.now()&&Y.now()-F<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 F=H&&K!==void 0&&H.main.mainAccountId===K?H.main.quota:void 0;if(V(Y.quotaManager.peekMainForPolicy(K)?.checkedAt,F?.primary?.checkedAt,F?.secondary?.checkedAt,F?.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:X1(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 F=L.get(N.id),q=N.accountId,A=F&&q!==void 0&&F.accountId===q?F.quota:void 0;if(V(Y.quotaManager.peekFallbackForPolicy(N.id,q)?.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 b=N.lastRefreshError;if(hY(b,N.refresh,Y.now())){G({account:N.id,ok:!1,error:gY(b,Y.now()),permanent:!0});continue}let E;try{E=await Y.fallbackManager.refreshAccount(N,B)}catch(g){f9.warn("fallback token refresh failed during quota poll",{pid:process.pid,accountId:N.id,error:X1(g)}),E=N}if(!E.access||(E.expires??0)<Y.now()){G({account:N.id,ok:!1,error:"no usable access token"});continue}let _;try{_=await J({accessToken:E.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:E.accountId,accountKey:N.id})}catch(g){if(!$U(g))throw g;if(f9.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}_=await J({accessToken:E.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:E.accountId,accountKey:N.id})}Y.quotaManager.setFallback(N.id,{quota:_,refreshAfter:Y.now()+300000,checkedAt:Y.now()},E.access,!0,E.accountId),U=!0,G({account:N.id,ok:!0})}catch(F){G({account:N.id,ok:!1,error:X1(F)})}}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 GU=300000,WU=30000,zU=240000,UU="bg-quota-refresh",LU=120000;function HU(Y,X){return yY({name:UU,ttlMs:LU,path:Y,renew:!0,...X})}function Q8(Y,X=y1,J=()=>HU(Y.configPath)){return NU(Y,X,J)}async function NU(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:zU})}finally{await Q?.release().catch(()=>{})}}class m9{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)*WU);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=$},GU+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 c9(Y){if(typeof Y!=="string")return!1;try{let X=JSON.parse(Y);return R(X)&&R(X.client_metadata)&&X.client_metadata.ws_request_header_x_openai_internal_codex_responses_lite==="true"}catch{return!1}}function u9(Y){if(typeof Y!=="string")return Y;try{let X=JSON.parse(Y);if(!R(X)||!R(X.client_metadata))return Y;if(!(("x-codex-turn-metadata"in X.client_metadata)||("x-codex-ws-stream-request-start-ms"in X.client_metadata)||("ws_request_header_x_openai_internal_codex_responses_lite"in X.client_metadata)))return Y;let J={...X.client_metadata};return delete J["x-codex-turn-metadata"],delete J["x-codex-ws-stream-request-start-ms"],delete J.ws_request_header_x_openai_internal_codex_responses_lite,JSON.stringify({...X,client_metadata:J})}catch{return Y}}function fY(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"),c9(Y.body))X.set("x-openai-internal-codex-responses-lite","true");return{...Y,headers:X,body:u9(Y.body)}}function U8(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 L8(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 $8(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 VU=300000,H8=1800000,G8=2*H8+900000,ZU=3600000,W8=1800000,z8=60000,KU=32,BU=8388608,p9=600000;function N8(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 FU(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 OU(Y,X){return N8(Y)?H8:X}function l9(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function V8(Y){if(!Y||typeof Y!=="object")return l9();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 jU(Y){try{let X=JSON.parse(Y);return V8(X.usage)}catch{return l9()}}function qU(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=V8(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??l9()}class d9{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??VU,this.tickIntervalMs=Y.tickIntervalMs??z8,this.leadMs=Y.leadMs??this.tickIntervalMs+15000;let X=Y.maxIdleWarmMs??Y.maxDurationMs;this.maxIdleWarmMs=typeof X==="number"&&Number.isFinite(X)&&X>0?X:ZU;let J=Y.maxSubagentIdleMs??W8;this.maxSubagentIdleMs=typeof J==="number"&&Number.isFinite(J)&&J>0?J:W8,this.tickIntervalMs=Y.tickIntervalMs??z8,this.maxTargets=Y.maxTargets??KU,this.maxBytes=Y.maxBytes??BU,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&&!$8(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,F]of this.targets){let q=Math.max(F.lastRealRequestAt,F.lastWarmedAt??0);if(q<B)V=N,B=q}if(V===void 0)break;let K=this.targets.get(V);if(K)this.totalBytes-=K.bodyText.length;this.targets.delete(V)}let H=OU(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:N8(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-G8;for(let[$,G]of this.targets){let W,U;if(this.isGpt56Subagent(G))W=Q,U=G8;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&&!$8(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()+p9;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 $=FU(X.bodyText),G;try{let q=JSON.parse($);G={warmBodyKeys:Object.keys(q),stream:q.stream,max_output_tokens:q.max_output_tokens,store:q.store,has_stream_options:"stream_options"in q,has_max_tokens:"max_tokens"in q,model:q.model}}catch{}this.log.debug("cachekeep warm request",this.logPayload({...G,headerKeys:Object.keys(Q),hasChatGptAccountId:"ChatGPT-Account-Id"in Q}));let W=fY({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()+p9,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?qU(H):jU(H),K=f1(U.headers),N=K.primary?.usedPercent??null,F=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:F})),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()+p9,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",error:$ instanceof Error?$.message:String($)}))}}}var B8=900000,DU=0.016666666666666666,Z8=0.000001;function n9(Y,X){for(let J of[Y?.primary?.checkedAt,Y?.checkedAt,X])if(typeof J==="number"&&Number.isFinite(J))return J;return}function o9(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let X=n9(Y.quota,Y.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||Y.now-X>B8)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let J=i9(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 PU(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,DU);return Q/G}function K8(Y,X){if(Y<X)return-1;if(Y>X)return 1;return 0}function MU(Y,X){if(!Y.quota)return;let J=n9(Y.quota,Y.quotaCheckedAt);if(J===void 0||X-J>B8)return;let Q=i9(Y.quota).map(({key:G,window:W})=>{return PU(W,Y.reservePercent[G]??0,X)}),$=Q.length>0?Math.min(...Q):0;return $>0?{candidate:Y,quotaCheckedAt:J,weight:$}:void 0}function F8(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(($)=>MU($,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,Z8),H=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,Z8);return U-H||G.candidate.configuredOrder-W.candidate.configuredOrder||K8(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||K8($.accountId,G.accountId)})[0];if(!Q)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Q.accountId,quotaCheckedAt:n9(Q.quota,Q.quotaCheckedAt),source:"mode-fallback"}}import{createHash as EU}from"node:crypto";import{chmod as wU,mkdir as AU,readdir as TU,readFile as RU,writeFile as r9}from"node:fs/promises";import{join as D8}from"node:path";var e9=H0("dump"),H1="x-cortexkit-openai-auth-dump-session",CU=["http","prewarm","main"],O8=0,m1=new Map,IU=100;function s9(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function P8(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 M8(Y){return EU("sha256").update(Y).digest("hex")}function a9(Y){return M8(JSON.stringify(Y))}function E8(Y){try{let X=JSON.parse(Y);return X!=null&&typeof X==="object"&&!Array.isArray(X)?X:void 0}catch{return}}function _U(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 SU(Y,X){if(!m1.has(Y))while(m1.size>=IU){let J=m1.keys().next().value;if(J===void 0)break;m1.delete(J)}m1.set(Y,X)}var j8=new Set;async function kU(Y,X,J){let Q=P8(X),$=CU.map((G)=>`-${Q}-${J}-${G}.body.json`);try{let W=(await TU(Y)).filter((U)=>$.some((H)=>U.endsWith(H))).sort().pop();if(!W)return;return await RU(D8(Y,W),"utf8")}catch{return}}function xU(Y){if(Y===void 0)return;return Object.fromEntries(new Headers(Y).entries())}function YX(Y){if(Array.isArray(Y))return Y.map(YX);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]=YX(Q)}return X}function bU(Y){let X=E8(Y);if(X===void 0)return Y;let J=vU(X),Q=JSON.stringify(J);if(Q===void 0)return Y;return JSON.stringify(X)===Q?Y:Q}function vU(Y){if(!R(Y))return t9(Y);let X={};for(let[J,Q]of Object.entries(Y))X[J]=J==="tools"?q8(Q):t9({[J]:Q})[J];return X}function hU(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function gU(Y){let X=E8(Y);if(!X)return{parseable:!1};let J=Array.isArray(X.input)?X.input:[],Q=Array.isArray(X.tools)?X.tools:[],$=Q.map(hU),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:a9(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:a9(J[0]),toolsCount:Q.length,toolTypes:$,toolsHash:a9(Q),hasWebSearch:$.includes("web_search"),clientMetadataKeys:G?Object.keys(G).sort():[]}}async function c1(Y){let X=E0();if(!X.dump)return;O8++;let J=Y.sessionID?.trim()||"session-unknown",Q=`${new Date().toISOString().replace(/[:.]/g,"-")}-${process.pid}-${String(O8).padStart(5,"0")}-${P8(J)}-${Y.transport}-${Y.phase}`,$=D8(X.dumpDir,Q),G={body:`${$}.body.json`,metadata:`${$}.meta.json`,request:`${$}.request.json`},W=`${Y.transport}:${J}`,U=m1.get(W),H=U?"memory":void 0;if(U===void 0&&!j8.has(W)){if(j8.add(W),U=await kU(X.dumpDir,J,Y.transport),U!==void 0)H="disk"}try{await AU(X.dumpDir,{recursive:!0,mode:448}),await wU(X.dumpDir,448).catch(()=>{});let L=bU(Y.bodyText),V={id:Q,createdAt:new Date().toISOString(),session:s9(J),transport:Y.transport,phase:Y.phase,accountId:Y.accountId,status:Y.status,error:Y.error,bodyBytes:Y.bodyText.length,bodyHash:M8(Y.bodyText),diff:_U(U,L),baselineSource:H,body:gU(Y.bodyText),files:G};await Promise.all([r9(G.body,L,{encoding:"utf8",mode:384}),r9(G.metadata,`${JSON.stringify(V,null,2)}
148
- `,{encoding:"utf8",mode:384}),r9(G.request,`${JSON.stringify(YX({url:Y.url,method:Y.method,accountId:Y.accountId,headers:xU(Y.headers)}),null,2)}
149
- `,{encoding:"utf8",mode:384})]),e9.debug("dumped request",{id:Q,session:s9(J),body:G.body,meta:G.metadata}),SU(W,L)}catch(L){e9.warn("request dump failed",{session:s9(J),error:L instanceof Error?L.message:String(L)})}}async function J1(Y){if(!E0().dump)return;e9.debug("diagnostic",Y)}import{tool as XY}from"@opencode-ai/plugin";var mY="ws_",T8=new Map,R8=XY({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:XY.schema.string().optional(),query:XY.schema.string().optional(),queries:XY.schema.array(XY.schema.string()).optional()},async execute(Y){return{title:"OpenAI Web Search",output:JSON.stringify({action:Y}),metadata:{action:Y}}}});function JX(Y){if(yU(Y))return;if(!mU(Y))return Y;let X=Y.item;return T8.set(X.id,X),{...Y,item:{type:"function_call",id:X.id,call_id:X.id,name:"web_search",arguments:JSON.stringify(R(X.action)?X.action:{})}}}function C8(Y){if(!Y.body)return Y;if(!(Y.headers.get("content-type")??"").includes("text/event-stream"))return Y;return new Response(fU(Y.body),{status:Y.status,statusText:Y.statusText,headers:Y.headers})}function I8(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(R(W)&&typeof W.call_id==="string"&&W.call_id.startsWith(mY)){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(cU(W)){J.set(W.call_id,W),X=!0;continue}if(uU(W,J)){Q.push(XX(W.call_id,W.output,J.get(W.call_id))),X=!0;continue}if(pU(W)){let U=T8.get(W.id);if(U)Q.push(XX(W.id,U));else{let H=$.get(W.id),L=G.get(W.id);if(H||L)Q.push(XX(W.id,L,H));else Q.push(W)}X=!0;continue}Q.push(W)}if(X)Y.input=Q;return X}function yU(Y){if(typeof Y.type==="string"&&Y.type.startsWith("response.web_search_call."))return!0;return Y.type==="response.output_item.added"&&R(Y.item)&&Y.item.type==="web_search_call"}function fU(Y){let X=new TextDecoder,J=new TextEncoder,Q="";return Y.pipeThrough(new TransformStream({transform($,G){Q+=X.decode($,{stream:!0});let W=w8(Q);while(W){let U=Q.slice(0,W.index);Q=Q.slice(W.index+W.length);let H=A8(U);if(H)G.enqueue(J.encode(H));W=w8(Q)}},flush($){if(Q+=X.decode(),!Q)return;let G=A8(Q);if(G)$.enqueue(J.encode(G))}}))}function w8(Y){let X=Y.indexOf(`
51
+ Warming limited to **${`${String(Z).padStart(2,"0")}-${String(U).padStart(2,"0")}`}** local hours.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:L?.sustain??$?.cachekeep?.sustain===!0,window:{startHour:Z,endHour:U},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`, `/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 pU={"openai-killswitch":yU,"openai-dump":fU,"openai-logging":mU,"openai-cachekeep":cU};function EX(Y,X,J){return PX(Y,X,J,pU)}var lU=300000,dU=30000,iU=240000,oU="bg-quota-refresh",nU=120000;function rU(Y,X){return H1({name:oU,ttlMs:nU,path:Y,renew:!0,...X})}function qQ(Y,X=E1,J=()=>rU(Y.paths.configPath)){return sU(Y,X,J)}async function sU(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:iU})}finally{await Q?.release().catch(()=>{})}}class MX{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)*dU);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=$},lU+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 wX(Y){if(typeof Y!=="string")return!1;try{let X=JSON.parse(Y);return h(X)&&h(X.client_metadata)&&X.client_metadata.ws_request_header_x_openai_internal_codex_responses_lite==="true"}catch{return!1}}function AX(Y){if(typeof Y!=="string")return Y;try{let X=JSON.parse(Y);if(!h(X)||!h(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 IY(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"),wX(Y.body))X.set("x-openai-internal-codex-responses-lite","true");return{...Y,headers:X,body:AX(Y.body)}}function PQ(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 EQ(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 FQ(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 aU=300000,MQ=1800000,OQ=2*MQ+900000,tU=3600000,jQ=1800000,DQ=60000,eU=32,YZ=8388608,TX=600000;function wQ(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 XZ(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 JZ(Y,X){return wQ(Y)?MQ:X}function RX(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function AQ(Y){if(!Y||typeof Y!=="object")return RX();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 QZ(Y){try{let X=JSON.parse(Y);return AQ(X.usage)}catch{return RX()}}function $Z(Y){let X,J=[],Q,$=()=>{if(!J.length)return;let G=J.join(`
52
+ `).trim();J=[];let W=X;if(X=void 0,!G||G==="[DONE]")return;try{let K=JSON.parse(G),Z=K.type??W;if(Z!=="response.completed"&&Z!=="response.done")return;let U=K.response;Q=AQ(U?.usage??K.usage)}catch{}};for(let G of Y.split(/\r?\n/)){if(G===""){$();continue}if(G.startsWith("event:")){X=G.slice(6).trim();continue}if(G.startsWith("data:"))J.push(G.slice(5).trim())}return $(),Q??RX()}class CX{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??aU,this.tickIntervalMs=Y.tickIntervalMs??DQ,this.leadMs=Y.leadMs??this.tickIntervalMs+15000;let X=Y.maxIdleWarmMs??Y.maxDurationMs;this.maxIdleWarmMs=typeof X==="number"&&Number.isFinite(X)&&X>0?X:tU;let J=Y.maxSubagentIdleMs??jQ;this.maxSubagentIdleMs=typeof J==="number"&&Number.isFinite(J)&&J>0?J:jQ,this.tickIntervalMs=Y.tickIntervalMs??DQ,this.maxTargets=Y.maxTargets??eU,this.maxBytes=Y.maxBytes??YZ,this.getWindow=Y.getWindow,this.getSustain=Y.getSustain}track(Y,X,J,Q,$={},G=!1){this.pruneStale();let W=X.length;if(W>this.maxBytes){this.log.debug("cachekeep track skipped (body exceeds maxBytes)",this.logPayload({sessionKey:Y,bodyBytes:W,maxBytes:this.maxBytes}));return}let K=this.getWindow?.();if(K&&!FQ(K,new Date(this.now()))){this.log.debug("cachekeep track skipped (outside window)",this.logPayload({sessionKey:Y,startHour:K.startHour,endHour:K.endHour}));return}if(this.targets.has(Y)){let L=this.targets.get(Y);if(L)this.totalBytes-=L.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 L,F=Number.POSITIVE_INFINITY;for(let[V,j]of this.targets){let R=Math.max(j.lastRealRequestAt,j.lastWarmedAt??0);if(R<F)L=V,F=R}if(L===void 0)break;let N=this.targets.get(L);if(N)this.totalBytes-=N.bodyText.length;this.targets.delete(L)}let Z=JZ(X,this.ttlMs),U={bodyText:X,accountId:J||void 0,chatgptAccountId:Q,route:"main",ttlMs:Z,cacheExpiresAt:this.now()+Z,warmCount:0,lastRealRequestAt:this.now(),replayHeaders:$,isSubagent:G,is56:wQ(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-OQ;for(let[$,G]of this.targets){let W,K;if(this.isGpt56Subagent(G))W=Q,K=OQ;else W=G.isSubagent?J:X,K=G.isSubagent?this.maxSubagentIdleMs:this.maxIdleWarmMs;if(!(G.isSubagent!==!0&&this.getSustain?.()===!0)&&G.lastRealRequestAt<W)this.log.debug("cachekeep pruned idle target",this.logPayload({sessionKey:$,accountId:G.accountId??"main",lastRealRequestAt:G.lastRealRequestAt,maxIdleWarmMs:K})),this.totalBytes-=G.bodyText.length,this.targets.delete($)}}start(){if(this.disposed=!1,this.timer)return;if(this.startedAt=this.now(),this.log.debug("cachekeep started",this.logPayload({ttlMs:this.ttlMs,leadMs:this.leadMs,maxIdleWarmMs:this.maxIdleWarmMs})),this.timer=setInterval(()=>{this.tick().catch(()=>{})},this.tickIntervalMs),"unref"in this.timer)this.timer.unref()}stop(){if(this.disposed=!0,this.abortController.abort(),this.abortController=new AbortController,this.timer)clearInterval(this.timer),this.timer=null;this.startedAt=null,this.targets.clear(),this.totalBytes=0,this.log.debug("cachekeep stopped",this.logPayload())}remove(Y){let X=this.targets.get(Y);if(X)this.totalBytes-=X.bodyText.length,this.targets.delete(Y),this.log.debug("cachekeep removed target",this.logPayload({sessionKey:Y}))}status(){let Y=this.now(),X=Array.from(this.targets.entries()).map(([J,Q])=>({sessionKey:J,accountId:Q.accountId,route:Q.route,cacheExpiresAt:Q.cacheExpiresAt,lastRealRequestAt:Q.lastRealRequestAt,lastWarmedAt:Q.lastWarmedAt,backoffUntil:Q.backoffUntil,bodyBytes:Q.bodyText.length}));return{running:this.timer!=null,tracked:this.targets.size,generatedAt:Y,startedAt:this.startedAt,maxIdleWarmMs:this.maxIdleWarmMs,maxSubagentIdleMs:this.maxSubagentIdleMs,ttlMs:this.ttlMs,leadMs:this.leadMs,sustain:this.getSustain?.()===!0,window:this.getWindow?.(),targets:X}}async tick(){if(this.tickInFlight)return;this.tickInFlight=!0;try{this.pruneStale();let Y=this.getWindow?.();if(Y&&!FQ(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,Q;try{if(X.accountId&&X.accountId!=="main"){let G=await this.refreshFallback(X.accountId);if(typeof G==="string")J=G;else J=G.token,Q=G.onAuthFailure}else J=await this.getMainToken()}catch(G){if(!this.disposed&&this.targets.get(Y)===X)X.backoffUntil=this.now()+TX;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 $={...X.replayHeaders,authorization:`Bearer ${J}`,"content-type":"application/json"};if(X.chatgptAccountId)$["ChatGPT-Account-Id"]=X.chatgptAccountId;else delete $["ChatGPT-Account-Id"];try{let G=XZ(X.bodyText),W;try{let S=JSON.parse(G);W={warmBodyKeys:Object.keys(S),stream:S.stream,max_output_tokens:S.max_output_tokens,store:S.store,has_stream_options:"stream_options"in S,has_max_tokens:"max_tokens"in S,model:S.model}}catch{}this.log.debug("cachekeep warm request",this.logPayload({...W,headerKeys:Object.keys($),hasChatGptAccountId:"ChatGPT-Account-Id"in $}));let K=IY({method:"POST",headers:$,body:G,signal:AbortSignal.any([AbortSignal.timeout(30000),this.abortController.signal])}),Z=await this.fetchImpl(this.codexResponsesUrl,K),U="";try{U=await Z.text()}catch{}if(this.disposed||this.targets.get(Y)!==X)return;if(!Z.ok){if(X.backoffUntil=this.now()+TX,Z.status===401)await Q?.(Z.status);this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",status:Z.status,error:`HTTP ${Z.status}`,responseBody:U.slice(0,600)}));return}let L=Z.headers.get("content-type")??"",F=L.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(U.slice(0,200));this.log.debug("cachekeep warm response",this.logPayload({status:Z.status,contentType:L,bodyLen:U.length,isSse:F}));let N=F?$Z(U):QZ(U),V=X9(Z.headers),j=V.primary?.usedPercent??null,R=V.secondary?.usedPercent??null;if(this.log.debug("cachekeep fired",this.logPayload({session:Y,accountId:X.accountId??"main",input_tokens:N.input_tokens,cached_tokens:N.cached_tokens,hit_rate:N.hit_rate,output_tokens:N.output_tokens,quota_primary_pct:j,quota_secondary_pct:R})),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()+TX,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",error:G instanceof Error?G.message:String(G)}))}}}import{createHash as zZ}from"node:crypto";import{isAbsolute as GZ,join as TQ}from"node:path";var WZ=B0("custody"),RQ=new Set;function IX(Y=process.env){let X=Y.CLAUSTRUM_OPENCODE_HANDLES;if(X&&GZ(X))return X;if(X&&!RQ.has(X))RQ.add(X),WZ.warn("ignoring non-absolute CLAUSTRUM_OPENCODE_HANDLES",{configuredPath:X});let J=Y.XDG_CONFIG_HOME||(Y.HOME?TQ(Y.HOME,".config"):".config");return TQ(J,"cortexkit","opencode-handles.json")}function s0(Y=IX(),X={}){return CQ(Y,X)}var _X="openai",IQ=250,bQ=new Set;function vQ(Y){if(typeof Y.access!=="string"||typeof Y.refresh!=="string")return;let X=Buffer.from(Y.access),J=Buffer.from(Y.refresh),Q=($)=>{let G=Buffer.alloc(4);return G.writeUInt32BE($.length),G};return zZ("sha256").update(Q(X)).update(X).update(Q(J)).update(J).digest("hex")}function hQ(Y){let X=vQ(Y);if(X)bQ.add(X)}function KZ(Y){let X=vQ(Y);return X!==void 0&&bQ.has(X)}function gQ(Y){if(!Y||typeof Y!=="object")return;let X=Y;if(X.type!=="oauth")return;return{type:"oauth",...typeof X.access==="string"?{access:X.access}:{},...typeof X.refresh==="string"?{refresh:X.refresh}:{},...typeof X.expires==="number"?{expires:X.expires}:{}}}function SY(Y){let X=gQ(Y);if(typeof X?.access!=="string"||typeof X.refresh!=="string")return;return{access:X.access,refresh:X.refresh,...typeof X.expires==="number"?{expires:X.expires}:{}}}function _Y(Y){let X=gQ(Y);if(!X)return{kind:"indeterminate"};if(!k0({id:"main",type:"oauth",access:X.access??"",refresh:X.refresh??"",expires:X.expires??0,addedAt:0},_X))return{kind:"real",oauth:X};let J=V1(_X);if(X.access===J.access&&X.expires===J.expires)return{kind:"tombstone",oauth:X};return{kind:"empty",oauth:X}}async function _Q(Y){if(!Y.auth.get)return;return Y.auth.get({path:{id:_X}})}async function SQ(Y){if(!Y.auth.all)return!1;return Object.keys(await Y.auth.all()).length>0}async function UZ(Y){let X=await _Q(Y.client);if(X!==void 0)return _Y(X);let J=await SQ(Y.client),Q=Y.now();if(await Y.sleep(IQ),Y.now()-Q<IQ)return{kind:"indeterminate"};let $=await _Q(Y.client);if($!==void 0)return _Y($);let G=await SQ(Y.client);return J&&G?{kind:"slot-absent"}:{kind:"indeterminate"}}function ZZ(Y){if(Y.ok)return"present";return Y.reason==="absent"?"absent":"unreadable"}function k9(Y){let X=Q1(Y);return X?$1(X):void 0}async function kQ(Y){let X=y0(Y.manifest).get("main");if(!X)return"no_handle";if(!Y.getCredential)return"cold";try{let J=await Y.getCredential(X),Q=k9(J.access);if(Y.mainAccountId&&Q&&Q!==Y.mainAccountId)return"identity_mismatch";return"serves"}catch{return Y.isReauth?.(X)?"needs_reauth":"cold"}}function xQ(Y){return Y.kind==="real"&&KZ(Y.oauth)}async function yQ(Y){let X=await UZ(Y);if(X.kind==="indeterminate")return;let J=ZZ(Y.manifest);if(X.kind==="slot-absent"){let $=await kQ(Y);return S9({mode:Y.mode,manifest:J,local:X.kind,verifiedInProcessLogin:xQ(X),vault:()=>$==="no_handle"||$==="identity_mismatch"?$:"serves"})}let Q=await kQ(Y);return S9({mode:Y.mode,manifest:J,local:X.kind,verifiedInProcessLogin:xQ(X),vault:()=>Q})}import{createHash as LZ}from"node:crypto";var dQ="claustrum-mode",u1="main-refresh",fQ=Promise.resolve();async function kX(){let Y,X=new Promise(($)=>{Y=$}),J=fQ;fQ=J.then(()=>X),await J;let Q=!1;return{async release(){if(Q)return;Q=!0,Y()}}}async function iQ(Y){let X=Y.now()+5000;while(Y.now()<X){try{let J=await Y.getAuth();if(J?.access===Y.accessToken&&J.refresh===Y.refreshToken){await Y.onObserved?.({access:J.access,refresh:J.refresh}),await Y.release();return}}catch{}await Y.sleep(Math.max(0,Math.min(100,X-Y.now())))}Y.warn("host write not observed within 5s; lease released"),await Y.release()}function mQ(Y){return Y.accounts.filter((X)=>V0(X)&&X.enabled!==!1)}function SX(Y,X){return Y<X?-1:Y>X?1:0}function uQ(Y,X){return[{id:"main",accountId:X?.mainAccountId,kind:"main"},...Y.map((J)=>({id:J,accountId:X?.accounts.find((Q)=>Q.id===J)?.accountId,kind:"fallback"}))].sort((J,Q)=>SX(J.id,Q.id))}function HZ(Y){return Y.kind==="main"?u1:M1(Y.id)}function cQ(Y){return Y.access?J9(Y.access,Y.refresh):void 0}function pQ(Y){return Object.values(Y).some((X)=>X==="new-local-family-under-claustrum"||X==="torn-read-deferred"||X.startsWith("aborted:"))}async function oQ(Y){let X=await kX(),J=[],Q={},$=!1,G=async(W)=>{await Y.onStep?.(W)};try{if(await G("mutex-acquired"),Y.accountIds.includes("main")||new Set(Y.accountIds).size!==Y.accountIds.length)return{status:"aborted",outcomes:Q,reason:"duplicate-account-lock"};let W=await Y.acquireLock({name:dQ,renew:!0});if(!W)return{status:"aborted",outcomes:Q,reason:"mode-lock-unavailable"};J.push(W),Y.warn?.(`transition deps: ${JSON.stringify({acquireLock:typeof Y.acquireLock,withStoreTransaction:typeof Y.withStoreTransaction,readManifest:typeof Y.readManifest,preflight:typeof Y.preflight,auth:typeof Y.auth,authAll:typeof Y.auth?.all,authGet:typeof Y.auth?.get,authSet:typeof Y.auth?.set,accountIds:Y.accountIds?.length})}`);let K=uQ(Y.accountIds);Y.warn?.(`transition participants: ${K.map((Z)=>Z.id).join(",")}`);for(let Z of K){let U=await Y.acquireLock({name:HZ(Z),renew:!0});if(!U)return{status:"aborted",outcomes:Q,reason:`account-lock-unavailable:${Z.id}`};J.push(U)}return await Y.withStoreTransaction(async(Z)=>{let U=await Z.read(),L=uQ(Y.accountIds,U),F=mQ(U).map((E)=>E.id).sort(SX),N=[...Y.accountIds].sort(SX);if(F.length!==N.length||F.some((E,b)=>E!==N[b]))return{status:"aborted",outcomes:Q,reason:"account-roster-changed"};let V=await Y.readManifest();if(!V.ok)return{status:"aborted",outcomes:Q,reason:`manifest-${V.reason}`};let j=y0(V),R=U.claustrum?.mode==="claustrum"?U.claustrum?.transition:void 0,S=R?R.fingerprints:{fallbacks:{}},u=R?.storeGeneration??lQ(U);if(!R){Y.warn?.(`capturing main slot fingerprint; auth.get is ${typeof Y.auth?.get}`);let E=SY(await Y.auth.get({path:{id:"openai"}}));if(Y.warn?.(`main slot captured: ${E?"complete":"absent"}`),E)S.main=J9(E.access,E.refresh);for(let b of mQ(U)){let f=cQ(b);if(f)S.fallbacks[b.id]=f}}await G("captured"),Y.warn?.(`handles resolved: isMap=${j instanceof Map} size=${j instanceof Map?j.size:"n/a"}`);for(let E of L){let b=j.get(E.id);if(Y.warn?.(`participant ${E.id}: handle=${b?"yes":"NO"}`),!b){Q[E.id]="no-handle";continue}let f=await Y.preflight({id:E.id,accountId:E.accountId,handle:b});Q[E.id]=f}if(await G("preflight"),Object.values(Q).some((E)=>E!=="ready"))return{status:"aborted",outcomes:Q,reason:"preflight-failed"};if(!R){let E=await Y.readManifest(),b=await Z.read();if(!E.ok||E.revision!==V.revision)return{status:"aborted",outcomes:Q,reason:"manifest-revision-changed"};if(lQ(b)!==u)return{status:"aborted",outcomes:Q,reason:"store-generation-changed"};await G("revalidated"),await Z.writeMode("claustrum",{manifestRevision:V.revision,storeGeneration:u,fingerprints:S}),await G("mode-written")}let I=!1;for(let E of K){if(E.kind==="main")continue;let b=await Z.read(),f=b.accounts.find((W0)=>W0.id===E.id&&W0.type==="oauth");if(f&&k0(f,"openai")){Q[E.id]="tombstoned";continue}let o=S.fallbacks[E.id];if(!f||!o||cQ(f)!==o){Q[E.id]="new-local-family-under-claustrum";continue}let t=structuredClone(b),N0=t.accounts.find((W0)=>W0.id===E.id&&W0.type==="oauth");if(!N0){Q[E.id]="new-local-family-under-claustrum";continue}Object.assign(N0,V1("openai"));try{await Z.write(t);let W0=(await Z.read()).accounts.find((F0)=>F0.id===E.id&&F0.type==="oauth");Q[E.id]=W0&&k0(W0,"openai")?"tombstoned":"aborted:post-write-readback"}catch{Q[E.id]="aborted:write-failed",I=!0;break}}if(I)return await G("material-written"),{status:"incomplete",outcomes:Q};if(Q.main=S.main?await xX(S.main,{auth:Y.auth,warn:(E)=>{if($)return;$=!0,Y.warn?.(E)}}):"new-local-family-under-claustrum",await G("material-written"),!pQ(Q))await Z.writeMode("claustrum");return{status:pQ(Q)?"incomplete":"completed",outcomes:Q}})}finally{for(let W of J.reverse())await W.release().catch(()=>{});await X.release(),await G("mutex-released").catch(()=>{})}}async function xX(Y,X){let J=SY(await X.auth.get({path:{id:"openai"}}));if(J&&k0({id:"main",type:"oauth",access:J.access,refresh:J.refresh,expires:J.expires??0},"openai"))return"tombstoned";if(!J||J9(J.access,J.refresh)!==Y)return"new-local-family-under-claustrum";let Q=await X.auth.all();if(Object.keys(Q).length===0)return X.warn?.("host auth store read empty; refusing to write — possible torn read"),"torn-read-deferred";try{let $=V1("openai");await X.auth.set.bind(X.auth)({path:{id:"openai"},body:$});let W=SY(await X.auth.get({path:{id:"openai"}}));return W&&W.access===$.access&&W.refresh===$.refresh&&W.expires===$.expires?"tombstoned":"new-local-family-under-claustrum"}catch{return"aborted:write-failed"}}async function nQ(Y){let X=await Y.acquireLock({name:dQ,renew:!0});if(!X)throw Error("Claustrum mode lock unavailable");try{await Y.withStoreTransaction(async(J)=>{return await J.writeMode("local"),{status:"completed",outcomes:{}}})}finally{await X.release()}}function lQ(Y){let X=Y.accounts.filter((J)=>J.type==="oauth").map((J)=>({id:J.id,enabled:J.enabled!==!1,accountId:J.accountId??"",access:J.access??"",refresh:J.refresh,expires:J.expires??null})).sort((J,Q)=>J.id<Q.id?-1:J.id>Q.id?1:0);return LZ("sha256").update(JSON.stringify(X)).digest("hex")}var eQ=900000,VZ=0.016666666666666666,rQ=0.000001;function vX(Y,X){for(let J of[Y?.primary?.checkedAt,Y?.checkedAt,X])if(typeof J==="number"&&Number.isFinite(J))return J;return}function hX(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let X=vX(Y.quota,Y.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||Y.now-X>eQ)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let J=bX(Y.quota).sort(($,G)=>{let W=$.windowMs,K=G.windowMs,Z=typeof W==="number"&&Number.isFinite(W),U=typeof K==="number"&&Number.isFinite(K);if(Z!==U)return Z?-1:1;if(Z&&U)return K-W;return 0});for(let{key:$,window:G}of J)if(Number.isFinite(G.remainingPercent)&&G.remainingPercent<=0)return{action:"migrate",reason:"exhausted",windowKey:$,...typeof G.resetsAt==="string"?{resetsAt:G.resetsAt}:{}};let Q=tQ(Y.quota,Y.now);if(Q)return{action:"migrate",reason:"exhausted",resetsAt:Q.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 sQ(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,VZ);return Q/G}function aQ(Y,X){if(Y<X)return-1;if(Y>X)return 1;return 0}function NZ(Y,X){if(!Y.quota)return;let J=vX(Y.quota,Y.quotaCheckedAt);if(J===void 0||X-J>eQ)return;let Q=bX(Y.quota).map(({key:W,window:K})=>{return sQ(K,Y.reservePercent[W]??0,X)}),$=Y.quota.spendControl;if($&&Number.isFinite($.remainingPercent))Q.push(sQ($,0,X));let G=Q.length>0?Math.min(...Q):0;return G>0?{candidate:Y,quotaCheckedAt:J,weight:G}:void 0}function Y5(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(($)=>NZ($,Y.now)).filter(($)=>$!==void 0);if(J.length>0){J.sort((G,W)=>{let K=((Y.pendingBytes.get(G.candidate.accountId)??0)+Y.requestBytes)/Math.max(G.weight,rQ),Z=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,rQ);return K-Z||G.candidate.configuredOrder-W.candidate.configuredOrder||aQ(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||aQ($.accountId,G.accountId)})[0];if(!Q)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Q.accountId,quotaCheckedAt:vX(Q.quota,Q.quotaCheckedAt),source:"mode-fallback"}}import{createHash as BZ}from"node:crypto";import{chmod as qZ,mkdir as FZ,readdir as OZ,readFile as jZ,writeFile as gX}from"node:fs/promises";import{join as $5}from"node:path";var uX=B0("dump"),w1="x-cortexkit-openai-auth-dump-session",DZ=["http","prewarm","main"],X5=0,Q9=new Map,PZ=100;function yX(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function G5(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 W5(Y){return BZ("sha256").update(Y).digest("hex")}function fX(Y){return W5(JSON.stringify(Y))}function z5(Y){try{let X=JSON.parse(Y);return X!=null&&typeof X==="object"&&!Array.isArray(X)?X:void 0}catch{return}}function EZ(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 MZ(Y,X){if(!Q9.has(Y))while(Q9.size>=PZ){let J=Q9.keys().next().value;if(J===void 0)break;Q9.delete(J)}Q9.set(Y,X)}var J5=new Set;async function wZ(Y,X,J){let Q=G5(X),$=DZ.map((G)=>`-${Q}-${J}-${G}.body.json`);try{let W=(await OZ(Y)).filter((K)=>$.some((Z)=>K.endsWith(Z))).sort().pop();if(!W)return;return await jZ($5(Y,W),"utf8")}catch{return}}function AZ(Y){if(Y===void 0)return;return Object.fromEntries(new Headers(Y).entries())}function cX(Y){if(Array.isArray(Y))return Y.map(cX);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]=cX(Q)}return X}function TZ(Y){let X=z5(Y);if(X===void 0)return Y;let J=RZ(X),Q=JSON.stringify(J);if(Q===void 0)return Y;return JSON.stringify(X)===Q?Y:Q}function RZ(Y){if(!h(Y))return mX(Y);let X={};for(let[J,Q]of Object.entries(Y))X[J]=J==="tools"?Q5(Q):mX({[J]:Q})[J];return X}function CZ(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function IZ(Y){let X=z5(Y);if(!X)return{parseable:!1};let J=Array.isArray(X.input)?X.input:[],Q=Array.isArray(X.tools)?X.tools:[],$=Q.map(CZ),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:fX(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:fX(J[0]),toolsCount:Q.length,toolTypes:$,toolsHash:fX(Q),hasWebSearch:$.includes("web_search"),clientMetadataKeys:G?Object.keys(G).sort():[]}}async function $9(Y){let X=g0();if(!X.dump)return;X5++;let J=Y.sessionID?.trim()||"session-unknown",Q=`${new Date().toISOString().replace(/[:.]/g,"-")}-${process.pid}-${String(X5).padStart(5,"0")}-${G5(J)}-${Y.transport}-${Y.phase}`,$=$5(X.dumpDir,Q),G={body:`${$}.body.json`,metadata:`${$}.meta.json`,request:`${$}.request.json`},W=`${Y.transport}:${J}`,K=Q9.get(W),Z=K?"memory":void 0;if(K===void 0&&!J5.has(W)){if(J5.add(W),K=await wZ(X.dumpDir,J,Y.transport),K!==void 0)Z="disk"}try{await FZ(X.dumpDir,{recursive:!0,mode:448}),await qZ(X.dumpDir,448).catch(()=>{});let U=TZ(Y.bodyText),L={id:Q,createdAt:new Date().toISOString(),session:yX(J),transport:Y.transport,phase:Y.phase,accountId:Y.accountId,status:Y.status,error:Y.error,bodyBytes:Y.bodyText.length,bodyHash:W5(Y.bodyText),diff:EZ(K,U),baselineSource:Z,body:IZ(Y.bodyText),files:G};await Promise.all([gX(G.body,U,{encoding:"utf8",mode:384}),gX(G.metadata,`${JSON.stringify(L,null,2)}
53
+ `,{encoding:"utf8",mode:384}),gX(G.request,`${JSON.stringify(cX({url:Y.url,method:Y.method,accountId:Y.accountId,headers:AZ(Y.headers)}),null,2)}
54
+ `,{encoding:"utf8",mode:384})]),uX.debug("dumped request",{id:Q,session:yX(J),body:G.body,meta:G.metadata}),MZ(W,U)}catch(U){uX.warn("request dump failed",{session:yX(J),error:U instanceof Error?U.message:String(U)})}}async function N1(Y){if(!g0().dump)return;uX.debug("diagnostic",Y)}import{tool as x9}from"@opencode-ai/plugin";var kY="ws_",Z5=new Map,L5=x9({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:x9.schema.string().optional(),query:x9.schema.string().optional(),queries:x9.schema.array(x9.schema.string()).optional()},async execute(Y){return{title:"OpenAI Web Search",output:JSON.stringify({action:Y}),metadata:{action:Y}}}});function lX(Y){if(_Z(Y))return;if(!kZ(Y))return Y;let X=Y.item;return Z5.set(X.id,X),{...Y,item:{type:"function_call",id:X.id,call_id:X.id,name:"web_search",arguments:JSON.stringify(h(X.action)?X.action:{})}}}function H5(Y){if(!Y.body)return Y;if(!(Y.headers.get("content-type")??"").includes("text/event-stream"))return Y;return new Response(SZ(Y.body),{status:Y.status,statusText:Y.statusText,headers:Y.headers})}function V5(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(h(W)&&typeof W.call_id==="string"&&W.call_id.startsWith(kY)){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(xZ(W)){J.set(W.call_id,W),X=!0;continue}if(bZ(W,J)){Q.push(pX(W.call_id,W.output,J.get(W.call_id))),X=!0;continue}if(vZ(W)){let K=Z5.get(W.id);if(K)Q.push(pX(W.id,K));else{let Z=$.get(W.id),U=G.get(W.id);if(Z||U)Q.push(pX(W.id,U,Z));else Q.push(W)}X=!0;continue}Q.push(W)}if(X)Y.input=Q;return X}function _Z(Y){if(typeof Y.type==="string"&&Y.type.startsWith("response.web_search_call."))return!0;return Y.type==="response.output_item.added"&&h(Y.item)&&Y.item.type==="web_search_call"}function SZ(Y){let X=new TextDecoder,J=new TextEncoder,Q="";return Y.pipeThrough(new TransformStream({transform($,G){Q+=X.decode($,{stream:!0});let W=K5(Q);while(W){let K=Q.slice(0,W.index);Q=Q.slice(W.index+W.length);let Z=U5(K);if(Z)G.enqueue(J.encode(Z));W=K5(Q)}},flush($){if(Q+=X.decode(),!Q)return;let G=U5(Q);if(G)$.enqueue(J.encode(G))}}))}function K5(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 A8(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 U5(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(!R(J))return`${Y}
63
+ `;try{let J=JSON.parse(X);if(!h(J))return`${Y}
159
64
 
160
- `;let Q=JX(J);if(!Q)return"";return`data: ${JSON.stringify(Q)}
65
+ `;let Q=lX(J);if(!Q)return"";return`data: ${JSON.stringify(Q)}
161
66
 
162
67
  `}catch{return`${Y}
163
68
 
164
- `}}function mU(Y){return Y.type==="response.output_item.done"&&R(Y.item)&&Y.item.type==="web_search_call"&&typeof Y.item.id==="string"}function cU(Y){return R(Y)&&Y.type==="function_call"&&Y.name==="web_search"&&typeof Y.call_id==="string"&&Y.call_id.startsWith(mY)}function uU(Y,X){return R(Y)&&Y.type==="function_call_output"&&typeof Y.call_id==="string"&&typeof Y.output==="string"&&Y.call_id.startsWith(mY)&&X.has(Y.call_id)}function pU(Y){return R(Y)&&Y.type==="item_reference"&&typeof Y.id==="string"&&Y.id.startsWith(mY)}function XX(Y,X,J){let Q=lU(X),$=R(Q?.action)?Q.action:dU(J?.arguments);return{type:"web_search_call",status:"completed",...$?{action:$}:{}}}function lU(Y){if(R(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return R(X)?X:void 0}catch{return}}function dU(Y){if(R(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return R(X)?X:void 0}catch{return}}import{readFile as iU}from"node:fs/promises";import{homedir as nU}from"node:os";import{join as _8}from"node:path";var oU="https://models.dev/api.json",rU="OPENCODE_OPENAI_AUTH_MODELS_CACHE",sU="OPENCODE_MODELS_PATH",aU="OPENCODE_DISABLE_MODELS_FETCH",tU=1e4,eU=300000;function N1(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function S8(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function QX(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=S8(Y.cache_read),$=S8(Y.cache_write);if(Q===null||$===null)return null;return{input:X,output:J,cache:{read:Q,write:$}}}function YL(Y){let X=N1(Y);if(!X)return null;let J=QX(X);if(!J)return null;let Q=J;if(Array.isArray(X.tiers)){let W=[];for(let U of X.tiers){let H=N1(U);if(!H)continue;let L=N1(H.tier),V=L?.size;if(L?.type!=="context")continue;if(typeof V!=="number"||!Number.isFinite(V)||V<=0)continue;let B=QX(H);if(!B)continue;W.push({...B,tier:{type:"context",size:V}})}if(W.length>0)Q.tiers=W}let $=N1(X.context_over_200k),G=$?QX($):null;if(G)Q.experimentalOver200K=G;return Q}function k8(Y){let X=N1(Y),J=N1(X?.openai),Q=N1(J?.models);if(!Q)return null;let $={};for(let[G,W]of Object.entries(Q)){let U=N1(W),H=YL(U?.cost);if(H)$[G]=H}return Object.keys($).length>0?$:null}function XL(){let Y=process.env[rU]?.trim();if(Y)return Y;let X=process.env[sU]?.trim();if(X)return X;let J=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||_8(nU(),".cache");return _8(J,"opencode","models.json")}function JL(){let Y=process.env[aU]?.toLowerCase();return Y==="true"||Y==="1"}async function QL(){try{let Y=k8(JSON.parse(await iU(XL(),"utf8")));if(Y)return Y}catch{}if(JL())return null;try{let Y=await fetch(oU,{signal:AbortSignal.timeout(tU)});if(!Y.ok)return null;return k8(await Y.json())}catch{return null}}var u1;function x8(){let Y=Date.now();if(u1&&u1.expiresAt>Y)return u1.promise;let X={expiresAt:Y+eU,promise:QL()};return u1=X,X.promise.then((J)=>{if(J===null&&u1===X)u1=void 0}),X.promise}function p1(Y){return typeof Y==="object"&&Y!==null}function $L(Y){if(Array.isArray(Y))return Y;if(p1(Y)&&Array.isArray(Y.data))return Y.data;return[]}function GL(Y){if(!p1(Y)||!p1(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function b8(Y){if(!p1(Y)||!p1(Y.info))return null;let X=Y.info,J=p1(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 v8(Y,X){return{agent:Y.agent??X.agent,model:Y.model??X.model,variant:Y.variant??X.variant}}function h8(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function g8(Y,X){if(!Y||!X)return null;let J=Y;if(typeof J.session?.messages!=="function")return null;let Q=[];try{Q=$L(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(GL(Q[G])!=="assistant")continue;let W=b8(Q[G]);if(!W)continue;if($=v8($,W),h8($))return $}for(let G=Q.length-1;G>=0;G--){let W=b8(Q[G]);if(!W)continue;if($=v8($,W),h8($))return $}if(!$.agent&&!$.model&&!$.variant)return null;return $}var V1=[],WL=1,$X=0,y8=new Map;function GX(Y,X){if(V1.push({id:WL++,type:"open-dialog",payload:Y,sessionId:X}),V1.length>100)V1=V1.slice(V1.length-100)}function f8(Y=0,X){let J=Date.now();if($X=J,X!==void 0)y8.set(X,J);let Q=($)=>X===void 0||$.sessionId===void 0||$.sessionId===X;if(Y>0)V1=V1.filter(($)=>{if($.id>Y)return!0;if(X===void 0)return!1;return $.sessionId!==X});return V1.filter(($)=>$.id>Y&&Q($))}function m8(Y){let X=Date.now();if(Y!==void 0){let J=y8.get(Y)??0;return J>0&&X-J<3000}return $X>0&&X-$X<3000}import{randomBytes as zL,timingSafeEqual as UL}from"node:crypto";import{unlink as LL}from"node:fs/promises";import{createServer as HL}from"node:http";import{join as NL}from"node:path";var c8=H0("rpc");function VL(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 ZL(Y,X){if(!Y?.startsWith("Bearer "))return!1;let J=Buffer.from(Y.slice(7)),Q=Buffer.from(X);return J.length===Q.length&&UL(J,Q)}async function l8(Y){let X=zL(32).toString("hex"),J=Y.timeoutMs??90000,Q=Y.receiptTimeoutMs??2000,$=HL((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(!ZL(U.headers.authorization,X))return L(401,{error:"unauthorized"});let B=V.slice(5),K=await VL(U),N=JSON.parse(K||"{}");if(B==="pending-notifications"){let F=Y.drain(Number(N.lastReceivedId??0),typeof N.sessionId==="string"?N.sessionId:void 0);return L(200,{messages:F})}if(B==="apply"){let F=await Y.apply(N);return L(200,F)}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 p8(Y.sweepRoot,Y.dir)}catch(U){c8.warn("rpc state sweep failed",{pid:process.pid,error:U instanceof Error?U.message:String(U)})}try{await u8(Y.dir,{port:W,token:X,pid:process.pid},{secureDir:Y.secureDir}),c8.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 LL(NL(Y.dir,`port-${process.pid}.json`)).catch(()=>{})}}}function Q1(Y){return JSON.stringify(WX(Y))??"undefined"}function WX(Y){if(Array.isArray(Y))return Y.map(WX);if(!R(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((X)=>[X,WX(Y[X])]))}function C1(){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 q1={};LX(q1,{withoutInternalHeaders:()=>A4,sanitizeHttpFallbackBody:()=>u9,orderCodexBody:()=>DY,hasWebSocketResponsesLiteMetadata:()=>c9,createWebSocketFetch:()=>FK,applyTurnId:()=>P4,advanceTurn:()=>zJ,TITLE_HEADER:()=>WJ,QUOTA_ACCOUNT_HEADER:()=>B9,OpenAIWebSocketPool:()=>q1,CODEX_BODY_KEY_ORDER:()=>q4});import{createHash as NK}from"node:crypto";var PQ="vercel.ai.error",KL=Symbol.for(PQ),d8,i8,D=class Y extends(i8=Error,d8=KL,i8){constructor({name:X,message:J,cause:Q}){super(J);this[d8]=!0,this.name=X,this.cause=Q}static isInstance(X){return Y.hasMarker(X,PQ)}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}},MQ="AI_APICallError",EQ=`vercel.ai.error.${MQ}`,BL=Symbol.for(EQ),n8,o8,JY=class extends(o8=D,n8=BL,o8){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:MQ,message:Y,cause:W});this[n8]=!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,EQ)}},wQ="AI_EmptyResponseBodyError",AQ=`vercel.ai.error.${wQ}`,FL=Symbol.for(AQ),r8,s8,OL=class extends(s8=D,r8=FL,s8){constructor({message:Y="Empty response body"}={}){super({name:wQ,message:Y});this[r8]=!0}static isInstance(Y){return D.hasMarker(Y,AQ)}};function I1(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 TQ="AI_InvalidArgumentError",RQ=`vercel.ai.error.${TQ}`,jL=Symbol.for(RQ),a8,t8,CQ=class extends(t8=D,a8=jL,t8){constructor({message:Y,cause:X,argument:J}){super({name:TQ,message:Y,cause:X});this[a8]=!0,this.argument=J}static isInstance(Y){return D.hasMarker(Y,RQ)}},IQ="AI_InvalidPromptError",_Q=`vercel.ai.error.${IQ}`,qL=Symbol.for(_Q),e8,YQ,DL=class extends(YQ=D,e8=qL,YQ){constructor({prompt:Y,message:X,cause:J}){super({name:IQ,message:`Invalid prompt: ${X}`,cause:J});this[e8]=!0,this.prompt=Y}static isInstance(Y){return D.hasMarker(Y,_Q)}},SQ="AI_InvalidResponseDataError",kQ=`vercel.ai.error.${SQ}`,PL=Symbol.for(kQ),XQ,JQ,ML=class extends(JQ=D,XQ=PL,JQ){constructor({data:Y,message:X=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:SQ,message:X});this[XQ]=!0,this.data=Y}static isInstance(Y){return D.hasMarker(Y,kQ)}},xQ="AI_JSONParseError",bQ=`vercel.ai.error.${xQ}`,EL=Symbol.for(bQ),QQ,$Q,cY=class extends($Q=D,QQ=EL,$Q){constructor({text:Y,cause:X}){super({name:xQ,message:`JSON parsing failed: Text: ${Y}.
165
- Error message: ${I1(X)}`,cause:X});this[QQ]=!0,this.text=Y}static isInstance(Y){return D.hasMarker(Y,bQ)}},vQ="AI_LoadAPIKeyError",hQ=`vercel.ai.error.${vQ}`,wL=Symbol.for(hQ),GQ,WQ,AL=class extends(WQ=D,GQ=wL,WQ){constructor({message:Y}){super({name:vQ,message:Y});this[GQ]=!0}static isInstance(Y){return D.hasMarker(Y,hQ)}},gQ="AI_LoadSettingError",yQ=`vercel.ai.error.${gQ}`,TL=Symbol.for(yQ),zQ,UQ,RL=class extends(UQ=D,zQ=TL,UQ){constructor({message:Y}){super({name:gQ,message:Y});this[zQ]=!0}static isInstance(Y){return D.hasMarker(Y,yQ)}},fQ="AI_NoContentGeneratedError",mQ=`vercel.ai.error.${fQ}`,CL=Symbol.for(mQ),LQ,HQ,IL=class extends(HQ=D,LQ=CL,HQ){constructor({message:Y="No content generated."}={}){super({name:fQ,message:Y});this[LQ]=!0}static isInstance(Y){return D.hasMarker(Y,mQ)}},cQ="AI_NoSuchModelError",uQ=`vercel.ai.error.${cQ}`,_L=Symbol.for(uQ),NQ,VQ,zX=class extends(VQ=D,NQ=_L,VQ){constructor({errorName:Y=cQ,modelId:X,modelType:J,message:Q=`No such ${J}: ${X}`}){super({name:Y,message:Q});this[NQ]=!0,this.modelId=X,this.modelType=J}static isInstance(Y){return D.hasMarker(Y,uQ)}},pQ="AI_NoSuchProviderReferenceError",lQ=`vercel.ai.error.${pQ}`,SL=Symbol.for(lQ),ZQ,KQ,kL=class extends(KQ=D,ZQ=SL,KQ){constructor({provider:Y,reference:X,message:J=`No provider reference found for provider '${Y}'. Available providers: ${Object.keys(X).join(", ")}`}){super({name:pQ,message:J});this[ZQ]=!0,this.provider=Y,this.reference=X}static isInstance(Y){return D.hasMarker(Y,lQ)}},dQ="AI_TooManyEmbeddingValuesForCallError",iQ=`vercel.ai.error.${dQ}`,xL=Symbol.for(iQ),BQ,FQ,bL=class extends(FQ=D,BQ=xL,FQ){constructor(Y){super({name:dQ,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[BQ]=!0,this.provider=Y.provider,this.modelId=Y.modelId,this.maxEmbeddingsPerCall=Y.maxEmbeddingsPerCall,this.values=Y.values}static isInstance(Y){return D.hasMarker(Y,iQ)}},nQ="AI_TypeValidationError",oQ=`vercel.ai.error.${nQ}`,vL=Symbol.for(oQ),OQ,jQ,k0=class Y extends(jQ=D,OQ=vL,jQ){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:nQ,message:`${$}: Value: ${JSON.stringify(X)}.
166
- Error message: ${I1(J)}`,cause:J});this[OQ]=!0,this.value=X,this.context=Q}static isInstance(X){return D.hasMarker(X,oQ)}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})}},rQ="AI_UnsupportedFunctionalityError",sQ=`vercel.ai.error.${rQ}`,hL=Symbol.for(sQ),qQ,DQ,gL=class extends(DQ=D,qQ=hL,DQ){constructor({functionality:Y,message:X=`'${Y}' functionality not supported.`}){super({name:rQ,message:X});this[qQ]=!0,this.functionality=Y}static isInstance(Y){return D.hasMarker(Y,sQ)}};var gF=Object.freeze({status:"aborted"});function j(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 yF=Symbol("zod_brand");class $1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class QY extends Error{constructor(Y){super(`Encountered unidirectional transform during encode: ${Y}`);this.name="ZodEncodeError"}}var uY={};function n0(Y){if(Y)Object.assign(uY,Y);return uY}var u={};LX(u,{unwrapMessage:()=>$Y,uint8ArrayToHex:()=>LH,uint8ArrayToBase64url:()=>zH,uint8ArrayToBase64:()=>$$,stringifyPrimitive:()=>Y$,shallowClone:()=>tQ,safeExtend:()=>XH,required:()=>$H,randomString:()=>oL,propertyKeyTypes:()=>VX,promiseAllObject:()=>nL,primitiveTypes:()=>eQ,prefixIssues:()=>W1,pick:()=>tL,partial:()=>QH,optionalKeys:()=>ZX,omit:()=>eL,objectClone:()=>lL,numKeys:()=>rL,nullish:()=>WY,normalizeParams:()=>h,mergeDefs:()=>K1,merge:()=>JH,jsonStringifyReplacer:()=>l1,joinValues:()=>pL,issue:()=>i1,isPlainObject:()=>B1,isObject:()=>_1,hexToUint8Array:()=>UH,getSizableOrigin:()=>J$,getParsedType:()=>sL,getLengthableOrigin:()=>UY,getEnumValues:()=>GY,getElementAtPath:()=>iL,floatSafeRemainder:()=>HX,finalizeIssue:()=>y0,extend:()=>YH,escapeRegex:()=>G1,esc:()=>pY,defineLazy:()=>d,createTransparentProxy:()=>aL,cloneDef:()=>dL,clone:()=>g0,cleanRegex:()=>zY,cleanEnum:()=>GH,captureStackTrace:()=>lY,cached:()=>d1,base64urlToUint8Array:()=>WH,base64ToUint8Array:()=>Q$,assignProp:()=>Z1,assertNotEqual:()=>fL,assertNever:()=>cL,assertIs:()=>mL,assertEqual:()=>yL,assert:()=>uL,allowsEval:()=>NX,aborted:()=>F1,NUMBER_FORMAT_RANGES:()=>KX,Class:()=>G$,BIGINT_FORMAT_RANGES:()=>X$});function yL(Y){return Y}function fL(Y){return Y}function mL(Y){}function cL(Y){throw Error()}function uL(Y){}function GY(Y){let X=Object.values(Y).filter((Q)=>typeof Q==="number");return Object.entries(Y).filter(([Q,$])=>X.indexOf(+Q)===-1).map(([Q,$])=>$)}function pL(Y,X="|"){return Y.map((J)=>Y$(J)).join(X)}function l1(Y,X){if(typeof X==="bigint")return X.toString();return X}function d1(Y){return{get value(){{let J=Y();return Object.defineProperty(this,"value",{value:J}),J}throw Error("cached value already set")}}}function WY(Y){return Y===null||Y===void 0}function zY(Y){let X=Y.startsWith("^")?1:0,J=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(X,J)}function HX(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 aQ=Symbol("evaluating");function d(Y,X,J){let Q=void 0;Object.defineProperty(Y,X,{get(){if(Q===aQ)return;if(Q===void 0)Q=aQ,Q=J();return Q},set($){Object.defineProperty(Y,X,{value:$})},configurable:!0})}function lL(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function Z1(Y,X,J){Object.defineProperty(Y,X,{value:J,writable:!0,enumerable:!0,configurable:!0})}function K1(...Y){let X={};for(let J of Y){let Q=Object.getOwnPropertyDescriptors(J);Object.assign(X,Q)}return Object.defineProperties({},X)}function dL(Y){return K1(Y._zod.def)}function iL(Y,X){if(!X)return Y;return X.reduce((J,Q)=>J?.[Q],Y)}function nL(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 oL(Y=10){let J="";for(let Q=0;Q<Y;Q++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function pY(Y){return JSON.stringify(Y)}var lY="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function _1(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var NX=d1(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function B1(Y){if(_1(Y)===!1)return!1;let X=Y.constructor;if(X===void 0)return!0;let J=X.prototype;if(_1(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function tQ(Y){if(B1(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function rL(Y){let X=0;for(let J in Y)if(Object.prototype.hasOwnProperty.call(Y,J))X++;return X}var sL=(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}`)}},VX=new Set(["string","number","symbol"]),eQ=new Set(["string","number","bigint","boolean","symbol","undefined"]);function G1(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function g0(Y,X,J){let Q=new Y._zod.constr(X??Y._zod.def);if(!X||J?.parent)Q._zod.parent=Y;return Q}function h(Y){let X=Y;if(!X)return{};if(typeof X==="string")return{error:()=>X};if(X?.message!==void 0){if(X?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");X.error=X.message}if(delete X.message,typeof X.error==="string")return{...X,error:()=>X.error};return X}function aL(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 Y$(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function ZX(Y){return Object.keys(Y).filter((X)=>{return Y[X]._zod.optin==="optional"&&Y[X]._zod.optout==="optional"})}var KX={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]},X$={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function tL(Y,X){let J=Y._zod.def,Q=K1(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 Z1(this,"shape",$),$},checks:[]});return g0(Y,Q)}function eL(Y,X){let J=Y._zod.def,Q=K1(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 Z1(this,"shape",$),$},checks:[]});return g0(Y,Q)}function YH(Y,X){if(!B1(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 $=K1(Y._zod.def,{get shape(){let G={...Y._zod.def.shape,...X};return Z1(this,"shape",G),G},checks:[]});return g0(Y,$)}function XH(Y,X){if(!B1(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 Z1(this,"shape",Q),Q},checks:Y._zod.def.checks};return g0(Y,J)}function JH(Y,X){let J=K1(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape,...X._zod.def.shape};return Z1(this,"shape",Q),Q},get catchall(){return X._zod.def.catchall},checks:[]});return g0(Y,J)}function QH(Y,X,J){let Q=K1(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 Z1(this,"shape",G),G},checks:[]});return g0(X,Q)}function $H(Y,X,J){let Q=K1(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 Z1(this,"shape",G),G},checks:[]});return g0(X,Q)}function F1(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 W1(Y,X){return X.map((J)=>{var Q;return(Q=J).path??(Q.path=[]),J.path.unshift(Y),J})}function $Y(Y){return typeof Y==="string"?Y:Y?.message}function y0(Y,X,J){let Q={...Y,path:Y.path??[]};if(!Y.message){let $=$Y(Y.inst?._zod.def?.error?.(Y))??$Y(X?.error?.(Y))??$Y(J.customError?.(Y))??$Y(J.localeError?.(Y))??"Invalid input";Q.message=$}if(delete Q.inst,delete Q.continue,!X?.reportInput)delete Q.input;return Q}function J$(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function UY(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function i1(...Y){let[X,J,Q]=Y;if(typeof X==="string")return{message:X,code:"custom",input:J,inst:Q};return{...X}}function GH(Y){return Object.entries(Y).filter(([X,J])=>{return Number.isNaN(Number.parseInt(X,10))}).map((X)=>X[1])}function Q$(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 $$(Y){let X="";for(let J=0;J<Y.length;J++)X+=String.fromCharCode(Y[J]);return btoa(X)}function WH(Y){let X=Y.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-X.length%4)%4);return Q$(X+J)}function zH(Y){return $$(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function UH(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 LH(Y){return Array.from(Y).map((X)=>X.toString(16).padStart(2,"0")).join("")}class G${constructor(...Y){}}var W$=(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,l1,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},dY=j("$ZodError",W$),BX=j("$ZodError",W$,{Parent:Error});function z$(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 U$(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 iY=(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 $1;if(W.issues.length){let U=new($?.Err??Y)(W.issues.map((H)=>y0(H,G,n0())));throw lY(U,$?.callee),U}return W.value};var nY=(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)=>y0(H,G,n0())));throw lY(U,$?.callee),U}return W.value};var LY=(Y)=>(X,J,Q)=>{let $=Q?{...Q,async:!1}:{async:!1},G=X._zod.run({value:J,issues:[]},$);if(G instanceof Promise)throw new $1;return G.issues.length?{success:!1,error:new(Y??dY)(G.issues.map((W)=>y0(W,$,n0())))}:{success:!0,data:G.value}},L$=LY(BX),HY=(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)=>y0(W,$,n0())))}:{success:!0,data:G.value}},H$=HY(BX),N$=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return iY(Y)(X,J,$)};var V$=(Y)=>(X,J,Q)=>{return iY(Y)(X,J,Q)};var Z$=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return nY(Y)(X,J,$)};var K$=(Y)=>async(X,J,Q)=>{return nY(Y)(X,J,Q)};var B$=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return LY(Y)(X,J,$)};var F$=(Y)=>(X,J,Q)=>{return LY(Y)(X,J,Q)};var O$=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return HY(Y)(X,J,$)};var j$=(Y)=>async(X,J,Q)=>{return HY(Y)(X,J,Q)};var q$=/^[cC][^\s-]{8,}$/,D$=/^[0-9a-z]+$/,P$=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,M$=/^[0-9a-vA-V]{20}$/,E$=/^[A-Za-z0-9]{27}$/,w$=/^[a-zA-Z0-9_-]{21}$/,A$=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var T$=/^([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})$/,FX=(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 R$=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function C$(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var I$=/^(?:(?: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}|:))$/,S$=/^((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])$/,k$=/^(([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])$/,x$=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,OX=/^[A-Za-z0-9_-]*$/,b$=/^(?=.{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 v$=/^\+(?:[0-9]){6,14}[0-9]$/,h$="(?:(?:\\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])))",g$=new RegExp(`^${h$}$`);function y$(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 f$(Y){return new RegExp(`^${y$(Y)}$`)}function m$(Y){let X=y$({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(`^${h$}T(?:${Q})$`)}var c$=(Y)=>{let X=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${X}$`)};var u$=/^-?\d+$/,p$=/^-?\d+(?:\.\d+)?/,l$=/^(?:true|false)$/i,d$=/^null$/i;var i$=/^[^A-Z]*$/,n$=/^[^a-z]*$/;var V0=j("$ZodCheck",(Y,X)=>{var J;Y._zod??(Y._zod={}),Y._zod.def=X,(J=Y._zod).onattach??(J.onattach=[])}),o$={number:"number",bigint:"bigint",object:"date"},jX=j("$ZodCheckLessThan",(Y,X)=>{V0.init(Y,X);let J=o$[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})}}),qX=j("$ZodCheckGreaterThan",(Y,X)=>{V0.init(Y,X);let J=o$[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})}}),r$=j("$ZodCheckMultipleOf",(Y,X)=>{V0.init(Y,X),Y._zod.onattach.push((J)=>{var Q;(Q=J._zod.bag).multipleOf??(Q.multipleOf=X.value)}),Y._zod.check=(J)=>{if(typeof J.value!==typeof X.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof J.value==="bigint"?J.value%X.value===BigInt(0):HX(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})}}),s$=j("$ZodCheckNumberFormat",(Y,X)=>{V0.init(Y,X),X.format=X.format||"float64";let J=X.format?.includes("int"),Q=J?"int":"number",[$,G]=KX[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=u$}),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 a$=j("$ZodCheckMaxLength",(Y,X)=>{var J;V0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!WY($)&&$.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=UY($);Q.issues.push({origin:W,code:"too_big",maximum:X.maximum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),t$=j("$ZodCheckMinLength",(Y,X)=>{var J;V0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!WY($)&&$.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=UY($);Q.issues.push({origin:W,code:"too_small",minimum:X.minimum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),e$=j("$ZodCheckLengthEquals",(Y,X)=>{var J;V0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!WY($)&&$.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=UY($),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})}}),NY=j("$ZodCheckStringFormat",(Y,X)=>{var J,Q;if(V0.init(Y,X),Y._zod.onattach.push(($)=>{let G=$._zod.bag;if(G.format=X.format,X.pattern)G.patterns??(G.patterns=new Set),G.patterns.add(X.pattern)}),X.pattern)(J=Y._zod).check??(J.check=($)=>{if(X.pattern.lastIndex=0,X.pattern.test($.value))return;$.issues.push({origin:"string",code:"invalid_format",format:X.format,input:$.value,...X.pattern?{pattern:X.pattern.toString()}:{},inst:Y,continue:!X.abort})});else(Q=Y._zod).check??(Q.check=()=>{})}),Y5=j("$ZodCheckRegex",(Y,X)=>{NY.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})}}),X5=j("$ZodCheckLowerCase",(Y,X)=>{X.pattern??(X.pattern=i$),NY.init(Y,X)}),J5=j("$ZodCheckUpperCase",(Y,X)=>{X.pattern??(X.pattern=n$),NY.init(Y,X)}),Q5=j("$ZodCheckIncludes",(Y,X)=>{V0.init(Y,X);let J=G1(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})}}),$5=j("$ZodCheckStartsWith",(Y,X)=>{V0.init(Y,X);let J=new RegExp(`^${G1(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})}}),G5=j("$ZodCheckEndsWith",(Y,X)=>{V0.init(Y,X);let J=new RegExp(`.*${G1(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 W5=j("$ZodCheckOverwrite",(Y,X)=>{V0.init(Y,X),Y._zod.check=(J)=>{J.value=X.tx(J.value)}});class DX{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(`
69
+ `}}function kZ(Y){return Y.type==="response.output_item.done"&&h(Y.item)&&Y.item.type==="web_search_call"&&typeof Y.item.id==="string"}function xZ(Y){return h(Y)&&Y.type==="function_call"&&Y.name==="web_search"&&typeof Y.call_id==="string"&&Y.call_id.startsWith(kY)}function bZ(Y,X){return h(Y)&&Y.type==="function_call_output"&&typeof Y.call_id==="string"&&typeof Y.output==="string"&&Y.call_id.startsWith(kY)&&X.has(Y.call_id)}function vZ(Y){return h(Y)&&Y.type==="item_reference"&&typeof Y.id==="string"&&Y.id.startsWith(kY)}function pX(Y,X,J){let Q=hZ(X),$=h(Q?.action)?Q.action:gZ(J?.arguments);return{type:"web_search_call",status:"completed",...$?{action:$}:{}}}function hZ(Y){if(h(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return h(X)?X:void 0}catch{return}}function gZ(Y){if(h(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return h(X)?X:void 0}catch{return}}import{readFile as yZ}from"node:fs/promises";import{homedir as fZ}from"node:os";import{join as N5}from"node:path";var mZ="https://models.dev/api.json",uZ="OPENCODE_OPENAI_AUTH_MODELS_CACHE",cZ="OPENCODE_MODELS_PATH",pZ="OPENCODE_DISABLE_MODELS_FETCH",lZ=1e4,dZ=300000;function A1(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function B5(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function dX(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=B5(Y.cache_read),$=B5(Y.cache_write);if(Q===null||$===null)return null;return{input:X,output:J,cache:{read:Q,write:$}}}function iZ(Y){let X=A1(Y);if(!X)return null;let J=dX(X);if(!J)return null;let Q=J;if(Array.isArray(X.tiers)){let W=[];for(let K of X.tiers){let Z=A1(K);if(!Z)continue;let U=A1(Z.tier),L=U?.size;if(U?.type!=="context")continue;if(typeof L!=="number"||!Number.isFinite(L)||L<=0)continue;let F=dX(Z);if(!F)continue;W.push({...F,tier:{type:"context",size:L}})}if(W.length>0)Q.tiers=W}let $=A1(X.context_over_200k),G=$?dX($):null;if(G)Q.experimentalOver200K=G;return Q}function q5(Y){let X=A1(Y),J=A1(X?.openai),Q=A1(J?.models);if(!Q)return null;let $={};for(let[G,W]of Object.entries(Q)){let K=A1(W),Z=iZ(K?.cost);if(Z)$[G]=Z}return Object.keys($).length>0?$:null}function oZ(){let Y=process.env[uZ]?.trim();if(Y)return Y;let X=process.env[cZ]?.trim();if(X)return X;let J=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||N5(fZ(),".cache");return N5(J,"opencode","models.json")}function nZ(){let Y=process.env[pZ]?.toLowerCase();return Y==="true"||Y==="1"}async function rZ(){try{let Y=q5(JSON.parse(await yZ(oZ(),"utf8")));if(Y)return Y}catch{}if(nZ())return null;try{let Y=await fetch(mZ,{signal:AbortSignal.timeout(lZ)});if(!Y.ok)return null;return q5(await Y.json())}catch{return null}}var G9;function F5(){let Y=Date.now();if(G9&&G9.expiresAt>Y)return G9.promise;let X={expiresAt:Y+dZ,promise:rZ()};return G9=X,X.promise.then((J)=>{if(J===null&&G9===X)G9=void 0}),X.promise}function W9(Y){return typeof Y==="object"&&Y!==null}function sZ(Y){if(Array.isArray(Y))return Y;if(W9(Y)&&Array.isArray(Y.data))return Y.data;return[]}function aZ(Y){if(!W9(Y)||!W9(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function O5(Y){if(!W9(Y)||!W9(Y.info))return null;let X=Y.info,J=W9(X.model)?X.model:void 0,Q=typeof X.agent==="string"?X.agent:void 0,$=typeof J?.providerID==="string"?J.providerID:typeof X.providerID==="string"?X.providerID:void 0,G=typeof J?.modelID==="string"?J.modelID:typeof X.modelID==="string"?X.modelID:void 0,W=typeof J?.variant==="string"?J.variant:typeof X.variant==="string"?X.variant:void 0;if(!Q&&(!$||!G)&&!W)return null;let K={};if(Q)K.agent=Q;if($&&G)K.model={providerID:$,modelID:G};if(W)K.variant=W;return K}function j5(Y,X){return{agent:Y.agent??X.agent,model:Y.model??X.model,variant:Y.variant??X.variant}}function D5(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function P5(Y,X){if(!Y||!X)return null;let J=Y;if(typeof J.session?.messages!=="function")return null;let Q=[];try{Q=sZ(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(aZ(Q[G])!=="assistant")continue;let W=O5(Q[G]);if(!W)continue;if($=j5($,W),D5($))return $}for(let G=Q.length-1;G>=0;G--){let W=O5(Q[G]);if(!W)continue;if($=j5($,W),D5($))return $}if(!$.agent&&!$.model&&!$.variant)return null;return $}var T1=[],tZ=1,E5=new Map;function iX(Y,X){if(T1.push({id:tZ++,type:"open-dialog",payload:Y,sessionId:X}),T1.length>100)T1=T1.slice(T1.length-100)}function M5(Y=0,X){let J=Date.now();if(X!==void 0)E5.set(X,J);let Q=($)=>X===void 0||$.sessionId===void 0||$.sessionId===X;if(Y>0)T1=T1.filter(($)=>{if($.id>Y)return!0;if(X===void 0)return!0;return $.sessionId!==X});return T1.filter(($)=>$.id>Y&&Q($))}function w5(Y){let X=Date.now(),J=E5.get(Y)??0;return J>0&&X-J<3000}import{randomBytes as eZ,timingSafeEqual as YL}from"node:crypto";import{readFile as XL,unlink as JL}from"node:fs/promises";import{createServer as QL}from"node:http";import{join as $L}from"node:path";var oX=B0("rpc");function GL(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 WL(Y,X){if(!Y?.startsWith("Bearer "))return!1;let J=Buffer.from(Y.slice(7)),Q=Buffer.from(X);return J.length===Q.length&&YL(J,Q)}async function R5(Y){let X=eZ(32).toString("hex"),J=Y.timeoutMs??90000,Q=Y.receiptTimeoutMs??2000,$=!1,G=QL((Z,U)=>{Z.setTimeout(J,()=>{Z.socket.destroy()}),W(Z,U)});G.requestTimeout=Q,G.headersTimeout=Q;async function W(Z,U){let L=(F,N)=>{if(U.headersSent||U.writableEnded||U.destroyed)return;U.writeHead(F,{"content-type":"application/json"}),U.end(JSON.stringify(N))};try{let F=Z.url??"";if(Z.method==="GET"&&F==="/health")return L(200,{ok:!0});if(Z.method!=="POST"||!F.startsWith("/rpc/"))return L(404,{error:"not found"});if(!WL(Z.headers.authorization,X))return L(401,{error:"unauthorized"});let N=F.slice(5),V=await GL(Z),j=JSON.parse(V||"{}");if(N==="pending-notifications"){let R=typeof j.sessionId==="string"?j.sessionId:void 0;if(R===void 0&&!$)$=!0,oX.warn("rpc notification drain missing session id",{pid:process.pid});let S=Y.drain(Number(j.lastReceivedId??0),R);return L(200,{messages:S})}if(N==="apply"){let R=await Y.apply(j);return L(200,R)}return L(404,{error:"unknown method"})}catch(F){L(500,{error:F instanceof Error?F.message:String(F)})}}let K=await new Promise((Z,U)=>{G.on("error",U),G.listen(0,"127.0.0.1",()=>{let L=G.address();if(L&&typeof L==="object")Z(L.port);else U(Error("no port"))})});if(G.unref(),Y.sweepRoot)try{await T5(Y.sweepRoot,Y.dir)}catch(Z){oX.warn("rpc state sweep failed",{pid:process.pid,error:Z instanceof Error?Z.message:String(Z)})}try{await A5(Y.dir,{port:K,token:X,pid:process.pid},{secureDir:Y.secureDir}),oX.debug("rpc server pid",{pid:process.pid,rpcPort:K})}catch(Z){throw await new Promise((U)=>G.close(()=>U())),Z}return{port:K,token:X,async stop(){await new Promise((L)=>G.close(()=>L()));let Z=$L(Y.dir,`port-${process.pid}.json`),U=await XL(Z,"utf8").then((L)=>JSON.parse(L)).catch(()=>{return});if(U?.port===K&&U.token===X)await JL(Z).catch(()=>{})}}}function B1(Y){return JSON.stringify(nX(Y))??"undefined"}function nX(Y){if(Array.isArray(Y))return Y.map(nX);if(!h(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((X)=>[X,nX(Y[X])]))}function c1(){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 x1={};aX(x1,{withoutInternalHeaders:()=>KK,sanitizeHttpFallbackBody:()=>AX,orderCodexBody:()=>e9,hasWebSocketResponsesLiteMetadata:()=>wX,createWebSocketFetch:()=>Zq,applyTurnId:()=>$K,advanceTurn:()=>r8,TITLE_HEADER:()=>n8,QUOTA_ACCOUNT_HEADER:()=>zX,OpenAIWebSocketPool:()=>x1,CODEX_BODY_KEY_ORDER:()=>JK});import{createHash as Gq}from"node:crypto";var $$="vercel.ai.error",zL=Symbol.for($$),C5,I5,T=class Y extends(I5=Error,C5=zL,I5){constructor({name:X,message:J,cause:Q}){super(J);this[C5]=!0,this.name=X,this.cause=Q}static isInstance(X){return Y.hasMarker(X,$$)}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}},G$="AI_APICallError",W$=`vercel.ai.error.${G$}`,KL=Symbol.for(W$),_5,S5,b9=class extends(S5=T,_5=KL,S5){constructor({message:Y,url:X,requestBodyValues:J,statusCode:Q,responseHeaders:$,responseBody:G,cause:W,isRetryable:K=Q!=null&&(Q===408||Q===409||Q===429||Q>=500),data:Z}){super({name:G$,message:Y,cause:W});this[_5]=!0,this.url=X,this.requestBodyValues=J,this.statusCode=Q,this.responseHeaders=$,this.responseBody=G,this.isRetryable=K,this.data=Z}static isInstance(Y){return T.hasMarker(Y,W$)}},z$="AI_EmptyResponseBodyError",K$=`vercel.ai.error.${z$}`,UL=Symbol.for(K$),k5,x5,ZL=class extends(x5=T,k5=UL,x5){constructor({message:Y="Empty response body"}={}){super({name:z$,message:Y});this[k5]=!0}static isInstance(Y){return T.hasMarker(Y,K$)}};function p1(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 U$="AI_InvalidArgumentError",Z$=`vercel.ai.error.${U$}`,LL=Symbol.for(Z$),b5,v5,L$=class extends(v5=T,b5=LL,v5){constructor({message:Y,cause:X,argument:J}){super({name:U$,message:Y,cause:X});this[b5]=!0,this.argument=J}static isInstance(Y){return T.hasMarker(Y,Z$)}},H$="AI_InvalidPromptError",V$=`vercel.ai.error.${H$}`,HL=Symbol.for(V$),h5,g5,VL=class extends(g5=T,h5=HL,g5){constructor({prompt:Y,message:X,cause:J}){super({name:H$,message:`Invalid prompt: ${X}`,cause:J});this[h5]=!0,this.prompt=Y}static isInstance(Y){return T.hasMarker(Y,V$)}},N$="AI_InvalidResponseDataError",B$=`vercel.ai.error.${N$}`,NL=Symbol.for(B$),y5,f5,BL=class extends(f5=T,y5=NL,f5){constructor({data:Y,message:X=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:N$,message:X});this[y5]=!0,this.data=Y}static isInstance(Y){return T.hasMarker(Y,B$)}},q$="AI_JSONParseError",F$=`vercel.ai.error.${q$}`,qL=Symbol.for(F$),m5,u5,xY=class extends(u5=T,m5=qL,u5){constructor({text:Y,cause:X}){super({name:q$,message:`JSON parsing failed: Text: ${Y}.
70
+ Error message: ${p1(X)}`,cause:X});this[m5]=!0,this.text=Y}static isInstance(Y){return T.hasMarker(Y,F$)}},O$="AI_LoadAPIKeyError",j$=`vercel.ai.error.${O$}`,FL=Symbol.for(j$),c5,p5,OL=class extends(p5=T,c5=FL,p5){constructor({message:Y}){super({name:O$,message:Y});this[c5]=!0}static isInstance(Y){return T.hasMarker(Y,j$)}},D$="AI_LoadSettingError",P$=`vercel.ai.error.${D$}`,jL=Symbol.for(P$),l5,d5,DL=class extends(d5=T,l5=jL,d5){constructor({message:Y}){super({name:D$,message:Y});this[l5]=!0}static isInstance(Y){return T.hasMarker(Y,P$)}},E$="AI_NoContentGeneratedError",M$=`vercel.ai.error.${E$}`,PL=Symbol.for(M$),i5,o5,EL=class extends(o5=T,i5=PL,o5){constructor({message:Y="No content generated."}={}){super({name:E$,message:Y});this[i5]=!0}static isInstance(Y){return T.hasMarker(Y,M$)}},w$="AI_NoSuchModelError",A$=`vercel.ai.error.${w$}`,ML=Symbol.for(A$),n5,r5,rX=class extends(r5=T,n5=ML,r5){constructor({errorName:Y=w$,modelId:X,modelType:J,message:Q=`No such ${J}: ${X}`}){super({name:Y,message:Q});this[n5]=!0,this.modelId=X,this.modelType=J}static isInstance(Y){return T.hasMarker(Y,A$)}},T$="AI_NoSuchProviderReferenceError",R$=`vercel.ai.error.${T$}`,wL=Symbol.for(R$),s5,a5,AL=class extends(a5=T,s5=wL,a5){constructor({provider:Y,reference:X,message:J=`No provider reference found for provider '${Y}'. Available providers: ${Object.keys(X).join(", ")}`}){super({name:T$,message:J});this[s5]=!0,this.provider=Y,this.reference=X}static isInstance(Y){return T.hasMarker(Y,R$)}},C$="AI_TooManyEmbeddingValuesForCallError",I$=`vercel.ai.error.${C$}`,TL=Symbol.for(I$),t5,e5,RL=class extends(e5=T,t5=TL,e5){constructor(Y){super({name:C$,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[t5]=!0,this.provider=Y.provider,this.modelId=Y.modelId,this.maxEmbeddingsPerCall=Y.maxEmbeddingsPerCall,this.values=Y.values}static isInstance(Y){return T.hasMarker(Y,I$)}},_$="AI_TypeValidationError",S$=`vercel.ai.error.${_$}`,CL=Symbol.for(S$),Y$,X$,r0=class Y extends(X$=T,Y$=CL,X$){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:_$,message:`${$}: Value: ${JSON.stringify(X)}.
71
+ Error message: ${p1(J)}`,cause:J});this[Y$]=!0,this.value=X,this.context=Q}static isInstance(X){return T.hasMarker(X,S$)}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})}},k$="AI_UnsupportedFunctionalityError",x$=`vercel.ai.error.${k$}`,IL=Symbol.for(x$),J$,Q$,_L=class extends(Q$=T,J$=IL,Q$){constructor({functionality:Y,message:X=`'${Y}' functionality not supported.`}){super({name:k$,message:X});this[J$]=!0,this.functionality=Y}static isInstance(Y){return T.hasMarker(Y,x$)}};var M6=Object.freeze({status:"aborted"});function P(Y,X,J){function Q(K,Z){var U;Object.defineProperty(K,"_zod",{value:K._zod??{},enumerable:!1}),(U=K._zod).traits??(U.traits=new Set),K._zod.traits.add(Y),X(K,Z);for(let L in W.prototype)if(!(L in K))Object.defineProperty(K,L,{value:W.prototype[L].bind(K)});K._zod.constr=W,K._zod.def=Z}let $=J?.Parent??Object;class G extends ${}Object.defineProperty(G,"name",{value:Y});function W(K){var Z;let U=J?.Parent?new G:this;Q(U,K),(Z=U._zod).deferred??(Z.deferred=[]);for(let L of U._zod.deferred)L();return U}return Object.defineProperty(W,"init",{value:Q}),Object.defineProperty(W,Symbol.hasInstance,{value:(K)=>{if(J?.Parent&&K instanceof J.Parent)return!0;return K?._zod?.traits?.has(Y)}}),Object.defineProperty(W,"name",{value:Y}),W}var w6=Symbol("zod_brand");class q1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class v9 extends Error{constructor(Y){super(`Encountered unidirectional transform during encode: ${Y}`);this.name="ZodEncodeError"}}var bY={};function G1(Y){if(Y)Object.assign(bY,Y);return bY}var a={};aX(a,{unwrapMessage:()=>h9,uint8ArrayToHex:()=>JH,uint8ArrayToBase64url:()=>YH,uint8ArrayToBase64:()=>u$,stringifyPrimitive:()=>g$,shallowClone:()=>v$,safeExtend:()=>nL,required:()=>aL,randomString:()=>uL,propertyKeyTypes:()=>Y8,promiseAllObject:()=>mL,primitiveTypes:()=>h$,prefixIssues:()=>O1,pick:()=>dL,partial:()=>sL,optionalKeys:()=>X8,omit:()=>iL,objectClone:()=>gL,numKeys:()=>cL,nullish:()=>y9,normalizeParams:()=>i,mergeDefs:()=>C1,merge:()=>rL,jsonStringifyReplacer:()=>z9,joinValues:()=>hL,issue:()=>U9,isPlainObject:()=>I1,isObject:()=>l1,hexToUint8Array:()=>XH,getSizableOrigin:()=>f$,getParsedType:()=>pL,getLengthableOrigin:()=>m9,getEnumValues:()=>g9,getElementAtPath:()=>fL,floatSafeRemainder:()=>tX,finalizeIssue:()=>t0,extend:()=>oL,escapeRegex:()=>F1,esc:()=>vY,defineLazy:()=>X0,createTransparentProxy:()=>lL,cloneDef:()=>yL,clone:()=>a0,cleanRegex:()=>f9,cleanEnum:()=>tL,captureStackTrace:()=>hY,cached:()=>K9,base64urlToUint8Array:()=>eL,base64ToUint8Array:()=>m$,assignProp:()=>R1,assertNotEqual:()=>kL,assertNever:()=>bL,assertIs:()=>xL,assertEqual:()=>SL,assert:()=>vL,allowsEval:()=>eX,aborted:()=>_1,NUMBER_FORMAT_RANGES:()=>J8,Class:()=>c$,BIGINT_FORMAT_RANGES:()=>y$});function SL(Y){return Y}function kL(Y){return Y}function xL(Y){}function bL(Y){throw Error()}function vL(Y){}function g9(Y){let X=Object.values(Y).filter((Q)=>typeof Q==="number");return Object.entries(Y).filter(([Q,$])=>X.indexOf(+Q)===-1).map(([Q,$])=>$)}function hL(Y,X="|"){return Y.map((J)=>g$(J)).join(X)}function z9(Y,X){if(typeof X==="bigint")return X.toString();return X}function K9(Y){return{get value(){{let J=Y();return Object.defineProperty(this,"value",{value:J}),J}throw Error("cached value already set")}}}function y9(Y){return Y===null||Y===void 0}function f9(Y){let X=Y.startsWith("^")?1:0,J=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(X,J)}function tX(Y,X){let J=(Y.toString().split(".")[1]||"").length,Q=X.toString(),$=(Q.split(".")[1]||"").length;if($===0&&/\d?e-\d?/.test(Q)){let Z=Q.match(/\d?e-(\d?)/);if(Z?.[1])$=Number.parseInt(Z[1])}let G=J>$?J:$,W=Number.parseInt(Y.toFixed(G).replace(".","")),K=Number.parseInt(X.toFixed(G).replace(".",""));return W%K/10**G}var b$=Symbol("evaluating");function X0(Y,X,J){let Q=void 0;Object.defineProperty(Y,X,{get(){if(Q===b$)return;if(Q===void 0)Q=b$,Q=J();return Q},set($){Object.defineProperty(Y,X,{value:$})},configurable:!0})}function gL(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function R1(Y,X,J){Object.defineProperty(Y,X,{value:J,writable:!0,enumerable:!0,configurable:!0})}function C1(...Y){let X={};for(let J of Y){let Q=Object.getOwnPropertyDescriptors(J);Object.assign(X,Q)}return Object.defineProperties({},X)}function yL(Y){return C1(Y._zod.def)}function fL(Y,X){if(!X)return Y;return X.reduce((J,Q)=>J?.[Q],Y)}function mL(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 uL(Y=10){let J="";for(let Q=0;Q<Y;Q++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function vY(Y){return JSON.stringify(Y)}var hY="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function l1(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var eX=K9(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function I1(Y){if(l1(Y)===!1)return!1;let X=Y.constructor;if(X===void 0)return!0;let J=X.prototype;if(l1(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function v$(Y){if(I1(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function cL(Y){let X=0;for(let J in Y)if(Object.prototype.hasOwnProperty.call(Y,J))X++;return X}var pL=(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}`)}},Y8=new Set(["string","number","symbol"]),h$=new Set(["string","number","bigint","boolean","symbol","undefined"]);function F1(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function a0(Y,X,J){let Q=new Y._zod.constr(X??Y._zod.def);if(!X||J?.parent)Q._zod.parent=Y;return Q}function i(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 lL(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 g$(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function X8(Y){return Object.keys(Y).filter((X)=>{return Y[X]._zod.optin==="optional"&&Y[X]._zod.optout==="optional"})}var J8={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]},y$={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function dL(Y,X){let J=Y._zod.def,Q=C1(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 R1(this,"shape",$),$},checks:[]});return a0(Y,Q)}function iL(Y,X){let J=Y._zod.def,Q=C1(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 R1(this,"shape",$),$},checks:[]});return a0(Y,Q)}function oL(Y,X){if(!I1(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 $=C1(Y._zod.def,{get shape(){let G={...Y._zod.def.shape,...X};return R1(this,"shape",G),G},checks:[]});return a0(Y,$)}function nL(Y,X){if(!I1(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 R1(this,"shape",Q),Q},checks:Y._zod.def.checks};return a0(Y,J)}function rL(Y,X){let J=C1(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape,...X._zod.def.shape};return R1(this,"shape",Q),Q},get catchall(){return X._zod.def.catchall},checks:[]});return a0(Y,J)}function sL(Y,X,J){let Q=C1(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 R1(this,"shape",G),G},checks:[]});return a0(X,Q)}function aL(Y,X,J){let Q=C1(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 R1(this,"shape",G),G},checks:[]});return a0(X,Q)}function _1(Y,X=0){if(Y.aborted===!0)return!0;for(let J=X;J<Y.issues.length;J++)if(Y.issues[J]?.continue!==!0)return!0;return!1}function O1(Y,X){return X.map((J)=>{var Q;return(Q=J).path??(Q.path=[]),J.path.unshift(Y),J})}function h9(Y){return typeof Y==="string"?Y:Y?.message}function t0(Y,X,J){let Q={...Y,path:Y.path??[]};if(!Y.message){let $=h9(Y.inst?._zod.def?.error?.(Y))??h9(X?.error?.(Y))??h9(J.customError?.(Y))??h9(J.localeError?.(Y))??"Invalid input";Q.message=$}if(delete Q.inst,delete Q.continue,!X?.reportInput)delete Q.input;return Q}function f$(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function m9(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function U9(...Y){let[X,J,Q]=Y;if(typeof X==="string")return{message:X,code:"custom",input:J,inst:Q};return{...X}}function tL(Y){return Object.entries(Y).filter(([X,J])=>{return Number.isNaN(Number.parseInt(X,10))}).map((X)=>X[1])}function m$(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 u$(Y){let X="";for(let J=0;J<Y.length;J++)X+=String.fromCharCode(Y[J]);return btoa(X)}function eL(Y){let X=Y.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-X.length%4)%4);return m$(X+J)}function YH(Y){return u$(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function XH(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 JH(Y){return Array.from(Y).map((X)=>X.toString(16).padStart(2,"0")).join("")}class c${constructor(...Y){}}var p$=(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,z9,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},gY=P("$ZodError",p$),Q8=P("$ZodError",p$,{Parent:Error});function l$(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 d$(Y,X){let J=X||function(G){return G.message},Q={_errors:[]},$=(G)=>{for(let W of G.issues)if(W.code==="invalid_union"&&W.errors.length)W.errors.map((K)=>$({issues:K}));else if(W.code==="invalid_key")$({issues:W.issues});else if(W.code==="invalid_element")$({issues:W.issues});else if(W.path.length===0)Q._errors.push(J(W));else{let K=Q,Z=0;while(Z<W.path.length){let U=W.path[Z];if(Z!==W.path.length-1)K[U]=K[U]||{_errors:[]};else K[U]=K[U]||{_errors:[]},K[U]._errors.push(J(W));K=K[U],Z++}}};return $(Y),Q}var yY=(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 q1;if(W.issues.length){let K=new($?.Err??Y)(W.issues.map((Z)=>t0(Z,G,G1())));throw hY(K,$?.callee),K}return W.value};var fY=(Y)=>async(X,J,Q,$)=>{let G=Q?Object.assign(Q,{async:!0}):{async:!0},W=X._zod.run({value:J,issues:[]},G);if(W instanceof Promise)W=await W;if(W.issues.length){let K=new($?.Err??Y)(W.issues.map((Z)=>t0(Z,G,G1())));throw hY(K,$?.callee),K}return W.value};var u9=(Y)=>(X,J,Q)=>{let $=Q?{...Q,async:!1}:{async:!1},G=X._zod.run({value:J,issues:[]},$);if(G instanceof Promise)throw new q1;return G.issues.length?{success:!1,error:new(Y??gY)(G.issues.map((W)=>t0(W,$,G1())))}:{success:!0,data:G.value}},i$=u9(Q8),c9=(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)=>t0(W,$,G1())))}:{success:!0,data:G.value}},o$=c9(Q8),n$=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return yY(Y)(X,J,$)};var r$=(Y)=>(X,J,Q)=>{return yY(Y)(X,J,Q)};var s$=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return fY(Y)(X,J,$)};var a$=(Y)=>async(X,J,Q)=>{return fY(Y)(X,J,Q)};var t$=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return u9(Y)(X,J,$)};var e$=(Y)=>(X,J,Q)=>{return u9(Y)(X,J,Q)};var YG=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return c9(Y)(X,J,$)};var XG=(Y)=>async(X,J,Q)=>{return c9(Y)(X,J,Q)};var JG=/^[cC][^\s-]{8,}$/,QG=/^[0-9a-z]+$/,$G=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,GG=/^[0-9a-vA-V]{20}$/,WG=/^[A-Za-z0-9]{27}$/,zG=/^[a-zA-Z0-9_-]{21}$/,KG=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var UG=/^([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})$/,$8=(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 ZG=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function LG(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var HG=/^(?:(?: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])$/,VG=/^(([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}|:))$/,NG=/^((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])$/,BG=/^(([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])$/,qG=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,G8=/^[A-Za-z0-9_-]*$/,FG=/^(?=.{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 OG=/^\+(?:[0-9]){6,14}[0-9]$/,jG="(?:(?:\\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])))",DG=new RegExp(`^${jG}$`);function PG(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 EG(Y){return new RegExp(`^${PG(Y)}$`)}function MG(Y){let X=PG({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(`^${jG}T(?:${Q})$`)}var wG=(Y)=>{let X=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${X}$`)};var AG=/^-?\d+$/,TG=/^-?\d+(?:\.\d+)?/,RG=/^(?:true|false)$/i,CG=/^null$/i;var IG=/^[^A-Z]*$/,_G=/^[^a-z]*$/;var w0=P("$ZodCheck",(Y,X)=>{var J;Y._zod??(Y._zod={}),Y._zod.def=X,(J=Y._zod).onattach??(J.onattach=[])}),SG={number:"number",bigint:"bigint",object:"date"},W8=P("$ZodCheckLessThan",(Y,X)=>{w0.init(Y,X);let J=SG[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})}}),z8=P("$ZodCheckGreaterThan",(Y,X)=>{w0.init(Y,X);let J=SG[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})}}),kG=P("$ZodCheckMultipleOf",(Y,X)=>{w0.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):tX(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})}}),xG=P("$ZodCheckNumberFormat",(Y,X)=>{w0.init(Y,X),X.format=X.format||"float64";let J=X.format?.includes("int"),Q=J?"int":"number",[$,G]=J8[X.format];Y._zod.onattach.push((W)=>{let K=W._zod.bag;if(K.format=X.format,K.minimum=$,K.maximum=G,J)K.pattern=AG}),Y._zod.check=(W)=>{let K=W.value;if(J){if(!Number.isInteger(K)){W.issues.push({expected:Q,format:X.format,code:"invalid_type",continue:!1,input:K,inst:Y});return}if(!Number.isSafeInteger(K)){if(K>0)W.issues.push({input:K,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:Q,continue:!X.abort});else W.issues.push({input:K,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:Q,continue:!X.abort});return}}if(K<$)W.issues.push({origin:"number",input:K,code:"too_small",minimum:$,inclusive:!0,inst:Y,continue:!X.abort});if(K>G)W.issues.push({origin:"number",input:K,code:"too_big",maximum:G,inst:Y})}});var bG=P("$ZodCheckMaxLength",(Y,X)=>{var J;w0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!y9($)&&$.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=m9($);Q.issues.push({origin:W,code:"too_big",maximum:X.maximum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),vG=P("$ZodCheckMinLength",(Y,X)=>{var J;w0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!y9($)&&$.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=m9($);Q.issues.push({origin:W,code:"too_small",minimum:X.minimum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),hG=P("$ZodCheckLengthEquals",(Y,X)=>{var J;w0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!y9($)&&$.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=m9($),K=G>X.length;Q.issues.push({origin:W,...K?{code:"too_big",maximum:X.length}:{code:"too_small",minimum:X.length},inclusive:!0,exact:!0,input:Q.value,inst:Y,continue:!X.abort})}}),p9=P("$ZodCheckStringFormat",(Y,X)=>{var J,Q;if(w0.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=()=>{})}),gG=P("$ZodCheckRegex",(Y,X)=>{p9.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})}}),yG=P("$ZodCheckLowerCase",(Y,X)=>{X.pattern??(X.pattern=IG),p9.init(Y,X)}),fG=P("$ZodCheckUpperCase",(Y,X)=>{X.pattern??(X.pattern=_G),p9.init(Y,X)}),mG=P("$ZodCheckIncludes",(Y,X)=>{w0.init(Y,X);let J=F1(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})}}),uG=P("$ZodCheckStartsWith",(Y,X)=>{w0.init(Y,X);let J=new RegExp(`^${F1(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})}}),cG=P("$ZodCheckEndsWith",(Y,X)=>{w0.init(Y,X);let J=new RegExp(`.*${F1(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 pG=P("$ZodCheckOverwrite",(Y,X)=>{w0.init(Y,X),Y._zod.check=(J)=>{J.value=X.tx(J.value)}});class K8{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
72
  `).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 U5={major:4,minor:1,patch:8};var r=j("$ZodType",(Y,X)=>{var J;Y??(Y={}),Y._zod.def=X,Y._zod.bag=Y._zod.bag||{},Y._zod.version=U5;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=F1(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 $1;if(V||N instanceof Promise)V=(V??Promise.resolve()).then(async()=>{if(await N,W.issues.length===K)return;if(!L)L=F1(W,K)});else{if(W.issues.length===K)continue;if(!L)L=F1(W,K)}}if(V)return V.then(()=>{return W});return W},G=(W,U,H)=>{if(F1(W))return W.aborted=!0,W;let L=$(U,Q,H);if(L instanceof Promise){if(H.async===!1)throw new $1;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 $1;return H.then((L)=>$(L,Q,U))}return $(H,Q,U)}}Y["~standard"]={validate:($)=>{try{let G=L$(Y,$);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return H$(Y,$).then((W)=>W.success?{value:W.data}:{issues:W.error?.issues})}},vendor:"zod",version:1}}),aY=j("$ZodString",(Y,X)=>{r.init(Y,X),Y._zod.pattern=[...Y?._zod.bag?.patterns??[]].pop()??c$(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=j("$ZodStringFormat",(Y,X)=>{NY.init(Y,X),aY.init(Y,X)}),O5=j("$ZodGUID",(Y,X)=>{X.pattern??(X.pattern=T$),s.init(Y,X)}),j5=j("$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=FX(Q))}else X.pattern??(X.pattern=FX());s.init(Y,X)}),q5=j("$ZodEmail",(Y,X)=>{X.pattern??(X.pattern=R$),s.init(Y,X)}),D5=j("$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:b$.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})}}}),P5=j("$ZodEmoji",(Y,X)=>{X.pattern??(X.pattern=C$()),s.init(Y,X)}),M5=j("$ZodNanoID",(Y,X)=>{X.pattern??(X.pattern=w$),s.init(Y,X)}),E5=j("$ZodCUID",(Y,X)=>{X.pattern??(X.pattern=q$),s.init(Y,X)}),w5=j("$ZodCUID2",(Y,X)=>{X.pattern??(X.pattern=D$),s.init(Y,X)}),A5=j("$ZodULID",(Y,X)=>{X.pattern??(X.pattern=P$),s.init(Y,X)}),T5=j("$ZodXID",(Y,X)=>{X.pattern??(X.pattern=M$),s.init(Y,X)}),R5=j("$ZodKSUID",(Y,X)=>{X.pattern??(X.pattern=E$),s.init(Y,X)}),C5=j("$ZodISODateTime",(Y,X)=>{X.pattern??(X.pattern=m$(X)),s.init(Y,X)}),I5=j("$ZodISODate",(Y,X)=>{X.pattern??(X.pattern=g$),s.init(Y,X)}),_5=j("$ZodISOTime",(Y,X)=>{X.pattern??(X.pattern=f$(X)),s.init(Y,X)}),S5=j("$ZodISODuration",(Y,X)=>{X.pattern??(X.pattern=A$),s.init(Y,X)}),k5=j("$ZodIPv4",(Y,X)=>{X.pattern??(X.pattern=I$),s.init(Y,X),Y._zod.onattach.push((J)=>{let Q=J._zod.bag;Q.format="ipv4"})}),x5=j("$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})}}}),b5=j("$ZodCIDRv4",(Y,X)=>{X.pattern??(X.pattern=S$),s.init(Y,X)}),v5=j("$ZodCIDRv6",(Y,X)=>{X.pattern??(X.pattern=k$),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 h5(Y){if(Y==="")return!0;if(Y.length%4!==0)return!1;try{return atob(Y),!0}catch{return!1}}var g5=j("$ZodBase64",(Y,X)=>{X.pattern??(X.pattern=x$),s.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64"}),Y._zod.check=(J)=>{if(h5(J.value))return;J.issues.push({code:"invalid_format",format:"base64",input:J.value,inst:Y,continue:!X.abort})}});function NH(Y){if(!OX.test(Y))return!1;let X=Y.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),J=X.padEnd(Math.ceil(X.length/4)*4,"=");return h5(J)}var y5=j("$ZodBase64URL",(Y,X)=>{X.pattern??(X.pattern=OX),s.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64url"}),Y._zod.check=(J)=>{if(NH(J.value))return;J.issues.push({code:"invalid_format",format:"base64url",input:J.value,inst:Y,continue:!X.abort})}}),f5=j("$ZodE164",(Y,X)=>{X.pattern??(X.pattern=v$),s.init(Y,X)});function VH(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 m5=j("$ZodJWT",(Y,X)=>{s.init(Y,X),Y._zod.check=(J)=>{if(VH(J.value,X.alg))return;J.issues.push({code:"invalid_format",format:"jwt",input:J.value,inst:Y,continue:!X.abort})}});var MX=j("$ZodNumber",(Y,X)=>{r.init(Y,X),Y._zod.pattern=Y._zod.bag.pattern??p$,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}}),c5=j("$ZodNumber",(Y,X)=>{s$.init(Y,X),MX.init(Y,X)}),u5=j("$ZodBoolean",(Y,X)=>{r.init(Y,X),Y._zod.pattern=l$,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 p5=j("$ZodNull",(Y,X)=>{r.init(Y,X),Y._zod.pattern=d$,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 l5=j("$ZodUnknown",(Y,X)=>{r.init(Y,X),Y._zod.parse=(J)=>J}),d5=j("$ZodNever",(Y,X)=>{r.init(Y,X),Y._zod.parse=(J,Q)=>{return J.issues.push({expected:"never",code:"invalid_type",input:J.value,inst:Y}),J}});function L5(Y,X,J){if(Y.issues.length)X.issues.push(...W1(J,Y.issues));X.value[J]=Y.value}var i5=j("$ZodArray",(Y,X)=>{r.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)=>L5(L,J,W)));else L5(H,J,W)}if(G.length)return Promise.all(G).then(()=>J);return J}});function sY(Y,X,J,Q){if(Y.issues.length)X.issues.push(...W1(J,Y.issues));if(Y.value===void 0){if(J in Q)X.value[J]=void 0}else X.value[J]=Y.value}function n5(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=ZX(Y.shape);return{...Y,keys:X,keySet:new Set(X),numKeys:X.length,optionalKeys:new Set(J)}}function o5(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)=>sY(K,J,V,X)));else sY(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 ZH=j("$ZodObject",(Y,X)=>{r.init(Y,X);let J=d1(()=>n5(X));d(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=_1,$=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((F)=>sY(F,W,B,H)));else sY(N,W,B,H)}if(!$)return L.length?Promise.all(L).then(()=>W):W;return o5(L,H,W,U,J.value,Y)}}),r5=j("$ZodObjectJIT",(Y,X)=>{ZH.init(Y,X);let J=Y._zod.parse,Q=d1(()=>n5(X)),$=(K)=>{let N=new DX(["shape","payload","ctx"]),F=Q.value,q=(_)=>{let g=pY(_);return`shape[${g}]._zod.run({ value: input[${g}], issues: [] }, ctx)`};N.write("const input = payload.value;");let A=Object.create(null),b=0;for(let _ of F.keys)A[_]=`key_${b++}`;N.write("const newResult = {};");for(let _ of F.keys){let g=A[_],p=pY(_);N.write(`const ${g} = ${q(_)};`),N.write(`
169
- if (${g}.issues.length) {
170
- payload.issues = payload.issues.concat(${g}.issues.map(iss => ({
73
+ `))}}var dG={major:4,minor:1,patch:8};var K0=P("$ZodType",(Y,X)=>{var J;Y??(Y={}),Y._zod.def=X,Y._zod.bag=Y._zod.bag||{},Y._zod.version=dG;let Q=[...Y._zod.def.checks??[]];if(Y._zod.traits.has("$ZodCheck"))Q.unshift(Y);for(let $ of Q)for(let G of $._zod.onattach)G(Y);if(Q.length===0)(J=Y._zod).deferred??(J.deferred=[]),Y._zod.deferred?.push(()=>{Y._zod.run=Y._zod.parse});else{let $=(W,K,Z)=>{let U=_1(W),L;for(let F of K){if(F._zod.def.when){if(!F._zod.def.when(W))continue}else if(U)continue;let N=W.issues.length,V=F._zod.check(W);if(V instanceof Promise&&Z?.async===!1)throw new q1;if(L||V instanceof Promise)L=(L??Promise.resolve()).then(async()=>{if(await V,W.issues.length===N)return;if(!U)U=_1(W,N)});else{if(W.issues.length===N)continue;if(!U)U=_1(W,N)}}if(L)return L.then(()=>{return W});return W},G=(W,K,Z)=>{if(_1(W))return W.aborted=!0,W;let U=$(K,Q,Z);if(U instanceof Promise){if(Z.async===!1)throw new q1;return U.then((L)=>Y._zod.parse(L,Z))}return Y._zod.parse(U,Z)};Y._zod.run=(W,K)=>{if(K.skipChecks)return Y._zod.parse(W,K);if(K.direction==="backward"){let U=Y._zod.parse({value:W.value,issues:[]},{...K,skipChecks:!0});if(U instanceof Promise)return U.then((L)=>{return G(L,W,K)});return G(U,W,K)}let Z=Y._zod.parse(W,K);if(Z instanceof Promise){if(K.async===!1)throw new q1;return Z.then((U)=>$(U,Q,K))}return $(Z,Q,K)}}Y["~standard"]={validate:($)=>{try{let G=i$(Y,$);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return o$(Y,$).then((W)=>W.success?{value:W.data}:{issues:W.error?.issues})}},vendor:"zod",version:1}}),pY=P("$ZodString",(Y,X)=>{K0.init(Y,X),Y._zod.pattern=[...Y?._zod.bag?.patterns??[]].pop()??wG(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}}),Z0=P("$ZodStringFormat",(Y,X)=>{p9.init(Y,X),pY.init(Y,X)}),Y2=P("$ZodGUID",(Y,X)=>{X.pattern??(X.pattern=UG),Z0.init(Y,X)}),X2=P("$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=$8(Q))}else X.pattern??(X.pattern=$8());Z0.init(Y,X)}),J2=P("$ZodEmail",(Y,X)=>{X.pattern??(X.pattern=ZG),Z0.init(Y,X)}),Q2=P("$ZodURL",(Y,X)=>{Z0.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:FG.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})}}}),$2=P("$ZodEmoji",(Y,X)=>{X.pattern??(X.pattern=LG()),Z0.init(Y,X)}),G2=P("$ZodNanoID",(Y,X)=>{X.pattern??(X.pattern=zG),Z0.init(Y,X)}),W2=P("$ZodCUID",(Y,X)=>{X.pattern??(X.pattern=JG),Z0.init(Y,X)}),z2=P("$ZodCUID2",(Y,X)=>{X.pattern??(X.pattern=QG),Z0.init(Y,X)}),K2=P("$ZodULID",(Y,X)=>{X.pattern??(X.pattern=$G),Z0.init(Y,X)}),U2=P("$ZodXID",(Y,X)=>{X.pattern??(X.pattern=GG),Z0.init(Y,X)}),Z2=P("$ZodKSUID",(Y,X)=>{X.pattern??(X.pattern=WG),Z0.init(Y,X)}),L2=P("$ZodISODateTime",(Y,X)=>{X.pattern??(X.pattern=MG(X)),Z0.init(Y,X)}),H2=P("$ZodISODate",(Y,X)=>{X.pattern??(X.pattern=DG),Z0.init(Y,X)}),V2=P("$ZodISOTime",(Y,X)=>{X.pattern??(X.pattern=EG(X)),Z0.init(Y,X)}),N2=P("$ZodISODuration",(Y,X)=>{X.pattern??(X.pattern=KG),Z0.init(Y,X)}),B2=P("$ZodIPv4",(Y,X)=>{X.pattern??(X.pattern=HG),Z0.init(Y,X),Y._zod.onattach.push((J)=>{let Q=J._zod.bag;Q.format="ipv4"})}),q2=P("$ZodIPv6",(Y,X)=>{X.pattern??(X.pattern=VG),Z0.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})}}}),F2=P("$ZodCIDRv4",(Y,X)=>{X.pattern??(X.pattern=NG),Z0.init(Y,X)}),O2=P("$ZodCIDRv6",(Y,X)=>{X.pattern??(X.pattern=BG),Z0.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 j2(Y){if(Y==="")return!0;if(Y.length%4!==0)return!1;try{return atob(Y),!0}catch{return!1}}var D2=P("$ZodBase64",(Y,X)=>{X.pattern??(X.pattern=qG),Z0.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64"}),Y._zod.check=(J)=>{if(j2(J.value))return;J.issues.push({code:"invalid_format",format:"base64",input:J.value,inst:Y,continue:!X.abort})}});function $H(Y){if(!G8.test(Y))return!1;let X=Y.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),J=X.padEnd(Math.ceil(X.length/4)*4,"=");return j2(J)}var P2=P("$ZodBase64URL",(Y,X)=>{X.pattern??(X.pattern=G8),Z0.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64url"}),Y._zod.check=(J)=>{if($H(J.value))return;J.issues.push({code:"invalid_format",format:"base64url",input:J.value,inst:Y,continue:!X.abort})}}),E2=P("$ZodE164",(Y,X)=>{X.pattern??(X.pattern=OG),Z0.init(Y,X)});function GH(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 M2=P("$ZodJWT",(Y,X)=>{Z0.init(Y,X),Y._zod.check=(J)=>{if(GH(J.value,X.alg))return;J.issues.push({code:"invalid_format",format:"jwt",input:J.value,inst:Y,continue:!X.abort})}});var Z8=P("$ZodNumber",(Y,X)=>{K0.init(Y,X),Y._zod.pattern=Y._zod.bag.pattern??TG,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}}),w2=P("$ZodNumber",(Y,X)=>{xG.init(Y,X),Z8.init(Y,X)}),A2=P("$ZodBoolean",(Y,X)=>{K0.init(Y,X),Y._zod.pattern=RG,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 T2=P("$ZodNull",(Y,X)=>{K0.init(Y,X),Y._zod.pattern=CG,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 R2=P("$ZodUnknown",(Y,X)=>{K0.init(Y,X),Y._zod.parse=(J)=>J}),C2=P("$ZodNever",(Y,X)=>{K0.init(Y,X),Y._zod.parse=(J,Q)=>{return J.issues.push({expected:"never",code:"invalid_type",input:J.value,inst:Y}),J}});function iG(Y,X,J){if(Y.issues.length)X.issues.push(...O1(J,Y.issues));X.value[J]=Y.value}var I2=P("$ZodArray",(Y,X)=>{K0.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value;if(!Array.isArray($))return J.issues.push({expected:"array",code:"invalid_type",input:$,inst:Y}),J;J.value=Array($.length);let G=[];for(let W=0;W<$.length;W++){let K=$[W],Z=X.element._zod.run({value:K,issues:[]},Q);if(Z instanceof Promise)G.push(Z.then((U)=>iG(U,J,W)));else iG(Z,J,W)}if(G.length)return Promise.all(G).then(()=>J);return J}});function cY(Y,X,J,Q){if(Y.issues.length)X.issues.push(...O1(J,Y.issues));if(Y.value===void 0){if(J in Q)X.value[J]=void 0}else X.value[J]=Y.value}function _2(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=X8(Y.shape);return{...Y,keys:X,keySet:new Set(X),numKeys:X.length,optionalKeys:new Set(J)}}function S2(Y,X,J,Q,$,G){let W=[],K=$.keySet,Z=$.catchall._zod,U=Z.def.type;for(let L of Object.keys(X)){if(K.has(L))continue;if(U==="never"){W.push(L);continue}let F=Z.run({value:X[L],issues:[]},Q);if(F instanceof Promise)Y.push(F.then((N)=>cY(N,J,L,X)));else cY(F,J,L,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 WH=P("$ZodObject",(Y,X)=>{K0.init(Y,X);let J=K9(()=>_2(X));X0(Y._zod,"propValues",()=>{let W=X.shape,K={};for(let Z in W){let U=W[Z]._zod;if(U.values){K[Z]??(K[Z]=new Set);for(let L of U.values)K[Z].add(L)}}return K});let Q=l1,$=X.catchall,G;Y._zod.parse=(W,K)=>{G??(G=J.value);let Z=W.value;if(!Q(Z))return W.issues.push({expected:"object",code:"invalid_type",input:Z,inst:Y}),W;W.value={};let U=[],L=G.shape;for(let F of G.keys){let V=L[F]._zod.run({value:Z[F],issues:[]},K);if(V instanceof Promise)U.push(V.then((j)=>cY(j,W,F,Z)));else cY(V,W,F,Z)}if(!$)return U.length?Promise.all(U).then(()=>W):W;return S2(U,Z,W,K,J.value,Y)}}),k2=P("$ZodObjectJIT",(Y,X)=>{WH.init(Y,X);let J=Y._zod.parse,Q=K9(()=>_2(X)),$=(N)=>{let V=new K8(["shape","payload","ctx"]),j=Q.value,R=(E)=>{let b=vY(E);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`};V.write("const input = payload.value;");let S=Object.create(null),u=0;for(let E of j.keys)S[E]=`key_${u++}`;V.write("const newResult = {};");for(let E of j.keys){let b=S[E],f=vY(E);V.write(`const ${b} = ${R(E)};`),V.write(`
74
+ if (${b}.issues.length) {
75
+ payload.issues = payload.issues.concat(${b}.issues.map(iss => ({
171
76
  ...iss,
172
- path: iss.path ? [${p}, ...iss.path] : [${p}]
77
+ path: iss.path ? [${f}, ...iss.path] : [${f}]
173
78
  })));
174
79
  }
175
80
 
176
81
 
177
- if (${g}.value === undefined) {
178
- if (${p} in input) {
179
- newResult[${p}] = undefined;
82
+ if (${b}.value === undefined) {
83
+ if (${f} in input) {
84
+ newResult[${f}] = undefined;
180
85
  }
181
86
  } else {
182
- newResult[${p}] = ${g}.value;
87
+ newResult[${f}] = ${b}.value;
183
88
  }
184
89
 
185
- `)}N.write("payload.value = newResult;"),N.write("return payload;");let E=N.compile();return(_,g)=>E(K,_,g)},G,W=_1,U=!uY.jitless,L=U&&NX.value,V=X.catchall,B;Y._zod.parse=(K,N)=>{B??(B=Q.value);let F=K.value;if(!W(F))return K.issues.push({expected:"object",code:"invalid_type",input:F,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 o5([],F,K,N,B,Y)}return J(K,N)}});function H5(Y,X,J,Q){for(let G of Y)if(G.issues.length===0)return X.value=G.value,X;let $=Y.filter((G)=>!F1(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)=>y0(W,Q,n0())))}),X}var EX=j("$ZodUnion",(Y,X)=>{r.init(Y,X),d(Y._zod,"optin",()=>X.options.some(($)=>$._zod.optin==="optional")?"optional":void 0),d(Y._zod,"optout",()=>X.options.some(($)=>$._zod.optout==="optional")?"optional":void 0),d(Y._zod,"values",()=>{if(X.options.every(($)=>$._zod.values))return new Set(X.options.flatMap(($)=>Array.from($._zod.values)));return}),d(Y._zod,"pattern",()=>{if(X.options.every(($)=>$._zod.pattern)){let $=X.options.map((G)=>G._zod.pattern);return new RegExp(`^(${$.map((G)=>zY(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 H5(U,$,Y,G);return Promise.all(U).then((H)=>{return H5(H,$,Y,G)})}}),s5=j("$ZodDiscriminatedUnion",(Y,X)=>{EX.init(Y,X);let J=Y._zod.parse;d(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=d1(()=>{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(!_1(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}),$}}),a5=j("$ZodIntersection",(Y,X)=>{r.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 N5(J,H,L)});return N5(J,G,W)}});function PX(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(B1(Y)&&B1(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=PX(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=PX($,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 N5(Y,X,J){if(X.issues.length)Y.issues.push(...X.issues);if(J.issues.length)Y.issues.push(...J.issues);if(F1(Y))return Y;let Q=PX(X.value,J.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return Y.value=Q.data,Y}var t5=j("$ZodRecord",(Y,X)=>{r.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value;if(!B1($))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(...W1(H,V.issues));J.value[H]=V.value}));else{if(L.issues.length)J.issues.push(...W1(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)=>y0(L,Q,n0())),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(...W1(W,L.issues));J.value[U.value]=L.value}));else{if(H.issues.length)J.issues.push(...W1(W,H.issues));J.value[U.value]=H.value}}}if(G.length)return Promise.all(G).then(()=>J);return J}});var e5=j("$ZodEnum",(Y,X)=>{r.init(Y,X);let J=GY(X.entries),Q=new Set(J);Y._zod.values=Q,Y._zod.pattern=new RegExp(`^(${J.filter(($)=>VX.has(typeof $)).map(($)=>typeof $==="string"?G1($):$.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}),$}}),YG=j("$ZodLiteral",(Y,X)=>{if(r.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"?G1(J):J?G1(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 XG=j("$ZodTransform",(Y,X)=>{r.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new QY(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 $1;return J.value=$,J}});function V5(Y,X){if(Y.issues.length&&X===void 0)return{issues:[],value:void 0};return Y}var JG=j("$ZodOptional",(Y,X)=>{r.init(Y,X),Y._zod.optin="optional",Y._zod.optout="optional",d(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,void 0]):void 0}),d(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${zY(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)=>V5(G,J.value));return V5($,J.value)}if(J.value===void 0)return J;return X.innerType._zod.run(J,Q)}}),QG=j("$ZodNullable",(Y,X)=>{r.init(Y,X),d(Y._zod,"optin",()=>X.innerType._zod.optin),d(Y._zod,"optout",()=>X.innerType._zod.optout),d(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${zY(J.source)}|null)$`):void 0}),d(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)}}),$G=j("$ZodDefault",(Y,X)=>{r.init(Y,X),Y._zod.optin="optional",d(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)=>Z5(G,X));return Z5($,X)}});function Z5(Y,X){if(Y.value===void 0)Y.value=X.defaultValue;return Y}var GG=j("$ZodPrefault",(Y,X)=>{r.init(Y,X),Y._zod.optin="optional",d(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)}}),WG=j("$ZodNonOptional",(Y,X)=>{r.init(Y,X),d(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)=>K5(G,Y));return K5($,Y)}});function K5(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 zG=j("$ZodCatch",(Y,X)=>{r.init(Y,X),d(Y._zod,"optin",()=>X.innerType._zod.optin),d(Y._zod,"optout",()=>X.innerType._zod.optout),d(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)=>y0(W,Q,n0()))},input:J.value}),J.issues=[];return J});if(J.value=$.value,$.issues.length)J.value=X.catchValue({...J,error:{issues:$.issues.map((G)=>y0(G,Q,n0()))},input:J.value}),J.issues=[];return J}});var UG=j("$ZodPipe",(Y,X)=>{r.init(Y,X),d(Y._zod,"values",()=>X.in._zod.values),d(Y._zod,"optin",()=>X.in._zod.optin),d(Y._zod,"optout",()=>X.out._zod.optout),d(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)=>rY(W,X.in,Q));return rY(G,X.in,Q)}let $=X.in._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>rY(G,X.out,Q));return rY($,X.out,Q)}});function rY(Y,X,J){if(Y.issues.length)return Y.aborted=!0,Y;return X._zod.run({value:Y.value,issues:Y.issues},J)}var LG=j("$ZodReadonly",(Y,X)=>{r.init(Y,X),d(Y._zod,"propValues",()=>X.innerType._zod.propValues),d(Y._zod,"values",()=>X.innerType._zod.values),d(Y._zod,"optin",()=>X.innerType._zod.optin),d(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(B5);return B5($)}});function B5(Y){return Y.value=Object.freeze(Y.value),Y}var HG=j("$ZodLazy",(Y,X)=>{r.init(Y,X),d(Y._zod,"innerType",()=>X.getter()),d(Y._zod,"pattern",()=>Y._zod.innerType._zod.pattern),d(Y._zod,"propValues",()=>Y._zod.innerType._zod.propValues),d(Y._zod,"optin",()=>Y._zod.innerType._zod.optin??void 0),d(Y._zod,"optout",()=>Y._zod.innerType._zod.optout??void 0),Y._zod.parse=(J,Q)=>{return Y._zod.innerType._zod.run(J,Q)}}),NG=j("$ZodCustom",(Y,X)=>{V0.init(Y,X),r.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)=>F5(G,J,Q,Y));F5($,J,Q,Y);return}});function F5(Y,X,J,Q){if(!Y){let $={code:"custom",input:J,inst:Q,path:[...Q._zod.def.path??[]],continue:!Q._zod.def.abort};if(Q._zod.def.params)$.params=Q._zod.def.params;X.issues.push(i1($))}}var eF=Symbol("ZodOutput"),YO=Symbol("ZodInput");class tY{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 KH(){return new tY}var S1=KH();function VG(Y,X){return new Y({type:"string",...h(X)})}function ZG(Y,X){return new Y({type:"string",format:"email",check:"string_format",abort:!1,...h(X)})}function wX(Y,X){return new Y({type:"string",format:"guid",check:"string_format",abort:!1,...h(X)})}function KG(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...h(X)})}function BG(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...h(X)})}function FG(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...h(X)})}function OG(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...h(X)})}function jG(Y,X){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...h(X)})}function qG(Y,X){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...h(X)})}function DG(Y,X){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...h(X)})}function PG(Y,X){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...h(X)})}function MG(Y,X){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...h(X)})}function EG(Y,X){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...h(X)})}function wG(Y,X){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...h(X)})}function AG(Y,X){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...h(X)})}function TG(Y,X){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...h(X)})}function RG(Y,X){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...h(X)})}function CG(Y,X){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...h(X)})}function IG(Y,X){return new Y({type:"string",format:"cidrv6",check:"string_format",abort:!1,...h(X)})}function _G(Y,X){return new Y({type:"string",format:"base64",check:"string_format",abort:!1,...h(X)})}function SG(Y,X){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...h(X)})}function kG(Y,X){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...h(X)})}function xG(Y,X){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...h(X)})}function bG(Y,X){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...h(X)})}function vG(Y,X){return new Y({type:"string",format:"date",check:"string_format",...h(X)})}function hG(Y,X){return new Y({type:"string",format:"time",check:"string_format",precision:null,...h(X)})}function gG(Y,X){return new Y({type:"string",format:"duration",check:"string_format",...h(X)})}function yG(Y,X){return new Y({type:"number",checks:[],...h(X)})}function fG(Y,X){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...h(X)})}function mG(Y,X){return new Y({type:"boolean",...h(X)})}function cG(Y,X){return new Y({type:"null",...h(X)})}function uG(Y){return new Y({type:"unknown"})}function pG(Y,X){return new Y({type:"never",...h(X)})}function eY(Y,X){return new jX({check:"less_than",...h(X),value:Y,inclusive:!1})}function VY(Y,X){return new jX({check:"less_than",...h(X),value:Y,inclusive:!0})}function Y9(Y,X){return new qX({check:"greater_than",...h(X),value:Y,inclusive:!1})}function ZY(Y,X){return new qX({check:"greater_than",...h(X),value:Y,inclusive:!0})}function X9(Y,X){return new r$({check:"multiple_of",...h(X),value:Y})}function J9(Y,X){return new a$({check:"max_length",...h(X),maximum:Y})}function n1(Y,X){return new t$({check:"min_length",...h(X),minimum:Y})}function Q9(Y,X){return new e$({check:"length_equals",...h(X),length:Y})}function AX(Y,X){return new Y5({check:"string_format",format:"regex",...h(X),pattern:Y})}function TX(Y){return new X5({check:"string_format",format:"lowercase",...h(Y)})}function RX(Y){return new J5({check:"string_format",format:"uppercase",...h(Y)})}function CX(Y,X){return new Q5({check:"string_format",format:"includes",...h(X),includes:Y})}function IX(Y,X){return new $5({check:"string_format",format:"starts_with",...h(X),prefix:Y})}function _X(Y,X){return new G5({check:"string_format",format:"ends_with",...h(X),suffix:Y})}function k1(Y){return new W5({check:"overwrite",tx:Y})}function SX(Y){return k1((X)=>X.normalize(Y))}function kX(){return k1((Y)=>Y.trim())}function xX(){return k1((Y)=>Y.toLowerCase())}function bX(){return k1((Y)=>Y.toUpperCase())}function lG(Y,X,J){return new Y({type:"array",element:X,...h(J)})}function dG(Y,X,J){let Q=h(J);return Q.abort??(Q.abort=!0),new Y({type:"custom",check:"custom",fn:X,...Q})}function iG(Y,X,J){return new Y({type:"custom",check:"custom",fn:X,...h(J)})}function nG(Y){let X=BH((J)=>{return J.addIssue=(Q)=>{if(typeof Q==="string")J.issues.push(i1(Q,J.value,X._zod.def));else{let $=Q;if($.fatal)$.continue=!1;$.code??($.code="custom"),$.input??($.input=J.value),$.inst??($.inst=X),$.continue??($.continue=!X._zod.def.abort),J.issues.push(i1($))}},Y(J.value,J)});return X}function BH(Y,X){let J=new V0({check:"custom",...h(X)});return J._zod.check=Y,J}class vX{constructor(Y){this.counter=0,this.metadataRegistry=Y?.metadata??S1,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:F,maximum:q,format:A,patterns:b,contentEncoding:E}=Y._zod.bag;if(typeof F==="number")N.minLength=F;if(typeof q==="number")N.maxLength=q;if(A){if(N.format=$[A]??A,N.format==="")delete N.format}if(E)N.contentEncoding=E;if(b&&b.size>0){let _=[...b];if(_.length===1)N.pattern=_[0].source;else if(_.length>1)W.schema.allOf=[..._.map((g)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))]}break}case"number":{let N=K,{minimum:F,maximum:q,format:A,multipleOf:b,exclusiveMaximum:E,exclusiveMinimum:_}=Y._zod.bag;if(typeof A==="string"&&A.includes("int"))N.type="integer";else N.type="number";if(typeof _==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")N.minimum=_,N.exclusiveMinimum=!0;else N.exclusiveMinimum=_;if(typeof F==="number"){if(N.minimum=F,typeof _==="number"&&this.target!=="draft-4")if(_>=F)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 q==="number"){if(N.maximum=q,typeof E==="number"&&this.target!=="draft-4")if(E<=q)delete N.maximum;else delete N.exclusiveMaximum}if(typeof b==="number")N.multipleOf=b;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:F,maximum:q}=Y._zod.bag;if(typeof F==="number")N.minItems=F;if(typeof q==="number")N.maxItems=q;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 F=Q.shape;for(let b in F)N.properties[b]=this.process(F[b],{...V,path:[...V.path,"properties",b]});let q=new Set(Object.keys(F)),A=new Set([...q].filter((b)=>{let E=Q.shape[b]._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,F=Q.options.map((q,A)=>this.process(q,{...V,path:[...V.path,"anyOf",A]}));N.anyOf=F;break}case"intersection":{let N=K,F=this.process(Q.left,{...V,path:[...V.path,"allOf",0]}),q=this.process(Q.right,{...V,path:[...V.path,"allOf",1]}),A=(E)=>("allOf"in E)&&Object.keys(E).length===1,b=[...A(F)?F.allOf:[F],...A(q)?q.allOf:[q]];N.allOf=b;break}case"tuple":{let N=K;N.type="array";let F=this.target==="draft-2020-12"?"prefixItems":"items",q=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",A=Q.items.map((g,p)=>this.process(g,{...V,path:[...V.path,F,p]})),b=Q.rest?this.process(Q.rest,{...V,path:[...V.path,q,...this.target==="openapi-3.0"?[Q.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(N.prefixItems=A,b)N.items=b}else if(this.target==="openapi-3.0"){if(N.items={anyOf:A},b)N.items.anyOf.push(b);if(N.minItems=A.length,!b)N.maxItems=A.length}else if(N.items=A,b)N.additionalItems=b;let{minimum:E,maximum:_}=Y._zod.bag;if(typeof E==="number")N.minItems=E;if(typeof _==="number")N.maxItems=_;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,F=GY(Q.entries);if(F.every((q)=>typeof q==="number"))N.type="number";if(F.every((q)=>typeof q==="string"))N.type="string";N.enum=F;break}case"literal":{let N=K,F=[];for(let q of Q.values)if(q===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof q==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else F.push(Number(q));else F.push(q);if(F.length===0);else if(F.length===1){let q=F[0];if(N.type=q===null?"null":typeof q,this.target==="draft-4"||this.target==="openapi-3.0")N.enum=[q];else N.const=q}else{if(F.every((q)=>typeof q==="number"))N.type="number";if(F.every((q)=>typeof q==="string"))N.type="string";if(F.every((q)=>typeof q==="boolean"))N.type="string";if(F.every((q)=>q===null))N.type="null";N.enum=F}break}case"file":{let N=K,F={type:"string",format:"binary",contentEncoding:"binary"},{minimum:q,maximum:A,mime:b}=Y._zod.bag;if(q!==void 0)F.minLength=q;if(A!==void 0)F.maxLength=A;if(b)if(b.length===1)F.contentMediaType=b[0],Object.assign(N,F);else N.anyOf=b.map((E)=>{return{...F,contentMediaType:E}});else Object.assign(N,F);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,F=Y._zod.pattern;if(!F)throw Error("Pattern not found in template literal");N.type="string",N.pattern=F.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"&&z0(Y))delete W.schema.examples,delete W.schema.default;if(this.io==="input"&&W.schema._prefault)(J=W.schema).default??(J.default=W.schema._prefault);return delete W.schema._prefault,this.seen.get(Y).schema}emit(Y,X){let J={cycles:X?.cycles??"ref",reused:X?.reused??"inline",external:X?.external??void 0},Q=this.seen.get(Y);if(!Q)throw Error("Unprocessed schema. This is a bug in Zod.");let $=(L)=>{let V=this.target==="draft-2020-12"?"$defs":"definitions";if(J.external){let F=J.external.registry.get(L[0])?.id,q=J.external.uri??((b)=>b);if(F)return{ref:q(F)};let A=L[1].defId??L[1].schema.id??`schema${this.counter++}`;return L[1].defId=A,{defId:A,ref:`${q("__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 F in N)delete N[F];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
+ `)}V.write("payload.value = newResult;"),V.write("return payload;");let I=V.compile();return(E,b)=>I(N,E,b)},G,W=l1,K=!bY.jitless,U=K&&eX.value,L=X.catchall,F;Y._zod.parse=(N,V)=>{F??(F=Q.value);let j=N.value;if(!W(j))return N.issues.push({expected:"object",code:"invalid_type",input:j,inst:Y}),N;if(K&&U&&V?.async===!1&&V.jitless!==!0){if(!G)G=$(X.shape);if(N=G(N,V),!L)return N;return S2([],j,N,V,F,Y)}return J(N,V)}});function oG(Y,X,J,Q){for(let G of Y)if(G.issues.length===0)return X.value=G.value,X;let $=Y.filter((G)=>!_1(G));if($.length===1)return X.value=$[0].value,$[0];return X.issues.push({code:"invalid_union",input:X.value,inst:J,errors:Y.map((G)=>G.issues.map((W)=>t0(W,Q,G1())))}),X}var L8=P("$ZodUnion",(Y,X)=>{K0.init(Y,X),X0(Y._zod,"optin",()=>X.options.some(($)=>$._zod.optin==="optional")?"optional":void 0),X0(Y._zod,"optout",()=>X.options.some(($)=>$._zod.optout==="optional")?"optional":void 0),X0(Y._zod,"values",()=>{if(X.options.every(($)=>$._zod.values))return new Set(X.options.flatMap(($)=>Array.from($._zod.values)));return}),X0(Y._zod,"pattern",()=>{if(X.options.every(($)=>$._zod.pattern)){let $=X.options.map((G)=>G._zod.pattern);return new RegExp(`^(${$.map((G)=>f9(G.source)).join("|")})$`)}return});let J=X.options.length===1,Q=X.options[0]._zod.run;Y._zod.parse=($,G)=>{if(J)return Q($,G);let W=!1,K=[];for(let Z of X.options){let U=Z._zod.run({value:$.value,issues:[]},G);if(U instanceof Promise)K.push(U),W=!0;else{if(U.issues.length===0)return U;K.push(U)}}if(!W)return oG(K,$,Y,G);return Promise.all(K).then((Z)=>{return oG(Z,$,Y,G)})}}),x2=P("$ZodDiscriminatedUnion",(Y,X)=>{L8.init(Y,X);let J=Y._zod.parse;X0(Y._zod,"propValues",()=>{let $={};for(let G of X.options){let W=G._zod.propValues;if(!W||Object.keys(W).length===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf(G)}"`);for(let[K,Z]of Object.entries(W)){if(!$[K])$[K]=new Set;for(let U of Z)$[K].add(U)}}return $});let Q=K9(()=>{let $=X.options,G=new Map;for(let W of $){let K=W._zod.propValues?.[X.discriminator];if(!K||K.size===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf(W)}"`);for(let Z of K){if(G.has(Z))throw Error(`Duplicate discriminator value "${String(Z)}"`);G.set(Z,W)}}return G});Y._zod.parse=($,G)=>{let W=$.value;if(!l1(W))return $.issues.push({code:"invalid_type",expected:"object",input:W,inst:Y}),$;let K=Q.value.get(W?.[X.discriminator]);if(K)return K._zod.run($,G);if(X.unionFallback)return J($,G);return $.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:X.discriminator,input:W,path:[X.discriminator],inst:Y}),$}}),b2=P("$ZodIntersection",(Y,X)=>{K0.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(([Z,U])=>{return nG(J,Z,U)});return nG(J,G,W)}});function U8(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(I1(Y)&&I1(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=U8(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=U8($,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 nG(Y,X,J){if(X.issues.length)Y.issues.push(...X.issues);if(J.issues.length)Y.issues.push(...J.issues);if(_1(Y))return Y;let Q=U8(X.value,J.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return Y.value=Q.data,Y}var v2=P("$ZodRecord",(Y,X)=>{K0.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value;if(!I1($))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 Z of W)if(typeof Z==="string"||typeof Z==="number"||typeof Z==="symbol"){let U=X.valueType._zod.run({value:$[Z],issues:[]},Q);if(U instanceof Promise)G.push(U.then((L)=>{if(L.issues.length)J.issues.push(...O1(Z,L.issues));J.value[Z]=L.value}));else{if(U.issues.length)J.issues.push(...O1(Z,U.issues));J.value[Z]=U.value}}let K;for(let Z in $)if(!W.has(Z))K=K??[],K.push(Z);if(K&&K.length>0)J.issues.push({code:"unrecognized_keys",input:$,inst:Y,keys:K})}else{J.value={};for(let W of Reflect.ownKeys($)){if(W==="__proto__")continue;let K=X.keyType._zod.run({value:W,issues:[]},Q);if(K instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(K.issues.length){J.issues.push({code:"invalid_key",origin:"record",issues:K.issues.map((U)=>t0(U,Q,G1())),input:W,path:[W],inst:Y}),J.value[K.value]=K.value;continue}let Z=X.valueType._zod.run({value:$[W],issues:[]},Q);if(Z instanceof Promise)G.push(Z.then((U)=>{if(U.issues.length)J.issues.push(...O1(W,U.issues));J.value[K.value]=U.value}));else{if(Z.issues.length)J.issues.push(...O1(W,Z.issues));J.value[K.value]=Z.value}}}if(G.length)return Promise.all(G).then(()=>J);return J}});var h2=P("$ZodEnum",(Y,X)=>{K0.init(Y,X);let J=g9(X.entries),Q=new Set(J);Y._zod.values=Q,Y._zod.pattern=new RegExp(`^(${J.filter(($)=>Y8.has(typeof $)).map(($)=>typeof $==="string"?F1($):$.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}),$}}),g2=P("$ZodLiteral",(Y,X)=>{if(K0.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"?F1(J):J?F1(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 y2=P("$ZodTransform",(Y,X)=>{K0.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new v9(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 q1;return J.value=$,J}});function rG(Y,X){if(Y.issues.length&&X===void 0)return{issues:[],value:void 0};return Y}var f2=P("$ZodOptional",(Y,X)=>{K0.init(Y,X),Y._zod.optin="optional",Y._zod.optout="optional",X0(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,void 0]):void 0}),X0(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${f9(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)=>rG(G,J.value));return rG($,J.value)}if(J.value===void 0)return J;return X.innerType._zod.run(J,Q)}}),m2=P("$ZodNullable",(Y,X)=>{K0.init(Y,X),X0(Y._zod,"optin",()=>X.innerType._zod.optin),X0(Y._zod,"optout",()=>X.innerType._zod.optout),X0(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${f9(J.source)}|null)$`):void 0}),X0(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)}}),u2=P("$ZodDefault",(Y,X)=>{K0.init(Y,X),Y._zod.optin="optional",X0(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)=>sG(G,X));return sG($,X)}});function sG(Y,X){if(Y.value===void 0)Y.value=X.defaultValue;return Y}var c2=P("$ZodPrefault",(Y,X)=>{K0.init(Y,X),Y._zod.optin="optional",X0(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)}}),p2=P("$ZodNonOptional",(Y,X)=>{K0.init(Y,X),X0(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)=>aG(G,Y));return aG($,Y)}});function aG(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 l2=P("$ZodCatch",(Y,X)=>{K0.init(Y,X),X0(Y._zod,"optin",()=>X.innerType._zod.optin),X0(Y._zod,"optout",()=>X.innerType._zod.optout),X0(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)=>t0(W,Q,G1()))},input:J.value}),J.issues=[];return J});if(J.value=$.value,$.issues.length)J.value=X.catchValue({...J,error:{issues:$.issues.map((G)=>t0(G,Q,G1()))},input:J.value}),J.issues=[];return J}});var d2=P("$ZodPipe",(Y,X)=>{K0.init(Y,X),X0(Y._zod,"values",()=>X.in._zod.values),X0(Y._zod,"optin",()=>X.in._zod.optin),X0(Y._zod,"optout",()=>X.out._zod.optout),X0(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)=>uY(W,X.in,Q));return uY(G,X.in,Q)}let $=X.in._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>uY(G,X.out,Q));return uY($,X.out,Q)}});function uY(Y,X,J){if(Y.issues.length)return Y.aborted=!0,Y;return X._zod.run({value:Y.value,issues:Y.issues},J)}var i2=P("$ZodReadonly",(Y,X)=>{K0.init(Y,X),X0(Y._zod,"propValues",()=>X.innerType._zod.propValues),X0(Y._zod,"values",()=>X.innerType._zod.values),X0(Y._zod,"optin",()=>X.innerType._zod.optin),X0(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(tG);return tG($)}});function tG(Y){return Y.value=Object.freeze(Y.value),Y}var o2=P("$ZodLazy",(Y,X)=>{K0.init(Y,X),X0(Y._zod,"innerType",()=>X.getter()),X0(Y._zod,"pattern",()=>Y._zod.innerType._zod.pattern),X0(Y._zod,"propValues",()=>Y._zod.innerType._zod.propValues),X0(Y._zod,"optin",()=>Y._zod.innerType._zod.optin??void 0),X0(Y._zod,"optout",()=>Y._zod.innerType._zod.optout??void 0),Y._zod.parse=(J,Q)=>{return Y._zod.innerType._zod.run(J,Q)}}),n2=P("$ZodCustom",(Y,X)=>{w0.init(Y,X),K0.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)=>eG(G,J,Q,Y));eG($,J,Q,Y);return}});function eG(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(U9($))}}var f6=Symbol("ZodOutput"),m6=Symbol("ZodInput");class lY{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 zH(){return new lY}var d1=zH();function r2(Y,X){return new Y({type:"string",...i(X)})}function s2(Y,X){return new Y({type:"string",format:"email",check:"string_format",abort:!1,...i(X)})}function H8(Y,X){return new Y({type:"string",format:"guid",check:"string_format",abort:!1,...i(X)})}function a2(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...i(X)})}function t2(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...i(X)})}function e2(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...i(X)})}function Y7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...i(X)})}function X7(Y,X){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...i(X)})}function J7(Y,X){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...i(X)})}function Q7(Y,X){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...i(X)})}function $7(Y,X){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...i(X)})}function G7(Y,X){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...i(X)})}function W7(Y,X){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...i(X)})}function z7(Y,X){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...i(X)})}function K7(Y,X){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...i(X)})}function U7(Y,X){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...i(X)})}function Z7(Y,X){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...i(X)})}function L7(Y,X){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...i(X)})}function H7(Y,X){return new Y({type:"string",format:"cidrv6",check:"string_format",abort:!1,...i(X)})}function V7(Y,X){return new Y({type:"string",format:"base64",check:"string_format",abort:!1,...i(X)})}function N7(Y,X){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...i(X)})}function B7(Y,X){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...i(X)})}function q7(Y,X){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...i(X)})}function F7(Y,X){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...i(X)})}function O7(Y,X){return new Y({type:"string",format:"date",check:"string_format",...i(X)})}function j7(Y,X){return new Y({type:"string",format:"time",check:"string_format",precision:null,...i(X)})}function D7(Y,X){return new Y({type:"string",format:"duration",check:"string_format",...i(X)})}function P7(Y,X){return new Y({type:"number",checks:[],...i(X)})}function E7(Y,X){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...i(X)})}function M7(Y,X){return new Y({type:"boolean",...i(X)})}function w7(Y,X){return new Y({type:"null",...i(X)})}function A7(Y){return new Y({type:"unknown"})}function T7(Y,X){return new Y({type:"never",...i(X)})}function dY(Y,X){return new W8({check:"less_than",...i(X),value:Y,inclusive:!1})}function l9(Y,X){return new W8({check:"less_than",...i(X),value:Y,inclusive:!0})}function iY(Y,X){return new z8({check:"greater_than",...i(X),value:Y,inclusive:!1})}function d9(Y,X){return new z8({check:"greater_than",...i(X),value:Y,inclusive:!0})}function oY(Y,X){return new kG({check:"multiple_of",...i(X),value:Y})}function nY(Y,X){return new bG({check:"max_length",...i(X),maximum:Y})}function Z9(Y,X){return new vG({check:"min_length",...i(X),minimum:Y})}function rY(Y,X){return new hG({check:"length_equals",...i(X),length:Y})}function V8(Y,X){return new gG({check:"string_format",format:"regex",...i(X),pattern:Y})}function N8(Y){return new yG({check:"string_format",format:"lowercase",...i(Y)})}function B8(Y){return new fG({check:"string_format",format:"uppercase",...i(Y)})}function q8(Y,X){return new mG({check:"string_format",format:"includes",...i(X),includes:Y})}function F8(Y,X){return new uG({check:"string_format",format:"starts_with",...i(X),prefix:Y})}function O8(Y,X){return new cG({check:"string_format",format:"ends_with",...i(X),suffix:Y})}function i1(Y){return new pG({check:"overwrite",tx:Y})}function j8(Y){return i1((X)=>X.normalize(Y))}function D8(){return i1((Y)=>Y.trim())}function P8(){return i1((Y)=>Y.toLowerCase())}function E8(){return i1((Y)=>Y.toUpperCase())}function R7(Y,X,J){return new Y({type:"array",element:X,...i(J)})}function C7(Y,X,J){let Q=i(J);return Q.abort??(Q.abort=!0),new Y({type:"custom",check:"custom",fn:X,...Q})}function I7(Y,X,J){return new Y({type:"custom",check:"custom",fn:X,...i(J)})}function _7(Y){let X=KH((J)=>{return J.addIssue=(Q)=>{if(typeof Q==="string")J.issues.push(U9(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(U9($))}},Y(J.value,J)});return X}function KH(Y,X){let J=new w0({check:"custom",...i(X)});return J._zod.check=Y,J}class M8{constructor(Y){this.counter=0,this.metadataRegistry=Y?.metadata??d1,this.target=Y?.target??"draft-2020-12",this.unrepresentable=Y?.unrepresentable??"throw",this.override=Y?.override??(()=>{}),this.io=Y?.io??"output",this.seen=new Map}process(Y,X={path:[],schemaPath:[]}){var J;let Q=Y._zod.def,$={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},G=this.seen.get(Y);if(G){if(G.count++,X.schemaPath.includes(Y))G.cycle=X.path;return G.schema}let W={schema:{},count:1,cycle:void 0,path:X.path};this.seen.set(Y,W);let K=Y._zod.toJSONSchema?.();if(K)W.schema=K;else{let L={...X,schemaPath:[...X.schemaPath,Y],path:X.path},F=Y._zod.parent;if(F)W.ref=F,this.process(F,L),this.seen.get(F).isParent=!0;else{let N=W.schema;switch(Q.type){case"string":{let V=N;V.type="string";let{minimum:j,maximum:R,format:S,patterns:u,contentEncoding:I}=Y._zod.bag;if(typeof j==="number")V.minLength=j;if(typeof R==="number")V.maxLength=R;if(S){if(V.format=$[S]??S,V.format==="")delete V.format}if(I)V.contentEncoding=I;if(u&&u.size>0){let E=[...u];if(E.length===1)V.pattern=E[0].source;else if(E.length>1)W.schema.allOf=[...E.map((b)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:b.source}))]}break}case"number":{let V=N,{minimum:j,maximum:R,format:S,multipleOf:u,exclusiveMaximum:I,exclusiveMinimum:E}=Y._zod.bag;if(typeof S==="string"&&S.includes("int"))V.type="integer";else V.type="number";if(typeof E==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")V.minimum=E,V.exclusiveMinimum=!0;else V.exclusiveMinimum=E;if(typeof j==="number"){if(V.minimum=j,typeof E==="number"&&this.target!=="draft-4")if(E>=j)delete V.minimum;else delete V.exclusiveMinimum}if(typeof I==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")V.maximum=I,V.exclusiveMaximum=!0;else V.exclusiveMaximum=I;if(typeof R==="number"){if(V.maximum=R,typeof I==="number"&&this.target!=="draft-4")if(I<=R)delete V.maximum;else delete V.exclusiveMaximum}if(typeof u==="number")V.multipleOf=u;break}case"boolean":{let V=N;V.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema");break}case"null":{if(this.target==="openapi-3.0")N.type="string",N.nullable=!0,N.enum=[null];else N.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":{N.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let V=N,{minimum:j,maximum:R}=Y._zod.bag;if(typeof j==="number")V.minItems=j;if(typeof R==="number")V.maxItems=R;V.type="array",V.items=this.process(Q.element,{...L,path:[...L.path,"items"]});break}case"object":{let V=N;V.type="object",V.properties={};let j=Q.shape;for(let u in j)V.properties[u]=this.process(j[u],{...L,path:[...L.path,"properties",u]});let R=new Set(Object.keys(j)),S=new Set([...R].filter((u)=>{let I=Q.shape[u]._zod;if(this.io==="input")return I.optin===void 0;else return I.optout===void 0}));if(S.size>0)V.required=Array.from(S);if(Q.catchall?._zod.def.type==="never")V.additionalProperties=!1;else if(!Q.catchall){if(this.io==="output")V.additionalProperties=!1}else if(Q.catchall)V.additionalProperties=this.process(Q.catchall,{...L,path:[...L.path,"additionalProperties"]});break}case"union":{let V=N,j=Q.options.map((R,S)=>this.process(R,{...L,path:[...L.path,"anyOf",S]}));V.anyOf=j;break}case"intersection":{let V=N,j=this.process(Q.left,{...L,path:[...L.path,"allOf",0]}),R=this.process(Q.right,{...L,path:[...L.path,"allOf",1]}),S=(I)=>("allOf"in I)&&Object.keys(I).length===1,u=[...S(j)?j.allOf:[j],...S(R)?R.allOf:[R]];V.allOf=u;break}case"tuple":{let V=N;V.type="array";let j=this.target==="draft-2020-12"?"prefixItems":"items",R=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",S=Q.items.map((b,f)=>this.process(b,{...L,path:[...L.path,j,f]})),u=Q.rest?this.process(Q.rest,{...L,path:[...L.path,R,...this.target==="openapi-3.0"?[Q.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(V.prefixItems=S,u)V.items=u}else if(this.target==="openapi-3.0"){if(V.items={anyOf:S},u)V.items.anyOf.push(u);if(V.minItems=S.length,!u)V.maxItems=S.length}else if(V.items=S,u)V.additionalItems=u;let{minimum:I,maximum:E}=Y._zod.bag;if(typeof I==="number")V.minItems=I;if(typeof E==="number")V.maxItems=E;break}case"record":{let V=N;if(V.type="object",this.target==="draft-7"||this.target==="draft-2020-12")V.propertyNames=this.process(Q.keyType,{...L,path:[...L.path,"propertyNames"]});V.additionalProperties=this.process(Q.valueType,{...L,path:[...L.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let V=N,j=g9(Q.entries);if(j.every((R)=>typeof R==="number"))V.type="number";if(j.every((R)=>typeof R==="string"))V.type="string";V.enum=j;break}case"literal":{let V=N,j=[];for(let R of Q.values)if(R===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof R==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else j.push(Number(R));else j.push(R);if(j.length===0);else if(j.length===1){let R=j[0];if(V.type=R===null?"null":typeof R,this.target==="draft-4"||this.target==="openapi-3.0")V.enum=[R];else V.const=R}else{if(j.every((R)=>typeof R==="number"))V.type="number";if(j.every((R)=>typeof R==="string"))V.type="string";if(j.every((R)=>typeof R==="boolean"))V.type="string";if(j.every((R)=>R===null))V.type="null";V.enum=j}break}case"file":{let V=N,j={type:"string",format:"binary",contentEncoding:"binary"},{minimum:R,maximum:S,mime:u}=Y._zod.bag;if(R!==void 0)j.minLength=R;if(S!==void 0)j.maxLength=S;if(u)if(u.length===1)j.contentMediaType=u[0],Object.assign(V,j);else V.anyOf=u.map((I)=>{return{...j,contentMediaType:I}});else Object.assign(V,j);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let V=this.process(Q.innerType,L);if(this.target==="openapi-3.0")W.ref=Q.innerType,N.nullable=!0;else N.anyOf=[V,{type:"null"}];break}case"nonoptional":{this.process(Q.innerType,L),W.ref=Q.innerType;break}case"success":{let V=N;V.type="boolean";break}case"default":{this.process(Q.innerType,L),W.ref=Q.innerType,N.default=JSON.parse(JSON.stringify(Q.defaultValue));break}case"prefault":{if(this.process(Q.innerType,L),W.ref=Q.innerType,this.io==="input")N._prefault=JSON.parse(JSON.stringify(Q.defaultValue));break}case"catch":{this.process(Q.innerType,L),W.ref=Q.innerType;let V;try{V=Q.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}N.default=V;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let V=N,j=Y._zod.pattern;if(!j)throw Error("Pattern not found in template literal");V.type="string",V.pattern=j.source;break}case"pipe":{let V=this.io==="input"?Q.in._zod.def.type==="transform"?Q.out:Q.in:Q.out;this.process(V,L),W.ref=V;break}case"readonly":{this.process(Q.innerType,L),W.ref=Q.innerType,N.readOnly=!0;break}case"promise":{this.process(Q.innerType,L),W.ref=Q.innerType;break}case"optional":{this.process(Q.innerType,L),W.ref=Q.innerType;break}case"lazy":{let V=Y._zod.innerType;this.process(V,L),W.ref=V;break}case"custom":{if(this.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema");break}case"function":{if(this.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema");break}default:}}}let Z=this.metadataRegistry.get(Y);if(Z)Object.assign(W.schema,Z);if(this.io==="input"&&D0(Y))delete W.schema.examples,delete W.schema.default;if(this.io==="input"&&W.schema._prefault)(J=W.schema).default??(J.default=W.schema._prefault);return delete W.schema._prefault,this.seen.get(Y).schema}emit(Y,X){let J={cycles:X?.cycles??"ref",reused:X?.reused??"inline",external:X?.external??void 0},Q=this.seen.get(Y);if(!Q)throw Error("Unprocessed schema. This is a bug in Zod.");let $=(U)=>{let L=this.target==="draft-2020-12"?"$defs":"definitions";if(J.external){let j=J.external.registry.get(U[0])?.id,R=J.external.uri??((u)=>u);if(j)return{ref:R(j)};let S=U[1].defId??U[1].schema.id??`schema${this.counter++}`;return U[1].defId=S,{defId:S,ref:`${R("__shared")}#/${L}/${S}`}}if(U[1]===Q)return{ref:"#"};let N=`${"#"}/${L}/`,V=U[1].schema.id??`__schema${this.counter++}`;return{defId:V,ref:N+V}},G=(U)=>{if(U[1].schema.$ref)return;let L=U[1],{ref:F,defId:N}=$(U);if(L.def={...L.schema},N)L.defId=N;let V=L.schema;for(let j in V)delete V[j];V.$ref=F};if(J.cycles==="throw")for(let U of this.seen.entries()){let L=U[1];if(L.cycle)throw Error(`Cycle detected: #/${L.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 F=B.ref;if(B.ref=null,F){W(F,V);let q=this.seen.get(F).schema;if(q.$ref&&(V.target==="draft-7"||V.target==="draft-4"||V.target==="openapi-3.0"))K.allOf=K.allOf??[],K.allOf.push(q);else Object.assign(K,q),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 oG(Y,X){if(Y instanceof tY){let Q=new vX(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 vX(X);return J.process(Y),J.emit(Y,X)}function z0(Y,X){let J=X??{seen:new Set};if(J.seen.has(Y))return!1;J.seen.add(Y);let $=Y._zod.def;switch($.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return z0($.element,J);case"object":{for(let G in $.shape)if(z0($.shape[G],J))return!0;return!1}case"union":{for(let G of $.options)if(z0(G,J))return!0;return!1}case"intersection":return z0($.left,J)||z0($.right,J);case"tuple":{for(let G of $.items)if(z0(G,J))return!0;if($.rest&&z0($.rest,J))return!0;return!1}case"record":return z0($.keyType,J)||z0($.valueType,J);case"map":return z0($.keyType,J)||z0($.valueType,J);case"set":return z0($.valueType,J);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return z0($.innerType,J);case"lazy":return z0($.getter(),J);case"default":return z0($.innerType,J);case"prefault":return z0($.innerType,J);case"custom":return!1;case"transform":return!0;case"pipe":return z0($.in,J)||z0($.out,J);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${$.type}`)}var PH=j("ZodISODateTime",(Y,X)=>{C5.init(Y,X),t.init(Y,X)});function rG(Y){return bG(PH,Y)}var MH=j("ZodISODate",(Y,X)=>{I5.init(Y,X),t.init(Y,X)});function sG(Y){return vG(MH,Y)}var EH=j("ZodISOTime",(Y,X)=>{_5.init(Y,X),t.init(Y,X)});function aG(Y){return hG(EH,Y)}var wH=j("ZodISODuration",(Y,X)=>{S5.init(Y,X),t.init(Y,X)});function tG(Y){return gG(wH,Y)}var eG=(Y,X)=>{dY.init(Y,X),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(J)=>U$(Y,J)},flatten:{value:(J)=>z$(Y,J)},addIssue:{value:(J)=>{Y.issues.push(J),Y.message=JSON.stringify(Y.issues,l1,2)}},addIssues:{value:(J)=>{Y.issues.push(...J),Y.message=JSON.stringify(Y.issues,l1,2)}},isEmpty:{get(){return Y.issues.length===0}}})},_O=j("ZodError",eG),_0=j("ZodError",eG,{Parent:Error});var YW=iY(_0),XW=nY(_0),JW=LY(_0),G9=HY(_0),QW=N$(_0),$W=V$(_0),GW=Z$(_0),WW=K$(_0),zW=B$(_0),UW=F$(_0),LW=O$(_0),HW=j$(_0);var e=j("ZodType",(Y,X)=>{return r.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)=>g0(Y,J,Q),Y.brand=()=>Y,Y.register=(J,Q)=>{return J.add(Y,Q),Y},Y.parse=(J,Q)=>YW(Y,J,Q,{callee:Y.parse}),Y.safeParse=(J,Q)=>JW(Y,J,Q),Y.parseAsync=async(J,Q)=>XW(Y,J,Q,{callee:Y.parseAsync}),Y.safeParseAsync=async(J,Q)=>G9(Y,J,Q),Y.spa=Y.safeParseAsync,Y.encode=(J,Q)=>QW(Y,J,Q),Y.decode=(J,Q)=>$W(Y,J,Q),Y.encodeAsync=async(J,Q)=>GW(Y,J,Q),Y.decodeAsync=async(J,Q)=>WW(Y,J,Q),Y.safeEncode=(J,Q)=>zW(Y,J,Q),Y.safeDecode=(J,Q)=>UW(Y,J,Q),Y.safeEncodeAsync=async(J,Q)=>LW(Y,J,Q),Y.safeDecodeAsync=async(J,Q)=>HW(Y,J,Q),Y.refine=(J,Q)=>Y.check(ON(J,Q)),Y.superRefine=(J)=>Y.check(jN(J)),Y.overwrite=(J)=>Y.check(k1(J)),Y.optional=()=>ZW(Y),Y.nullable=()=>KW(Y),Y.nullish=()=>ZW(KW(Y)),Y.nonoptional=(J)=>HN(Y,J),Y.array=()=>yX(Y),Y.or=(J)=>fX([Y,J]),Y.and=(J)=>YN(Y,J),Y.transform=(J)=>BW(Y,$N(J)),Y.default=(J)=>zN(Y,J),Y.prefault=(J)=>LN(Y,J),Y.catch=(J)=>VN(Y,J),Y.pipe=(J)=>BW(Y,J),Y.readonly=()=>BN(Y),Y.describe=(J)=>{let Q=Y.clone();return S1.add(Q,{description:J}),Q},Object.defineProperty(Y,"description",{get(){return S1.get(Y)?.description},configurable:!0}),Y.meta=(...J)=>{if(J.length===0)return S1.get(Y);let Q=Y.clone();return S1.add(Q,J[0]),Q},Y.isOptional=()=>Y.safeParse(void 0).success,Y.isNullable=()=>Y.safeParse(null).success,Y}),FW=j("_ZodString",(Y,X)=>{aY.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(AX(...Q)),Y.includes=(...Q)=>Y.check(CX(...Q)),Y.startsWith=(...Q)=>Y.check(IX(...Q)),Y.endsWith=(...Q)=>Y.check(_X(...Q)),Y.min=(...Q)=>Y.check(n1(...Q)),Y.max=(...Q)=>Y.check(J9(...Q)),Y.length=(...Q)=>Y.check(Q9(...Q)),Y.nonempty=(...Q)=>Y.check(n1(1,...Q)),Y.lowercase=(Q)=>Y.check(TX(Q)),Y.uppercase=(Q)=>Y.check(RX(Q)),Y.trim=()=>Y.check(kX()),Y.normalize=(...Q)=>Y.check(SX(...Q)),Y.toLowerCase=()=>Y.check(xX()),Y.toUpperCase=()=>Y.check(bX())}),CH=j("ZodString",(Y,X)=>{aY.init(Y,X),FW.init(Y,X),Y.email=(J)=>Y.check(ZG(IH,J)),Y.url=(J)=>Y.check(jG(_H,J)),Y.jwt=(J)=>Y.check(xG(dH,J)),Y.emoji=(J)=>Y.check(qG(SH,J)),Y.guid=(J)=>Y.check(wX(NW,J)),Y.uuid=(J)=>Y.check(KG(W9,J)),Y.uuidv4=(J)=>Y.check(BG(W9,J)),Y.uuidv6=(J)=>Y.check(FG(W9,J)),Y.uuidv7=(J)=>Y.check(OG(W9,J)),Y.nanoid=(J)=>Y.check(DG(kH,J)),Y.guid=(J)=>Y.check(wX(NW,J)),Y.cuid=(J)=>Y.check(PG(xH,J)),Y.cuid2=(J)=>Y.check(MG(bH,J)),Y.ulid=(J)=>Y.check(EG(vH,J)),Y.base64=(J)=>Y.check(_G(uH,J)),Y.base64url=(J)=>Y.check(SG(pH,J)),Y.xid=(J)=>Y.check(wG(hH,J)),Y.ksuid=(J)=>Y.check(AG(gH,J)),Y.ipv4=(J)=>Y.check(TG(yH,J)),Y.ipv6=(J)=>Y.check(RG(fH,J)),Y.cidrv4=(J)=>Y.check(CG(mH,J)),Y.cidrv6=(J)=>Y.check(IG(cH,J)),Y.e164=(J)=>Y.check(kG(lH,J)),Y.datetime=(J)=>Y.check(rG(J)),Y.date=(J)=>Y.check(sG(J)),Y.time=(J)=>Y.check(aG(J)),Y.duration=(J)=>Y.check(tG(J))});function OW(Y){return VG(CH,Y)}var t=j("ZodStringFormat",(Y,X)=>{s.init(Y,X),FW.init(Y,X)}),IH=j("ZodEmail",(Y,X)=>{q5.init(Y,X),t.init(Y,X)});var NW=j("ZodGUID",(Y,X)=>{O5.init(Y,X),t.init(Y,X)});var W9=j("ZodUUID",(Y,X)=>{j5.init(Y,X),t.init(Y,X)});var _H=j("ZodURL",(Y,X)=>{D5.init(Y,X),t.init(Y,X)});var SH=j("ZodEmoji",(Y,X)=>{P5.init(Y,X),t.init(Y,X)});var kH=j("ZodNanoID",(Y,X)=>{M5.init(Y,X),t.init(Y,X)});var xH=j("ZodCUID",(Y,X)=>{E5.init(Y,X),t.init(Y,X)});var bH=j("ZodCUID2",(Y,X)=>{w5.init(Y,X),t.init(Y,X)});var vH=j("ZodULID",(Y,X)=>{A5.init(Y,X),t.init(Y,X)});var hH=j("ZodXID",(Y,X)=>{T5.init(Y,X),t.init(Y,X)});var gH=j("ZodKSUID",(Y,X)=>{R5.init(Y,X),t.init(Y,X)});var yH=j("ZodIPv4",(Y,X)=>{k5.init(Y,X),t.init(Y,X)});var fH=j("ZodIPv6",(Y,X)=>{x5.init(Y,X),t.init(Y,X)});var mH=j("ZodCIDRv4",(Y,X)=>{b5.init(Y,X),t.init(Y,X)});var cH=j("ZodCIDRv6",(Y,X)=>{v5.init(Y,X),t.init(Y,X)});var uH=j("ZodBase64",(Y,X)=>{g5.init(Y,X),t.init(Y,X)});var pH=j("ZodBase64URL",(Y,X)=>{y5.init(Y,X),t.init(Y,X)});var lH=j("ZodE164",(Y,X)=>{f5.init(Y,X),t.init(Y,X)});var dH=j("ZodJWT",(Y,X)=>{m5.init(Y,X),t.init(Y,X)});var jW=j("ZodNumber",(Y,X)=>{MX.init(Y,X),e.init(Y,X),Y.gt=(Q,$)=>Y.check(Y9(Q,$)),Y.gte=(Q,$)=>Y.check(ZY(Q,$)),Y.min=(Q,$)=>Y.check(ZY(Q,$)),Y.lt=(Q,$)=>Y.check(eY(Q,$)),Y.lte=(Q,$)=>Y.check(VY(Q,$)),Y.max=(Q,$)=>Y.check(VY(Q,$)),Y.int=(Q)=>Y.check(VW(Q)),Y.safe=(Q)=>Y.check(VW(Q)),Y.positive=(Q)=>Y.check(Y9(0,Q)),Y.nonnegative=(Q)=>Y.check(ZY(0,Q)),Y.negative=(Q)=>Y.check(eY(0,Q)),Y.nonpositive=(Q)=>Y.check(VY(0,Q)),Y.multipleOf=(Q,$)=>Y.check(X9(Q,$)),Y.step=(Q,$)=>Y.check(X9(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 qW(Y){return yG(jW,Y)}var iH=j("ZodNumberFormat",(Y,X)=>{c5.init(Y,X),jW.init(Y,X)});function VW(Y){return fG(iH,Y)}var nH=j("ZodBoolean",(Y,X)=>{u5.init(Y,X),e.init(Y,X)});function DW(Y){return mG(nH,Y)}var oH=j("ZodNull",(Y,X)=>{p5.init(Y,X),e.init(Y,X)});function PW(Y){return cG(oH,Y)}var rH=j("ZodUnknown",(Y,X)=>{l5.init(Y,X),e.init(Y,X)});function KY(){return uG(rH)}var sH=j("ZodNever",(Y,X)=>{d5.init(Y,X),e.init(Y,X)});function gX(Y){return pG(sH,Y)}var aH=j("ZodArray",(Y,X)=>{i5.init(Y,X),e.init(Y,X),Y.element=X.element,Y.min=(J,Q)=>Y.check(n1(J,Q)),Y.nonempty=(J)=>Y.check(n1(1,J)),Y.max=(J,Q)=>Y.check(J9(J,Q)),Y.length=(J,Q)=>Y.check(Q9(J,Q)),Y.unwrap=()=>Y.element});function yX(Y,X){return lG(aH,Y,X)}var MW=j("ZodObject",(Y,X)=>{r5.init(Y,X),e.init(Y,X),u.defineLazy(Y,"shape",()=>X.shape),Y.keyof=()=>mX(Object.keys(Y._zod.def.shape)),Y.catchall=(J)=>Y.clone({...Y._zod.def,catchall:J}),Y.passthrough=()=>Y.clone({...Y._zod.def,catchall:KY()}),Y.loose=()=>Y.clone({...Y._zod.def,catchall:KY()}),Y.strict=()=>Y.clone({...Y._zod.def,catchall:gX()}),Y.strip=()=>Y.clone({...Y._zod.def,catchall:void 0}),Y.extend=(J)=>{return u.extend(Y,J)},Y.safeExtend=(J)=>{return u.safeExtend(Y,J)},Y.merge=(J)=>u.merge(Y,J),Y.pick=(J)=>u.pick(Y,J),Y.omit=(J)=>u.omit(Y,J),Y.partial=(...J)=>u.partial(IW,Y,J[0]),Y.required=(...J)=>u.required(_W,Y,J[0])});function EW(Y,X){let J={type:"object",get shape(){return u.assignProp(this,"shape",Y?u.objectClone(Y):{}),this.shape},...u.normalizeParams(X)};return new MW(J)}function wW(Y,X){return new MW({type:"object",get shape(){return u.assignProp(this,"shape",u.objectClone(Y)),this.shape},catchall:KY(),...u.normalizeParams(X)})}var AW=j("ZodUnion",(Y,X)=>{EX.init(Y,X),e.init(Y,X),Y.options=X.options});function fX(Y,X){return new AW({type:"union",options:Y,...u.normalizeParams(X)})}var tH=j("ZodDiscriminatedUnion",(Y,X)=>{AW.init(Y,X),s5.init(Y,X)});function TW(Y,X,J){return new tH({type:"union",options:X,discriminator:Y,...u.normalizeParams(J)})}var eH=j("ZodIntersection",(Y,X)=>{a5.init(Y,X),e.init(Y,X)});function YN(Y,X){return new eH({type:"intersection",left:Y,right:X})}var XN=j("ZodRecord",(Y,X)=>{t5.init(Y,X),e.init(Y,X),Y.keyType=X.keyType,Y.valueType=X.valueType});function RW(Y,X,J){return new XN({type:"record",keyType:Y,valueType:X,...u.normalizeParams(J)})}var hX=j("ZodEnum",(Y,X)=>{e5.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 hX({...X,checks:[],...u.normalizeParams($),entries:G})},Y.exclude=(Q,$)=>{let G={...X.entries};for(let W of Q)if(J.has(W))delete G[W];else throw Error(`Key ${W} not found in enum`);return new hX({...X,checks:[],...u.normalizeParams($),entries:G})}});function mX(Y,X){let J=Array.isArray(Y)?Object.fromEntries(Y.map((Q)=>[Q,Q])):Y;return new hX({type:"enum",entries:J,...u.normalizeParams(X)})}var JN=j("ZodLiteral",(Y,X)=>{YG.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 CW(Y,X){return new JN({type:"literal",values:Array.isArray(Y)?Y:[Y],...u.normalizeParams(X)})}var QN=j("ZodTransform",(Y,X)=>{XG.init(Y,X),e.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new QY(Y.constructor.name);J.addIssue=(G)=>{if(typeof G==="string")J.issues.push(u.issue(G,J.value,X));else{let W=G;if(W.fatal)W.continue=!1;W.code??(W.code="custom"),W.input??(W.input=J.value),W.inst??(W.inst=Y),J.issues.push(u.issue(W))}};let $=X.transform(J.value,J);if($ instanceof Promise)return $.then((G)=>{return J.value=G,J});return J.value=$,J}});function $N(Y){return new QN({type:"transform",transform:Y})}var IW=j("ZodOptional",(Y,X)=>{JG.init(Y,X),e.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function ZW(Y){return new IW({type:"optional",innerType:Y})}var GN=j("ZodNullable",(Y,X)=>{QG.init(Y,X),e.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function KW(Y){return new GN({type:"nullable",innerType:Y})}var WN=j("ZodDefault",(Y,X)=>{$G.init(Y,X),e.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function zN(Y,X){return new WN({type:"default",innerType:Y,get defaultValue(){return typeof X==="function"?X():u.shallowClone(X)}})}var UN=j("ZodPrefault",(Y,X)=>{GG.init(Y,X),e.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function LN(Y,X){return new UN({type:"prefault",innerType:Y,get defaultValue(){return typeof X==="function"?X():u.shallowClone(X)}})}var _W=j("ZodNonOptional",(Y,X)=>{WG.init(Y,X),e.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function HN(Y,X){return new _W({type:"nonoptional",innerType:Y,...u.normalizeParams(X)})}var NN=j("ZodCatch",(Y,X)=>{zG.init(Y,X),e.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function VN(Y,X){return new NN({type:"catch",innerType:Y,catchValue:typeof X==="function"?X:()=>X})}var ZN=j("ZodPipe",(Y,X)=>{UG.init(Y,X),e.init(Y,X),Y.in=X.in,Y.out=X.out});function BW(Y,X){return new ZN({type:"pipe",in:Y,out:X})}var KN=j("ZodReadonly",(Y,X)=>{LG.init(Y,X),e.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function BN(Y){return new KN({type:"readonly",innerType:Y})}var FN=j("ZodLazy",(Y,X)=>{HG.init(Y,X),e.init(Y,X),Y.unwrap=()=>Y._zod.def.getter()});function SW(Y){return new FN({type:"lazy",getter:Y})}var cX=j("ZodCustom",(Y,X)=>{NG.init(Y,X),e.init(Y,X)});function kW(Y,X){return dG(cX,Y??(()=>!0),X)}function ON(Y,X={}){return iG(cX,Y,X)}function jN(Y){return nG(Y)}function xW(Y,X={error:`Input not instance of ${Y.name}`}){let J=new cX({type:"custom",check:"custom",fn:(Q)=>Q instanceof Y,abort:!0,...u.normalizeParams(X)});return J._zod.bag.Class=Y,J}function pW(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 qN(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 o1(Y,...X){let J=new Headers(qN(Y)),Q=J.get("user-agent")||"";return J.set("user-agent",[Q,...X].filter(Boolean).join(" ")),Object.fromEntries(J.entries())}var DN=[{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]}],Oj=[...DN,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];var PN=12,MN=131072,jj=MN+PN;async function z9(Y){var X;try{await((X=Y.body)==null?void 0:X.cancel())}catch(J){}}var lW="AI_DownloadError",dW=`vercel.ai.error.${lW}`,EN=Symbol.for(dW),bW,vW,q0=class extends(vW=D,bW=EN,vW){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:lW,message:$,cause:Q});this[bW]=!0,this.url=Y,this.statusCode=X,this.statusText=J}static isInstance(Y){return D.hasMarker(Y,dW)}};function wN(Y=globalThis){return Y.window!=null}function hW(Y,X){try{return new URL(Y).origin===new URL(X).origin}catch(J){return!1}}function AN(Y){let X;try{X=new URL(Y)}catch(Q){throw new q0({url:Y,message:`Invalid URL: ${Y}`})}if(X.protocol==="data:")return;if(X.protocol!=="http:"&&X.protocol!=="https:")throw new q0({url:Y,message:`URL scheme must be http, https, or data, got ${X.protocol}`});let J=X.hostname.toLowerCase().replace(/\.+$/,"");if(!J)throw new q0({url:Y,message:"URL must have a hostname"});if(J==="localhost"||J.endsWith(".local")||J.endsWith(".localhost"))throw new q0({url:Y,message:`URL with hostname ${J} is not allowed`});if(J.startsWith("[")&&J.endsWith("]")){let Q=J.slice(1,-1);if(iW(Q))throw new q0({url:Y,message:`URL with IPv6 address ${J} is not allowed`});return}if(nX(J)){if(oX(J))throw new q0({url:Y,message:`URL with IP address ${J} is not allowed`});return}}function TN({address:Y,family:X,hostname:J}){if(X===4?!nX(Y)||oX(Y):X===6?iW(Y):!0)throw new q0({url:J,message:`Hostname ${J} resolved to disallowed IP address ${Y}`})}function nX(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 oX(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 RN(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||!nX(V))return null;let[B,K,N,F]=V.split(".").map(Number);U.push(B<<8|K,N<<8|F);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 iW(Y){let X=RN(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 oX(`${$}.${G}.${W}.${U}`)}return!1}function CN(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)TN({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 uX,nW=globalThis.fetch,IN=kN(nW);function _N(){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 SN(){if(!_N()||!IN||globalThis.fetch!==nW)return globalThis.fetch;return uX!=null?uX:uX=Promise.resolve().then(xN)}function kN(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 xN(){let{createRequire:Y}=gW("node:module"),{lookup:X}=gW("node:dns"),{Agent:J,fetch:Q}=Y(oW())("undici"),$=new J({connect:{lookup:CN(X)}});return(G,W)=>Q(G,{...W,dispatcher:$})}function gW(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 oW(){let Y=Error.prepareStackTrace;try{Error.prepareStackTrace=($,G)=>G;let X=Error("Capture current module path");Error.captureStackTrace(X,oW);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 bN=["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 vN(Y){let X=new Headers(Y);for(let J of bN)X.delete(J);return X}var hN=10,gN=new Set([301,302,303,307,308]);async function yN(Y){return Y==null||Y===globalThis.fetch?await SN():Y}async function rW({url:Y,headers:X,abortSignal:J,maxRedirects:Q=hN,fetch:$,trustedOrigin:G}){var W;let U=X===void 0?void 0:vN(X),H=(V)=>{let B={signal:J,redirect:V};if(U!==void 0)B.headers=new Headers(U);return B},L=Y;for(let V=0;V<=Q;V++){let B=G!==void 0&&hW(L,G);if(!B)AN(L);let K=B&&$!=null?$:B?globalThis.fetch:await yN($),N=await K(L,H("manual"));if(N.type==="opaqueredirect"){if(!wN())throw new q0({url:Y,message:`Redirect from ${L} could not be validated and was blocked`});return await K(L,H("follow"))}let F=(W=N.headers)==null?void 0:W.get("location");if(gN.has(N.status)&&F){await z9(N);let q=new URL(F,L).toString();if(U!==void 0&&!hW(q,L)){let A=U.get("user-agent");U=new Headers(A==null?void 0:{"user-agent":A})}L=q;continue}return N}throw new q0({url:Y,message:`Too many redirects (max ${Q})`})}var rX=2147483648;async function sW({response:Y,url:X,maxBytes:J=rX}){let Q=Y.headers.get("content-length");if(Q!=null){let V=parseInt(Q,10);if(!isNaN(V)&&V>J)throw await z9(Y),new q0({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 q0({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 G0=({prefix:Y,size:X=16,alphabet:J="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:Q="-"}={})=>{let $=()=>{let G=J.length,W=Array(X);for(let U=0;U<X;U++)W[U]=J[Math.random()*G|0];return W.join("")};if(Y==null)return $;if(J.includes(Q))throw new CQ({argument:"separator",message:`The separator "${Q}" must not be part of the alphabet "${J}".`});return()=>`${Y}${Q}${$()}`},Pj=G0();function aW(Y){var X,J;return(J=(X=globalThis.Buffer)==null?void 0:X.isBuffer(Y))!=null?J:!1}var fN=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,mN=/"(?: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 yW(Y){let X=JSON.parse(Y);if(X===null||typeof X!=="object")return X;if(fN.test(Y)===!1&&mN.test(Y)===!1)return X;return cN(X)}function cN(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 uN(Y){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(J){return yW(Y)}try{return yW(Y)}finally{Error.stackTraceLimit=X}}function sX(Y){if(Y.type==="object"||Array.isArray(Y.type)&&Y.type.includes("object")){let{additionalProperties:J}=Y;Y.additionalProperties=J!=null&&typeof J!=="boolean"?O1(J):!1;let{properties:Q}=Y;if(Q!=null)for(let $ of Object.keys(Q))Q[$]=O1(Q[$])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(O1):O1(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(O1);if(Y.allOf!=null)Y.allOf=Y.allOf.map(O1);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(O1);let{definitions:X}=Y;if(X!=null)for(let J of Object.keys(X))X[J]=O1(X[J]);return Y}function O1(Y){if(typeof Y==="boolean")return Y;return sX(Y)}var pN=Symbol("Let zodToJsonSchema decide on which parser to use"),fW={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"},lN=(Y)=>typeof Y==="string"?{...fW,name:Y}:{...fW,...Y};function S0(){return{}}function dN(Y,X){var J,Q,$;let G={type:"array"};if(((J=Y.type)==null?void 0:J._def)&&(($=(Q=Y.type)==null?void 0:Q._def)==null?void 0:$.typeName)!=="ZodAny")G.items=n(Y.type._def,{...X,currentPath:[...X.currentPath,"items"]});if(Y.minLength)G.minItems=Y.minLength.value;if(Y.maxLength)G.maxItems=Y.maxLength.value;if(Y.exactLength)G.minItems=Y.exactLength.value,G.maxItems=Y.exactLength.value;return G}function iN(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 nN(){return{type:"boolean"}}function tW(Y,X){return n(Y.type._def,X)}var oN=(Y,X)=>{return n(Y.innerType._def,X)};function eW(Y,X,J){let Q=J!=null?J:X.dateStrategy;if(Array.isArray(Q))return{anyOf:Q.map(($)=>eW(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 rN(Y)}}var rN=(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 sN(Y,X){return{...n(Y.innerType._def,X),default:Y.defaultValue()}}function aN(Y,X){return X.effectStrategy==="input"?n(Y.schema._def,X):S0()}function tN(Y){return{type:"string",enum:Array.from(Y.values)}}var eN=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function YV(Y,X){let J=[n(Y.left._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),n(Y.right._def,{...X,currentPath:[...X.currentPath,"allOf","1"]})].filter(($)=>!!$),Q=[];return J.forEach(($)=>{if(eN($))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 XV(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 pX=void 0,f0={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(pX===void 0)pX=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return pX},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 Y2(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":m0(J,"email",Q.message,X);break;case"format:idn-email":m0(J,"idn-email",Q.message,X);break;case"pattern:zod":j0(J,f0.email,Q.message,X);break}break;case"url":m0(J,"uri",Q.message,X);break;case"uuid":m0(J,"uuid",Q.message,X);break;case"regex":j0(J,Q.regex,Q.message,X);break;case"cuid":j0(J,f0.cuid,Q.message,X);break;case"cuid2":j0(J,f0.cuid2,Q.message,X);break;case"startsWith":j0(J,RegExp(`^${lX(Q.value,X)}`),Q.message,X);break;case"endsWith":j0(J,RegExp(`${lX(Q.value,X)}$`),Q.message,X);break;case"datetime":m0(J,"date-time",Q.message,X);break;case"date":m0(J,"date",Q.message,X);break;case"time":m0(J,"time",Q.message,X);break;case"duration":m0(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":{j0(J,RegExp(lX(Q.value,X)),Q.message,X);break}case"ip":{if(Q.version!=="v6")m0(J,"ipv4",Q.message,X);if(Q.version!=="v4")m0(J,"ipv6",Q.message,X);break}case"base64url":j0(J,f0.base64url,Q.message,X);break;case"jwt":j0(J,f0.jwt,Q.message,X);break;case"cidr":{if(Q.version!=="v6")j0(J,f0.ipv4Cidr,Q.message,X);if(Q.version!=="v4")j0(J,f0.ipv6Cidr,Q.message,X);break}case"emoji":j0(J,f0.emoji(),Q.message,X);break;case"ulid":{j0(J,f0.ulid,Q.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{m0(J,"binary",Q.message,X);break}case"contentEncoding:base64":{J.contentEncoding="base64";break}case"pattern:zod":{j0(J,f0.base64,Q.message,X);break}}break}case"nanoid":j0(J,f0.nanoid,Q.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return J}function lX(Y,X){return X.patternStrategy==="escape"?QV(Y):Y}var JV=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function QV(Y){let X="";for(let J=0;J<Y.length;J++){if(!JV.has(Y[J]))X+="\\";X+=Y[J]}return X}function m0(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 j0(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:mW(X,Q),...J&&Q.errorMessages&&{errorMessage:{pattern:J}}})}else Y.pattern=mW(X,Q)}function mW(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 X2(Y,X){var J,Q,$,G,W,U;let H={type:"object",additionalProperties:(J=n(Y.valueType._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]}))!=null?J:X.allowedAdditionalProperties};if(((Q=Y.keyType)==null?void 0:Q._def.typeName)==="ZodString"&&(($=Y.keyType._def.checks)==null?void 0:$.length)){let{type:L,...V}=Y2(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}=tW(Y.keyType._def,X);return{...H,propertyNames:V}}return H}function $V(Y,X){if(X.mapStrategy==="record")return X2(Y,X);let J=n(Y.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||S0(),Q=n(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||S0();return{type:"array",maxItems:125,items:{type:"array",items:[J,Q],minItems:2,maxItems:2}}}function GV(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 WV(){return{not:S0()}}function zV(){return{type:"null"}}var dX={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function UV(Y,X){let J=Y.options instanceof Map?Array.from(Y.options.values()):Y.options;if(J.every((Q)=>(Q._def.typeName in dX)&&(!Q._def.checks||!Q._def.checks.length))){let Q=J.reduce(($,G)=>{let W=dX[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 LV(Y,X)}var LV=(Y,X)=>{let J=(Y.options instanceof Map?Array.from(Y.options.values()):Y.options).map((Q,$)=>n(Q._def,{...X,currentPath:[...X.currentPath,"anyOf",`${$}`]})).filter((Q)=>!!Q&&(!X.strictUnions||typeof Q==="object"&&Object.keys(Q).length>0));return J.length?{anyOf:J}:void 0};function HV(Y,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Y.innerType._def.typeName)&&(!Y.innerType._def.checks||!Y.innerType._def.checks.length))return{type:[dX[Y.innerType._def.typeName],"null"]};let J=n(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return J&&{anyOf:[J,{type:"null"}]}}function NV(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 VV(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=KV(U),L=n(U._def,{...X,currentPath:[...X.currentPath,"properties",W],propertyPath:[...X.currentPath,"properties",W]});if(L===void 0)continue;if(J.properties[W]=L,!H)Q.push(W)}if(Q.length)J.required=Q;let G=ZV(Y,X);if(G!==void 0)J.additionalProperties=G;return J}function ZV(Y,X){if(Y.catchall._def.typeName!=="ZodNever")return n(Y.catchall._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]});switch(Y.unknownKeys){case"passthrough":return X.allowedAdditionalProperties;case"strict":return X.rejectedAdditionalProperties;case"strip":return X.removeAdditionalStrategy==="strict"?X.allowedAdditionalProperties:X.rejectedAdditionalProperties}}function KV(Y){try{return Y.isOptional()}catch(X){return!0}}var BV=(Y,X)=>{var J;if(X.currentPath.toString()===((J=X.propertyPath)==null?void 0:J.toString()))return n(Y.innerType._def,X);let Q=n(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return Q?{anyOf:[{not:S0()},Q]}:S0()},FV=(Y,X)=>{if(X.pipeStrategy==="input")return n(Y.in._def,X);else if(X.pipeStrategy==="output")return n(Y.out._def,X);let J=n(Y.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),Q=n(Y.out._def,{...X,currentPath:[...X.currentPath,"allOf",J?"1":"0"]});return{allOf:[J,Q].filter(($)=>$!==void 0)}};function OV(Y,X){return n(Y.type._def,X)}function jV(Y,X){let Q={type:"array",uniqueItems:!0,items:n(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items"]})};if(Y.minSize)Q.minItems=Y.minSize.value;if(Y.maxSize)Q.maxItems=Y.maxSize.value;return Q}function qV(Y,X){if(Y.rest)return{type:"array",minItems:Y.items.length,items:Y.items.map((J,Q)=>n(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[]),additionalItems:n(Y.rest._def,{...X,currentPath:[...X.currentPath,"additionalItems"]})};else return{type:"array",minItems:Y.items.length,maxItems:Y.items.length,items:Y.items.map((J,Q)=>n(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[])}}function DV(){return{not:S0()}}function PV(){return S0()}var MV=(Y,X)=>{return n(Y.innerType._def,X)},EV=(Y,X,J)=>{switch(X){case"ZodString":return Y2(Y,J);case"ZodNumber":return NV(Y);case"ZodObject":return VV(Y,J);case"ZodBigInt":return iN(Y);case"ZodBoolean":return nN();case"ZodDate":return eW(Y,J);case"ZodUndefined":return DV();case"ZodNull":return zV();case"ZodArray":return dN(Y,J);case"ZodUnion":case"ZodDiscriminatedUnion":return UV(Y,J);case"ZodIntersection":return YV(Y,J);case"ZodTuple":return qV(Y,J);case"ZodRecord":return X2(Y,J);case"ZodLiteral":return XV(Y);case"ZodEnum":return tN(Y);case"ZodNativeEnum":return GV(Y);case"ZodNullable":return HV(Y,J);case"ZodOptional":return BV(Y,J);case"ZodMap":return $V(Y,J);case"ZodSet":return jV(Y,J);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return OV(Y,J);case"ZodNaN":case"ZodNever":return WV();case"ZodEffects":return aN(Y,J);case"ZodAny":return S0();case"ZodUnknown":return PV();case"ZodDefault":return sN(Y,J);case"ZodBranded":return tW(Y,J);case"ZodReadonly":return MV(Y,J);case"ZodCatch":return oN(Y,J);case"ZodPipeline":return FV(Y,J);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Q)=>{return})(X)}},wV=(Y,X)=>{let J=0;for(;J<Y.length&&J<X.length;J++)if(Y[J]!==X[J])break;return[(Y.length-J).toString(),...X.slice(J)].join("/")};function n(Y,X,J=!1){var Q;let $=X.seen.get(Y);if(X.override){let H=(Q=X.override)==null?void 0:Q.call(X,Y,X,$,J);if(H!==pN)return H}if($&&!J){let H=AV($,X);if(H!==void 0)return H}let G={def:Y,path:X.currentPath,jsonSchema:void 0};X.seen.set(Y,G);let W=EV(Y,Y.typeName,X),U=typeof W==="function"?n(W(),X):W;if(U)TV(Y,X,U);if(X.postProcess){let H=X.postProcess(U,Y,X);return G.jsonSchema=U,H}return G.jsonSchema=U,U}var AV=(Y,X)=>{switch(X.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:wV(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`),S0();return X.$refStrategy==="seen"?S0():void 0}}},TV=(Y,X,J)=>{if(Y.description)J.description=Y.description;return J},RV=(Y)=>{let X=lN(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}]))}},CV=(Y,X)=>{var J;let Q=RV(X),$=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((L,[V,B])=>{var K;return{...L,[V]:(K=n(B._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,V]},!0))!=null?K:S0()}},{}):void 0,G=typeof X==="string"?X:(X==null?void 0:X.nameStrategy)==="title"?void 0:X==null?void 0:X.name,W=(J=n(Y._def,G===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,G]},!1))!=null?J:S0(),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},iX=Symbol.for("vercel.ai.schema");function U9(Y){let X;return()=>{if(X==null)X=Y();return X}}function L9(Y,{validate:X}={}){return{[iX]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:X}}function IV(Y){return typeof Y==="object"&&Y!==null&&iX in Y&&Y[iX]===!0&&"jsonSchema"in Y&&"validate"in Y}function H9(Y){return Y==null?L9({type:"object",properties:{},additionalProperties:!1}):IV(Y)?Y:("~standard"in Y)?Y["~standard"].vendor==="zod"?BY(Y):_V(Y):Y()}function _V(Y){return L9(()=>{if(!SV(Y))throw Error(`Standard schema vendor '${Y["~standard"].vendor}' does not support JSON Schema conversion.`);return sX(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 k0({value:X,cause:J.issues})}}})}function SV(Y){return Y["~standard"].jsonSchema!=null}function kV(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return L9(()=>CV(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 xV(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return L9(()=>sX(oG(Y,{target:"draft-7",io:"input",reused:Q?"ref":"inline"})),{validate:async($)=>{let G=await G9(Y,$);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function bV(Y){return"_zod"in Y}function BY(Y,X){if(bV(Y))return xV(Y,X);else return kV(Y,X)}async function r1({value:Y,schema:X,context:J}){let Q=H9(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:k0.wrap({value:Y,cause:$.error,context:J}),rawValue:Y}}catch($){return{success:!1,error:k0.wrap({value:Y,cause:$,context:J}),rawValue:Y}}}async function j1({text:Y,schema:X}){try{let J=uN(Y);if(X==null)return{success:!0,value:J,rawValue:J};return await r1({value:J,schema:X})}catch(J){return{success:!1,error:cY.isInstance(J)?J:new cY({text:Y,cause:J}),rawValue:void 0}}}async function aX(Y){if(typeof Y==="function")Y=Y();return Promise.resolve(Y)}var J2="AI_SerializationError",Q2=`vercel.ai.error.${J2}`,vV=Symbol.for(Q2),cW,uW,Cj=class extends(uW=D,cW=vV,uW){constructor({message:Y="Failed to serialize value.",cause:X}={}){super({name:J2,message:Y,cause:X});this[cW]=!0}static isInstance(Y){return D.hasMarker(Y,Q2)}};var yV=Object.defineProperty,fV=(Y,X)=>{for(var J in X)yV(Y,J,{get:X[J],enumerable:!0})},Y7="AI_InvalidArgumentError",X7=`vercel.ai.error.${Y7}`,mV=Symbol.for(X7),$2,G2,tX=class extends(G2=D,$2=mV,G2){constructor({parameter:Y,value:X,message:J}){super({name:Y7,message:`Invalid argument for parameter ${Y}: ${J}`});this[$2]=!0,this.parameter=Y,this.value=X}static isInstance(Y){return D.hasMarker(Y,X7)}},J7="AI_InvalidStreamPartError",Q7=`vercel.ai.error.${J7}`,cV=Symbol.for(Q7),W2,z2,mj=class extends(z2=D,W2=cV,z2){constructor({chunk:Y,message:X}){super({name:J7,message:X});this[W2]=!0,this.chunk=Y}static isInstance(Y){return D.hasMarker(Y,Q7)}},$7="AI_InvalidToolApprovalError",G7=`vercel.ai.error.${$7}`,uV=Symbol.for(G7),U2,L2,uj=class extends(L2=D,U2=uV,L2){constructor({approvalId:Y}){super({name:$7,message:`Tool approval response references unknown approvalId: "${Y}". No matching tool-approval-request found in message history.`});this[U2]=!0,this.approvalId=Y}static isInstance(Y){return D.hasMarker(Y,G7)}},W7="AI_InvalidToolApprovalSignatureError",z7=`vercel.ai.error.${W7}`,pV=Symbol.for(z7),H2,N2,lj=class extends(N2=D,H2=pV,N2){constructor({approvalId:Y,toolCallId:X,reason:J}){super({name:W7,message:`Tool approval signature verification failed for approval "${Y}" (tool call "${X}"): ${J}`});this[H2]=!0,this.approvalId=Y,this.toolCallId=X}static isInstance(Y){return D.hasMarker(Y,z7)}},U7="AI_InvalidToolInputError",L7=`vercel.ai.error.${U7}`,lV=Symbol.for(L7),V2,Z2,ij=class extends(Z2=D,V2=lV,Z2){constructor({toolInput:Y,toolName:X,cause:J,message:Q=`Invalid input for tool ${X}: ${I1(J)}`}){super({name:U7,message:Q,cause:J});this[V2]=!0,this.toolInput=Y,this.toolName=X}static isInstance(Y){return D.hasMarker(Y,L7)}},H7="AI_ToolCallNotFoundForApprovalError",N7=`vercel.ai.error.${H7}`,dV=Symbol.for(N7),K2,B2,oj=class extends(B2=D,K2=dV,B2){constructor({toolCallId:Y,approvalId:X}){super({name:H7,message:`Tool call "${Y}" not found for approval request "${X}".`});this[K2]=!0,this.toolCallId=Y,this.approvalId=X}static isInstance(Y){return D.hasMarker(Y,N7)}},V7="AI_MissingToolResultsError",Z7=`vercel.ai.error.${V7}`,iV=Symbol.for(Z7),F2,O2,sj=class extends(O2=D,F2=iV,O2){constructor({toolCallIds:Y}){super({name:V7,message:`Tool result${Y.length>1?"s are":" is"} missing for tool call${Y.length>1?"s":""} ${Y.join(", ")}.`});this[F2]=!0,this.toolCallIds=Y}static isInstance(Y){return D.hasMarker(Y,Z7)}},K7="AI_NoImageGeneratedError",B7=`vercel.ai.error.${K7}`,nV=Symbol.for(B7),j2,q2,tj=class extends(q2=D,j2=nV,q2){constructor({message:Y="No image generated.",cause:X,calls:J,responses:Q}){super({name:K7,message:Y,cause:X});this[j2]=!0,this.calls=J,this.responses=Q}static isInstance(Y){return D.hasMarker(Y,B7)}},F7="AI_NoObjectGeneratedError",O7=`vercel.ai.error.${F7}`,oV=Symbol.for(O7),D2,P2,z1=class extends(P2=D,D2=oV,P2){constructor({message:Y="No object generated.",cause:X,text:J,response:Q,usage:$,finishReason:G}){super({name:F7,message:Y,cause:X});this[D2]=!0,this.text=J,this.response=Q,this.usage=$,this.finishReason=G}static isInstance(Y){return D.hasMarker(Y,O7)}},j7="AI_NoOutputGeneratedError",q7=`vercel.ai.error.${j7}`,rV=Symbol.for(q7),M2,E2,Xq=class extends(E2=D,M2=rV,E2){constructor({message:Y="No output generated.",cause:X}={}){super({name:j7,message:Y,cause:X});this[M2]=!0}static isInstance(Y){return D.hasMarker(Y,q7)}},D7="AI_NoSpeechGeneratedError",P7=`vercel.ai.error.${D7}`,sV=Symbol.for(P7),w2,A2,Qq=class extends(A2=D,w2=sV,A2){constructor(Y){super({name:D7,message:"No speech audio generated."});this[w2]=!0,this.responses=Y.responses}static isInstance(Y){return D.hasMarker(Y,P7)}},M7="AI_NoTranscriptGeneratedError",E7=`vercel.ai.error.${M7}`,aV=Symbol.for(E7),T2,R2,Gq=class extends(R2=D,T2=aV,R2){constructor(Y){super({name:M7,message:"No transcript generated."});this[T2]=!0,this.responses=Y.responses}static isInstance(Y){return D.hasMarker(Y,E7)}},w7="AI_NoTranslationGeneratedError",A7=`vercel.ai.error.${w7}`,tV=Symbol.for(A7),C2,I2,zq=class extends(I2=D,C2=tV,I2){constructor(Y){super({name:w7,message:"No translation generated."});this[C2]=!0,this.response=Y.response}static isInstance(Y){return D.hasMarker(Y,A7)}},eX="AI_NoVideoGeneratedError",T7=`vercel.ai.error.${eX}`,eV=Symbol.for(T7),_2,S2,Lq=class extends(S2=D,_2=eV,S2){constructor({message:Y="No video generated.",cause:X,responses:J}){super({name:eX,message:Y,cause:X});this[_2]=!0,this.responses=J}static isInstance(Y){return D.hasMarker(Y,T7)}static isNoVideoGeneratedError(Y){return Y instanceof Error&&Y.name===eX&&typeof Y.responses<"u"?!0:!1}toJSON(){return{name:this.name,message:this.message,stack:this.stack,cause:this.cause,responses:this.responses}}},R7="AI_NoSuchToolError",C7=`vercel.ai.error.${R7}`,YZ=Symbol.for(C7),k2,x2,Nq=class extends(x2=D,k2=YZ,x2){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:R7,message:J});this[k2]=!0,this.toolName=Y,this.availableTools=X}static isInstance(Y){return D.hasMarker(Y,C7)}},I7="AI_StreamProviderError",_7=`vercel.ai.error.${I7}`,XZ=Symbol.for(_7),b2,v2,Zq=class extends(v2=D,b2=XZ,v2){constructor({message:Y,type:X,code:J,statusCode:Q,isRetryable:$=JZ(Q),data:G,cause:W}){super({name:I7,message:Y,cause:W});this[b2]=!0,this.type=X,this.code=J,this.statusCode=Q,this.isRetryable=$,this.data=G}static isInstance(Y){return D.hasMarker(Y,_7)}};function JZ(Y){return Y!=null&&(Y===408||Y===409||Y===429||Y>=500)}var S7="AI_ToolCallRepairError",k7=`vercel.ai.error.${S7}`,QZ=Symbol.for(k7),h2,g2,Bq=class extends(g2=D,h2=QZ,g2){constructor({cause:Y,originalError:X,message:J=`Error repairing tool call: ${I1(Y)}`}){super({name:S7,message:J,cause:Y});this[h2]=!0,this.originalError=X}static isInstance(Y){return D.hasMarker(Y,k7)}},x7="AI_ToolChoiceViolationError",b7=`vercel.ai.error.${x7}`,$Z=Symbol.for(b7),y2,f2,Oq=class extends(f2=D,y2=$Z,f2){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:x7,message:G});this[y2]=!0,this.toolChoice=Y,this.finishReason=X,this.provider=J,this.modelId=Q,this.content=$}static isInstance(Y){return D.hasMarker(Y,b7)}};var v7="AI_UIMessageStreamError",h7=`vercel.ai.error.${v7}`,GZ=Symbol.for(h7),m2,c2,qq=class extends(c2=D,m2=GZ,c2){constructor({chunkType:Y,chunkId:X,message:J}){super({name:v7,message:J});this[m2]=!0,this.chunkType=Y,this.chunkId=X}static isInstance(Y){return D.hasMarker(Y,h7)}},g7="AI_InvalidDataContentError",y7=`vercel.ai.error.${g7}`,WZ=Symbol.for(y7),u2,p2,Pq=class extends(p2=D,u2=WZ,p2){constructor({content:Y,cause:X,message:J=`Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof Y}.`}){super({name:g7,message:J,cause:X});this[u2]=!0,this.content=Y}static isInstance(Y){return D.hasMarker(Y,y7)}},f7="AI_InvalidMessageRoleError",m7=`vercel.ai.error.${f7}`,zZ=Symbol.for(m7),l2,d2,Eq=class extends(d2=D,l2=zZ,d2){constructor({role:Y,message:X=`Invalid message role: '${Y}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:f7,message:X});this[l2]=!0,this.role=Y}static isInstance(Y){return D.hasMarker(Y,m7)}},c7="AI_MessageConversionError",u7=`vercel.ai.error.${c7}`,UZ=Symbol.for(u7),i2,n2,Aq=class extends(n2=D,i2=UZ,n2){constructor({originalMessage:Y,message:X}){super({name:c7,message:X});this[i2]=!0,this.originalMessage=Y}static isInstance(Y){return D.hasMarker(Y,u7)}},p7="AI_RetryError",l7=`vercel.ai.error.${p7}`,LZ=Symbol.for(l7),o2,r2,Rq=class extends(r2=D,o2=LZ,r2){constructor({message:Y,reason:X,errors:J}){super({name:p7,message:Y});this[o2]=!0,this.reason=X,this.errors=J,this.lastError=J[J.length-1]}static isInstance(Y){return D.hasMarker(Y,l7)}};var HZ="7.0.102",NZ=async({url:Y,maxBytes:X,abortSignal:J})=>{var Q;let $=Y.toString();try{let G=o1({},`ai-sdk/${HZ}`,pW()),W=await rW({url:$,headers:G,abortSignal:J});if(!W.ok)throw await z9(W),new q0({url:$,statusCode:W.status,statusText:W.statusText});return{data:await sW({response:W,url:$,maxBytes:X!=null?X:rX}),mediaType:(Q=W.headers.get("content-type"))!=null?Q:void 0}}catch(G){if(q0.isInstance(G))throw G;throw new q0({url:$,cause:G})}};var z={array:yX,boolean:DW,custom:kW,discriminatedUnion:TW,enum:mX,instanceof:xW,lazy:SW,literal:CW,looseObject:wW,never:gX,null:PW,number:qW,object:EW,record:RW,string:OW,union:fX,unknown:KY},x1=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),x1.optional()),z.array(x1)])),C=z.record(z.string(),z.record(z.string(),x1.optional())),OY=z.union([z.string(),z.instanceof(Uint8Array),z.instanceof(ArrayBuffer),z.custom(aW,{message:"Must be a Buffer"})]),YJ=z.record(z.string(),z.string()),d7=z.object({type:z.literal("text"),text:z.string(),providerOptions:C.optional()}),VZ=z.object({type:z.literal("image"),image:z.union([OY,z.instanceof(URL),YJ]),mediaType:z.string().optional(),providerOptions:C.optional()}),i7=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:OY}),z.object({type:z.literal("url"),url:z.instanceof(URL)}),z.object({type:z.literal("reference"),reference:YJ}),z.object({type:z.literal("text"),text:z.string()})]),ZZ=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:OY}),z.object({type:z.literal("url"),url:z.instanceof(URL)})]),n7=z.object({type:z.literal("file"),data:z.union([i7,OY,z.instanceof(URL),YJ]),filename:z.string().optional(),mediaType:z.string(),providerOptions:C.optional()}),KZ=z.object({type:z.literal("reasoning"),text:z.string(),providerOptions:C.optional()}),BZ=z.object({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerOptions:C.optional()}),FZ=z.object({type:z.literal("reasoning-file"),data:z.union([ZZ,OY,z.instanceof(URL)]),mediaType:z.string(),providerOptions:C.optional()}),OZ=z.object({type:z.literal("tool-call"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerOptions:C.optional(),providerExecuted:z.boolean().optional()}),jZ=z.discriminatedUnion("type",[z.object({type:z.literal("text"),value:z.string(),providerOptions:C.optional()}),z.object({type:z.literal("json"),value:x1,providerOptions:C.optional()}),z.object({type:z.literal("execution-denied"),reason:z.string().optional(),providerOptions:C.optional()}),z.object({type:z.literal("error-text"),value:z.string(),providerOptions:C.optional()}),z.object({type:z.literal("error-json"),value:x1,providerOptions:C.optional()}),z.object({type:z.literal("content"),value:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),providerOptions:C.optional()}),z.object({type:z.literal("file"),data:i7,mediaType:z.string(),filename:z.string().optional(),providerOptions:C.optional()}),z.object({type:z.literal("file-data"),data:z.string(),mediaType:z.string(),filename:z.string().optional(),providerOptions:C.optional()}),z.object({type:z.literal("file-url"),url:z.string(),mediaType:z.string().optional(),providerOptions:C.optional()}),z.object({type:z.literal("file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:C.optional()}),z.object({type:z.literal("file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:C.optional()}),z.object({type:z.literal("image-data"),data:z.string(),mediaType:z.string(),providerOptions:C.optional()}),z.object({type:z.literal("image-url"),url:z.string(),providerOptions:C.optional()}),z.object({type:z.literal("image-file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:C.optional()}),z.object({type:z.literal("image-file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:C.optional()}),z.object({type:z.literal("custom"),providerOptions:C.optional()})]))})]),o7=z.object({type:z.literal("tool-result"),toolCallId:z.string(),toolName:z.string(),output:jZ,providerOptions:C.optional()}),qZ=z.object({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string(),reason:z.string().optional()}),DZ=z.object({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional()}),PZ=z.object({role:z.literal("system"),content:z.string(),providerOptions:C.optional()}),MZ=z.object({role:z.literal("user"),content:z.union([z.string(),z.array(z.union([d7,VZ,n7]))]),providerOptions:C.optional()}),EZ=z.object({role:z.literal("assistant"),content:z.union([z.string(),z.array(z.union([d7,BZ,n7,KZ,FZ,OZ,o7,qZ]))]),providerOptions:C.optional()}),wZ=z.object({role:z.literal("tool"),content:z.array(z.union([o7,DZ])),providerOptions:C.optional()}),Sq=z.union([PZ,MZ,EZ,wZ]);var AZ={};fV(AZ,{array:()=>IZ,choice:()=>_Z,json:()=>SZ,object:()=>CZ,text:()=>RZ});function TZ(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 N9(Y){if(Y===void 0)return{value:void 0,state:"undefined-input"};let X=await j1({text:Y});if(X.success)return{value:X.value,state:"successful-parse"};if(X=await j1({text:TZ(Y)}),X.success)return{value:X.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var RZ=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:Y}){return Y},async parsePartialOutput({text:Y}){return{partial:Y}},createElementStreamTransform(){return}}),CZ=({schema:Y,name:X,description:J})=>{let Q=H9(Y);return{name:"object",responseFormat:aX(Q.jsonSchema).then(($)=>({type:"json",schema:$,...X!=null&&{name:X},...J!=null&&{description:J}})),async parseCompleteOutput({text:$},G){let W=await j1({text:$});if(!W.success)throw new z1({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 r1({value:W.value,schema:Q});if(!U.success)throw new z1({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 N9($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:G.value}}},createElementStreamTransform(){return}}},IZ=({element:Y,minItems:X,maxItems:J,name:Q,description:$})=>{if(s2({name:"minItems",value:X}),s2({name:"maxItems",value:J}),X!=null&&J!=null&&X>J)throw new tX({parameter:"minItems",value:X,message:"minItems must be less than or equal to maxItems"});let G=H9(Y);return{name:"array",responseFormat:aX(G.jsonSchema).then((W)=>{let{$schema:U,definitions:H,$defs:L,...V}=W;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",...H!=null&&{definitions:H},...L!=null&&{$defs:L},type:"object",properties:{elements:{type:"array",items:V,...X!=null&&{minItems:X},...J!=null&&{maxItems:J}}},required:["elements"],additionalProperties:!1},...Q!=null&&{name:Q},...$!=null&&{description:$}}}),async parseCompleteOutput({text:W},U){let H=await j1({text:W});if(!H.success)throw new z1({message:"No object generated: could not parse the response.",cause:H.error,text:W,response:U.response,usage:U.usage,finishReason:U.finishReason});let L=H.value;if(L==null||typeof L!=="object"||!("elements"in L)||!Array.isArray(L.elements))throw new z1({message:"No object generated: response did not match schema.",cause:new k0({value:L,cause:"response must be an object with an elements array"}),text:W,response:U.response,usage:U.usage,finishReason:U.finishReason});let V=a2({value:L.elements,minItems:X,maxItems:J});if(V!=null)throw new z1({message:"No object generated: response did not match schema.",cause:V,text:W,response:U.response,usage:U.usage,finishReason:U.finishReason});let B=[];for(let K of L.elements){let N=await r1({value:K,schema:G});if(!N.success)throw new z1({message:"No object generated: response did not match schema.",cause:N.error,text:W,response:U.response,usage:U.usage,finishReason:U.finishReason});B.push(N.value)}return B},async parsePartialOutput({text:W}){let U=await N9(W);switch(U.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let H=U.value;if(H==null||typeof H!=="object"||!("elements"in H)||!Array.isArray(H.elements))return;let L=U.state==="repaired-parse"&&H.elements.length>0?H.elements.slice(0,-1):H.elements,V=[];for(let B of L){let K=await r1({value:B,schema:G});if(K.success)V.push(K.value)}return{partial:V}}}},createElementStreamTransform(){let W=0;return new TransformStream({transform({partialOutput:U},H){if(U!=null)for(;W<U.length;W++){if(J!=null&&W>=J){H.error(a2({value:U,maxItems:J}));return}H.enqueue(U[W])}}})}}};function s2({name:Y,value:X}){if(X==null)return;if(!Number.isInteger(X))throw new tX({parameter:Y,value:X,message:`${Y} must be an integer`});if(X<0)throw new tX({parameter:Y,value:X,message:`${Y} must be greater than or equal to 0`})}function a2({value:Y,minItems:X,maxItems:J}){if(X!=null&&Y.length<X)return new k0({value:Y,cause:`elements array must contain at least ${X} items`});if(J!=null&&Y.length>J)return new k0({value:Y,cause:`elements array must contain at most ${J} items`});return}var _Z=({options:Y,name:X,description:J})=>{return{name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:Y}},required:["result"],additionalProperties:!1},...X!=null&&{name:X},...J!=null&&{description:J}}),async parseCompleteOutput({text:Q},$){let G=await j1({text:Q});if(!G.success)throw new z1({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 z1({message:"No object generated: response did not match schema.",cause:new k0({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 N9(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}}},SZ=({name:Y,description:X}={})=>{return{name:"json",responseFormat:Promise.resolve({type:"json",...Y!=null&&{name:Y},...X!=null&&{description:X}}),async parseCompleteOutput({text:J},Q){let $=await j1({text:J});if(!$.success)throw new z1({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 N9(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 vq=G0({prefix:"aitxt",size:24}),hq=G0({prefix:"call",size:24});var yq=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 L=U[1];if(Y===U[0]){G(U);continue}if(J.external){let N=J.external.registry.get(U[0])?.id;if(Y!==U[0]&&N){G(U);continue}}if(this.metadataRegistry.get(U[0])?.id){G(U);continue}if(L.cycle){G(U);continue}if(L.count>1){if(J.reused==="ref"){G(U);continue}}}let W=(U,L)=>{let F=this.seen.get(U),N=F.def??F.schema,V={...N};if(F.ref===null)return;let j=F.ref;if(F.ref=null,j){W(j,L);let R=this.seen.get(j).schema;if(R.$ref&&(L.target==="draft-7"||L.target==="draft-4"||L.target==="openapi-3.0"))N.allOf=N.allOf??[],N.allOf.push(R);else Object.assign(N,R),Object.assign(N,V)}if(!F.isParent)this.override({zodSchema:U,jsonSchema:N,path:F.path??[]})};for(let U of[...this.seen.entries()].reverse())W(U[0],{target:this.target});let K={};if(this.target==="draft-2020-12")K.$schema="https://json-schema.org/draft/2020-12/schema";else if(this.target==="draft-7")K.$schema="http://json-schema.org/draft-07/schema#";else if(this.target==="draft-4")K.$schema="http://json-schema.org/draft-04/schema#";else if(this.target==="openapi-3.0");else console.warn(`Invalid target: ${this.target}`);if(J.external?.uri){let U=J.external.registry.get(Y)?.id;if(!U)throw Error("Schema is missing an `id` property");K.$id=J.external.uri(U)}Object.assign(K,Q.def);let Z=J.external?.defs??{};for(let U of this.seen.entries()){let L=U[1];if(L.def&&L.defId)Z[L.defId]=L.def}if(J.external);else if(Object.keys(Z).length>0)if(this.target==="draft-2020-12")K.$defs=Z;else K.definitions=Z;try{return JSON.parse(JSON.stringify(K))}catch(U){throw Error("Error converting schema to JSON.")}}}function S7(Y,X){if(Y instanceof lY){let Q=new M8(X),$={};for(let K of Y._idmap.entries()){let[Z,U]=K;Q.process(U)}let G={},W={registry:Y,uri:X?.uri,defs:$};for(let K of Y._idmap.entries()){let[Z,U]=K;G[Z]=Q.emit(U,{...X,external:W})}if(Object.keys($).length>0){let K=Q.target==="draft-2020-12"?"$defs":"definitions";G.__shared={[K]:$}}return{schemas:G}}let J=new M8(X);return J.process(Y),J.emit(Y,X)}function D0(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 D0($.element,J);case"object":{for(let G in $.shape)if(D0($.shape[G],J))return!0;return!1}case"union":{for(let G of $.options)if(D0(G,J))return!0;return!1}case"intersection":return D0($.left,J)||D0($.right,J);case"tuple":{for(let G of $.items)if(D0(G,J))return!0;if($.rest&&D0($.rest,J))return!0;return!1}case"record":return D0($.keyType,J)||D0($.valueType,J);case"map":return D0($.keyType,J)||D0($.valueType,J);case"set":return D0($.valueType,J);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return D0($.innerType,J);case"lazy":return D0($.getter(),J);case"default":return D0($.innerType,J);case"prefault":return D0($.innerType,J);case"custom":return!1;case"transform":return!0;case"pipe":return D0($.in,J)||D0($.out,J);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${$.type}`)}var NH=P("ZodISODateTime",(Y,X)=>{L2.init(Y,X),L0.init(Y,X)});function k7(Y){return F7(NH,Y)}var BH=P("ZodISODate",(Y,X)=>{H2.init(Y,X),L0.init(Y,X)});function x7(Y){return O7(BH,Y)}var qH=P("ZodISOTime",(Y,X)=>{V2.init(Y,X),L0.init(Y,X)});function b7(Y){return j7(qH,Y)}var FH=P("ZodISODuration",(Y,X)=>{N2.init(Y,X),L0.init(Y,X)});function v7(Y){return D7(FH,Y)}var h7=(Y,X)=>{gY.init(Y,X),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(J)=>d$(Y,J)},flatten:{value:(J)=>l$(Y,J)},addIssue:{value:(J)=>{Y.issues.push(J),Y.message=JSON.stringify(Y.issues,z9,2)}},addIssues:{value:(J)=>{Y.issues.push(...J),Y.message=JSON.stringify(Y.issues,z9,2)}},isEmpty:{get(){return Y.issues.length===0}}})},qj=P("ZodError",h7),d0=P("ZodError",h7,{Parent:Error});var g7=yY(d0),y7=fY(d0),f7=u9(d0),aY=c9(d0),m7=n$(d0),u7=r$(d0),c7=s$(d0),p7=a$(d0),l7=t$(d0),d7=e$(d0),i7=YG(d0),o7=XG(d0);var H0=P("ZodType",(Y,X)=>{return K0.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)=>a0(Y,J,Q),Y.brand=()=>Y,Y.register=(J,Q)=>{return J.add(Y,Q),Y},Y.parse=(J,Q)=>g7(Y,J,Q,{callee:Y.parse}),Y.safeParse=(J,Q)=>f7(Y,J,Q),Y.parseAsync=async(J,Q)=>y7(Y,J,Q,{callee:Y.parseAsync}),Y.safeParseAsync=async(J,Q)=>aY(Y,J,Q),Y.spa=Y.safeParseAsync,Y.encode=(J,Q)=>m7(Y,J,Q),Y.decode=(J,Q)=>u7(Y,J,Q),Y.encodeAsync=async(J,Q)=>c7(Y,J,Q),Y.decodeAsync=async(J,Q)=>p7(Y,J,Q),Y.safeEncode=(J,Q)=>l7(Y,J,Q),Y.safeDecode=(J,Q)=>d7(Y,J,Q),Y.safeEncodeAsync=async(J,Q)=>i7(Y,J,Q),Y.safeDecodeAsync=async(J,Q)=>o7(Y,J,Q),Y.refine=(J,Q)=>Y.check(ZV(J,Q)),Y.superRefine=(J)=>Y.check(LV(J)),Y.overwrite=(J)=>Y.check(i1(J)),Y.optional=()=>s7(Y),Y.nullable=()=>a7(Y),Y.nullish=()=>s7(a7(Y)),Y.nonoptional=(J)=>QV(Y,J),Y.array=()=>T8(Y),Y.or=(J)=>R8([Y,J]),Y.and=(J)=>oH(Y,J),Y.transform=(J)=>t7(Y,aH(J)),Y.default=(J)=>YV(Y,J),Y.prefault=(J)=>JV(Y,J),Y.catch=(J)=>GV(Y,J),Y.pipe=(J)=>t7(Y,J),Y.readonly=()=>KV(Y),Y.describe=(J)=>{let Q=Y.clone();return d1.add(Q,{description:J}),Q},Object.defineProperty(Y,"description",{get(){return d1.get(Y)?.description},configurable:!0}),Y.meta=(...J)=>{if(J.length===0)return d1.get(Y);let Q=Y.clone();return d1.add(Q,J[0]),Q},Y.isOptional=()=>Y.safeParse(void 0).success,Y.isNullable=()=>Y.safeParse(null).success,Y}),e7=P("_ZodString",(Y,X)=>{pY.init(Y,X),H0.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(V8(...Q)),Y.includes=(...Q)=>Y.check(q8(...Q)),Y.startsWith=(...Q)=>Y.check(F8(...Q)),Y.endsWith=(...Q)=>Y.check(O8(...Q)),Y.min=(...Q)=>Y.check(Z9(...Q)),Y.max=(...Q)=>Y.check(nY(...Q)),Y.length=(...Q)=>Y.check(rY(...Q)),Y.nonempty=(...Q)=>Y.check(Z9(1,...Q)),Y.lowercase=(Q)=>Y.check(N8(Q)),Y.uppercase=(Q)=>Y.check(B8(Q)),Y.trim=()=>Y.check(D8()),Y.normalize=(...Q)=>Y.check(j8(...Q)),Y.toLowerCase=()=>Y.check(P8()),Y.toUpperCase=()=>Y.check(E8())}),PH=P("ZodString",(Y,X)=>{pY.init(Y,X),e7.init(Y,X),Y.email=(J)=>Y.check(s2(EH,J)),Y.url=(J)=>Y.check(X7(MH,J)),Y.jwt=(J)=>Y.check(q7(yH,J)),Y.emoji=(J)=>Y.check(J7(wH,J)),Y.guid=(J)=>Y.check(H8(n7,J)),Y.uuid=(J)=>Y.check(a2(tY,J)),Y.uuidv4=(J)=>Y.check(t2(tY,J)),Y.uuidv6=(J)=>Y.check(e2(tY,J)),Y.uuidv7=(J)=>Y.check(Y7(tY,J)),Y.nanoid=(J)=>Y.check(Q7(AH,J)),Y.guid=(J)=>Y.check(H8(n7,J)),Y.cuid=(J)=>Y.check($7(TH,J)),Y.cuid2=(J)=>Y.check(G7(RH,J)),Y.ulid=(J)=>Y.check(W7(CH,J)),Y.base64=(J)=>Y.check(V7(vH,J)),Y.base64url=(J)=>Y.check(N7(hH,J)),Y.xid=(J)=>Y.check(z7(IH,J)),Y.ksuid=(J)=>Y.check(K7(_H,J)),Y.ipv4=(J)=>Y.check(U7(SH,J)),Y.ipv6=(J)=>Y.check(Z7(kH,J)),Y.cidrv4=(J)=>Y.check(L7(xH,J)),Y.cidrv6=(J)=>Y.check(H7(bH,J)),Y.e164=(J)=>Y.check(B7(gH,J)),Y.datetime=(J)=>Y.check(k7(J)),Y.date=(J)=>Y.check(x7(J)),Y.time=(J)=>Y.check(b7(J)),Y.duration=(J)=>Y.check(v7(J))});function Y4(Y){return r2(PH,Y)}var L0=P("ZodStringFormat",(Y,X)=>{Z0.init(Y,X),e7.init(Y,X)}),EH=P("ZodEmail",(Y,X)=>{J2.init(Y,X),L0.init(Y,X)});var n7=P("ZodGUID",(Y,X)=>{Y2.init(Y,X),L0.init(Y,X)});var tY=P("ZodUUID",(Y,X)=>{X2.init(Y,X),L0.init(Y,X)});var MH=P("ZodURL",(Y,X)=>{Q2.init(Y,X),L0.init(Y,X)});var wH=P("ZodEmoji",(Y,X)=>{$2.init(Y,X),L0.init(Y,X)});var AH=P("ZodNanoID",(Y,X)=>{G2.init(Y,X),L0.init(Y,X)});var TH=P("ZodCUID",(Y,X)=>{W2.init(Y,X),L0.init(Y,X)});var RH=P("ZodCUID2",(Y,X)=>{z2.init(Y,X),L0.init(Y,X)});var CH=P("ZodULID",(Y,X)=>{K2.init(Y,X),L0.init(Y,X)});var IH=P("ZodXID",(Y,X)=>{U2.init(Y,X),L0.init(Y,X)});var _H=P("ZodKSUID",(Y,X)=>{Z2.init(Y,X),L0.init(Y,X)});var SH=P("ZodIPv4",(Y,X)=>{B2.init(Y,X),L0.init(Y,X)});var kH=P("ZodIPv6",(Y,X)=>{q2.init(Y,X),L0.init(Y,X)});var xH=P("ZodCIDRv4",(Y,X)=>{F2.init(Y,X),L0.init(Y,X)});var bH=P("ZodCIDRv6",(Y,X)=>{O2.init(Y,X),L0.init(Y,X)});var vH=P("ZodBase64",(Y,X)=>{D2.init(Y,X),L0.init(Y,X)});var hH=P("ZodBase64URL",(Y,X)=>{P2.init(Y,X),L0.init(Y,X)});var gH=P("ZodE164",(Y,X)=>{E2.init(Y,X),L0.init(Y,X)});var yH=P("ZodJWT",(Y,X)=>{M2.init(Y,X),L0.init(Y,X)});var X4=P("ZodNumber",(Y,X)=>{Z8.init(Y,X),H0.init(Y,X),Y.gt=(Q,$)=>Y.check(iY(Q,$)),Y.gte=(Q,$)=>Y.check(d9(Q,$)),Y.min=(Q,$)=>Y.check(d9(Q,$)),Y.lt=(Q,$)=>Y.check(dY(Q,$)),Y.lte=(Q,$)=>Y.check(l9(Q,$)),Y.max=(Q,$)=>Y.check(l9(Q,$)),Y.int=(Q)=>Y.check(r7(Q)),Y.safe=(Q)=>Y.check(r7(Q)),Y.positive=(Q)=>Y.check(iY(0,Q)),Y.nonnegative=(Q)=>Y.check(d9(0,Q)),Y.negative=(Q)=>Y.check(dY(0,Q)),Y.nonpositive=(Q)=>Y.check(l9(0,Q)),Y.multipleOf=(Q,$)=>Y.check(oY(Q,$)),Y.step=(Q,$)=>Y.check(oY(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 J4(Y){return P7(X4,Y)}var fH=P("ZodNumberFormat",(Y,X)=>{w2.init(Y,X),X4.init(Y,X)});function r7(Y){return E7(fH,Y)}var mH=P("ZodBoolean",(Y,X)=>{A2.init(Y,X),H0.init(Y,X)});function Q4(Y){return M7(mH,Y)}var uH=P("ZodNull",(Y,X)=>{T2.init(Y,X),H0.init(Y,X)});function $4(Y){return w7(uH,Y)}var cH=P("ZodUnknown",(Y,X)=>{R2.init(Y,X),H0.init(Y,X)});function i9(){return A7(cH)}var pH=P("ZodNever",(Y,X)=>{C2.init(Y,X),H0.init(Y,X)});function A8(Y){return T7(pH,Y)}var lH=P("ZodArray",(Y,X)=>{I2.init(Y,X),H0.init(Y,X),Y.element=X.element,Y.min=(J,Q)=>Y.check(Z9(J,Q)),Y.nonempty=(J)=>Y.check(Z9(1,J)),Y.max=(J,Q)=>Y.check(nY(J,Q)),Y.length=(J,Q)=>Y.check(rY(J,Q)),Y.unwrap=()=>Y.element});function T8(Y,X){return R7(lH,Y,X)}var G4=P("ZodObject",(Y,X)=>{k2.init(Y,X),H0.init(Y,X),a.defineLazy(Y,"shape",()=>X.shape),Y.keyof=()=>C8(Object.keys(Y._zod.def.shape)),Y.catchall=(J)=>Y.clone({...Y._zod.def,catchall:J}),Y.passthrough=()=>Y.clone({...Y._zod.def,catchall:i9()}),Y.loose=()=>Y.clone({...Y._zod.def,catchall:i9()}),Y.strict=()=>Y.clone({...Y._zod.def,catchall:A8()}),Y.strip=()=>Y.clone({...Y._zod.def,catchall:void 0}),Y.extend=(J)=>{return a.extend(Y,J)},Y.safeExtend=(J)=>{return a.safeExtend(Y,J)},Y.merge=(J)=>a.merge(Y,J),Y.pick=(J)=>a.pick(Y,J),Y.omit=(J)=>a.omit(Y,J),Y.partial=(...J)=>a.partial(H4,Y,J[0]),Y.required=(...J)=>a.required(V4,Y,J[0])});function W4(Y,X){let J={type:"object",get shape(){return a.assignProp(this,"shape",Y?a.objectClone(Y):{}),this.shape},...a.normalizeParams(X)};return new G4(J)}function z4(Y,X){return new G4({type:"object",get shape(){return a.assignProp(this,"shape",a.objectClone(Y)),this.shape},catchall:i9(),...a.normalizeParams(X)})}var K4=P("ZodUnion",(Y,X)=>{L8.init(Y,X),H0.init(Y,X),Y.options=X.options});function R8(Y,X){return new K4({type:"union",options:Y,...a.normalizeParams(X)})}var dH=P("ZodDiscriminatedUnion",(Y,X)=>{K4.init(Y,X),x2.init(Y,X)});function U4(Y,X,J){return new dH({type:"union",options:X,discriminator:Y,...a.normalizeParams(J)})}var iH=P("ZodIntersection",(Y,X)=>{b2.init(Y,X),H0.init(Y,X)});function oH(Y,X){return new iH({type:"intersection",left:Y,right:X})}var nH=P("ZodRecord",(Y,X)=>{v2.init(Y,X),H0.init(Y,X),Y.keyType=X.keyType,Y.valueType=X.valueType});function Z4(Y,X,J){return new nH({type:"record",keyType:Y,valueType:X,...a.normalizeParams(J)})}var w8=P("ZodEnum",(Y,X)=>{h2.init(Y,X),H0.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 w8({...X,checks:[],...a.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 w8({...X,checks:[],...a.normalizeParams($),entries:G})}});function C8(Y,X){let J=Array.isArray(Y)?Object.fromEntries(Y.map((Q)=>[Q,Q])):Y;return new w8({type:"enum",entries:J,...a.normalizeParams(X)})}var rH=P("ZodLiteral",(Y,X)=>{g2.init(Y,X),H0.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 L4(Y,X){return new rH({type:"literal",values:Array.isArray(Y)?Y:[Y],...a.normalizeParams(X)})}var sH=P("ZodTransform",(Y,X)=>{y2.init(Y,X),H0.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new v9(Y.constructor.name);J.addIssue=(G)=>{if(typeof G==="string")J.issues.push(a.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(a.issue(W))}};let $=X.transform(J.value,J);if($ instanceof Promise)return $.then((G)=>{return J.value=G,J});return J.value=$,J}});function aH(Y){return new sH({type:"transform",transform:Y})}var H4=P("ZodOptional",(Y,X)=>{f2.init(Y,X),H0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function s7(Y){return new H4({type:"optional",innerType:Y})}var tH=P("ZodNullable",(Y,X)=>{m2.init(Y,X),H0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function a7(Y){return new tH({type:"nullable",innerType:Y})}var eH=P("ZodDefault",(Y,X)=>{u2.init(Y,X),H0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function YV(Y,X){return new eH({type:"default",innerType:Y,get defaultValue(){return typeof X==="function"?X():a.shallowClone(X)}})}var XV=P("ZodPrefault",(Y,X)=>{c2.init(Y,X),H0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function JV(Y,X){return new XV({type:"prefault",innerType:Y,get defaultValue(){return typeof X==="function"?X():a.shallowClone(X)}})}var V4=P("ZodNonOptional",(Y,X)=>{p2.init(Y,X),H0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function QV(Y,X){return new V4({type:"nonoptional",innerType:Y,...a.normalizeParams(X)})}var $V=P("ZodCatch",(Y,X)=>{l2.init(Y,X),H0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function GV(Y,X){return new $V({type:"catch",innerType:Y,catchValue:typeof X==="function"?X:()=>X})}var WV=P("ZodPipe",(Y,X)=>{d2.init(Y,X),H0.init(Y,X),Y.in=X.in,Y.out=X.out});function t7(Y,X){return new WV({type:"pipe",in:Y,out:X})}var zV=P("ZodReadonly",(Y,X)=>{i2.init(Y,X),H0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function KV(Y){return new zV({type:"readonly",innerType:Y})}var UV=P("ZodLazy",(Y,X)=>{o2.init(Y,X),H0.init(Y,X),Y.unwrap=()=>Y._zod.def.getter()});function N4(Y){return new UV({type:"lazy",getter:Y})}var I8=P("ZodCustom",(Y,X)=>{n2.init(Y,X),H0.init(Y,X)});function B4(Y,X){return C7(I8,Y??(()=>!0),X)}function ZV(Y,X={}){return I7(I8,Y,X)}function LV(Y){return _7(Y)}function q4(Y,X={error:`Input not instance of ${Y.name}`}){let J=new I8({type:"custom",check:"custom",fn:(Q)=>Q instanceof Y,abort:!0,...a.normalizeParams(X)});return J._zod.bag.Class=Y,J}function T4(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 HV(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 L9(Y,...X){let J=new Headers(HV(Y)),Q=J.get("user-agent")||"";return J.set("user-agent",[Q,...X].filter(Boolean).join(" ")),Object.fromEntries(J.entries())}var VV=[{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]}],QD=[...VV,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];var NV=12,BV=131072,$D=BV+NV;async function eY(Y){var X;try{await((X=Y.body)==null?void 0:X.cancel())}catch(J){}}var R4="AI_DownloadError",C4=`vercel.ai.error.${R4}`,qV=Symbol.for(C4),F4,O4,b0=class extends(O4=T,F4=qV,O4){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:R4,message:$,cause:Q});this[F4]=!0,this.url=Y,this.statusCode=X,this.statusText=J}static isInstance(Y){return T.hasMarker(Y,C4)}};function FV(Y=globalThis){return Y.window!=null}function j4(Y,X){try{return new URL(Y).origin===new URL(X).origin}catch(J){return!1}}function OV(Y){let X;try{X=new URL(Y)}catch(Q){throw new b0({url:Y,message:`Invalid URL: ${Y}`})}if(X.protocol==="data:")return;if(X.protocol!=="http:"&&X.protocol!=="https:")throw new b0({url:Y,message:`URL scheme must be http, https, or data, got ${X.protocol}`});let J=X.hostname.toLowerCase().replace(/\.+$/,"");if(!J)throw new b0({url:Y,message:"URL must have a hostname"});if(J==="localhost"||J.endsWith(".local")||J.endsWith(".localhost"))throw new b0({url:Y,message:`URL with hostname ${J} is not allowed`});if(J.startsWith("[")&&J.endsWith("]")){let Q=J.slice(1,-1);if(I4(Q))throw new b0({url:Y,message:`URL with IPv6 address ${J} is not allowed`});return}if(v8(J)){if(h8(J))throw new b0({url:Y,message:`URL with IP address ${J} is not allowed`});return}}function jV({address:Y,family:X,hostname:J}){if(X===4?!v8(Y)||h8(Y):X===6?I4(Y):!0)throw new b0({url:J,message:`Hostname ${J} resolved to disallowed IP address ${Y}`})}function v8(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 h8(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 DV(Y){let X=Y.toLowerCase(),J=X.indexOf("%");if(J!==-1)X=X.slice(0,J);let Q=X.split("::");if(Q.length>2)return null;let $=(W)=>{if(W==="")return[];let K=[],Z=W.split(":");for(let U=0;U<Z.length;U++){let L=Z[U];if(L.includes(".")){if(U!==Z.length-1||!v8(L))return null;let[F,N,V,j]=L.split(".").map(Number);K.push(F<<8|N,V<<8|j);continue}if(!/^[0-9a-f]{1,4}$/.test(L))return null;K.push(parseInt(L,16))}return K},G=$(Q[0]);if(G===null)return null;if(Q.length===2){let W=$(Q[1]);if(W===null)return null;let K=8-G.length-W.length;if(K<0)return null;return[...G,...Array(K).fill(0),...W]}return G.length===8?G:null}function I4(Y){let X=DV(Y);if(X===null)return!0;let J=($)=>X.slice(0,$).every((G)=>G===0);if(J(7)&&(X[7]===0||X[7]===1))return!0;if((X[0]&65024)===64512)return!0;if((X[0]&65472)===65152)return!0;if((X[0]&65472)===65216)return!0;if((X[0]&65280)===65280)return!0;if(X[0]===8193&&X[1]===3512)return!0;if(X[0]===16383&&(X[1]&61440)===0)return!0;if(J(6)||J(5)&&X[5]===65535||J(4)&&X[4]===65535&&X[5]===0||X[0]===100&&X[1]===65435&&X[2]===0&&X[3]===0&&X[4]===0&&X[5]===0||X[0]===100&&X[1]===65435&&X[2]===1){let $=X[6]>>8&255,G=X[6]&255,W=X[7]>>8&255,K=X[7]&255;return h8(`${$}.${G}.${W}.${K}`)}return!1}function PV(Y){return(X,J,Q)=>{Y(X,{...J,all:!0},($,G)=>{if($){Q($);return}try{let[W]=G;if(W==null)throw Error(`Hostname ${X} did not resolve to an address`);for(let{address:K,family:Z}of G)jV({address:K,family:Z,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 _8,_4=globalThis.fetch,EV=AV(_4);function MV(){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 wV(){if(!MV()||!EV||globalThis.fetch!==_4)return globalThis.fetch;return _8!=null?_8:_8=Promise.resolve().then(TV)}function AV(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 TV(){let{createRequire:Y}=D4("node:module"),{lookup:X}=D4("node:dns"),{Agent:J,fetch:Q}=Y(S4())("undici"),$=new J({connect:{lookup:PV(X)}});return(G,W)=>Q(G,{...W,dispatcher:$})}function D4(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 S4(){let Y=Error.prepareStackTrace;try{Error.prepareStackTrace=($,G)=>G;let X=Error("Capture current module path");Error.captureStackTrace(X,S4);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 RV=["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 CV(Y){let X=new Headers(Y);for(let J of RV)X.delete(J);return X}var IV=10,_V=new Set([301,302,303,307,308]);async function SV(Y){return Y==null||Y===globalThis.fetch?await wV():Y}async function k4({url:Y,headers:X,abortSignal:J,maxRedirects:Q=IV,fetch:$,trustedOrigin:G}){var W;let K=X===void 0?void 0:CV(X),Z=(L)=>{let F={signal:J,redirect:L};if(K!==void 0)F.headers=new Headers(K);return F},U=Y;for(let L=0;L<=Q;L++){let F=G!==void 0&&j4(U,G);if(!F)OV(U);let N=F&&$!=null?$:F?globalThis.fetch:await SV($),V=await N(U,Z("manual"));if(V.type==="opaqueredirect"){if(!FV())throw new b0({url:Y,message:`Redirect from ${U} could not be validated and was blocked`});return await N(U,Z("follow"))}let j=(W=V.headers)==null?void 0:W.get("location");if(_V.has(V.status)&&j){await eY(V);let R=new URL(j,U).toString();if(K!==void 0&&!j4(R,U)){let S=K.get("user-agent");K=new Headers(S==null?void 0:{"user-agent":S})}U=R;continue}return V}throw new b0({url:Y,message:`Too many redirects (max ${Q})`})}var g8=2147483648;async function x4({response:Y,url:X,maxBytes:J=g8}){let Q=Y.headers.get("content-length");if(Q!=null){let L=parseInt(Q,10);if(!isNaN(L)&&L>J)throw await eY(Y),new b0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes (Content-Length: ${L}).`})}let $=Y.body;if($==null)return new Uint8Array(0);let G=$.getReader(),W=[],K=0;try{while(!0){let{done:L,value:F}=await G.read();if(L)break;if(K+=F.length,K>J)throw new b0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes.`});W.push(F)}}finally{try{await G.cancel()}catch(L){}finally{G.releaseLock()}}let Z=new Uint8Array(K),U=0;for(let L of W)Z.set(L,U),U+=L.length;return Z}var O0=({prefix:Y,size:X=16,alphabet:J="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:Q="-"}={})=>{let $=()=>{let G=J.length,W=Array(X);for(let K=0;K<X;K++)W[K]=J[Math.random()*G|0];return W.join("")};if(Y==null)return $;if(J.includes(Q))throw new L$({argument:"separator",message:`The separator "${Q}" must not be part of the alphabet "${J}".`});return()=>`${Y}${Q}${$()}`},zD=O0();function b4(Y){var X,J;return(J=(X=globalThis.Buffer)==null?void 0:X.isBuffer(Y))!=null?J:!1}var kV=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,xV=/"(?: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 P4(Y){let X=JSON.parse(Y);if(X===null||typeof X!=="object")return X;if(kV.test(Y)===!1&&xV.test(Y)===!1)return X;return bV(X)}function bV(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 vV(Y){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(J){return P4(Y)}try{return P4(Y)}finally{Error.stackTraceLimit=X}}function y8(Y){if(Y.type==="object"||Array.isArray(Y.type)&&Y.type.includes("object")){let{additionalProperties:J}=Y;Y.additionalProperties=J!=null&&typeof J!=="boolean"?S1(J):!1;let{properties:Q}=Y;if(Q!=null)for(let $ of Object.keys(Q))Q[$]=S1(Q[$])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(S1):S1(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(S1);if(Y.allOf!=null)Y.allOf=Y.allOf.map(S1);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(S1);let{definitions:X}=Y;if(X!=null)for(let J of Object.keys(X))X[J]=S1(X[J]);return Y}function S1(Y){if(typeof Y==="boolean")return Y;return y8(Y)}var hV=Symbol("Let zodToJsonSchema decide on which parser to use"),E4={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"},gV=(Y)=>typeof Y==="string"?{...E4,name:Y}:{...E4,...Y};function i0(){return{}}function yV(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=G0(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 fV(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 mV(){return{type:"boolean"}}function v4(Y,X){return G0(Y.type._def,X)}var uV=(Y,X)=>{return G0(Y.innerType._def,X)};function h4(Y,X,J){let Q=J!=null?J:X.dateStrategy;if(Array.isArray(Q))return{anyOf:Q.map(($)=>h4(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 cV(Y)}}var cV=(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 pV(Y,X){return{...G0(Y.innerType._def,X),default:Y.defaultValue()}}function lV(Y,X){return X.effectStrategy==="input"?G0(Y.schema._def,X):i0()}function dV(Y){return{type:"string",enum:Array.from(Y.values)}}var iV=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function oV(Y,X){let J=[G0(Y.left._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),G0(Y.right._def,{...X,currentPath:[...X.currentPath,"allOf","1"]})].filter(($)=>!!$),Q=[];return J.forEach(($)=>{if(iV($))Q.push(...$.allOf);else{let G=$;if("additionalProperties"in $&&$.additionalProperties===!1){let{additionalProperties:W,...K}=$;G=K}Q.push(G)}}),Q.length?{allOf:Q}:void 0}function nV(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 S8=void 0,e0={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(S8===void 0)S8=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return S8},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 g4(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":Y1(J,"email",Q.message,X);break;case"format:idn-email":Y1(J,"idn-email",Q.message,X);break;case"pattern:zod":x0(J,e0.email,Q.message,X);break}break;case"url":Y1(J,"uri",Q.message,X);break;case"uuid":Y1(J,"uuid",Q.message,X);break;case"regex":x0(J,Q.regex,Q.message,X);break;case"cuid":x0(J,e0.cuid,Q.message,X);break;case"cuid2":x0(J,e0.cuid2,Q.message,X);break;case"startsWith":x0(J,RegExp(`^${k8(Q.value,X)}`),Q.message,X);break;case"endsWith":x0(J,RegExp(`${k8(Q.value,X)}$`),Q.message,X);break;case"datetime":Y1(J,"date-time",Q.message,X);break;case"date":Y1(J,"date",Q.message,X);break;case"time":Y1(J,"time",Q.message,X);break;case"duration":Y1(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":{x0(J,RegExp(k8(Q.value,X)),Q.message,X);break}case"ip":{if(Q.version!=="v6")Y1(J,"ipv4",Q.message,X);if(Q.version!=="v4")Y1(J,"ipv6",Q.message,X);break}case"base64url":x0(J,e0.base64url,Q.message,X);break;case"jwt":x0(J,e0.jwt,Q.message,X);break;case"cidr":{if(Q.version!=="v6")x0(J,e0.ipv4Cidr,Q.message,X);if(Q.version!=="v4")x0(J,e0.ipv6Cidr,Q.message,X);break}case"emoji":x0(J,e0.emoji(),Q.message,X);break;case"ulid":{x0(J,e0.ulid,Q.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{Y1(J,"binary",Q.message,X);break}case"contentEncoding:base64":{J.contentEncoding="base64";break}case"pattern:zod":{x0(J,e0.base64,Q.message,X);break}}break}case"nanoid":x0(J,e0.nanoid,Q.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return J}function k8(Y,X){return X.patternStrategy==="escape"?sV(Y):Y}var rV=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function sV(Y){let X="";for(let J=0;J<Y.length;J++){if(!rV.has(Y[J]))X+="\\";X+=Y[J]}return X}function Y1(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 x0(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:M4(X,Q),...J&&Q.errorMessages&&{errorMessage:{pattern:J}}})}else Y.pattern=M4(X,Q)}function M4(Y,X){var J;if(!X.applyRegexFlags||!Y.flags)return Y.source;let Q={i:Y.flags.includes("i"),m:Y.flags.includes("m"),s:Y.flags.includes("s")},$=Q.i?Y.source.toLowerCase():Y.source,G="",W=!1,K=!1,Z=!1;for(let U=0;U<$.length;U++){if(W){G+=$[U],W=!1;continue}if(Q.i){if(K){if($[U].match(/[a-z]/)){if(Z)G+=$[U],G+=`${$[U-2]}-${$[U]}`.toUpperCase(),Z=!1;else if($[U+1]==="-"&&((J=$[U+2])==null?void 0:J.match(/[a-z]/)))G+=$[U],Z=!0;else G+=`${$[U]}${$[U].toUpperCase()}`;continue}}else if($[U].match(/[a-z]/)){G+=`[${$[U]}${$[U].toUpperCase()}]`;continue}}if(Q.m){if($[U]==="^"){G+=`(^|(?<=[\r
93
+ ]))`;continue}else if($[U]==="$"){G+=`($|(?=[\r
94
+ ]))`;continue}}if(Q.s&&$[U]==="."){G+=K?`${$[U]}\r
95
+ `:`[${$[U]}\r
96
+ ]`;continue}if(G+=$[U],$[U]==="\\")W=!0;else if(K&&$[U]==="]")K=!1;else if(!K&&$[U]==="[")K=!0}try{new RegExp(G)}catch(U){return console.warn(`Could not convert regex pattern at ${X.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Y.source}return G}function y4(Y,X){var J,Q,$,G,W,K;let Z={type:"object",additionalProperties:(J=G0(Y.valueType._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]}))!=null?J:X.allowedAdditionalProperties};if(((Q=Y.keyType)==null?void 0:Q._def.typeName)==="ZodString"&&(($=Y.keyType._def.checks)==null?void 0:$.length)){let{type:U,...L}=g4(Y.keyType._def,X);return{...Z,propertyNames:L}}else if(((G=Y.keyType)==null?void 0:G._def.typeName)==="ZodEnum")return{...Z,propertyNames:{enum:Y.keyType._def.values}};else if(((W=Y.keyType)==null?void 0:W._def.typeName)==="ZodBranded"&&Y.keyType._def.type._def.typeName==="ZodString"&&((K=Y.keyType._def.type._def.checks)==null?void 0:K.length)){let{type:U,...L}=v4(Y.keyType._def,X);return{...Z,propertyNames:L}}return Z}function aV(Y,X){if(X.mapStrategy==="record")return y4(Y,X);let J=G0(Y.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||i0(),Q=G0(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||i0();return{type:"array",maxItems:125,items:{type:"array",items:[J,Q],minItems:2,maxItems:2}}}function tV(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 eV(){return{not:i0()}}function YN(){return{type:"null"}}var x8={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function XN(Y,X){let J=Y.options instanceof Map?Array.from(Y.options.values()):Y.options;if(J.every((Q)=>(Q._def.typeName in x8)&&(!Q._def.checks||!Q._def.checks.length))){let Q=J.reduce(($,G)=>{let W=x8[G._def.typeName];return W&&!$.includes(W)?[...$,W]:$},[]);return{type:Q.length>1?Q:Q[0]}}else if(J.every((Q)=>Q._def.typeName==="ZodLiteral"&&!Q.description)){let Q=J.reduce(($,G)=>{let W=typeof G._def.value;switch(W){case"string":case"number":case"boolean":return[...$,W];case"bigint":return[...$,"integer"];case"object":if(G._def.value===null)return[...$,"null"];case"symbol":case"undefined":case"function":default:return $}},[]);if(Q.length===J.length){let $=Q.filter((G,W,K)=>K.indexOf(G)===W);return{type:$.length>1?$:$[0],enum:J.reduce((G,W)=>{return G.includes(W._def.value)?G:[...G,W._def.value]},[])}}}else if(J.every((Q)=>Q._def.typeName==="ZodEnum"))return{type:"string",enum:J.reduce((Q,$)=>[...Q,...$._def.values.filter((G)=>!Q.includes(G))],[])};return JN(Y,X)}var JN=(Y,X)=>{let J=(Y.options instanceof Map?Array.from(Y.options.values()):Y.options).map((Q,$)=>G0(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 QN(Y,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Y.innerType._def.typeName)&&(!Y.innerType._def.checks||!Y.innerType._def.checks.length))return{type:[x8[Y.innerType._def.typeName],"null"]};let J=G0(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return J&&{anyOf:[J,{type:"null"}]}}function $N(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 GN(Y,X){let J={type:"object",properties:{}},Q=[],$=Y.shape();for(let W in $){let K=$[W];if(K===void 0||K._def===void 0)continue;let Z=zN(K),U=G0(K._def,{...X,currentPath:[...X.currentPath,"properties",W],propertyPath:[...X.currentPath,"properties",W]});if(U===void 0)continue;if(J.properties[W]=U,!Z)Q.push(W)}if(Q.length)J.required=Q;let G=WN(Y,X);if(G!==void 0)J.additionalProperties=G;return J}function WN(Y,X){if(Y.catchall._def.typeName!=="ZodNever")return G0(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 zN(Y){try{return Y.isOptional()}catch(X){return!0}}var KN=(Y,X)=>{var J;if(X.currentPath.toString()===((J=X.propertyPath)==null?void 0:J.toString()))return G0(Y.innerType._def,X);let Q=G0(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return Q?{anyOf:[{not:i0()},Q]}:i0()},UN=(Y,X)=>{if(X.pipeStrategy==="input")return G0(Y.in._def,X);else if(X.pipeStrategy==="output")return G0(Y.out._def,X);let J=G0(Y.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),Q=G0(Y.out._def,{...X,currentPath:[...X.currentPath,"allOf",J?"1":"0"]});return{allOf:[J,Q].filter(($)=>$!==void 0)}};function ZN(Y,X){return G0(Y.type._def,X)}function LN(Y,X){let Q={type:"array",uniqueItems:!0,items:G0(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 HN(Y,X){if(Y.rest)return{type:"array",minItems:Y.items.length,items:Y.items.map((J,Q)=>G0(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[]),additionalItems:G0(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)=>G0(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[])}}function VN(){return{not:i0()}}function NN(){return i0()}var BN=(Y,X)=>{return G0(Y.innerType._def,X)},qN=(Y,X,J)=>{switch(X){case"ZodString":return g4(Y,J);case"ZodNumber":return $N(Y);case"ZodObject":return GN(Y,J);case"ZodBigInt":return fV(Y);case"ZodBoolean":return mV();case"ZodDate":return h4(Y,J);case"ZodUndefined":return VN();case"ZodNull":return YN();case"ZodArray":return yV(Y,J);case"ZodUnion":case"ZodDiscriminatedUnion":return XN(Y,J);case"ZodIntersection":return oV(Y,J);case"ZodTuple":return HN(Y,J);case"ZodRecord":return y4(Y,J);case"ZodLiteral":return nV(Y);case"ZodEnum":return dV(Y);case"ZodNativeEnum":return tV(Y);case"ZodNullable":return QN(Y,J);case"ZodOptional":return KN(Y,J);case"ZodMap":return aV(Y,J);case"ZodSet":return LN(Y,J);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return ZN(Y,J);case"ZodNaN":case"ZodNever":return eV();case"ZodEffects":return lV(Y,J);case"ZodAny":return i0();case"ZodUnknown":return NN();case"ZodDefault":return pV(Y,J);case"ZodBranded":return v4(Y,J);case"ZodReadonly":return BN(Y,J);case"ZodCatch":return uV(Y,J);case"ZodPipeline":return UN(Y,J);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Q)=>{return})(X)}},FN=(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 G0(Y,X,J=!1){var Q;let $=X.seen.get(Y);if(X.override){let Z=(Q=X.override)==null?void 0:Q.call(X,Y,X,$,J);if(Z!==hV)return Z}if($&&!J){let Z=ON($,X);if(Z!==void 0)return Z}let G={def:Y,path:X.currentPath,jsonSchema:void 0};X.seen.set(Y,G);let W=qN(Y,Y.typeName,X),K=typeof W==="function"?G0(W(),X):W;if(K)jN(Y,X,K);if(X.postProcess){let Z=X.postProcess(K,Y,X);return G.jsonSchema=K,Z}return G.jsonSchema=K,K}var ON=(Y,X)=>{switch(X.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:FN(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`),i0();return X.$refStrategy==="seen"?i0():void 0}}},jN=(Y,X,J)=>{if(Y.description)J.description=Y.description;return J},DN=(Y)=>{let X=gV(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}]))}},PN=(Y,X)=>{var J;let Q=DN(X),$=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((U,[L,F])=>{var N;return{...U,[L]:(N=G0(F._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,L]},!0))!=null?N:i0()}},{}):void 0,G=typeof X==="string"?X:(X==null?void 0:X.nameStrategy)==="title"?void 0:X==null?void 0:X.name,W=(J=G0(Y._def,G===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,G]},!1))!=null?J:i0(),K=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if(K!==void 0)W.title=K;let Z=G===void 0?$?{...W,[Q.definitionPath]:$}:W:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,G].join("/"),[Q.definitionPath]:{...$,[G]:W}};return Z.$schema="http://json-schema.org/draft-07/schema#",Z},b8=Symbol.for("vercel.ai.schema");function YX(Y){let X;return()=>{if(X==null)X=Y();return X}}function XX(Y,{validate:X}={}){return{[b8]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:X}}function EN(Y){return typeof Y==="object"&&Y!==null&&b8 in Y&&Y[b8]===!0&&"jsonSchema"in Y&&"validate"in Y}function JX(Y){return Y==null?XX({type:"object",properties:{},additionalProperties:!1}):EN(Y)?Y:("~standard"in Y)?Y["~standard"].vendor==="zod"?o9(Y):MN(Y):Y()}function MN(Y){return XX(()=>{if(!wN(Y))throw Error(`Standard schema vendor '${Y["~standard"].vendor}' does not support JSON Schema conversion.`);return y8(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 r0({value:X,cause:J.issues})}}})}function wN(Y){return Y["~standard"].jsonSchema!=null}function AN(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return XX(()=>PN(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 TN(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return XX(()=>y8(S7(Y,{target:"draft-7",io:"input",reused:Q?"ref":"inline"})),{validate:async($)=>{let G=await aY(Y,$);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function RN(Y){return"_zod"in Y}function o9(Y,X){if(RN(Y))return TN(Y,X);else return AN(Y,X)}async function H9({value:Y,schema:X,context:J}){let Q=JX(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:r0.wrap({value:Y,cause:$.error,context:J}),rawValue:Y}}catch($){return{success:!1,error:r0.wrap({value:Y,cause:$,context:J}),rawValue:Y}}}async function k1({text:Y,schema:X}){try{let J=vV(Y);if(X==null)return{success:!0,value:J,rawValue:J};return await H9({value:J,schema:X})}catch(J){return{success:!1,error:xY.isInstance(J)?J:new xY({text:Y,cause:J}),rawValue:void 0}}}async function f8(Y){if(typeof Y==="function")Y=Y();return Promise.resolve(Y)}var f4="AI_SerializationError",m4=`vercel.ai.error.${f4}`,CN=Symbol.for(m4),w4,A4,ND=class extends(A4=T,w4=CN,A4){constructor({message:Y="Failed to serialize value.",cause:X}={}){super({name:f4,message:Y,cause:X});this[w4]=!0}static isInstance(Y){return T.hasMarker(Y,m4)}};var SN=Object.defineProperty,kN=(Y,X)=>{for(var J in X)SN(Y,J,{get:X[J],enumerable:!0})},gW="AI_InvalidArgumentError",yW=`vercel.ai.error.${gW}`,xN=Symbol.for(yW),u4,c4,m8=class extends(c4=T,u4=xN,c4){constructor({parameter:Y,value:X,message:J}){super({name:gW,message:`Invalid argument for parameter ${Y}: ${J}`});this[u4]=!0,this.parameter=Y,this.value=X}static isInstance(Y){return T.hasMarker(Y,yW)}},fW="AI_InvalidStreamPartError",mW=`vercel.ai.error.${fW}`,bN=Symbol.for(mW),p4,l4,TD=class extends(l4=T,p4=bN,l4){constructor({chunk:Y,message:X}){super({name:fW,message:X});this[p4]=!0,this.chunk=Y}static isInstance(Y){return T.hasMarker(Y,mW)}},uW="AI_InvalidToolApprovalError",cW=`vercel.ai.error.${uW}`,vN=Symbol.for(cW),d4,i4,CD=class extends(i4=T,d4=vN,i4){constructor({approvalId:Y}){super({name:uW,message:`Tool approval response references unknown approvalId: "${Y}". No matching tool-approval-request found in message history.`});this[d4]=!0,this.approvalId=Y}static isInstance(Y){return T.hasMarker(Y,cW)}},pW="AI_InvalidToolApprovalSignatureError",lW=`vercel.ai.error.${pW}`,hN=Symbol.for(lW),o4,n4,_D=class extends(n4=T,o4=hN,n4){constructor({approvalId:Y,toolCallId:X,reason:J}){super({name:pW,message:`Tool approval signature verification failed for approval "${Y}" (tool call "${X}"): ${J}`});this[o4]=!0,this.approvalId=Y,this.toolCallId=X}static isInstance(Y){return T.hasMarker(Y,lW)}},dW="AI_InvalidToolInputError",iW=`vercel.ai.error.${dW}`,gN=Symbol.for(iW),r4,s4,kD=class extends(s4=T,r4=gN,s4){constructor({toolInput:Y,toolName:X,cause:J,message:Q=`Invalid input for tool ${X}: ${p1(J)}`}){super({name:dW,message:Q,cause:J});this[r4]=!0,this.toolInput=Y,this.toolName=X}static isInstance(Y){return T.hasMarker(Y,iW)}},oW="AI_ToolCallNotFoundForApprovalError",nW=`vercel.ai.error.${oW}`,yN=Symbol.for(nW),a4,t4,bD=class extends(t4=T,a4=yN,t4){constructor({toolCallId:Y,approvalId:X}){super({name:oW,message:`Tool call "${Y}" not found for approval request "${X}".`});this[a4]=!0,this.toolCallId=Y,this.approvalId=X}static isInstance(Y){return T.hasMarker(Y,nW)}},rW="AI_MissingToolResultsError",sW=`vercel.ai.error.${rW}`,fN=Symbol.for(sW),e4,YW,hD=class extends(YW=T,e4=fN,YW){constructor({toolCallIds:Y}){super({name:rW,message:`Tool result${Y.length>1?"s are":" is"} missing for tool call${Y.length>1?"s":""} ${Y.join(", ")}.`});this[e4]=!0,this.toolCallIds=Y}static isInstance(Y){return T.hasMarker(Y,sW)}},aW="AI_NoImageGeneratedError",tW=`vercel.ai.error.${aW}`,mN=Symbol.for(tW),XW,JW,yD=class extends(JW=T,XW=mN,JW){constructor({message:Y="No image generated.",cause:X,calls:J,responses:Q}){super({name:aW,message:Y,cause:X});this[XW]=!0,this.calls=J,this.responses=Q}static isInstance(Y){return T.hasMarker(Y,tW)}},eW="AI_NoObjectGeneratedError",Yz=`vercel.ai.error.${eW}`,uN=Symbol.for(Yz),QW,$W,j1=class extends($W=T,QW=uN,$W){constructor({message:Y="No object generated.",cause:X,text:J,response:Q,usage:$,finishReason:G}){super({name:eW,message:Y,cause:X});this[QW]=!0,this.text=J,this.response=Q,this.usage=$,this.finishReason=G}static isInstance(Y){return T.hasMarker(Y,Yz)}},Xz="AI_NoOutputGeneratedError",Jz=`vercel.ai.error.${Xz}`,cN=Symbol.for(Jz),GW,WW,uD=class extends(WW=T,GW=cN,WW){constructor({message:Y="No output generated.",cause:X}={}){super({name:Xz,message:Y,cause:X});this[GW]=!0}static isInstance(Y){return T.hasMarker(Y,Jz)}},Qz="AI_NoSpeechGeneratedError",$z=`vercel.ai.error.${Qz}`,pN=Symbol.for($z),zW,KW,pD=class extends(KW=T,zW=pN,KW){constructor(Y){super({name:Qz,message:"No speech audio generated."});this[zW]=!0,this.responses=Y.responses}static isInstance(Y){return T.hasMarker(Y,$z)}},Gz="AI_NoTranscriptGeneratedError",Wz=`vercel.ai.error.${Gz}`,lN=Symbol.for(Wz),UW,ZW,dD=class extends(ZW=T,UW=lN,ZW){constructor(Y){super({name:Gz,message:"No transcript generated."});this[UW]=!0,this.responses=Y.responses}static isInstance(Y){return T.hasMarker(Y,Wz)}},zz="AI_NoTranslationGeneratedError",Kz=`vercel.ai.error.${zz}`,dN=Symbol.for(Kz),LW,HW,oD=class extends(HW=T,LW=dN,HW){constructor(Y){super({name:zz,message:"No translation generated."});this[LW]=!0,this.response=Y.response}static isInstance(Y){return T.hasMarker(Y,Kz)}},u8="AI_NoVideoGeneratedError",Uz=`vercel.ai.error.${u8}`,iN=Symbol.for(Uz),VW,NW,rD=class extends(NW=T,VW=iN,NW){constructor({message:Y="No video generated.",cause:X,responses:J}){super({name:u8,message:Y,cause:X});this[VW]=!0,this.responses=J}static isInstance(Y){return T.hasMarker(Y,Uz)}static isNoVideoGeneratedError(Y){return Y instanceof Error&&Y.name===u8&&typeof Y.responses<"u"?!0:!1}toJSON(){return{name:this.name,message:this.message,stack:this.stack,cause:this.cause,responses:this.responses}}},Zz="AI_NoSuchToolError",Lz=`vercel.ai.error.${Zz}`,oN=Symbol.for(Lz),BW,qW,aD=class extends(qW=T,BW=oN,qW){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:Zz,message:J});this[BW]=!0,this.toolName=Y,this.availableTools=X}static isInstance(Y){return T.hasMarker(Y,Lz)}},Hz="AI_StreamProviderError",Vz=`vercel.ai.error.${Hz}`,nN=Symbol.for(Vz),FW,OW,eD=class extends(OW=T,FW=nN,OW){constructor({message:Y,type:X,code:J,statusCode:Q,isRetryable:$=rN(Q),data:G,cause:W}){super({name:Hz,message:Y,cause:W});this[FW]=!0,this.type=X,this.code=J,this.statusCode=Q,this.isRetryable=$,this.data=G}static isInstance(Y){return T.hasMarker(Y,Vz)}};function rN(Y){return Y!=null&&(Y===408||Y===409||Y===429||Y>=500)}var Nz="AI_ToolCallRepairError",Bz=`vercel.ai.error.${Nz}`,sN=Symbol.for(Bz),jW,DW,XP=class extends(DW=T,jW=sN,DW){constructor({cause:Y,originalError:X,message:J=`Error repairing tool call: ${p1(Y)}`}){super({name:Nz,message:J,cause:Y});this[jW]=!0,this.originalError=X}static isInstance(Y){return T.hasMarker(Y,Bz)}},qz="AI_ToolChoiceViolationError",Fz=`vercel.ai.error.${qz}`,aN=Symbol.for(Fz),PW,EW,QP=class extends(EW=T,PW=aN,EW){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:qz,message:G});this[PW]=!0,this.toolChoice=Y,this.finishReason=X,this.provider=J,this.modelId=Q,this.content=$}static isInstance(Y){return T.hasMarker(Y,Fz)}};var Oz="AI_UIMessageStreamError",jz=`vercel.ai.error.${Oz}`,tN=Symbol.for(jz),MW,wW,GP=class extends(wW=T,MW=tN,wW){constructor({chunkType:Y,chunkId:X,message:J}){super({name:Oz,message:J});this[MW]=!0,this.chunkType=Y,this.chunkId=X}static isInstance(Y){return T.hasMarker(Y,jz)}},Dz="AI_InvalidDataContentError",Pz=`vercel.ai.error.${Dz}`,eN=Symbol.for(Pz),AW,TW,zP=class extends(TW=T,AW=eN,TW){constructor({content:Y,cause:X,message:J=`Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof Y}.`}){super({name:Dz,message:J,cause:X});this[AW]=!0,this.content=Y}static isInstance(Y){return T.hasMarker(Y,Pz)}},Ez="AI_InvalidMessageRoleError",Mz=`vercel.ai.error.${Ez}`,YB=Symbol.for(Mz),RW,CW,UP=class extends(CW=T,RW=YB,CW){constructor({role:Y,message:X=`Invalid message role: '${Y}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Ez,message:X});this[RW]=!0,this.role=Y}static isInstance(Y){return T.hasMarker(Y,Mz)}},wz="AI_MessageConversionError",Az=`vercel.ai.error.${wz}`,XB=Symbol.for(Az),IW,_W,LP=class extends(_W=T,IW=XB,_W){constructor({originalMessage:Y,message:X}){super({name:wz,message:X});this[IW]=!0,this.originalMessage=Y}static isInstance(Y){return T.hasMarker(Y,Az)}},Tz="AI_RetryError",Rz=`vercel.ai.error.${Tz}`,JB=Symbol.for(Rz),SW,kW,VP=class extends(kW=T,SW=JB,kW){constructor({message:Y,reason:X,errors:J}){super({name:Tz,message:Y});this[SW]=!0,this.reason=X,this.errors=J,this.lastError=J[J.length-1]}static isInstance(Y){return T.hasMarker(Y,Rz)}};var QB="7.0.102",$B=async({url:Y,maxBytes:X,abortSignal:J})=>{var Q;let $=Y.toString();try{let G=L9({},`ai-sdk/${QB}`,T4()),W=await k4({url:$,headers:G,abortSignal:J});if(!W.ok)throw await eY(W),new b0({url:$,statusCode:W.status,statusText:W.statusText});return{data:await x4({response:W,url:$,maxBytes:X!=null?X:g8}),mediaType:(Q=W.headers.get("content-type"))!=null?Q:void 0}}catch(G){if(b0.isInstance(G))throw G;throw new b0({url:$,cause:G})}};var z={array:T8,boolean:Q4,custom:B4,discriminatedUnion:U4,enum:C8,instanceof:q4,lazy:N4,literal:L4,looseObject:z4,never:A8,null:$4,number:J4,object:W4,record:Z4,string:Y4,union:R8,unknown:i9},o1=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),o1.optional()),z.array(o1)])),g=z.record(z.string(),z.record(z.string(),o1.optional())),r9=z.union([z.string(),z.instanceof(Uint8Array),z.instanceof(ArrayBuffer),z.custom(b4,{message:"Must be a Buffer"})]),c8=z.record(z.string(),z.string()),Cz=z.object({type:z.literal("text"),text:z.string(),providerOptions:g.optional()}),GB=z.object({type:z.literal("image"),image:z.union([r9,z.instanceof(URL),c8]),mediaType:z.string().optional(),providerOptions:g.optional()}),Iz=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:r9}),z.object({type:z.literal("url"),url:z.instanceof(URL)}),z.object({type:z.literal("reference"),reference:c8}),z.object({type:z.literal("text"),text:z.string()})]),WB=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:r9}),z.object({type:z.literal("url"),url:z.instanceof(URL)})]),_z=z.object({type:z.literal("file"),data:z.union([Iz,r9,z.instanceof(URL),c8]),filename:z.string().optional(),mediaType:z.string(),providerOptions:g.optional()}),zB=z.object({type:z.literal("reasoning"),text:z.string(),providerOptions:g.optional()}),KB=z.object({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerOptions:g.optional()}),UB=z.object({type:z.literal("reasoning-file"),data:z.union([WB,r9,z.instanceof(URL)]),mediaType:z.string(),providerOptions:g.optional()}),ZB=z.object({type:z.literal("tool-call"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerOptions:g.optional(),providerExecuted:z.boolean().optional()}),LB=z.discriminatedUnion("type",[z.object({type:z.literal("text"),value:z.string(),providerOptions:g.optional()}),z.object({type:z.literal("json"),value:o1,providerOptions:g.optional()}),z.object({type:z.literal("execution-denied"),reason:z.string().optional(),providerOptions:g.optional()}),z.object({type:z.literal("error-text"),value:z.string(),providerOptions:g.optional()}),z.object({type:z.literal("error-json"),value:o1,providerOptions:g.optional()}),z.object({type:z.literal("content"),value:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),providerOptions:g.optional()}),z.object({type:z.literal("file"),data:Iz,mediaType:z.string(),filename:z.string().optional(),providerOptions:g.optional()}),z.object({type:z.literal("file-data"),data:z.string(),mediaType:z.string(),filename:z.string().optional(),providerOptions:g.optional()}),z.object({type:z.literal("file-url"),url:z.string(),mediaType:z.string().optional(),providerOptions:g.optional()}),z.object({type:z.literal("file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:g.optional()}),z.object({type:z.literal("file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:g.optional()}),z.object({type:z.literal("image-data"),data:z.string(),mediaType:z.string(),providerOptions:g.optional()}),z.object({type:z.literal("image-url"),url:z.string(),providerOptions:g.optional()}),z.object({type:z.literal("image-file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:g.optional()}),z.object({type:z.literal("image-file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:g.optional()}),z.object({type:z.literal("custom"),providerOptions:g.optional()})]))})]),Sz=z.object({type:z.literal("tool-result"),toolCallId:z.string(),toolName:z.string(),output:LB,providerOptions:g.optional()}),HB=z.object({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string(),reason:z.string().optional()}),VB=z.object({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional()}),NB=z.object({role:z.literal("system"),content:z.string(),providerOptions:g.optional()}),BB=z.object({role:z.literal("user"),content:z.union([z.string(),z.array(z.union([Cz,GB,_z]))]),providerOptions:g.optional()}),qB=z.object({role:z.literal("assistant"),content:z.union([z.string(),z.array(z.union([Cz,KB,_z,zB,UB,ZB,Sz,HB]))]),providerOptions:g.optional()}),FB=z.object({role:z.literal("tool"),content:z.array(z.union([Sz,VB])),providerOptions:g.optional()}),FP=z.union([NB,BB,qB,FB]);var OB={};kN(OB,{array:()=>EB,choice:()=>MB,json:()=>wB,object:()=>PB,text:()=>DB});function jB(Y){let X=["ROOT"],J=-1,Q=null,$=0;function G(L){return L>="0"&&L<="9"||L>="A"&&L<="F"||L>="a"&&L<="f"}function W(L,F,N){switch(L){case'"':{J=F,X.pop(),X.push(N),X.push("INSIDE_STRING");break}case"f":case"t":case"n":{J=F,Q=F,X.pop(),X.push(N),X.push("INSIDE_LITERAL");break}case"-":{X.pop(),X.push(N),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=F,X.pop(),X.push(N),X.push("INSIDE_NUMBER");break}case"{":{J=F,X.pop(),X.push(N),X.push("INSIDE_OBJECT_START");break}case"[":{J=F,X.pop(),X.push(N),X.push("INSIDE_ARRAY_START");break}}}function K(L,F){switch(L){case",":{X.pop(),X.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{J=F,X.pop();break}}}function Z(L,F){switch(L){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=F,X.pop();break}}}for(let L=0;L<Y.length;L++){let F=Y[L];switch(X[X.length-1]){case"ROOT":W(F,L,"FINISH");break;case"INSIDE_OBJECT_START":{switch(F){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}case"}":{J=L,X.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(F){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(F){case'"':{X.pop(),X.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(F){case":":{X.pop(),X.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{W(F,L,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{K(F,L);break}case"INSIDE_STRING":{switch(F){case'"':{X.pop(),J=L;break}case"\\":{X.push("INSIDE_STRING_ESCAPE");break}default:J=L}break}case"INSIDE_ARRAY_START":{switch(F){case"]":{J=L,X.pop();break}default:{J=L,W(F,L,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(F){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=L,X.pop();break}default:{J=L;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{W(F,L,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{if(X.pop(),F==="u")$=0,X.push("INSIDE_STRING_UNICODE_ESCAPE");else J=L;break}case"INSIDE_STRING_UNICODE_ESCAPE":{if(G(F)){if($++,$===4)X.pop(),J=L}break}case"INSIDE_NUMBER":{switch(F){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=L;break}case"e":case"E":case"-":case".":break;case",":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")Z(F,L);if(X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(F,L);break}case"}":{if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(F,L);break}case"]":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")Z(F,L);break}default:{X.pop();break}}break}case"INSIDE_LITERAL":{let V=Y.substring(Q,L+1);if(!"false".startsWith(V)&&!"true".startsWith(V)&&!"null".startsWith(V)){if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(F,L);else if(X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")Z(F,L)}else J=L;break}}}let U=Y.slice(0,J+1);for(let L=X.length-1;L>=0;L--)switch(X[L]){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 N=Y.substring(Q,Y.length);if("true".startsWith(N))U+="true".slice(N.length);else if("false".startsWith(N))U+="false".slice(N.length);else if("null".startsWith(N))U+="null".slice(N.length)}}return U}async function QX(Y){if(Y===void 0)return{value:void 0,state:"undefined-input"};let X=await k1({text:Y});if(X.success)return{value:X.value,state:"successful-parse"};if(X=await k1({text:jB(Y)}),X.success)return{value:X.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var DB=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:Y}){return Y},async parsePartialOutput({text:Y}){return{partial:Y}},createElementStreamTransform(){return}}),PB=({schema:Y,name:X,description:J})=>{let Q=JX(Y);return{name:"object",responseFormat:f8(Q.jsonSchema).then(($)=>({type:"json",schema:$,...X!=null&&{name:X},...J!=null&&{description:J}})),async parseCompleteOutput({text:$},G){let W=await k1({text:$});if(!W.success)throw new j1({message:"No object generated: could not parse the response.",cause:W.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let K=await H9({value:W.value,schema:Q});if(!K.success)throw new j1({message:"No object generated: response did not match schema.",cause:K.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});return K.value},async parsePartialOutput({text:$}){let G=await QX($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:G.value}}},createElementStreamTransform(){return}}},EB=({element:Y,minItems:X,maxItems:J,name:Q,description:$})=>{if(xW({name:"minItems",value:X}),xW({name:"maxItems",value:J}),X!=null&&J!=null&&X>J)throw new m8({parameter:"minItems",value:X,message:"minItems must be less than or equal to maxItems"});let G=JX(Y);return{name:"array",responseFormat:f8(G.jsonSchema).then((W)=>{let{$schema:K,definitions:Z,$defs:U,...L}=W;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",...Z!=null&&{definitions:Z},...U!=null&&{$defs:U},type:"object",properties:{elements:{type:"array",items:L,...X!=null&&{minItems:X},...J!=null&&{maxItems:J}}},required:["elements"],additionalProperties:!1},...Q!=null&&{name:Q},...$!=null&&{description:$}}}),async parseCompleteOutput({text:W},K){let Z=await k1({text:W});if(!Z.success)throw new j1({message:"No object generated: could not parse the response.",cause:Z.error,text:W,response:K.response,usage:K.usage,finishReason:K.finishReason});let U=Z.value;if(U==null||typeof U!=="object"||!("elements"in U)||!Array.isArray(U.elements))throw new j1({message:"No object generated: response did not match schema.",cause:new r0({value:U,cause:"response must be an object with an elements array"}),text:W,response:K.response,usage:K.usage,finishReason:K.finishReason});let L=bW({value:U.elements,minItems:X,maxItems:J});if(L!=null)throw new j1({message:"No object generated: response did not match schema.",cause:L,text:W,response:K.response,usage:K.usage,finishReason:K.finishReason});let F=[];for(let N of U.elements){let V=await H9({value:N,schema:G});if(!V.success)throw new j1({message:"No object generated: response did not match schema.",cause:V.error,text:W,response:K.response,usage:K.usage,finishReason:K.finishReason});F.push(V.value)}return F},async parsePartialOutput({text:W}){let K=await QX(W);switch(K.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let Z=K.value;if(Z==null||typeof Z!=="object"||!("elements"in Z)||!Array.isArray(Z.elements))return;let U=K.state==="repaired-parse"&&Z.elements.length>0?Z.elements.slice(0,-1):Z.elements,L=[];for(let F of U){let N=await H9({value:F,schema:G});if(N.success)L.push(N.value)}return{partial:L}}}},createElementStreamTransform(){let W=0;return new TransformStream({transform({partialOutput:K},Z){if(K!=null)for(;W<K.length;W++){if(J!=null&&W>=J){Z.error(bW({value:K,maxItems:J}));return}Z.enqueue(K[W])}}})}}};function xW({name:Y,value:X}){if(X==null)return;if(!Number.isInteger(X))throw new m8({parameter:Y,value:X,message:`${Y} must be an integer`});if(X<0)throw new m8({parameter:Y,value:X,message:`${Y} must be greater than or equal to 0`})}function bW({value:Y,minItems:X,maxItems:J}){if(X!=null&&Y.length<X)return new r0({value:Y,cause:`elements array must contain at least ${X} items`});if(J!=null&&Y.length>J)return new r0({value:Y,cause:`elements array must contain at most ${J} items`});return}var MB=({options:Y,name:X,description:J})=>{return{name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:Y}},required:["result"],additionalProperties:!1},...X!=null&&{name:X},...J!=null&&{description:J}}),async parseCompleteOutput({text:Q},$){let G=await k1({text:Q});if(!G.success)throw new j1({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 j1({message:"No object generated: response did not match schema.",cause:new r0({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 QX(Q);switch($.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let G=$.value;if(G==null||typeof G!=="object"||!("result"in G)||typeof G.result!=="string")return;let W=Y.filter((K)=>K.startsWith(G.result));if($.state==="successful-parse")return W.includes(G.result)?{partial:G.result}:void 0;else return W.length===1?{partial:W[0]}:void 0}}},createElementStreamTransform(){return}}},wB=({name:Y,description:X}={})=>{return{name:"json",responseFormat:Promise.resolve({type:"json",...Y!=null&&{name:Y},...X!=null&&{description:X}}),async parseCompleteOutput({text:J},Q){let $=await k1({text:J});if(!$.success)throw new j1({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 QX(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 PP=O0({prefix:"aitxt",size:24}),EP=O0({prefix:"call",size:24});var wP=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 FY=z.record(z.string(),x1.optional()),mq=U9(()=>BY(z.union([z.looseObject({type:z.literal("text-start"),id:z.string(),providerMetadata:C.optional()}),z.looseObject({type:z.literal("text-delta"),id:z.string(),delta:z.string(),providerMetadata:C.optional()}),z.looseObject({type:z.literal("text-end"),id:z.string(),providerMetadata:C.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:C.optional(),toolMetadata:FY.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:C.optional(),toolMetadata:FY.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:C.optional(),toolMetadata:FY.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:C.optional()}),z.looseObject({type:z.literal("tool-output-available"),toolCallId:z.string(),output:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:C.optional(),toolMetadata:FY.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:C.optional(),toolMetadata:FY.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:C.optional()}),z.looseObject({type:z.literal("reasoning-delta"),id:z.string(),delta:z.string(),providerMetadata:C.optional()}),z.looseObject({type:z.literal("reasoning-end"),id:z.string(),providerMetadata:C.optional()}),z.looseObject({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerMetadata:C.optional()}),z.looseObject({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:C.optional()}),z.looseObject({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:C.optional()}),z.looseObject({type:z.literal("file"),url:z.string(),mediaType:z.string(),providerMetadata:C.optional()}),z.looseObject({type:z.literal("reasoning-file"),url:z.string(),mediaType:z.string(),providerMetadata:C.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 uq=G0({prefix:"aitxt",size:24}),pq=G0({prefix:"call",size:24});var lq=G0({prefix:"aitxt",size:24}),dq=G0({prefix:"call",size:24});var w0=z.record(z.string(),x1.optional()),kZ=z.record(z.string(),z.string());var nq=U9(()=>BY(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:C.optional()}),z.object({type:z.literal("reasoning"),id:z.string().optional(),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:C.optional()}),z.object({type:z.literal("custom"),kind:z.string(),providerMetadata:C.optional()}),z.object({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:C.optional()}),z.object({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:C.optional()}),z.object({type:z.literal("file"),mediaType:z.string(),filename:z.string().optional(),url:z.string(),providerReference:kZ.optional(),providerMetadata:C.optional()}),z.object({type:z.literal("reasoning-file"),mediaType:z.string(),url:z.string(),providerMetadata:C.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(),title:z.string().optional(),toolMetadata:w0.optional(),state:z.literal("input-streaming"),input:z.unknown().optional(),providerExecuted:z.boolean().optional(),callProviderMetadata:C.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(),title:z.string().optional(),toolMetadata:w0.optional(),state:z.literal("input-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:C.optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:w0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:C.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(),title:z.string().optional(),toolMetadata:w0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:C.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(),title:z.string().optional(),toolMetadata:w0.optional(),state:z.literal("output-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:C.optional(),resultProviderMetadata:C.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(),title:z.string().optional(),toolMetadata:w0.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:C.optional(),resultProviderMetadata:C.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(),title:z.string().optional(),toolMetadata:w0.optional(),state:z.literal("output-denied"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:C.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(),title:z.string().optional(),toolMetadata:w0.optional(),state:z.literal("input-streaming"),providerExecuted:z.boolean().optional(),callProviderMetadata:C.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(),title:z.string().optional(),toolMetadata:w0.optional(),state:z.literal("input-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:C.optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:w0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:C.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(),title:z.string().optional(),toolMetadata:w0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:C.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(),title:z.string().optional(),toolMetadata:w0.optional(),state:z.literal("output-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:C.optional(),resultProviderMetadata:C.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(),title:z.string().optional(),toolMetadata:w0.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:C.optional(),resultProviderMetadata:C.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(),title:z.string().optional(),toolMetadata:w0.optional(),state:z.literal("output-denied"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:C.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 rq=G0({prefix:"call",size:24});var aq=G0({prefix:"call",size:24});var eq=G0({prefix:"aiobj",size:24});function r7(Y){return({url:X,abortSignal:J})=>NZ({url:X,maxBytes:Y==null?void 0:Y.maxBytes,abortSignal:J})}var X6=G0({prefix:"aiobj",size:24});var J6=r7();var Q6=z.object({token:z.string().refine((Y)=>Y.trim().length>0),url:z.string().refine((Y)=>{try{let X=new URL(Y);return(X.protocol==="ws:"||X.protocol==="wss:")&&X.hostname!==""}catch(X){return!1}}),expiresAt:z.number().positive().max(Number.MAX_SAFE_INTEGER).optional(),tools:z.array(z.object({type:z.literal("function"),name:z.string().min(1),description:z.string().optional(),parameters:z.record(z.string(),z.unknown())})).optional()});var s7="AI_NoSuchProviderError",a7=`vercel.ai.error.${s7}`,xZ=Symbol.for(a7),t2,e2,G6=class extends(e2=zX,t2=xZ,e2){constructor({modelId:Y,modelType:X,providerId:J,availableProviders:Q,message:$=`No such provider: ${J} (available providers: ${Q.join()})`}){super({errorName:s7,modelId:Y,modelType:X,message:$});this[t2]=!0,this.providerId=J,this.availableProviders=Q}static isInstance(Y){return D.hasMarker(Y,a7)}};var z6=G0({prefix:"call",size:24});var U6=r7();class A0 extends JY{name="ProviderResponseStreamError";constructor(Y,X){super({message:Y,url:"",requestBodyValues:void 0,cause:X?.cause,isRetryable:X?.retryable??!0})}}var B0={};LX(B0,{toWebSocketUrl:()=>aZ,streamResponsesWebSocket:()=>JK,parseRateLimitSignal:()=>qY,normalizeHeaders:()=>tZ,markOversizedFrame:()=>U4,isUpgradeFailure:()=>eZ,isOversizedFrame:()=>YK,isAbortError:()=>$J,connectResponsesWebSocket:()=>XK,TERMINAL_AFTER_OUTPUT_MESSAGE:()=>H4,PROTOCOL_HEADER:()=>G4,OpenAIWebSocket:()=>B0,OVERSIZED_FRAME_MESSAGE:()=>N4});function jY(Y){let X=Number(Y.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(X)?X:void 0}function V9(Y,X,J=!1){let $=Buffer.from(Y.slice(0,X)).toString("latin1").split(`\r
196
- `),G=$[0]??"",W=jY(G);if(W===void 0||W===101)return;let U=Object.fromEntries($.slice(1).flatMap((N)=>{let F=N.indexOf(":");return F===-1?[]:[[N.slice(0,F).trim().toLowerCase(),N.slice(F+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 R(N)?N:void 0}catch{return}})();return{message:`WS upgrade failed: ${G}`,status:W,status_code:W,headers:U,body:B,...R(K?.error)?{error:K.error}:{}}}var bZ="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",t7=["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 XJ{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+bZ));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 t7)if(L[K]!==void 0)V.push(`${vZ(K)}: ${L[K]}`);for(let[K,N]of Object.entries(X))if(!t7.includes(K.toLowerCase())&&K.toLowerCase()!=="content-length")V.push(`${K}: ${N}`);let B=`${V.join(`\r
100
+ `)}})}};var n9=z.record(z.string(),o1.optional()),TP=YX(()=>o9(z.union([z.looseObject({type:z.literal("text-start"),id:z.string(),providerMetadata:g.optional()}),z.looseObject({type:z.literal("text-delta"),id:z.string(),delta:z.string(),providerMetadata:g.optional()}),z.looseObject({type:z.literal("text-end"),id:z.string(),providerMetadata:g.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:g.optional(),toolMetadata:n9.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:g.optional(),toolMetadata:n9.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:g.optional(),toolMetadata:n9.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:g.optional()}),z.looseObject({type:z.literal("tool-output-available"),toolCallId:z.string(),output:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:g.optional(),toolMetadata:n9.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:g.optional(),toolMetadata:n9.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:g.optional()}),z.looseObject({type:z.literal("reasoning-delta"),id:z.string(),delta:z.string(),providerMetadata:g.optional()}),z.looseObject({type:z.literal("reasoning-end"),id:z.string(),providerMetadata:g.optional()}),z.looseObject({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerMetadata:g.optional()}),z.looseObject({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:g.optional()}),z.looseObject({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:g.optional()}),z.looseObject({type:z.literal("file"),url:z.string(),mediaType:z.string(),providerMetadata:g.optional()}),z.looseObject({type:z.literal("reasoning-file"),url:z.string(),mediaType:z.string(),providerMetadata:g.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 CP=O0({prefix:"aitxt",size:24}),IP=O0({prefix:"call",size:24});var _P=O0({prefix:"aitxt",size:24}),SP=O0({prefix:"call",size:24});var f0=z.record(z.string(),o1.optional()),AB=z.record(z.string(),z.string());var xP=YX(()=>o9(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:g.optional()}),z.object({type:z.literal("reasoning"),id:z.string().optional(),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:g.optional()}),z.object({type:z.literal("custom"),kind:z.string(),providerMetadata:g.optional()}),z.object({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:g.optional()}),z.object({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:g.optional()}),z.object({type:z.literal("file"),mediaType:z.string(),filename:z.string().optional(),url:z.string(),providerReference:AB.optional(),providerMetadata:g.optional()}),z.object({type:z.literal("reasoning-file"),mediaType:z.string(),url:z.string(),providerMetadata:g.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(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("input-streaming"),input:z.unknown().optional(),providerExecuted:z.boolean().optional(),callProviderMetadata:g.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(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("input-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:g.optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:g.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(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:g.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(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("output-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:g.optional(),resultProviderMetadata:g.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(),title:z.string().optional(),toolMetadata:f0.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:g.optional(),resultProviderMetadata:g.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(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("output-denied"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:g.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(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("input-streaming"),providerExecuted:z.boolean().optional(),callProviderMetadata:g.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(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("input-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:g.optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:g.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(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:g.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(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("output-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:g.optional(),resultProviderMetadata:g.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(),title:z.string().optional(),toolMetadata:f0.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:g.optional(),resultProviderMetadata:g.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(),title:z.string().optional(),toolMetadata:f0.optional(),state:z.literal("output-denied"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:g.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 vP=O0({prefix:"call",size:24});var gP=O0({prefix:"call",size:24});var fP=O0({prefix:"aiobj",size:24});function kz(Y){return({url:X,abortSignal:J})=>$B({url:X,maxBytes:Y==null?void 0:Y.maxBytes,abortSignal:J})}var uP=O0({prefix:"aiobj",size:24});var cP=kz();var pP=z.object({token:z.string().refine((Y)=>Y.trim().length>0),url:z.string().refine((Y)=>{try{let X=new URL(Y);return(X.protocol==="ws:"||X.protocol==="wss:")&&X.hostname!==""}catch(X){return!1}}),expiresAt:z.number().positive().max(Number.MAX_SAFE_INTEGER).optional(),tools:z.array(z.object({type:z.literal("function"),name:z.string().min(1),description:z.string().optional(),parameters:z.record(z.string(),z.unknown())})).optional()});var xz="AI_NoSuchProviderError",bz=`vercel.ai.error.${xz}`,TB=Symbol.for(bz),vW,hW,dP=class extends(hW=rX,vW=TB,hW){constructor({modelId:Y,modelType:X,providerId:J,availableProviders:Q,message:$=`No such provider: ${J} (available providers: ${Q.join()})`}){super({errorName:xz,modelId:Y,modelType:X,message:$});this[vW]=!0,this.providerId=J,this.availableProviders=Q}static isInstance(Y){return T.hasMarker(Y,bz)}};var oP=O0({prefix:"call",size:24});var nP=kz();class m0 extends b9{name="ProviderResponseStreamError";constructor(Y,X){super({message:Y,url:"",requestBodyValues:void 0,cause:X?.cause,isRetryable:X?.retryable??!0})}}var _0={};aX(_0,{toWebSocketUrl:()=>lB,streamResponsesWebSocket:()=>rB,parseRateLimitSignal:()=>a9,normalizeHeaders:()=>dB,markOversizedFrame:()=>dz,isUpgradeFailure:()=>iB,isOversizedFrame:()=>oB,isAbortError:()=>i8,connectResponsesWebSocket:()=>nB,TERMINAL_AFTER_OUTPUT_MESSAGE:()=>oz,PROTOCOL_HEADER:()=>cz,OpenAIWebSocket:()=>_0,OVERSIZED_FRAME_MESSAGE:()=>nz});function s9(Y){let X=Number(Y.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(X)?X:void 0}function $X(Y,X,J=!1){let $=Buffer.from(Y.slice(0,X)).toString("latin1").split(`\r
101
+ `),G=$[0]??"",W=s9(G);if(W===void 0||W===101)return;let K=Object.fromEntries($.slice(1).flatMap((V)=>{let j=V.indexOf(":");return j===-1?[]:[[V.slice(0,j).trim().toLowerCase(),V.slice(j+1).trim()]]})),Z=Y.slice(X+4),U=K["content-length"],L=Number(U);if(!J&&(U===void 0||Number.isFinite(L)&&Z.length<L))return;let F=Buffer.from(Z).toString("utf8"),N=(()=>{try{let V=JSON.parse(F);return h(V)?V:void 0}catch{return}})();return{message:`WS upgrade failed: ${G}`,status:W,status_code:W,headers:K,body:F,...h(N?.error)?{error:N.error}:{}}}var RB="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",vz=["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 p8{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)),K=Buffer.from(W).toString("base64"),Z=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(K+RB));this.expectedAccept=Buffer.from(new Uint8Array(Z)).toString("base64");let U={};for(let[N,V]of Object.entries(X))U[N.toLowerCase()]=V;let L=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${K}`];for(let N of vz)if(U[N]!==void 0)L.push(`${CB(N)}: ${U[N]}`);for(let[N,V]of Object.entries(X))if(!vz.includes(N.toLowerCase())&&N.toLowerCase()!=="content-length")L.push(`${N}: ${V}`);let F=`${L.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,F)=>this.onData(F),drain:()=>this.flushWrites(),error:(N,F)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let q=F instanceof Error?F.message:String(F);this.log("socket_error",{message:q}),this.emit("error",{message:q})},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=hZ(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:$,tls:J.protocol==="https:"});let N=globalThis.Bun?.connect;if(!N)throw Error("Bun.connect is not available");this.socket=await N({hostname:Q,port:$,tls:J.protocol==="https:"?{serverName:Q}:void 0,socket:{open:(V)=>{this.socket=V,this.enqueueWrite(new TextEncoder().encode(F))},data:(V,j)=>this.onData(j),drain:()=>this.flushWrites(),error:(V,j)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let R=j instanceof Error?j.message:String(j);this.log("socket_error",{message:R}),this.emit("error",{message:R})},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(N){this.readyState=3;let V=N instanceof Error?N.message:String(N);this.log("connect_exception",{message:V}),this.emit("error",{message:V})}}onData(Y){if(this.rxBuffer=IB(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
200
105
  \r
201
106
  `);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=jY($);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
107
+ `)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=s9($);if(W!==101){if(W===void 0){this.readyState=3;try{this.socket?.end()}catch{}this.log("upgrade_failed",{statusLine:$}),this.emit("error",{message:`WS upgrade failed: ${$}`});return}if(!this.emitRejectedUpgrade())return;try{this.socket?.end()}catch{}return}if(!G||G[1]!==this.expectedAccept){this.readyState=3;try{this.socket?.end()}catch{}this.log("accept_mismatch",{statusLine:$}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(J+4),this.log("open",{statusLine:$}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let X=Buffer.from(this.rxBuffer).indexOf(`\r
203
108
  \r
204
- `);if(X===-1)return!1;let J=V9(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=gZ(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 J1({component:"raw-ws-bun",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function vZ(Y){return Y}function hZ(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function gZ(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 yZ}from"node:net";import{connect as fZ}from"node:tls";var mZ="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",e7=["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 JJ{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+mZ));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 e7)if(L[K]!==void 0)V.push(`${cZ(K)}: ${L[K]}`);for(let[K,N]of Object.entries(X))if(!e7.includes(K.toLowerCase())&&K.toLowerCase()!=="content-length")V.push(`${K}: ${N}`);let B=`${V.join(`\r
109
+ `);if(X===-1)return!1;let J=$X(this.rxBuffer,X,Y);if(!J)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:J.status,partial:Y}),this.emit("error",J),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let X=Y[0],J=Y[1],Q=(X&128)!==0,$=X&15,G=(J&128)!==0,W=J&127,K=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],K=4}else if(W===127){if(Y.length<10)return;W=0;for(let U=0;U<8;U++)W=W*256+Y[2+U];K=10}if(G)K+=4;if(Y.length<K+W)return;let Z=Y.slice(K,K+W);this.rxBuffer=Y.slice(K+W),this.handleFrame(Q,$,Z)}}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=_B(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let $=Buffer.from(Q).toString("utf-8");this.emit("message",{data:$})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),$;if(J<126)$=[128|Y,128|J];else if(J<65536)$=[128|Y,254,J>>8&255,J&255];else{$=[128|Y,255];for(let K=7;K>=0;K--)$.push(J/2**(8*K)&255)}let G=new Uint8Array(J);for(let K=0;K<J;K++)G[K]=X[K]^Q[K%4];let W=new Uint8Array($.length+4+J);W.set($,0),W.set(Q,$.length),W.set(G,$.length+4);try{this.enqueueWrite(W)}catch{}}enqueueWrite(Y){this.writeQueue.push(Y),this.flushWrites()}flushWrites(){let Y=this.socket;if(!Y)return;while(this.writeQueue.length>0){let X=this.writeQueue[0],J=Y.write(X);if(J<X.length){this.writeQueue[0]=X.slice(J),this.log("write_backpressure",{written:J,remaining:X.length-J});return}this.writeQueue.shift()}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return N1({component:"raw-ws-bun",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function CB(Y){return Y}function IB(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function _B(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 SB}from"node:net";import{connect as kB}from"node:tls";var xB="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hz=["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 l8{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)),K=Buffer.from(W).toString("base64"),Z=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(K+xB));this.expectedAccept=Buffer.from(new Uint8Array(Z)).toString("base64");let U={};for(let[N,V]of Object.entries(X))U[N.toLowerCase()]=V;let L=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${K}`];for(let N of hz)if(U[N]!==void 0)L.push(`${bB(N)}: ${U[N]}`);for(let[N,V]of Object.entries(X))if(!hz.includes(N.toLowerCase())&&N.toLowerCase()!=="content-length")L.push(`${N}: ${V}`);let F=`${L.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:"?fZ({host:Q,port:$,servername:Q},K):yZ({host:Q,port:$},K);this.socket=N,N.on("data",(F)=>{this.onData(typeof F==="string"?Buffer.from(F,"binary"):F)}),N.on("error",(F)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let q=F instanceof Error?F.message:String(F);this.log("socket_error",{message:q}),this.emit("error",{message:q})}),N.on("close",(F)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close",{hadError:F}),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=uZ(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:$,tls:J.protocol==="https:"});let N=()=>{this.socket?.write(F)},V=J.protocol==="https:"?kB({host:Q,port:$,servername:Q},N):SB({host:Q,port:$},N);this.socket=V,V.on("data",(j)=>{this.onData(typeof j==="string"?Buffer.from(j,"binary"):j)}),V.on("error",(j)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let R=j instanceof Error?j.message:String(j);this.log("socket_error",{message:R}),this.emit("error",{message:R})}),V.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(N){this.readyState=3,this.log("connect_exception",{message:N instanceof Error?N.message:String(N)}),this.emit("error",{message:N instanceof Error?N.message:String(N)})}}onData(Y){if(this.rxBuffer=vB(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
208
113
  \r
209
114
  `);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=jY($);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
115
+ `)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=s9($);if(W!==101){if(W===void 0){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:$}),this.emit("error",{message:`WS upgrade failed: ${$}`});return}if(!this.emitRejectedUpgrade())return;this.socket?.destroy?.();return}if(!G||G[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:$}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(J+4),this.log("open",{statusLine:$}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let X=Buffer.from(this.rxBuffer).indexOf(`\r
211
116
  \r
212
- `);if(X===-1)return!1;let J=V9(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=pZ(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 J1({component:"raw-ws-node",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function cZ(Y){return Y}function uZ(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function pZ(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 lZ(){return typeof globalThis.Bun?.connect==="function"}var Y4=lZ()?XJ:JJ;function Z9(Y){return process.env[Y]??process.env[Y.toLowerCase()]}function dZ(Y){let X=Z9("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 iZ(Y){let X=new URL(Y);if(dZ(X))return;if(X.protocol==="http:")return Z9("HTTP_PROXY");if(X.protocol==="https:")return Z9("HTTPS_PROXY")??Z9("HTTP_PROXY");return}var X4={getProxyForUrl:iZ};var nZ=H0("quota"),K9=H0("transport"),G4="responses_websockets=2026-02-06",J4=["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"],oZ=new Set([H1,"x-opencode-title"]);function rZ(Y){let X=new Map;for(let Q of Object.keys(Y))X.set(Q.toLowerCase(),Q);let J={};for(let Q of J4){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(!J4.includes(Q.toLowerCase()))J[Q]=$;return J}function sZ(Y){let X={};for(let[J,Q]of Object.entries(Y)){if(oZ.has(J.toLowerCase()))continue;X[J]=Q}return X}function aZ(Y){return Y.replace(/^http/,"ws")}function tZ(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 $J(Y){return Y instanceof DOMException&&Y.name==="AbortError"}var W4=new WeakSet;function eZ(Y){return typeof Y==="object"&&Y!==null&&W4.has(Y)}var z4=new WeakSet;function YK(Y){return typeof Y==="object"&&Y!==null&&z4.has(Y)}function U4(Y){return z4.add(Y),Y}function Q4(Y,X){let J=Error(Y,X===void 0?void 0:{cause:X});return W4.add(J),J}function XK(Y){return new Promise((X,J)=>{if(Y.signal?.aborted){J(QJ(Y.signal));return}let Q={...Y.headers,"openai-beta":Y.headers["openai-beta"]??G4},$=Q[H1]??Q["session-id"];delete Q["content-length"],Q=rZ(sZ(Q));let G=typeof Bun>"u"?void 0:X4.getProxyForUrl(Y.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),W=!0,U=Y.rawWebSocket?new Y4(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(F){L(),J(Q4(X1(F),F))}function K(F){L(),J(Q4(V4("WebSocket closed before open",F.code,F.reason)))}function N(){L(),U.close(),J(QJ(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 JK(Y){let X=new TextEncoder,J=Y.socket,Q,$=()=>{},G=!1,W=0,U=!1,H=!1,L,V=[],B=12,K=typeof Y.body.previous_response_id==="string"?Y.body.previous_response_id:void 0,N=typeof Y.body.prompt_cache_key==="string"?Y.body.prompt_cache_key:void 0,F={sessionID:Y.sessionID,codexSessionID:N},q,A=0,b,E=new Set;function _(){if(L)clearTimeout(L);$(),Y.signal?.removeEventListener("abort",s0)}function g(M=J){M.close()}function p(){_(),Q?.enqueue(X.encode(`data: [DONE]
117
+ `);if(X===-1)return!1;let J=$X(this.rxBuffer,X,Y);if(!J)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:J.status,partial:Y}),this.emit("error",J),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let X=Y[0],J=Y[1],Q=(X&128)!==0,$=X&15,G=(J&128)!==0,W=J&127,K=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],K=4}else if(W===127){if(Y.length<10)return;W=0;for(let U=0;U<8;U++)W=W*256+Y[2+U];K=10}if(G)K+=4;if(Y.length<K+W)return;let Z=Y.slice(K,K+W);this.rxBuffer=Y.slice(K+W),this.handleFrame(Q,$,Z)}}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=hB(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let $=Buffer.from(Q).toString("utf-8");this.emit("message",{data:$})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),$;if(J<126)$=[128|Y,128|J];else if(J<65536)$=[128|Y,254,J>>8&255,J&255];else{$=[128|Y,255];for(let K=7;K>=0;K--)$.push(J/2**(8*K)&255)}let G=new Uint8Array(J);for(let K=0;K<J;K++)G[K]=X[K]^Q[K%4];let W=new Uint8Array($.length+4+J);W.set($,0),W.set(Q,$.length),W.set(G,$.length+4);try{this.socket?.write(W)}catch{}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return N1({component:"raw-ws-node",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function bB(Y){return Y}function vB(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function hB(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 gB(){return typeof globalThis.Bun?.connect==="function"}var gz=gB()?p8:l8;function GX(Y){return process.env[Y]??process.env[Y.toLowerCase()]}function yB(Y){let X=GX("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 fB(Y){let X=new URL(Y);if(yB(X))return;if(X.protocol==="http:")return GX("HTTP_PROXY");if(X.protocol==="https:")return GX("HTTPS_PROXY")??GX("HTTP_PROXY");return}var yz={getProxyForUrl:fB};var mB=B0("quota"),WX=B0("transport"),cz="responses_websockets=2026-02-06",fz=["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"],uB=new Set([w1,"x-opencode-title"]);function cB(Y){let X=new Map;for(let Q of Object.keys(Y))X.set(Q.toLowerCase(),Q);let J={};for(let Q of fz){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(!fz.includes(Q.toLowerCase()))J[Q]=$;return J}function pB(Y){let X={};for(let[J,Q]of Object.entries(Y)){if(uB.has(J.toLowerCase()))continue;X[J]=Q}return X}function lB(Y){return Y.replace(/^http/,"ws")}function dB(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 i8(Y){return Y instanceof DOMException&&Y.name==="AbortError"}var pz=new WeakSet;function iB(Y){return typeof Y==="object"&&Y!==null&&pz.has(Y)}var lz=new WeakSet;function oB(Y){return typeof Y==="object"&&Y!==null&&lz.has(Y)}function dz(Y){return lz.add(Y),Y}function mz(Y,X){let J=Error(Y,X===void 0?void 0:{cause:X});return pz.add(J),J}function nB(Y){return new Promise((X,J)=>{if(Y.signal?.aborted){J(d8(Y.signal));return}let Q={...Y.headers,"openai-beta":Y.headers["openai-beta"]??cz},$=Q[w1]??Q["session-id"];delete Q["content-length"],Q=cB(pB(Q));let G=typeof Bun>"u"?void 0:yz.getProxyForUrl(Y.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),W=!0,K=Y.rawWebSocket?new gz(Y.url,Q,{sessionID:$}):new globalThis.WebSocket(Y.url,{headers:Q,...G?{proxy:G}:{},perMessageDeflate:W}),Z=Y.timeout?setTimeout(()=>{U(),K.close(),J(Error("WebSocket connect timed out"))},Y.timeout):void 0;function U(){if(Z)clearTimeout(Z);K.removeEventListener("open",L),K.removeEventListener("error",F),K.removeEventListener("close",N),Y.signal?.removeEventListener("abort",V)}function L(){U(),X(K)}function F(j){U(),J(mz(t9(j),j))}function N(j){U(),J(mz(rz("WebSocket closed before open",j.code,j.reason)))}function V(){U(),K.close(),J(d8(Y.signal))}K.addEventListener("open",L,{once:!0}),K.addEventListener("error",F,{once:!0}),K.addEventListener("close",N,{once:!0}),Y.signal?.addEventListener("abort",V,{once:!0})})}function rB(Y){let X=new TextEncoder,J=Y.socket,Q,$=()=>{},G=!1,W=0,K=!1,Z=!1,U,L=[],F=12,N=typeof Y.body.previous_response_id==="string"?Y.body.previous_response_id:void 0,V=typeof Y.body.prompt_cache_key==="string"?Y.body.prompt_cache_key:void 0,j={sessionID:Y.sessionID,codexSessionID:V},R,S=0,u,I=new Set;function E(){if(U)clearTimeout(U);$(),Y.signal?.removeEventListener("abort",c)}function b(B=J){B.close()}function f(){E(),Q?.enqueue(X.encode(`data: [DONE]
213
118
 
214
- `)),Q?.close()}function F0(M){m(M,M)}function o(M){let c={...F,openingFrameTypes:V,responseID:q,previousResponseID:K,hasContinuation:K!==void 0,framesSinceCreated:A,msSinceLastFrame:b===void 0?void 0:Date.now()-b};if(H){let y=H4;K9.warn("stream failed after output; not retried",{reason:M.message,emittedOutput:!0,...c}),m(Error(y,{cause:M}),new A0(y,{cause:M}));return}K9.warn("stream failed before output; retryable",{reason:M.message,emittedOutput:!1,...c}),F0(M)}function m(M,c){if(G)return;G=!0,_(),Y.onConnectionInvalid?.(c),Q?.error(M)}function P0(M){if(G)return;if(!Y.idleTimeout)return;if(L)clearTimeout(L);L=setTimeout(()=>o(new A0(M)),Y.idleTimeout)}async function c0(M){if(G)return;if(typeof M.data!=="string"){o(new A0("Unexpected binary WebSocket frame"));return}let c=M.data,y=(()=>{try{let l=JSON.parse(c);return typeof l==="object"&&l!==null?l:void 0}catch{return}})();if(y?.type==="codex.rate_limits"){nZ.debug("codex.rate_limits frame received",{pid:process.pid}),P0("idle timeout waiting for websocket");let l=$4(y);Y.onQuota?.(l);return}let Z0=!H?qY(y):void 0;if(Z0&&y){G=!0,_(),Y.onRateLimitReached?.(Z0.window,Z0.resetAt),Y.onTerminal?.(y),Y.onFirstEvent?.(),Q?.error(new A0(`OpenAI account rate limit reached at admission (${Z0.window})`));return}if(y?.type==="error"&&Y.onRetryableTerminal){if($(),L)clearTimeout(L);L=void 0;try{let l=await Y.onRetryableTerminal(y);if(G){if(l)g(l);return}if(l){a0(l);return}}catch(l){o(new A0(l instanceof Error?l.message:String(l),{cause:l}));return}}let T0=zK(y,c);if(T0&&y){if(!U)Y.onFirstEvent?.(T0);G=!0,_(),Y.onTerminal?.(y);let l=new JY({message:T0.message,url:J.url,requestBodyValues:Y.body,statusCode:T0.status,responseHeaders:T0.headers,responseBody:T0.body});Q?.error(H?Error(l.message,{cause:l}):l);return}if(R(y)&&y.type==="response.failed"){let l=R(y.response)?y.response.failed:void 0,R0=R(l)?l.rate_limit_reached_type:void 0;if(typeof R0==="string"){if(G=!0,_(),Y.onRateLimitReached?.(R0),Y.onTerminal?.(y),!H)Y.onFirstEvent?.(),Q?.error(new A0(`OpenAI account rate limit reached mid-stream (${R0})`));else p();return}}if(y)QK(y,Y.sessionID),GK(y,E);let Y0=y?JX(y):y;if(!Y0){if(!U)Y.onFirstEvent?.();P0("idle timeout waiting for websocket");return}let x0=Y0===y?c:JSON.stringify(Y0);if(!U)Y.onFirstEvent?.();if(Q?.enqueue(X.encode(`${x0.split(/\r?\n/).map((l)=>`data: ${l}`).join(`
119
+ `)),Q?.close()}function o(B){N0(B,B)}function t(B){let D={...j,openingFrameTypes:L,responseID:R,previousResponseID:N,hasContinuation:N!==void 0,framesSinceCreated:S,msSinceLastFrame:u===void 0?void 0:Date.now()-u};if(Z){let w=oz;WX.warn("stream failed after output; not retried",{reason:B.message,emittedOutput:!0,...D}),N0(Error(w,{cause:B}),new m0(w,{cause:B}));return}WX.warn("stream failed before output; retryable",{reason:B.message,emittedOutput:!1,...D}),o(B)}function N0(B,D){if(G)return;G=!0,E(),Y.onConnectionInvalid?.(D),Q?.error(B)}function W0(B){if(G)return;if(!Y.idleTimeout)return;if(U)clearTimeout(U);U=setTimeout(()=>t(new m0(B)),Y.idleTimeout)}async function F0(B){if(G)return;if(typeof B.data!=="string"){t(new m0("Unexpected binary WebSocket frame"));return}let D=B.data,w=(()=>{try{let r=JSON.parse(D);return typeof r==="object"&&r!==null?r:void 0}catch{return}})();if(w?.type==="codex.rate_limits"){mB.debug("codex.rate_limits frame received",{pid:process.pid}),W0("idle timeout waiting for websocket");let r=uz(w);Y.onQuota?.(r);return}let m=!Z?a9(w):void 0;if(m&&w){G=!0,E(),Y.onRateLimitReached?.(m.window,m.resetAt),Y.onTerminal?.(w),Y.onFirstEvent?.(),Q?.error(new m0(`OpenAI account rate limit reached at admission (${m.window})`));return}if(w?.type==="error"&&Y.onRetryableTerminal){if($(),U)clearTimeout(U);U=void 0;try{let r=await Y.onRetryableTerminal(w);if(G){if(r)b(r);return}if(r){A(r);return}}catch(r){t(new m0(r instanceof Error?r.message:String(r),{cause:r}));return}}let p=Yq(w,D);if(p&&w){if(!K)Y.onFirstEvent?.(p);G=!0,E(),Y.onTerminal?.(w);let r=new b9({message:p.message,url:J.url,requestBodyValues:Y.body,statusCode:p.status,responseHeaders:p.headers,responseBody:p.body});Q?.error(Z?Error(r.message,{cause:r}):r);return}if(h(w)&&w.type==="response.failed"){let r=h(w.response)?w.response.failed:void 0,v0=h(r)?r.rate_limit_reached_type:void 0;if(typeof v0==="string"){if(G=!0,E(),Y.onRateLimitReached?.(v0),Y.onTerminal?.(w),!Z)Y.onFirstEvent?.(),Q?.error(new m0(`OpenAI account rate limit reached mid-stream (${v0})`));else f();return}}if(w)sB(w,Y.sessionID),tB(w,I);let n=w?lX(w):w;if(!n){if(!K)Y.onFirstEvent?.();W0("idle timeout waiting for websocket");return}let z0=n===w?D:JSON.stringify(n);if(!K)Y.onFirstEvent?.();if(Q?.enqueue(X.encode(`${z0.split(/\r?\n/).map((r)=>`data: ${r}`).join(`
215
120
  `)}
216
121
 
217
- `)),U=!0,b=Date.now(),q!==void 0)A++;if(V.length<B)V.push(String(Y0.type));if(Y0.type==="response.created")q=HK(Y0),K9.debug("response created",{...F,responseID:q,previousResponseID:K,hasContinuation:K!==void 0});if(Y0.type!=="response.created"&&Y0.type!=="response.in_progress")H=!0;if(P0("idle timeout waiting for websocket"),!Y0)return;if(Y0.type==="response.completed"||Y0.type==="response.done"){G=!0,WK(Y0,E),Y.onComplete?.(Y0,E),Y.onTerminal?.(Y0),p();return}if(Y0.type==="response.failed"||Y0.type==="response.incomplete"||Y0.type==="error")G=!0,Y.onTerminal?.(Y0),p()}function U0(M){o(new A0(X1(M),{cause:M}))}function D1(M){if(G)return;let c=M.code===1009,y=new A0(c?N4:V4("WebSocket closed before response.completed",M.code,M.reason),{retryable:!c});if(c)K9.warn("websocket peer refused the request size",{...F,requestBytes:W,reason:M.reason.toString()});o(c?U4(y):y)}function s0(){let M=QJ(Y.signal);if(G)return;G=!0,_(),g(),Y.onAbort?.(M),Q?.error(M)}function P1(M){if(G)return;G=!0,_(),g(),Y.onAbort?.(UK(M))}function a0(M){$(),J=M,J.addEventListener("message",c0),J.addEventListener("error",U0,{once:!0}),J.addEventListener("close",D1,{once:!0}),$=()=>{J.removeEventListener("message",c0),J.removeEventListener("error",U0),J.removeEventListener("close",D1)};let{background:c,...y}=Y.body;P0("idle timeout sending websocket request");try{let Z0=JSON.stringify({type:"response.create",...y});W=Z0.length,J.send(Z0),P0("idle timeout waiting for websocket")}catch(Z0){if(G)return;F0(new A0(Z0 instanceof Error?Z0.message:String(Z0),{cause:Z0}))}}return new Response(new ReadableStream({start(M){if(Q=M,Y.signal?.addEventListener("abort",s0,{once:!0}),Y.signal?.aborted){s0();return}a0(J)},cancel(M){P1(M)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function QK(Y,X){if(!$K(Y))return;await J1({component:"ws",event:"provider_native_web_search_event",sessionID:X,serverEventType:Y.type,itemType:R(Y.item)?Y.item.type:void 0,serverEvent:Y})}function $K(Y){if(typeof Y.type==="string"&&(Y.type.startsWith("response.web_search_call.")||Y.type.startsWith("response.web_search_preview_call.")))return!0;if(R(Y.item)&&typeof Y.item.type==="string")return Y.item.type==="web_search_call"||Y.item.type==="web_search_preview_call";return!1}function GK(Y,X){if(Y.type!=="response.output_item.done")return;if(!R(Y.item))return;L4(Y.item,X)}function WK(Y,X){let J=Y.response;if(!R(J)||!Array.isArray(J.output))return;for(let Q of J.output)if(R(Q))L4(Q,X)}function L4(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 zK(Y,X){if(Y?.type!=="error")return;let J=Y.status??Y.status_code;if(typeof J!=="number"||J>=200&&J<300)return;return{status:J,headers:R(Y.headers)?Object.fromEntries(Object.entries(Y.headers).flatMap(([Q,$])=>typeof $==="string"||typeof $==="number"||typeof $==="boolean"?[[Q,String($)]]:[])):void 0,body:X,message:R(Y.error)&&typeof Y.error.message==="string"?Y.error.message:`${J}`}}function qY(Y){if(typeof Y==="string")try{return qY(JSON.parse(Y))}catch{return}if(!R(Y))return;let X=qY(Y.cause);if(X)return X;let J=qY(Y.body);if(J)return J;let Q=R(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 UK(Y){if($J(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function QJ(Y){let X=Y?.reason;if($J(X))return X;if(LK(X))return X;return new DOMException(X instanceof Error?X.message:"Aborted","AbortError")}function LK(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function HK(Y){let X=Y.response;if(!R(X))return;return typeof X.id==="string"?X.id:void 0}var H4="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.",N4="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 WJ="x-opencode-title",B9="x-openai-auth-quota-account",GJ=new Set([WJ,H1,B9,"x-opencode-session"]),VK=15000,ZK=300000,KK=3300000,Z4="websocket_connection_limit_reached";function BK(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 NK("sha256").update(Q).digest("hex").slice(0,12)}function FK(Y){let X=Y?.httpFetch??globalThis.fetch,J=new Map,Q=Y?.connectTimeout??VK,$=Y?.idleTimeout??ZK,G=Y?.maxConnectionAge??KK,W=Y?.streamRetries??5,U=Y?.firstEventGraceMs??250,H=Y?.rawWebSocket??!1,L=Y?.onQuota,V=Y?.onRateLimitReached,B=setInterval(()=>q(),Math.min($,60000));if(typeof B==="object"&&"unref"in B&&typeof B.unref==="function")B.unref();function K(E,_,g){if(!_||!g)return g;zJ(E,K4(_));let p=new Headers(g.headers),F0=p.get("x-codex-turn-metadata");if(!F0)return g;let o=M4(F0,E.turnID,E.turnStartedAt);if(!o)return g;return p.set("x-codex-turn-metadata",o),{...g,headers:p}}async function N(E,_){let g=E instanceof URL?E.toString():typeof E==="string"?E:E.url,p=B0.normalizeHeaders(_?.headers),F0=A4(_),o=fY(F0);if(_?.method!=="POST"||!new URL(g).pathname.endsWith("/responses"))return X(E,o);let m=(()=>{try{if(typeof _?.body!=="string")return;let c=JSON.parse(_.body);return typeof c==="object"&&c!==null?c:void 0}catch{return}})();if(!m?.stream)return X(E,o);if(p[WJ]==="true")return X(E,o);let P0=p[H1]??p["x-session-affinity"]??p["session-id"],c0=P0;if(!P0)return X(E,o);let U0=B0.normalizeHeaders(F0?.headers),D1=BK(U0),s0=`${P0}:${D1}:conversation`,P1=typeof p[B9]==="string"?p[B9]:void 0,a0=V?(c,y)=>V(c,P1,y):void 0,M=J.get(s0)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};if(J.set(s0,M),M.fallback)return X(E,K(M,m,o));if(M.busy)return X(E,K(M,m,o));M.busy=!0,M.lastUsedAt=Date.now();try{let c=K4(m),y=B0.normalizeHeaders(F0?.headers),Z0=typeof y.authorization==="string"&&y.authorization.startsWith("Bearer ")?y.authorization.slice(7):"",T0=typeof y["chatgpt-account-id"]==="string"?y["chatgpt-account-id"]:void 0,Y0=L?(a)=>L(a,Z0,P1,T0):void 0,x0=!M.socket&&!M.continuation?AK(y):y;if(M.socket=await DK(M,Y?.url??g,x0,Q,G,H,_?.signal),IK(M,c))await PK(M,c,$,{signal:_?.signal??void 0,sessionID:c0,url:Y?.url??g,headers:F0?.headers,onRateLimitReached:a0});let l=()=>{},R0=()=>{},M1=new Promise((a,b0)=>{l=a,R0=b0}),q9=CK(M,c),t0=DY(P4(M,q9,c)),M0=typeof t0.previous_response_id==="string";await c1({sessionID:c0,transport:"websocket",phase:"main",bodyText:JSON.stringify(t0),url:Y?.url??g,method:F0?.method,headers:F0?.headers});let u0=B0.streamResponsesWebSocket({socket:M.socket,body:t0,sessionID:c0??void 0,idleTimeout:$,signal:_?.signal??void 0,onQuota:Y0,onRateLimitReached:a0,onFirstEvent:(a)=>l(a??!0),onComplete:(a,b0)=>{let D9=O4(a);J1({component:"ws-pool",event:"main_completed",sessionID:c0,responseID:F4(a),usage:D9}),D4(M,c,a,b0,M0)},onTerminal:(a)=>{if(M.busy=!1,M.lastUsedAt=Date.now(),M.streamFailures=0,a.type!=="response.completed"&&a.type!=="response.done")M.continuation=void 0,U1(M)},onConnectionInvalid:(a)=>{if(M.busy=!1,M.lastUsedAt=Date.now(),B0.isOversizedFrame(a))M.fallback=!0;if(!M.fallback)F(M);M.continuation=void 0,U1(M),l(!1)},onAbort:(a)=>{M.busy=!1,M.lastUsedAt=Date.now(),M.streamFailures=0,M.continuation=void 0,U1(M),R0(a)},onRetryableTerminal:async(a)=>{let b0=B4(a);if(!b0)return;throw M.fallback=!0,b0}}),p0=await OK(M1,U);if(p0!==!1){if(p0===!0||p0.status<200||p0.status>599)return u0;return new Response(p0.body,{status:p0.status,headers:{"content-type":"application/json",...p0.headers}})}let v1=()=>X(E,K(M,m,o));if(!M.fallback)return jK(u0,v1);return v1()}catch(c){if(M.busy=!1,M.lastUsedAt=Date.now(),B0.isAbortError(c))throw M.streamFailures=0,M.continuation=void 0,U1(M),c;let y=B0.parseRateLimitSignal(c);if(y)a0?.(y.window,y.resetAt);if(B0.isUpgradeFailure(c)&&!H)M.fallback=!0;if(F(M),M.continuation=void 0,U1(M),M.fallback)return X(E,K(M,m,o));return qK(new A0(c instanceof Error?c.message:String(c),{cause:c}))}}function F(E){if(E.streamFailures++,E.streamFailures>W)E.fallback=!0}function q(){let E=Date.now();for(let[_,g]of J){if(g.busy)continue;if(E-g.lastUsedAt<$)continue;U1(g),J.delete(_)}}function A(){clearInterval(B);for(let E of J.values())U1(E);J.clear()}function b(E){let _=`${E}:`;for(let[g,p]of J){if(!g.startsWith(_))continue;U1(p),J.delete(g)}}return Object.assign(N,{close:A,remove:b})}function B4(Y){if(Y.type!=="error"||!R(Y.error)||Y.error.code!==Z4)return;return Error(typeof Y.error.message==="string"?Y.error.message:Z4)}async function OK(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 jK(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 A0(`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 qK(Y){return new Response(new ReadableStream({start(X){X.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function DK(Y,X,J,Q,$,G,W){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<$)return Y.socket;U1(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 U1(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function PK(Y,X,J,Q){if(!Y.socket||!Array.isArray(X.input)||X.input.length===0)return;let $=EK(X);await c1({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)=>{J1({component:"ws-pool",event:"prewarm_completed",sessionID:Q.sessionID,responseID:F4(W),usage:O4(W)}),D4(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=B4(W);if(!U)return;throw Y.fallback=!0,U}});await MK(G)}function F4(Y){let X=Y.response;if(!R(X))return;return typeof X.id==="string"?X.id:void 0}function O4(Y){let X=Y.response;if(!R(X))return;return R(X.usage)?X.usage:void 0}async function MK(Y){let X=Y.body?.getReader();if(!X)return;while(!0)if((await X.read()).done)return}function EK(Y){return DY({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:wK(Y.client_metadata)})}function j4(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 wK(Y){if(!R(Y))return Y;if(typeof Y["x-codex-turn-metadata"]!=="string")return Y;try{let X=JSON.parse(Y["x-codex-turn-metadata"]);if(!R(X))return Y;return{...Y,"x-codex-turn-metadata":j4(X),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function AK(Y){let X=Y["x-codex-turn-metadata"];if(!X)return Y;try{let J=JSON.parse(X);if(!R(J))return Y;return{...Y,"x-codex-turn-metadata":j4(J)}}catch{return Y}}var q4=["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 K4(Y){let X={...Y};if(Array.isArray(Y.input))X.input=Y.input.map(TK);return X}function DY(Y){let X={};for(let J of q4)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 TK(Y){if(!R(Y))return Y;if(typeof Y.type==="string")return Y;if(typeof Y.role!=="string")return Y;if(!("content"in Y))return Y;return{...Y,type:"message"}}function D4(Y,X,J,Q,$){let G=J.response,W=R(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:UJ(X),finalizedCallIds:U}}function zJ(Y,X,J=X){let Q=Array.isArray(X.input)?X.input:[],$=Array.isArray(J.input)?J.input:Q,G=UJ(J),W=Y.turnInput&&Y.turnSignature===G?RK(Y.turnInput,$):void 0,U=W===void 0?Q:$.slice(W);if(U.length>0&&U.some(E4)||!Y.turnID)Y.turnID=C1(),Y.turnStartedAt=Date.now();Y.turnInput=$.slice(),Y.turnSignature=G}function P4(Y,X,J=X){zJ(Y,X,J);let Q=X.client_metadata;if(!R(Q)||typeof Q["x-codex-turn-metadata"]!=="string")return X;let $=M4(Q["x-codex-turn-metadata"],Y.turnID,Y.turnStartedAt);if(!$)return X;return{...X,client_metadata:{...Q,"x-codex-turn-metadata":$}}}function M4(Y,X,J){let Q;try{Q=JSON.parse(Y)}catch{return}if(!R(Q))return;return JSON.stringify({session_id:Q.session_id,thread_id:Q.thread_id,thread_source:Q.thread_source,turn_id:X,sandbox:Q.sandbox,turn_started_at_unix_ms:J,request_kind:"turn",window_id:Q.window_id})}function RK(Y,X){if(Y.length>X.length)return;for(let J=0;J<Y.length;J++)if(Q1(Y[J])!==Q1(X[J]))return;return Y.length}function CK(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!J||!Y.continuation)return X;if(Y.continuation.signature!==UJ(X))return Y.continuation=void 0,X;if(!w4(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),$=_K(Q,Y.continuation.finalizedCallIds);if($.length===0)return X;return{...X,previous_response_id:Y.continuation.responseID,input:$}}function IK(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!Y.continuation)return!0;if(!J)return!1;if(!w4(Y.continuation.input,J))return!0;return J.slice(Y.continuation.input.length).some(E4)}function E4(Y){if(!R(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function _K(Y,X){return Y.filter((J)=>{if(!R(J))return!0;if(typeof J.type==="string"&&J.type.endsWith("_output"))return!0;if(J.type==="function_call_output"||J.type==="custom_tool_call_output")return!0;if(J.type==="function_call"||J.type==="custom_tool_call"){let Q=typeof J.call_id==="string"?J.call_id:typeof J.id==="string"?J.id:void 0;return Q?!X.has(Q):!0}if(J.type==="message")return J.role!=="assistant";if(typeof J.role==="string")return J.role!=="assistant";return!1})}function UJ(Y){return Q1(SK(Object.fromEntries(Object.entries(Y).filter(([X])=>X!=="input"&&X!=="stream"&&X!=="background"&&X!=="previous_response_id"&&X!=="generate"))))}function SK(Y){if(!R(Y.client_metadata))return Y;let X=Object.fromEntries(Object.entries(Y.client_metadata).filter(([J])=>J!=="x-codex-turn-metadata"&&J!=="x-codex-ws-stream-request-start-ms"));return{...Y,client_metadata:X}}function w4(Y,X){if(Y.length>=X.length)return!1;for(let J=0;J<Y.length;J++)if(Q1(Y[J])!==Q1(X[J]))return!1;return!0}function A4(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let X=new Headers(Y.headers);for(let J of GJ)X.delete(J);return{...Y,headers:X}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((X)=>!GJ.has(X[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([X])=>!GJ.has(X.toLowerCase())))}}var yK=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),fK=new Set(["gpt-5.6","gpt-6"]),mK=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-6-astra"]),cK="opencode-oauth-dummy-key",uK="terminal_resize_reflow",VJ="0.153.0",pK=`codex_exec/${VJ} (Debian 12.0.0; aarch64) unknown (codex_exec; ${VJ})`,lK="seccomp",dK="main-refresh",iK=120000,nK=90000,oK=4000,T4=50,R4=3,rK=25,sK=60000,aK="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",C4=!1,I4=H0("models"),_4=!1,S4=!1;class KJ 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 o0 extends Error{code;constructor(Y,X){super(X);this.name="ResetTargetResolutionError",this.code=Y}}function k4(Y,X,J,Q){let $=(J?.refresh?.refreshBeforeExpiryMinutes??240)*60000;return!Y||!X||X-Q<=$}function tK(Y){return async(X)=>{if(X==="main"){let U=await Y.loadAccounts(Y.accountStoragePath),H=await Y.getAuth();if(H.type!=="oauth")throw new o0("non_oauth_account","Main OpenAI account is not authenticated with OAuth.");if(k4(H.access,H.expires,U,Y.now()))H={type:"oauth",...await Y.refreshMainWithLease()};if(!H.access)throw new o0("token_unavailable","Main OpenAI account has no usable access token.");let L=s1(H.access),V=L?a1(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 o0("unknown_account",`Fallback account ${X} was not found.`);if(Q.enabled===!1)throw new o0("disabled_account",`Fallback account ${X} is disabled.`);if(!r0(Q))throw new o0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);let $=Q;if(k4($.access,$.expires,J,Y.now()))$=await Y.refreshFallbackAccount($,J);if(!$.access)throw new o0("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 o0("unknown_account",`Fallback account ${X} was not found.`);if(W.enabled===!1)throw new o0("disabled_account",`Fallback account ${X} is disabled.`);if(!r0(W))throw new o0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);return{accountKey:X,label:$.label??X,accessToken:$.access,chatgptAccountId:W.accountId}}}function eK(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function HJ(Y){return Y instanceof KJ}function x4(){throw Error(aK)}function YB(Y){return Math.floor(Math.random()*Y)}function XB(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 JB(Y,X,J){let Q=Y.get(X);if(Q)return Q;let $=C1(),G={threadID:$,turnID:C1(),windowID:`${$}:0`};return Y.set(X,G),J?.(),G}function Nz(){return gK(SY(),"openai-auth-sessions.json")}function QB(){let Y=new Map;try{let X=JSON.parse(xK(Nz(),"utf8"));if(!R(X.sessions))return Y;for(let[J,Q]of Object.entries(X.sessions)){if(!R(Q)||typeof Q.threadID!=="string")continue;Y.set(J,{threadID:Q.threadID,turnID:C1(),windowID:`${Q.threadID}:0`})}}catch{}return Y}function $B(Y){let X=Nz(),J=`${X}.tmp-${process.pid}`;try{kK(SY(),{recursive:!0});let Q={version:1,sessions:Object.fromEntries([...Y.entries()].map(([$,G])=>[$,{threadID:G.threadID}]))};hK(J,`${JSON.stringify(Q,null,2)}
218
- `,"utf8"),bK(J,X)}catch{}}function b4(Y,X){return R(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===X}function GB(Y,X){if(Y.length>X.length)return!1;for(let J=0;J<Y.length;J++)if(Q1(Y[J])!==Q1(X[J]))return!1;return!0}function WB(Y,X){if(!Y.input)return X.length>0;if(!GB(Y.input,X))return!0;return X.slice(Y.input.length).some((Q)=>b4(Q,"user")||b4(Q,"developer"))}function zB(Y,X){let J=Array.isArray(X?.input)?X.input:void 0;if(J&&(WB(Y,J)||!Y.turnID))Y.turnID=C1(),Y.turnStartedAt=Date.now();else if(!Y.turnStartedAt)Y.turnStartedAt=Date.now();if(J)Y.input=J}function UB(Y){if(!Y.metadata)return{init:Y.init};let X=XB(Y.init?.body);if(!Y.websocket)zB(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:lK,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",uK),Y.headers.set("x-codex-turn-metadata",J),Y.headers.set("user-agent",pK),Y.headers.set("version",VJ),Y.dumpSessionID)Y.headers.set(H1,Y.dumpSessionID);let Q=X;if(!Q)return{init:Y.init};let $=Y.responsesLite&&typeof Q.model==="string"&&mK.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(OB);if(BB(Q),FB(Q),I8(Q),NB(Q),ZB(Q,Y.metadata),$)KB(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(DY(Q))}}}function LB(Y,X){return Y.find((J)=>J.enabled!==!1&&r0(J)&&(J.id===X||J.accountId===X))}function v4(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 F9(Y,X){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:X}}function Vz(Y,X,J=Date.now(),Q=X.mainAccountId){let $=Y.getMain(),G=$?.quota;return{main:{quota:G?{...G,checkedAt:$.checkedAt,primary:F9(G.primary,$.checkedAt),secondary:F9(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:F9(H.primary,U.checkedAt),secondary:F9(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 iD(Y,X,J,Q=Date.now()){return{...Vz(Y,X,Q),activeId:J}}function h4(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 HB(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 g4(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}function NB(Y){if(!E0().webSearch)return;if(!Array.isArray(Y.tools)||Y.tools.length===0)return;if(Y.tools.some((X)=>R(X)&&X.type==="web_search"))return;Y.tools=[...Y.tools,{type:"web_search",external_web_access:!1,search_content_types:["text","image"]}]}function ZJ(Y){if(Array.isArray(Y)){for(let X of Y)ZJ(X);return}if(!R(Y))return;if(Y.type==="input_image")delete Y.detail;for(let X of Object.values(Y))ZJ(X)}var VB=new Set(["gpt-6-astra"]);function ZB(Y,X){let J=typeof Y.model==="string"?Y.model:"";if(!VB.has(J))return;let Q=R(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 KB(Y){let X=R(Y.reasoning)?{...Y.reasoning}:{};X.context="all_turns",Y.reasoning=X,Y.parallel_tool_calls=!1;let J=Array.isArray(Y.input)?Y.input:[];ZJ(J);let $=[{type:"additional_tools",role:"developer",tools:Array.isArray(Y.tools)?Y.tools.filter((G)=>!(R(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 BB(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(R(X)&&X.type==="function"&&X.name==="web_search"))}function FB(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(R(X)&&X.type==="function"&&X.name==="websearch_web_search_exa"))}function OB(Y){if(!R(Y))return Y;if(Y.type!=="function")return Y;let X=R(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:H,...L}=Y.parameters;return L})():Y.parameters,{type:J,name:Q,description:$,strict:G,parameters:W,...U}=Y;return{type:J,name:Q,description:$,strict:G??!1,parameters:X,...U}}async function jB(Y,X={}){let J=X.codexApiEndpoint??E0().codexApiEndpoint,Q=crypto.randomUUID(),$=QB(),G=()=>$B($),W=!1,U=[],H=null,L=null,V,B=new m9;async function K(N,F){let q=Y.client.session;if(typeof q?.promptAsync==="function"){let A=await g8(Y.client,N),b={noReply:!0,parts:[{type:"text",text:F,ignored:!0}]};if(A?.agent)b.agent=A.agent;if(A?.model)b.model=A.model;if(A?.variant)b.variant=A.variant;await q.promptAsync({path:{id:N},body:b});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 F=N.event.properties.info,q=$.get(F.id);if(q)H?.cacheKeepManager?.remove(q.threadID);if($.delete(F.id))G();if(V){let A=(await D0($0()))?.accounts;await zz(F.id,A,V)}for(let A of U)A.remove(F.id)},provider:{id:"openai",async models(N,F){if(F.auth?.type!=="oauth")return N.models;let q=await D0($0()),A=!q||a4(q),b=A?null:await x8();if(!A&&b&&!_4)_4=!0,I4.debug("restoring OAuth model costs from models.dev catalog");if(!A&&!b&&!S4)S4=!0,I4.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(yK.has(E.api.id))return!0;if(fK.has(E.api.id))return!1;let g=E.api.id.match(/^gpt-(\d+(?:\.\d+)?)/)?.[1];return g?parseFloat(g)>5.4:!1}).map(([E,_])=>[E,{..._,cost:A?{input:0,output:0,cache:{read:0,write:0}}:b?.[_.api.id]??b?.[E]??_.cost,limit:_.id.includes("gpt-5.5")?{context:400000,input:272000,output:128000}:_.id.includes("gpt-6-astra")?{context:872000,input:744000,output:128000}:_.id.includes("gpt-5.6")?{context:372000,input:244000,output:128000}:_.limit}]))}},tool:{web_search:R8},auth:{provider:"openai",async loader(N){let F=await N();if(F.type!=="oauth")return{};await e4({type:"oauth",access:F.access??"",refresh:F.refresh??"",expires:F.expires??0},$0());let q=await D0($0()).catch((Z)=>{let O=$0();throw Error(`OpenAI auth store at ${O} is corrupt or unreadable: ${Z instanceof Error?Z.message:String(Z)}. Fix or remove it to continue.`,{cause:Z})}),A;async function b(){let Z=$0();try{let O=vK(Z);if(A?.path===Z&&A.mtimeMs===O.mtimeMs&&A.size===O.size)return A.storage;let P=await D0(Z);return A={path:Z,mtimeMs:O.mtimeMs,size:O.size,storage:P},P}catch{return A=void 0,D0(Z)}}function E(){A=void 0}if(q&&F.access){let Z=O9({id_token:"",access_token:F.access,refresh_token:F.refresh??""});if(Z&&Z!==q.mainAccountId)await Q0((O)=>{return O.mainAccountId=Z,O},$0()),q.mainAccountId=Z,E()}let _=q?.logging?.level;if(_&&typeof _==="string")vY(_);let g=H0("transport"),p=H0("quota"),F0=H0("refresh"),o=H0("accounts");g.info("codex auth loader ready",{codexApiEndpoint:J,transport:E0().rawWebSocket?"raw-websocket":E0().webSockets?"websocket":"http",webSearch:E0().webSearch});let m=new s4({storage:q,fetchQuotaFn:void 0}),P0,c0=0,U0=new Yz({refreshFn:(Z)=>b1({refreshToken:Z.refreshToken,fetchImpl:Z.fetchImpl,now:Z.now}),quotaManager:m,onFallbackStorageChanged:E});if(q&&q.accounts.length>0)U0.startBackgroundRefresh();let D1=H0("cachekeep"),s0=q?.cachekeep?.enabled===!0,P1=q?.cachekeep?.subagents===!0,a0=q?.cachekeep?.sustain===!0,M=L8(q),c;async function y(Z){await new Promise((O)=>setTimeout(O,Z))}async function Z0(Z){let O;for(let P=1;P<=R4;P++)try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:Z.refresh,access:Z.access,expires:Z.expires}});return}catch(I){if(O=I,P<R4)await y(rK*P)}throw new KJ(O)}async function T0(Z){await Q0((O)=>{return O.refresh=O.refresh??{},Z(O),O},$0()),E()}async function Y0(Z){let O=Date.now()+oK;while(Date.now()<O){await new Promise((x)=>setTimeout(x,T4+YB(T4)));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 F0.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 x0(){if(!c)c=(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 O=y4(Z.refresh),P=await D0($0()),I=P?.refresh?.mainLastRefreshError;if(I&&hY(I,Z.refresh,Date.now()))throw Error(gY(I,Date.now()));if(P?.refresh?.mainRefreshLeaseUntil&&P.refresh.mainRefreshLeaseUntil>Date.now()&&P.refresh.mainRefreshLeaseTokenHash===O){let k=await Y0(Z);if(k)return k;throw Error("Codex OAuth refresh is already in progress")}let x=await yY({name:dK,ttlMs:iK,path:$0(),renew:!0});if(!x){let k=await Y0(Z);if(k)return k;throw Error("Codex OAuth refresh is already in progress")}let S=crypto.randomUUID(),T=O;try{await T0((f)=>{f.refresh=f.refresh??{},f.refresh.mainRefreshLeaseId=S,f.refresh.mainRefreshLeaseUntil=Date.now()+nK,f.refresh.mainRefreshLeaseTokenHash=O});let k=await D0($0());if(k?.refresh?.mainRefreshLeaseId!==S||k.refresh.mainRefreshLeaseTokenHash!==O)throw Error("Codex OAuth refresh is already in progress");let w=await b1({refreshToken:Z.refresh,fetchImpl:fetch,now:Date.now});return await Z0(w),await T0((f)=>{if(f.refresh=f.refresh??{},f.refresh.mainLastRefreshError=void 0,f.refresh.mainRefreshLeaseId===S)f.refresh.mainRefreshLeaseId=void 0,f.refresh.mainRefreshLeaseUntil=void 0,f.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),T=void 0,w}catch(k){if(Z.refresh&&!HJ(k))await T0((w)=>{w.refresh=w.refresh??{},w.refresh.mainLastRefreshError=f4({error:k,now:Date.now(),refreshToken:Z.refresh??"",previous:w.refresh.mainLastRefreshError})}).catch(()=>{});throw k}finally{if(T)await T0((k)=>{if(k.refresh?.mainRefreshLeaseId===S&&k.refresh.mainRefreshLeaseTokenHash===T)k.refresh.mainRefreshLeaseId=void 0,k.refresh.mainRefreshLeaseUntil=void 0,k.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await x.release().catch(()=>{})}})().finally(()=>{c=void 0});return c}let l=globalThis;l.__openaiAuthCacheKeepManager?.stop();let R0=new d9({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 x0()).access}catch(O){if(HJ(O))throw O;if(Z.access)return Z.access;throw Error("main token refresh failed")}return Z.access},refreshFallback:async(Z)=>{let O=await b(),P=O?LB(O.accounts,Z):void 0;if(!P)throw Error(`fallback account ${Z} not found`);let I=await U0.refreshAccount(P,O??{version:1,accounts:[P]});if(!I.access)throw Error(`no access token for ${Z}`);return I.access},codexResponsesUrl:J,logger:D1,now:Date.now,getWindow:()=>M,getSustain:()=>a0});l.__openaiAuthCacheKeepManager=R0;async function M1(Z,O,P,I,x=!1){if(Object.keys(Z).length===0&&!x)return;let S=Date.now(),T=Z,k={quota:T,refreshAfter:S+300000,checkedAt:S},w;if(P&&P!=="main"){let v=O?s1(O):null,J0=v?a1(v):void 0,O0=m.peekFallbackForPolicy(P)?.quota,l0=v4(T,O0);k={...k,quota:l0},m.setFallback(P,k,O,x,J0)}else{if(w=I,!w&&O){let O0=s1(O);w=O0?a1(O0):void 0}if(w&&P0&&w!==P0){p.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:w,currentMainIdentity:P0});return}let v=m.peekMainForPolicy(w)?.quota,J0=v4(T,v);k={...k,quota:J0},m.setMain(O,k,w,x)}p.debug("quota pushed",{pid:process.pid,accountId:P??"main",snapshot:k.quota});let f=await b();await u0(m,f,P&&P!=="main"?f?.mainAccountId:w)}function q9(Z,O,P){let I=Z==="main"?m.peekMainForPolicy()?.quota:m.peekFallbackForPolicy(Z)?.quota;return r4(I,O,Date.now(),sK,P)}let t0=X.experimentalWebSockets?q1.createWebSocketFetch({httpFetch:fetch,rawWebSocket:E0().rawWebSocket,onQuota:(Z,O,P,I)=>{M1(Z,O,P,!P||P==="main"?I:void 0,!0)},onRateLimitReached:(Z,O,P)=>{if(!O)p.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:Z});let I=O??"main",x=q9(I,Z,P);m.markRateLimited(I,x),p.debug("mid-stream rate limit mark",{pid:process.pid,accountId:I,window:Z})}}):void 0;if(t0)U.push(t0),W=!0;let M0=Xz();V=M0;async function u0(Z,O,P=O?.mainAccountId){if(!O)return;await Gz(Vz(Z,O,Date.now(),P),M0)}async function p0(Z,O,P,I,x){let S={activeId:P,route:I,updatedAt:Date.now()};if(Z){if(await j9({sessionId:Z,...S},x,M0),O&&O!==Z){if(I==="sticky-balanced"){let T=(await R1(M0)).stickyAssignments?.[AY(O)]?.accountId,k=x===void 0||T==="main"||x.some((w)=>w.enabled!==!1&&w.id===T);if(!T||!k)return;await j9({sessionId:O,activeId:T,route:I,updatedAt:Date.now()},x,M0);return}await j9({sessionId:O,...S},x,M0)}return}await Wz(S,M0)}H={accountStoragePath:$0(),quotaManager:m,loadAccounts:D0,client:Y.client,resolveResetTarget:tK({getAuth:N,refreshMainWithLease:x0,refreshFallbackAccount:(Z,O)=>U0.refreshAccount(Z,O),loadAccounts:D0,accountStoragePath:$0(),now:Date.now}),...eK(),cacheKeepManager:R0,setCacheKeepEnabled:(Z)=>{s0=Z},setCacheKeepSubagents:(Z)=>{P1=Z},setCacheKeepSustain:(Z)=>{a0=Z},setCacheKeepWindow:(Z)=>{M=Z},clearStickyRouting:(Z)=>Lz(Z,M0),getStickyRouting:async(Z)=>$z(await R1(M0),Z),refreshSidebar:async()=>{let Z=await D0($0());await u0(m,Z)},refreshAllQuota:async()=>y1({getAuth:N,codexRefreshFn:b1,refreshMainWithLease:x0,fallbackManager:U0,quotaManager:m,loadAccounts:D0,writeSidebarState:u0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:$0(),storageMainAccountId:q?.mainAccountId,isOAuthAccountFn:r0,whamFn:L1}),refreshResetTargetQuota:async(Z)=>{return(await y1({getAuth:N,codexRefreshFn:b1,refreshMainWithLease:x0,fallbackManager:U0,quotaManager:m,loadAccounts:D0,writeSidebarState:u0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:$0(),storageMainAccountId:q?.mainAccountId,isOAuthAccountFn:r0,whamFn:L1,respectBackoff:!1},{accountKey:Z})).find((P)=>P.account===Z)??{account:Z,ok:!1,error:"targeted quota refresh returned no result"}}};let v1=null;if(Y.directory){let Z=await Hz(Y.directory),O=globalThis;if(O.__openaiAuthRpcServer)await O.__openaiAuthRpcServer.stop().catch(()=>{}),O.__openaiAuthRpcServer=void 0;try{v1=await l8({dir:Z.dir,secureDir:Z.secureDir,sweepRoot:Z.sweepRoot,drain:f8,apply:async(P)=>{let I={...H,sessionId:P.sessionId},x=await y9(P.command,P.arguments,I);return{text:x.text,knobs:x.knobs}}}),O.__openaiAuthRpcServer=v1,L=v1}catch{}}async function a(Z,O,P,I,x="main"){let S=h4(Z,O);if(S.delete("x-api-key"),S.delete("api-key"),S.set("authorization",`Bearer ${P}`),I)S.set("ChatGPT-Account-Id",I);S.set(q1.QUOTA_ACCOUNT_HEADER,x);let T=g4(S),k=T?JB($,T,G):void 0,w=Z instanceof URL?Z:new URL(typeof Z==="string"?Z:Z.url),f=w.pathname.includes("/v1/responses")||w.pathname.includes("/chat/completions")?new URL(J):w,J0=UB({init:{...O,headers:S},headers:S,metadata:k,installationID:Q,websocket:Boolean(t0&&w.pathname.endsWith("/responses")),responsesLite:X.responsesLite??!1,dumpSessionID:T}).init,O0=s0,l0=new Headers(J0?.headers),W0=U8({enabled:O0,includeSubagents:P1,headers:l0,body:J0?.body});if(O0)D1.trace("cachekeep headers",{pid:process.pid,hasParent:l0.has("x-parent-session-id"),sessionKey:W0?.sessionKey,captured:Boolean(W0),affinity:l0.get("x-session-affinity"),opencodeSession:l0.get("x-opencode-session"),sessionId:l0.get("session-id")});if(t0&&w.pathname.endsWith("/responses")){if(g.debug("WS transport",{pid:process.pid,pathname:w.pathname,accountId:x}),W0)R0.track(W0.sessionKey,W0.bodyText,x,I,W0.replayHeaders,W0.isSubagent);return t0(f,J0)}let K0=q1.withoutInternalHeaders(J0);if(typeof K0?.body!=="string")return fetch(f,K0);if(W0)R0.track(W0.sessionKey,W0.bodyText,x,I,W0.replayHeaders,W0.isSubagent);g.debug("HTTP transport",{pid:process.pid,pathname:w.pathname,accountId:x});try{let v0=await fetch(f,K0);return await c1({sessionID:T,transport:"http",phase:"http",bodyText:K0.body,accountId:x,url:f.toString(),method:K0.method,headers:K0.headers,status:v0.status}),C8(v0)}catch(v0){throw await c1({sessionID:T,transport:"http",phase:"http",bodyText:K0.body,accountId:x,url:f.toString(),method:K0.method,headers:K0.headers,error:v0 instanceof Error?v0.message:String(v0)}),v0}}function b0(Z,O){if((O?.method??(Z instanceof Request?Z.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof O?.body!=="string")return!1;try{let I=Z instanceof URL?Z.toString():typeof Z==="string"?Z:Z.url;return new URL(I).pathname.endsWith("/responses")}catch{return!1}}function D9(Z){return m.peekMainForPolicy(Z)?.quota}function BJ(Z,O){for(let P of[Z?.primary?.checkedAt,Z?.secondary?.checkedAt,Z?.checkedAt,O])if(typeof P==="number"&&Number.isFinite(P))return P;return}function t1(Z,O,P,I,x){let S=BJ(Z,O),T=BJ(P),k=I===x&&P!=null&&(Z===void 0||T!==void 0&&(S===void 0||T>S));return{quota:k?P:Z,quotaCheckedAt:k?T:S,source:k?"file":"memory"}}function FJ(Z,O,P,I,x){let S=Z?.quota,T=t1(S,Z?.checkedAt,O,I,x),k=T.source,w=T.quota;if(!Qz(w,P))return{exhausted:!1};let f=Jz(w,P);if(!f)return{exhausted:!1};return{exhausted:!0,source:k,...f}}function OJ(Z,O){p.debug("admission skip: exhausted account",{accountId:Z,source:O.source,resetsAt:O.resetsAt})}function Zz(Z,O="killswitch",P){let I=Date.now(),x=m.getMain()?.quota,S=(Z?.accounts??[]).filter((v)=>v.enabled!==!1&&r0(v)).map((v)=>({accountId:v.id,quota:m.getFallback(v.id)?.quota})),T=t4(x,S,I,Z);if(O==="quota-exhausted"&&P!==void 0)T=Math.max(1,Math.ceil((P-I)/1000));else if(O==="mid-stream-rate-limit"&&P!==void 0){let v=Math.max(1,Math.ceil((P-I)/1000));T=Math.min(T,v)}let k=Math.floor(T/60),w=T%60,f=O==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${k}m ${w}s.`:O==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${k}m ${w}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${k}m ${w}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 jJ(Z){let O=Z?.resetCreditsAvailable;return typeof O==="number"&&Number.isFinite(O)?O:void 0}async function Kz(Z){let O=EY(Z.storage),P=Date.now(),I=m.peekMainForPolicy(Z.mainAccountIdentity),x=t1(I?.quota,I?.checkedAt,Z.sidebarState.main.quota,Z.sidebarState.main.mainAccountId,Z.mainAccountIdentity),S=O?wY(I?.quota,Z.storage,void 0,P):void 0,T=[{accountId:"main",wireAccountId:Z.mainAccountIdentity,access:Z.primaryAccess,keepwarmAccountKey:"main",quota:x.quota,quotaCheckedAt:x.quotaCheckedAt,reservePercent:NJ(Z.storage),configuredOrder:0,resetCreditsApplicable:jJ(x.quota),killswitchPasses:S}],k=await U0.getUsableFallbackAccounts(Z.storage);for(let w of k){if(!w.access)continue;let f=Z.sidebarState.fallbacks.find((l0)=>l0.id===w.id),v=m.peekFallbackForPolicy(w.id,w.accountId),J0=t1(v?.quota,v?.checkedAt,f?.quota,f?.accountId,w.accountId),O0=O?wY(v?.quota,Z.storage,w.id,P):void 0;T.push({accountId:w.id,wireAccountId:w.accountId,access:w.access,keepwarmAccountKey:w.id,fallback:w,quota:J0.quota,quotaCheckedAt:J0.quotaCheckedAt,reservePercent:NJ(Z.storage,w.id),configuredOrder:T.length,resetCreditsApplicable:jJ(J0.quota),killswitchPasses:O0})}return T}function qJ(Z,O,P,I,x){let S=EY(x)?Z.killswitchPasses:void 0;if(Z.accountId==="main"){let f=m.peekMainForPolicy(Z.wireAccountId),v=t1(f?.quota,f?.checkedAt,O.main.quota,O.main.mainAccountId,Z.wireAccountId);return o9({quota:v.quota,quotaCheckedAt:v.quotaCheckedAt,status:P,now:I,killswitchPasses:S})}let T=O.fallbacks.find((f)=>f.id===Z.accountId),k=m.peekFallbackForPolicy(Z.accountId,Z.wireAccountId),w=t1(k?.quota,k?.checkedAt,T?.quota,T?.accountId,Z.wireAccountId);return o9({quota:w.quota,quotaCheckedAt:w.quotaCheckedAt,status:P,now:I,killswitchPasses:S})}function Bz(Z){return Z.accountId==="main"?"main":Z.keepwarmAccountKey}function DJ(Z){return m.isRateLimited(Bz(Z))}async function P9(Z){let O=Z.candidates.filter((w)=>!DJ(w)),P=new Map(O.map((w)=>[w.accountId,w])),I=Object.fromEntries(O.map((w)=>[w.accountId,w.quotaCheckedAt])),x=Object.fromEntries(O.map((w)=>[w.accountId,w.wireAccountId])),S=new Set(Z.excludeAccountIds),T,k=await Uz({sessionId:Z.sessionId,requestBytes:Z.requestBytes,now:Z.now,validPinnedAccountIds:[...P.keys()],excludeAccountIds:Z.excludeAccountIds,quotaCheckedAtByAccount:I,wireAccountIdByAccount:x,choose:(w)=>{let f=O.filter((J0)=>!S.has(J0.accountId));if(f.length===0)return;let v=F8({candidates:f,pendingBytes:w,requestBytes:Z.requestBytes,now:Z.now,onEmptyWeightedSet:()=>{o.debug("sticky routing: no fresh weighted candidates; using configured order")}});if(!v)return;return T={accountId:v.accountId,source:v.source,pendingBytes:w.get(v.accountId)??0},v}},M0);if(T&&k?.accountId===T.accountId)o.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:AY(Z.sessionId),accountId:T.accountId,source:T.source,requestBytes:Z.requestBytes,pendingBytes:T.pendingBytes});return k?P.get(k.accountId):void 0}async function Fz(Z,O){let P=await U0.getUsableFallbackAccounts(Z),I=[];for(let v of P)if(v.access)I.push({access:v.access,accountId:v.accountId,keepwarmAccountKey:v.id,quotaAccountId:v.id,fallback:v});let x=I.filter((v)=>!m.isRateLimited(v.quotaAccountId)),S=EY(Z)?x.filter((v)=>wY(m.peekFallbackForPolicy(v.quotaAccountId,v.accountId)?.quota,Z,v.quotaAccountId,Date.now())):x,T=new Map(O.fallbacks.map((v)=>[v.id,{quota:v.quota,accountId:v.accountId}])),k=[],w=[],f=Date.now();for(let v of S){let J0=T.get(v.quotaAccountId),O0=FJ(m.peekFallbackForPolicy(v.quotaAccountId,v.accountId),J0?.quota,f,J0?.accountId,v.accountId);if(O0.exhausted)w.push({candidate:v,decision:O0});else k.push(v)}return{current:S,retained:k,skipped:w}}function PJ(Z,O){if(Z.retained.length===0&&!O)return Z.current;for(let{candidate:P,decision:I}of Z.skipped)OJ(P.quotaAccountId,I);return Z.retained}async function MJ(Z,O){try{let P=f1(Z.headers);await M1(P,O.access,O.quotaAccountId,void 0,PY(Z.headers))}catch{}}async function Oz(Z,O,P,I){for(let x of I){let S;try{S=await a(Z,O,x.access,x.accountId,x.keepwarmAccountKey)}catch(T){if(T instanceof DOMException&&T.name==="AbortError")throw T;if(O?.signal?.aborted)throw T;throw o.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:x.quotaAccountId}),T}if(!MY(S.status,P))return U0.markUsed(x.fallback),{response:S,accessToken:x.access,quotaAccountId:x.quotaAccountId,activeId:x.keepwarmAccountKey};await MJ(S,x),S.body?.cancel().catch(()=>{})}return}async function jz(Z,O,P,I,x){if(!b0(Z,O))return{response:P};if(!x.length)return{response:P};let S=P,T;for(let k of x){let w;try{w=await a(Z,O,k.access,k.accountId,k.keepwarmAccountKey)}catch(f){if(f instanceof DOMException&&f.name==="AbortError")throw f;if(O?.signal?.aborted)throw f;return o.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:k.quotaAccountId}),{response:S,...T}}if(S.body?.cancel().catch(()=>{}),S=w,T={accessToken:k.access,accountId:k.quotaAccountId},!MY(w.status,I))return U0.markUsed(k.fallback),{response:w,...T};await MJ(w,k)}return{response:S,...T}}if(!C4){if(C4=!0,q){let Z=[];for(let O of q.accounts)if(r0(O))Z.push(O);m.seedFallbacksFromAccounts(Z)}u0(m,q).catch(()=>{}),y1({getAuth:N,codexRefreshFn:b1,refreshMainWithLease:x0,fallbackManager:U0,quotaManager:m,loadAccounts:D0,writeSidebarState:u0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:$0(),storageMainAccountId:q?.mainAccountId,isOAuthAccountFn:r0,whamFn:L1,respectBackoff:!0}).catch((Z)=>p.warn("boot quota seed failed",{pid:process.pid,error:X1(Z)}))}return B.start(async()=>{let O=(await Q8({getAuth:N,codexRefreshFn:b1,refreshMainWithLease:x0,fallbackManager:U0,quotaManager:m,loadAccounts:D0,writeSidebarState:(P,I)=>B.isStopped()?Promise.resolve():u0(P,I),client:Y.client,fetchImpl:fetch,now:Date.now,configPath:$0(),storageMainAccountId:q?.mainAccountId,isOAuthAccountFn:r0,whamFn:L1,readSidebarState:()=>R1(M0)})).filter((P)=>!P.ok);if(O.length>0)p.warn("background quota refresh completed with failures",{pid:process.pid,failures:O})},(Z)=>{p.warn("background quota refresh failed",{pid:process.pid,error:Z instanceof Error?Z.message:String(Z)})}),{apiKey:cK,async fetch(Z,O){let P=h4(Z,O),I=g4(P),x=P.get("x-parent-session-id")?.trim()||void 0,S=await b(),T=await N(),k=++c0;if(T.type!=="oauth")return fetch(Z,O);O=await HB(Z,O);let w=T.access??"";if(!T.access||(T.expires??0)<Date.now()){F0.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(T.access),expiresInMs:T.expires?T.expires-Date.now():void 0});try{let X0=await x0();T.access=X0.access,T.refresh=X0.refresh,T.expires=X0.expires}catch(X0){if(HJ(X0))throw X0}}w=T.access??"";let v=T.accountId??(w?a1(s1(w)??{}):void 0);if(k===c0)P0=v;let J0=S?.routing?.mode??"main-first",O0,W0=await(()=>{return O0??=R1(M0),O0})();if(J0==="sticky-balanced"&&I&&b0(Z,O)&&typeof O?.body==="string"){let X0=Buffer.byteLength(O.body,"utf8"),N0=await Kz({storage:S,sidebarState:W0,primaryAccess:w,mainAccountIdentity:v}),L0=await P9({sessionId:I,requestBytes:X0,candidates:N0,now:Date.now()});if(L0){let IJ=DJ(L0)?{action:"migrate",reason:"exhausted"}:qJ(L0,W0,void 0,Date.now(),S);if(IJ.action==="migrate"){let C0=await P9({sessionId:I,requestBytes:X0,candidates:N0,excludeAccountIds:[L0.accountId],now:Date.now()});if(C0)o.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:AY(I),fromAccountId:L0.accountId,toAccountId:C0.accountId,reason:IJ.reason}),L0=C0}let d0=await a(Z,O,L0.access,L0.wireAccountId,L0.keepwarmAccountKey),_J=async(C0,E1)=>{try{let qz=f1(C0.headers);await M1(qz,E1.access,E1.accountId==="main"?void 0:E1.accountId,E1.accountId==="main"?E1.wireAccountId:void 0,PY(C0.headers))}catch{}};await _J(d0,L0);let SJ=qJ(L0,W0,d0.status,Date.now(),S);if((d0.status===401||d0.status===403||d0.status===429)&&SJ.action==="migrate"){let C0=await P9({sessionId:I,requestBytes:X0,candidates:N0,excludeAccountIds:[L0.accountId],now:Date.now()});if(C0){o.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:AY(I),fromAccountId:L0.accountId,toAccountId:C0.accountId,reason:SJ.reason});let E1=d0;d0=await a(Z,O,C0.access,C0.wireAccountId,C0.keepwarmAccountKey),E1.body?.cancel().catch(()=>{}),L0=C0,await _J(d0,L0)}}if(L0.fallback&&!MY(d0.status,S))U0.markUsed(L0.fallback);return await p0(I,x,L0.accountId,J0,S?.accounts).catch(()=>{}),d0}}let K0=FJ(m.peekMainForPolicy(v),W0.main.quota,Date.now(),W0.main.mainAccountId,v),v0=EY(S)&&!wY(D9(v),S,void 0,Date.now()),TY=m.isRateLimited("main"),EJ,M9=()=>{return EJ??=Fz(S,W0),EJ},e0,h1,wJ=!1,RY;if(J0==="fallback-first"&&b0(Z,O)){wJ=!0;let X0=await M9();RY=PJ(X0,!v0&&!TY&&!K0.exhausted);let N0=await Oz(Z,O,S,RY);if(N0)e0=N0.response,h1={accessToken:N0.accessToken,accountId:N0.quotaAccountId,activeId:N0.activeId}}if(!e0){let X0=K0.exhausted&&b0(Z,O)&&(await M9()).retained.length>0;if(v0||TY||X0){let N0=v0?"killswitch":TY?"mid-stream-rate-limit":"quota-exhausted";if(N0==="quota-exhausted"&&K0.exhausted)OJ("main",K0);o.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:N0}),e0=Zz(S,N0,N0==="quota-exhausted"&&K0.exhausted?K0.resetAtMs:TY?m.rateLimitedUntil("main"):void 0)}else e0=await a(Z,O,w,v,"main")}let AJ=Boolean(h1),e1=e0,TJ=h1?.accessToken??w,RJ=h1?.accountId,CJ=h1?.activeId??"main";if(!h1&&!wJ&&MY(e0.status,S)){o.debug("reactive fallback triggered",{pid:process.pid,status:e0.status}),RY??=PJ(await M9(),!1);let X0=await jz(Z,O,e0,S,RY),N0=X0.response;if(N0!==e0){if(AJ=!0,e1=N0,TJ=X0.accessToken??w,RJ=X0.accountId,X0.accountId)CJ=X0.accountId}}try{let X0=f1(e1.headers);if(AJ)await M1(X0,TJ,RJ,void 0,PY(e1.headers));else await M1(X0,w,void 0,v,PY(e1.headers))}catch{}return await p0(I,x,CJ,J0,S?.accounts).catch(()=>{}),e1},async dispose(){if(B.stop(),R0.stop(),l.__openaiAuthCacheKeepManager===R0)l.__openaiAuthCacheKeepManager=void 0;if(U0.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 d4(),F=await u4(),q=c4(crypto.getRandomValues(new Uint8Array(32)).buffer),A=p4(N,F,q),b=i4(F,q);return{url:A,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let E=await b,_=O9(E);return{type:"success",refresh:E.refresh_token,access:E.access_token,expires:Date.now()+(E.expires_in??3600)*1000,accountId:_}}finally{l4(q)}}}}},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:async()=>{let{deviceData:N,url:F,instructions:q}=await n4();return{url:F,instructions:q,method:"auto",async callback(){try{let A=await o4(N);return{type:"success",refresh:A.refresh_token,access:A.access_token,expires:Date.now()+(A.expires_in??3600)*1000,accountId:O9(A)}}catch{return{type:"failed"}}}}}},{label:"Manually enter API Key",type:"api"}]},"chat.headers":async(N,F)=>{if(N.model.providerID!=="openai")return;if(F.headers.originator="opencode",F.headers["User-Agent"]=`${m4} (${LJ.platform()} ${LJ.release()}; ${LJ.arch()})`,F.headers["session-id"]=N.sessionID,W&&N.agent==="title")F.headers[q1.TITLE_HEADER]="true"},"chat.params":async(N,F)=>{if(N.model.providerID!=="openai")return;F.maxOutputTokens=void 0},config:async(N)=>{N.command={...N.command??{},[S9]:{template:S9,description:"Show current OpenAI Codex OAuth quota usage for all accounts."},[k9]:{template:k9,description:"Manage OpenAI accounts — add, switch, remove, or reorder."},[x9]:{template:x9,description:"Show or change OpenAI account routing between main-first, fallback-first, and sticky-balanced."},[b9]:{template:b9,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."},[v9]:{template:v9,description:"Show or toggle OpenAI Codex request dump capture for debugging."},[h9]:{template:h9,description:"Show or change the plugin log level (error, warn, info, debug, trace)."},[g9]:{template:g9,description:"Keep Codex prompt cache alive during idle by shadow-replaying the last request."},[T1]:{template:T1,description:"Spend one reset credit on an exhausted Codex account."}}},"command.execute.before":async(N)=>{if(!X8.includes(N.command))return;if(!H)await K(N.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),x4();let F=N.command,q={...H,sessionId:N.sessionID,notify:(b)=>{GX(b,N.sessionID)}},A=await y9(F,N.arguments,q);if(m8(N.sessionID))GX(A,N.sessionID);else await K(N.sessionID,A.text);x4()}}}var qB=async(Y)=>{let X=E0();return jB(Y,{codexApiEndpoint:X.codexApiEndpoint,experimentalWebSockets:X.webSockets,responsesLite:X.responsesLite})},nD={id:"cortexkit-openai-auth",server:qB};export{g4 as resolveSidebarSessionId,s1 as parseJwtClaims,v4 as mergePushedQuotaMetadata,LB as findCachekeepFallbackAccount,a1 as extractAccountIdFromClaims,nD as default,tK as createResetTargetResolver,iD as buildSidebarState,Vz as buildSidebarMachineState,eK as buildResetRedemptionDeps,o0 as ResetTargetResolutionError,qB as OpenAIAuthPlugin,iK as MAIN_REFRESH_LOCK_TTL_MS,nK as MAIN_REFRESH_LEASE_TTL_MS,jB as CodexAuthPlugin,KJ as AuthPersistError};
122
+ `)),K=!0,u=Date.now(),R!==void 0)S++;if(L.length<F)L.push(String(n.type));if(n.type==="response.created")R=Qq(n),WX.debug("response created",{...j,responseID:R,previousResponseID:N,hasContinuation:N!==void 0});if(!$q(n.type))Z=!0;if(W0("idle timeout waiting for websocket"),!n)return;if(n.type==="response.completed"||n.type==="response.done"){G=!0,eB(n,I),Y.onComplete?.(n,I),Y.onTerminal?.(n),f();return}if(n.type==="response.failed"||n.type==="response.incomplete"||n.type==="error")G=!0,Y.onTerminal?.(n),f()}function u0(B){t(new m0(t9(B),{cause:B}))}function z1(B){if(G)return;let D=B.code===1009,w=new m0(D?nz:rz("WebSocket closed before response.completed",B.code,B.reason),{retryable:!D});if(D)WX.warn("websocket peer refused the request size",{...j,requestBytes:W,reason:B.reason.toString()});t(D?dz(w):w)}function c(){let B=d8(Y.signal);if(G)return;G=!0,E(),b(),Y.onAbort?.(B),Q?.error(B)}function M(B){if(G)return;G=!0,E(),b(),Y.onAbort?.(Xq(B))}function A(B){$(),J=B,J.addEventListener("message",F0),J.addEventListener("error",u0,{once:!0}),J.addEventListener("close",z1,{once:!0}),$=()=>{J.removeEventListener("message",F0),J.removeEventListener("error",u0),J.removeEventListener("close",z1)};let{background:D,...w}=Y.body;W0("idle timeout sending websocket request");try{let m=JSON.stringify({type:"response.create",...w});W=m.length,J.send(m),W0("idle timeout waiting for websocket")}catch(m){if(G)return;o(new m0(m instanceof Error?m.message:String(m),{cause:m}))}}return new Response(new ReadableStream({start(B){if(Q=B,Y.signal?.addEventListener("abort",c,{once:!0}),Y.signal?.aborted){c();return}A(J)},cancel(B){M(B)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function sB(Y,X){if(!aB(Y))return;await N1({component:"ws",event:"provider_native_web_search_event",sessionID:X,serverEventType:Y.type,itemType:h(Y.item)?Y.item.type:void 0,serverEvent:Y})}function aB(Y){if(typeof Y.type==="string"&&(Y.type.startsWith("response.web_search_call.")||Y.type.startsWith("response.web_search_preview_call.")))return!0;if(h(Y.item)&&typeof Y.item.type==="string")return Y.item.type==="web_search_call"||Y.item.type==="web_search_preview_call";return!1}function tB(Y,X){if(Y.type!=="response.output_item.done")return;if(!h(Y.item))return;iz(Y.item,X)}function eB(Y,X){let J=Y.response;if(!h(J)||!Array.isArray(J.output))return;for(let Q of J.output)if(h(Q))iz(Q,X)}function iz(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 Yq(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:h(Y.headers)?Object.fromEntries(Object.entries(Y.headers).flatMap(([Q,$])=>typeof $==="string"||typeof $==="number"||typeof $==="boolean"?[[Q,String($)]]:[])):void 0,body:X,message:h(Y.error)&&typeof Y.error.message==="string"?Y.error.message:`${J}`}}function a9(Y){if(typeof Y==="string")try{return a9(JSON.parse(Y))}catch{return}if(!h(Y))return;let X=a9(Y.cause);if(X)return X;let J=a9(Y.body);if(J)return J;let Q=h(Y.error)?Y.error:Y,$=typeof Q.type==="string"?Q.type:void 0,G=Y.status??Y.status_code;if($!=="usage_limit_reached"&&G!==429)return;let{resets_at:W,resets_in_seconds:K}=Q,Z=typeof W==="number"&&Number.isFinite(W)&&W>0?W*1000:typeof K==="number"&&Number.isFinite(K)&&K>0?Date.now()+K*1000:void 0;return{window:$??"primary",resetAt:Z}}function Xq(Y){if(i8(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function d8(Y){let X=Y?.reason;if(i8(X))return X;if(Jq(X))return X;return new DOMException(X instanceof Error?X.message:"Aborted","AbortError")}function Jq(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function Qq(Y){let X=Y.response;if(!h(X))return;return typeof X.id==="string"?X.id:void 0}function $q(Y){return Y==="response.created"||Y==="response.in_progress"||Y.startsWith("codex.")}var oz="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.",nz="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 rz(Y,X,J){let Q=[`code ${X}`];if(J.length>0)Q.push(J.toString());return`${Y} (${Q.join(": ")})`}var n8="x-opencode-title",zX="x-openai-auth-quota-account",o8=new Set([n8,w1,zX,"x-opencode-session"]),Wq=15000,zq=300000,Kq=3300000,sz="websocket_connection_limit_reached";function Uq(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 Gq("sha256").update(Q).digest("hex").slice(0,12)}function Zq(Y){let X=Y?.httpFetch??globalThis.fetch,J=new Map,Q=Y?.connectTimeout??Wq,$=Y?.idleTimeout??zq,G=Y?.maxConnectionAge??Kq,W=Y?.streamRetries??5,K=Y?.firstEventGraceMs??250,Z=Y?.rawWebSocket??!1,U=Y?.onQuota,L=Y?.onRateLimitReached,F=setInterval(()=>R(),Math.min($,60000));if(typeof F==="object"&&"unref"in F&&typeof F.unref==="function")F.unref();function N(I,E,b){if(!E||!b)return b;r8(I,az(E));let f=new Headers(b.headers),o=f.get("x-codex-turn-metadata");if(!o)return b;let t=GK(o,I.turnID,I.turnStartedAt);if(!t)return b;return f.set("x-codex-turn-metadata",t),{...b,headers:f}}async function V(I,E){let b=I instanceof URL?I.toString():typeof I==="string"?I:I.url,f=_0.normalizeHeaders(E?.headers),o=KK(E),t=IY(o);if(E?.method!=="POST"||!new URL(b).pathname.endsWith("/responses"))return X(I,t);let N0=(()=>{try{if(typeof E?.body!=="string")return;let D=JSON.parse(E.body);return typeof D==="object"&&D!==null?D:void 0}catch{return}})();if(!N0?.stream)return X(I,t);if(f[n8]==="true")return X(I,t);let W0=f[w1]??f["x-session-affinity"]??f["session-id"],F0=W0;if(!W0)return X(I,t);let u0=_0.normalizeHeaders(o?.headers),z1=Uq(u0),c=`${W0}:${z1}:conversation`,M=typeof f[zX]==="string"?f[zX]:void 0,A=L?(D,w)=>L(D,M,w):void 0,B=J.get(c)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};if(J.set(c,B),B.fallback)return X(I,N(B,N0,t));if(B.busy)return X(I,N(B,N0,t));B.busy=!0,B.lastUsedAt=Date.now();try{let D=az(N0),w=_0.normalizeHeaders(o?.headers),m=typeof w.authorization==="string"&&w.authorization.startsWith("Bearer ")?w.authorization.slice(7):"",p=typeof w["chatgpt-account-id"]==="string"?w["chatgpt-account-id"]:void 0,n=U?(Q0)=>U(Q0,m,M,p):void 0,z0=!B.socket&&!B.continuation?jq(w):w;if(B.socket=await Nq(B,Y?.url??b,z0,Q,G,Z,E?.signal),Mq(B,D))await Bq(B,D,$,{signal:E?.signal??void 0,sessionID:F0,url:Y?.url??b,headers:o?.headers,onRateLimitReached:A});let r=()=>{},v0=()=>{},K1=new Promise((Q0,T0)=>{r=Q0,v0=T0}),A0=Eq(B,D),s1=e9($K(B,A0,D)),X1=typeof s1.previous_response_id==="string";await $9({sessionID:F0,transport:"websocket",phase:"main",bodyText:JSON.stringify(s1),url:Y?.url??b,method:o?.method,headers:o?.headers});let J0=_0.streamResponsesWebSocket({socket:B.socket,body:s1,sessionID:F0??void 0,idleTimeout:$,signal:E?.signal??void 0,onQuota:n,onRateLimitReached:A,onFirstEvent:(Q0)=>r(Q0??!0),onComplete:(Q0,T0)=>{let g1=YK(Q0);N1({component:"ws-pool",event:"main_completed",sessionID:F0,responseID:ez(Q0),usage:g1}),QK(B,D,Q0,T0,X1)},onTerminal:(Q0)=>{if(B.busy=!1,B.lastUsedAt=Date.now(),B.streamFailures=0,Q0.type!=="response.completed"&&Q0.type!=="response.done")B.continuation=void 0,D1(B)},onConnectionInvalid:(Q0)=>{if(B.busy=!1,B.lastUsedAt=Date.now(),_0.isOversizedFrame(Q0))B.fallback=!0;if(!B.fallback)j(B);B.continuation=void 0,D1(B),r(!1)},onAbort:(Q0)=>{B.busy=!1,B.lastUsedAt=Date.now(),B.streamFailures=0,B.continuation=void 0,D1(B),v0(Q0)},onRetryableTerminal:async(Q0)=>{let T0=tz(Q0);if(!T0)return;throw B.fallback=!0,T0}}),o0=await Lq(K1,K);if(o0!==!1){if(o0===!0||o0.status<200||o0.status>599)return J0;return new Response(o0.body,{status:o0.status,headers:{"content-type":"application/json",...o0.headers}})}let V9=()=>X(I,N(B,N0,t));if(!B.fallback)return Hq(J0,V9);return V9()}catch(D){if(B.busy=!1,B.lastUsedAt=Date.now(),_0.isAbortError(D))throw B.streamFailures=0,B.continuation=void 0,D1(B),D;let w=_0.parseRateLimitSignal(D);if(w)A?.(w.window,w.resetAt);if(_0.isUpgradeFailure(D)&&!Z)B.fallback=!0;if(j(B),B.continuation=void 0,D1(B),B.fallback)return X(I,N(B,N0,t));return Vq(new m0(D instanceof Error?D.message:String(D),{cause:D}))}}function j(I){if(I.streamFailures++,I.streamFailures>W)I.fallback=!0}function R(){let I=Date.now();for(let[E,b]of J){if(b.busy)continue;if(I-b.lastUsedAt<$)continue;D1(b),J.delete(E)}}function S(){clearInterval(F);for(let I of J.values())D1(I);J.clear()}function u(I){let E=`${I}:`;for(let[b,f]of J){if(!b.startsWith(E))continue;D1(f),J.delete(b)}}return Object.assign(V,{close:S,remove:u})}function tz(Y){if(Y.type!=="error"||!h(Y.error)||Y.error.code!==sz)return;return Error(typeof Y.error.message==="string"?Y.error.message:sz)}async function Lq(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 Hq(Y,X){let J=Y.body;if(!J)return Y;let Q=!1,$=new ReadableStream({async start(G){let W=J.getReader(),K=async(Z)=>{while(!0){let{done:U,value:L}=await Z.read();if(U)return;if(L&&L.length>0)Q=!0,G.enqueue(L)}};try{await K(W),G.close()}catch(Z){if(Q||!_0.isOversizedFrame(Z)){G.error(Z);return}try{let U=await X();if(!U.ok){G.error(new m0(`HTTP fallback after an oversized WebSocket frame failed with ${U.status}`));return}if(U.body)await K(U.body.getReader());G.close()}catch(U){G.error(U)}}},cancel(G){J.cancel(G)}});return new Response($,{status:Y.status,headers:Y.headers})}function Vq(Y){return new Response(new ReadableStream({start(X){X.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function Nq(Y,X,J,Q,$,G,W){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<$)return Y.socket;D1(Y);let K=await _0.connectResponsesWebSocket({url:_0.toWebSocketUrl(X),headers:J,timeout:Q,rawWebSocket:G,signal:W??void 0});return Y.connectedAt=Date.now(),K}function D1(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function Bq(Y,X,J,Q){if(!Y.socket||!Array.isArray(X.input)||X.input.length===0)return;let $=Fq(X);await $9({sessionID:Q.sessionID,transport:"websocket",phase:"prewarm",bodyText:JSON.stringify($),url:Q.url,method:"POST",headers:Q.headers});let G=_0.streamResponsesWebSocket({socket:Y.socket,body:$,sessionID:Q.sessionID,idleTimeout:J,signal:Q.signal,onRateLimitReached:Q.onRateLimitReached,onComplete:(W,K)=>{N1({component:"ws-pool",event:"prewarm_completed",sessionID:Q.sessionID,responseID:ez(W),usage:YK(W)}),QK(Y,$,W,K,!1)},onTerminal:(W)=>{if(W.type!=="response.completed"&&W.type!=="response.done")Y.continuation=void 0},onConnectionInvalid:()=>{Y.continuation=void 0},onAbort:()=>{Y.continuation=void 0},onRetryableTerminal:async(W)=>{let K=tz(W);if(!K)return;throw Y.fallback=!0,K}});await qq(G)}function ez(Y){let X=Y.response;if(!h(X))return;return typeof X.id==="string"?X.id:void 0}function YK(Y){let X=Y.response;if(!h(X))return;return h(X.usage)?X.usage:void 0}async function qq(Y){let X=Y.body?.getReader();if(!X)return;while(!0)if((await X.read()).done)return}function Fq(Y){return e9({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:Oq(Y.client_metadata)})}function XK(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 Oq(Y){if(!h(Y))return Y;if(typeof Y["x-codex-turn-metadata"]!=="string")return Y;try{let X=JSON.parse(Y["x-codex-turn-metadata"]);if(!h(X))return Y;return{...Y,"x-codex-turn-metadata":XK(X),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function jq(Y){let X=Y["x-codex-turn-metadata"];if(!X)return Y;try{let J=JSON.parse(X);if(!h(J))return Y;return{...Y,"x-codex-turn-metadata":XK(J)}}catch{return Y}}var JK=["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 az(Y){let X={...Y};if(Array.isArray(Y.input))X.input=Y.input.map(Dq);return X}function e9(Y){let X={};for(let J of JK)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 Dq(Y){if(!h(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 QK(Y,X,J,Q,$){let G=J.response,W=h(G)&&typeof G.id==="string"?G.id:void 0;if(!W||!Array.isArray(X.input)){Y.continuation=void 0;return}let K=$?new Set(Y.continuation?.finalizedCallIds):new Set;for(let Z of Q)K.add(Z);Y.continuation={responseID:W,input:X.input,signature:s8(X),finalizedCallIds:K}}function r8(Y,X,J=X){let Q=Array.isArray(X.input)?X.input:[],$=Array.isArray(J.input)?J.input:Q,G=s8(J),W=Y.turnInput&&Y.turnSignature===G?Pq(Y.turnInput,$):void 0,K=W===void 0?Q:$.slice(W);if(K.length>0&&K.some(WK)||!Y.turnID)Y.turnID=c1(),Y.turnStartedAt=Date.now();Y.turnInput=$.slice(),Y.turnSignature=G}function $K(Y,X,J=X){r8(Y,X,J);let Q=X.client_metadata;if(!h(Q)||typeof Q["x-codex-turn-metadata"]!=="string")return X;let $=GK(Q["x-codex-turn-metadata"],Y.turnID,Y.turnStartedAt);if(!$)return X;return{...X,client_metadata:{...Q,"x-codex-turn-metadata":$}}}function GK(Y,X,J){let Q;try{Q=JSON.parse(Y)}catch{return}if(!h(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 Pq(Y,X){if(Y.length>X.length)return;for(let J=0;J<Y.length;J++)if(B1(Y[J])!==B1(X[J]))return;return Y.length}function Eq(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!J||!Y.continuation)return X;if(Y.continuation.signature!==s8(X))return Y.continuation=void 0,X;if(!zK(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),$=wq(Q,Y.continuation.finalizedCallIds);if($.length===0)return X;return{...X,previous_response_id:Y.continuation.responseID,input:$}}function Mq(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!Y.continuation)return!0;if(!J)return!1;if(!zK(Y.continuation.input,J))return!0;return J.slice(Y.continuation.input.length).some(WK)}function WK(Y){if(!h(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function wq(Y,X){return Y.filter((J)=>{if(!h(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 s8(Y){return B1(Aq(Object.fromEntries(Object.entries(Y).filter(([X])=>X!=="input"&&X!=="stream"&&X!=="background"&&X!=="previous_response_id"&&X!=="generate"))))}function Aq(Y){if(!h(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 zK(Y,X){if(Y.length>=X.length)return!1;for(let J=0;J<Y.length;J++)if(B1(Y[J])!==B1(X[J]))return!1;return!0}function KK(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let X=new Headers(Y.headers);for(let J of o8)X.delete(J);return{...Y,headers:X}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((X)=>!o8.has(X[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([X])=>!o8.has(X.toLowerCase())))}}var Tq=300000,Rq=30000,Cq=5000,Iq=100;function JJ(Y){let X=Y.logger,J=Y.now??Date.now,Q=Y.manifestPath??IX(),$=Y.cacheConnector??bq(X),G=Y.detectClaustrumConnection??LK,W,K,Z,U,L,F=!1,N=new Map,V=new Set,j,S={isEnabled:()=>U?.status==="available",wasDetected:()=>U?.status==="available",getCache:()=>W,async ensureCache(){if(W)return W;return await u(),W},getTransport:()=>K,getCustodyProjection:(c,M)=>{let A=N.get(c.id);if(A)return A;return UK(c,Y.storage,M,W,j)},async boot(){if(F)return;try{U=await G()}catch(w){X.warn("custody detection failed",{error:w instanceof Error?w.message:String(w)});return}if(U.status!=="available"){if(U.status==="malformed")X.warn("custody connection malformed; disabled for this process",{reason:U.reason});else X.info("custody not configured; no client/timer created",{});return}let c=await Y.readCustodyManifest(Q);if(j=c,await E(c),Y.storage?.claustrum?.mode!=="claustrum"){X.info("custody connection available but mode is local; manifest read for the refresh gate, no client/timer",{});return}if(!await u()){F0();return}let M=W;if(!M)return;if(!c.ok&&c.reason!=="absent"){I(await Y.loadAccounts(s(Y.configPath))),F0();return}await f(),await o(c);let A=await Y.loadAccounts(s(Y.configPath));await Y.onReconcileStep?.("enabled-manifest-join");let B=a8(c,A),D=[];for(let w of t8(A)){if(A?.claustrum?.transition?.fingerprints.fallbacks[w.id])continue;if(!e8(w,c,E0)&&!(k0(w,E0)&&!w.accountId))continue;if(!B.get(w.id))continue;let p=u0(M);D.push(YJ(w,p).then((n)=>z1(w,n,c)).catch((n)=>X.warn("custody boot sweep failed",{error:n instanceof Error?n.message:String(n)})))}await Promise.all(D),await xq(B,M,A,Iq),F0()},async runTick(){if(F)return;if(Y.storage?.claustrum?.mode!=="claustrum")return;let c=j?.ok?j.revision:void 0,M=Y.readCustodyManifest(Q),A=W?void 0:u(),B=await M;if(j=B,!B.ok&&B.reason!=="absent"){I(await Y.loadAccounts(s(Y.configPath)));return}let D=B.ok&&B.revision!==c?await E(B):await Y.loadAccounts(s(Y.configPath));if(!W&&!await A)return;if(B.ok&&B.revision===c){await f(),await Y.onReconcileStep?.("enabled-manifest-join");let m=a8(B,D);await b(B,m),await W0(B,m);return}await f(),await o(B),await Y.onReconcileStep?.("enabled-manifest-join");let w=a8(B,D);await b(B,w),await W0(B,w)},dispose(){if(F)return;if(F=!0,L)(Y.clearIntervalFn??clearInterval)(L),L=void 0;try{W?.close()}catch{}if(!W)try{K?.close()}catch{}W=void 0,K=void 0}};async function u(){if(F)return!1;if(W)return!0;if(Z)return Z;if(!U)return!1;let c=(async()=>{let M;try{let A=$({connectionFile:hq(U),handshakeTimeoutMs:Cq});M=new NK({connector:()=>A,now:J});let B=await A;if(F)return M.close(),!1;return W=M,K=B,!0}catch(A){return M?.close(),X.warn("custody connect failed; disabled until tick reconnect",{error:A instanceof Error?A.message:String(A)}),!1}})();Z=c;try{return await c}finally{if(Z===c)Z=void 0}}function I(c){for(let M of t8(c))N.set(M.id,{state:"inert",reason:"manifest-unreadable"})}async function E(c){let M=await Y.loadAccounts(s(Y.configPath));if(!M||!c.ok)return M;for(let[A,B]of y0(c)){if(!M)break;if(A==="main")continue;if(M.accounts.some((p)=>p.id===A))continue;let D=M.claustrum?.rowHistory?.includes(A)?"row removed":"awaiting discovery",w=`${A}:${D}`;if(!V.has(w))V.add(w),X.info(`orphan-binding: ${D}`,{accountId:A});if(M.claustrum?.mode!=="claustrum")continue;let m=null;while(!m&&!F)if(m=await Y.acquireRefreshFileLock({name:M1(A),ttlMs:b1,path:Y.configPath,renew:!0}),!m)await new Promise((p)=>setTimeout(p,5));if(!m)continue;try{await Y.onReconcileStep?.("discovery-lock-acquired",A);let p=await Y.readCustodyManifest(Q),n=await Y.loadAccounts(s(Y.configPath));if(n?.claustrum?.mode!=="claustrum"||!p.ok||y0(p).get(A)!==B||n.accounts.some((z0)=>z0.id===A))continue;await Y.mutateAccounts((z0)=>{if(z0.claustrum?.mode!=="claustrum"||z0.accounts.some((r)=>r.id===A))return z0;return{...z0,claustrum:{...z0.claustrum,mode:"claustrum",rowHistory:[...new Set([...z0.claustrum?.rowHistory??[],A])]},accounts:[...z0.accounts,{id:A,...V1(E0),enabled:!0}]}},s(Y.configPath))}finally{await m.release().catch(()=>{})}M=await Y.loadAccounts(s(Y.configPath))}return M}async function b(c,M){if(!W)return;let A=await Y.loadAccounts(s(Y.configPath)),B=u0(W);for(let D of t8(A)){if(A?.claustrum?.transition?.fingerprints.fallbacks[D.id])continue;if(!e8(D,c,E0)&&!(k0(D,E0)&&!D.accountId))continue;if(!M.has(D.id))continue;let w=await YJ(D,B);z1(D,w,c)}}async function f(){let c=await Y.loadAccounts(s(Y.configPath)),M=c?.claustrum?.transition;if(c?.claustrum?.mode!=="claustrum"||!M)return;let A=!1;for(let[B,D]of Object.entries(M.fingerprints.fallbacks)){let w=await Y.acquireRefreshFileLock({name:M1(B),ttlMs:b1,path:Y.configPath,renew:!0});if(!w){A=!0;continue}try{if(!await Y.withAccountStoreTransaction(async(p)=>{let n=await p.read(),z0=n.accounts.find((A0)=>A0.id===B);if(z0?.type==="oauth"&&k0(z0,"openai"))return!0;if(!z0||!V0(z0)||!z0.access||J9(z0.access,z0.refresh)!==D)return N.set(B,{state:"inert",reason:"new-local-family-under-claustrum"}),!1;let r=structuredClone(n),v0=r.accounts.find((A0)=>A0.id===B);if(!v0||!V0(v0))return!1;Object.assign(v0,V1(E0)),await p.write(r);let K1=(await p.read()).accounts.find((A0)=>A0.id===B);return!!(K1?.type==="oauth"&&k0(K1,"openai"))},s(Y.configPath)))A=!0}catch{A=!0}finally{await w.release().catch(()=>{})}}if(M.fingerprints.main)if(!Y.auth)A=!0;else{let B=await Y.acquireRefreshFileLock({name:u1,ttlMs:b1,path:Y.configPath,renew:!0});if(!B)A=!0;else try{if(await xX(M.fingerprints.main,{auth:Y.auth,warn:(w)=>X.warn(w,{})})!=="tombstoned")A=!0}finally{await B.release().catch(()=>{})}}if(A)return;await Y.withAccountStoreTransaction(async(B)=>{let D=await B.read();if(D.claustrum?.mode!=="claustrum"||D.claustrum.transition?.manifestRevision!==M.manifestRevision||D.claustrum.transition?.storeGeneration!==M.storeGeneration)return;await B.writeMode("claustrum")},s(Y.configPath))}async function o(c){if(!W||!c.ok)return;let M=await Y.loadAccounts(s(Y.configPath));if(M?.claustrum?.mode!=="claustrum")return;let A=y0(c);for(let B of M.accounts){if(B.type!=="oauth"||B.corrupt!==!0)continue;let D=A.get(B.id),w=D?await t(B.id,B.accountId,D):"no_handle",m=S9({mode:"claustrum",manifest:D?"present":"absent",local:"gone",vault:()=>w,verifiedInProcessLogin:!1});if(!("installTombstone"in m)||!m.installTombstone||!D)continue;await N0(B.id,D)}}async function t(c,M,A){if(Y.resolveFallbackVaultState)return Y.resolveFallbackVaultState({accountId:c,handle:A});if(!W)return"cold";if(W.isReauth(A,J()))return"needs_reauth";try{let B=await W.get(A,v1(Y.storage),{force:!0}),D=Q1(B.payload.access),w=D?$1(D):void 0;if(M&&w&&w!==M)return"identity_mismatch";if(!w)X.warn("custody identity unverifiable; serving",{credentialId:A});return"serves"}catch{return W.isReauth(A,J())?"needs_reauth":"cold"}}async function N0(c,M){let A=await Y.acquireRefreshFileLock({name:M1(c),ttlMs:b1,path:Y.configPath,renew:!0});if(!A)return;try{let B=await Y.readCustodyManifest(Q),D=await Y.loadAccounts(s(Y.configPath)),w=D?.accounts.find((m)=>m.id===c);if(D?.claustrum?.mode!=="claustrum"||!B.ok||y0(B).get(c)!==M||w?.type!=="oauth"||w.corrupt!==!0)return;await Y.mutateAccounts((m)=>{let p=m.accounts.find((r)=>r.id===c);if(p?.type!=="oauth"||p.corrupt!==!0)return m;let{corrupt:n,...z0}=p;return{...m,accounts:m.accounts.map((r)=>r.id===c?{...z0,...V1(E0)}:r)}},s(Y.configPath))}finally{await A.release().catch(()=>{})}}async function W0(c,M){if(!W)return;for(let[A,B]of M){if(W.isReauth(B,J()))continue;let w=(await Y.loadAccounts(s(Y.configPath)))?.accounts.find((m)=>m.id===A);if(!w||!V0(w))continue;if(!VK(w,c,Y.storage??{}))continue;try{let m=await W.get(B);N.set(A,{state:"vault",recordVersion:m.recordVersion})}catch{}}}function F0(){if(F)return;let c=Y.setIntervalFn??setInterval,M=Math.floor((Math.random()*2-1)*Rq),A=Tq+M;if(L=c(()=>{if(F)return;S.runTick().catch((D)=>X.warn("custody tick failed",{error:D instanceof Error?D.message:String(D)}))},A),L&&typeof L==="object"&&"unref"in L)L.unref?.()}function u0(c){return{loadAccounts:Y.loadAccounts,readCustodyManifest:Y.readCustodyManifest,acquireRefreshFileLock:Y.acquireRefreshFileLock,configPath:Y.configPath,paths:s(Y.configPath),manifestPath:Q,cache:c,minTtlMs:v1(Y.storage),mutateAccounts:Y.mutateAccounts,provider:E0,now:J}}function z1(c,M,A){if(M.kind==="succeeded"){N.set(c.id,{state:"vault",recordVersion:M.recordVersion});return}if(M.kind==="failed"){let D={gone:"gone",identityMismatch:"identityMismatch",nullClaim:"nullClaim",unavailable:"unavailable"}[M.reason];N.set(c.id,{state:"inert",reason:D==="unavailable"?"takeover-incomplete/vault-unavailable":"identity-mismatch"}),Sq(X,c.id,D,M.recordVersion,J());return}if(M.reason==="notEnrolling"){let B=J(),D=UK(c,Y.storage,B,W,A);if(D)N.set(c.id,D)}}return S}var _q=3600000,XJ=new Map;function Sq(Y,X,J,Q,$){let G=`${X}:${J}`,W=XJ.get(G);if(W!==void 0&&$-W<_q)return;XJ.set(G,$),Y.warn("custody enroll-completion sweep failed",{accountId:X,reason:J,...typeof Q==="number"?{recordVersion:Q}:{}})}function kq(){XJ.clear()}function v1(Y){return((Y?.refresh?.refreshBeforeExpiryMinutes??240)+30)*60000}function a8(Y,X){let J=new Map;for(let[Q,$]of y0(Y)){let G=X?.accounts.find((W)=>W.id===Q);if(G?.type!=="oauth")continue;if(!KX(G,Y,E0))continue;J.set(Q,$)}return J}function UK(Y,X,J,Q,$){let G=X??{},W=$?y0($).get(Y.id):void 0;if(!k0(Y,E0)&&!W)return;if(!k0(Y,E0))return;if(G.claustrum?.mode!=="claustrum"||!W)return YY({kind:"NEEDS_LOGIN"});return YY({kind:"INERT",reason:Q?.isReauth(W,J)?"vault-reauth":"vault-cold"})}async function xq(Y,X,J,Q,$=[]){if(Y.size===0&&$.length===0)return;let G=[...$];for(let[,W]of Y)G.push(X.get(W).then(()=>{return}).catch(()=>{}));await Promise.race([Promise.all(G),new Promise((W)=>setTimeout(W,Q))])}function t8(Y){if(!Y)return[];return Y.accounts.filter(V0)}function bq(Y){return async(X)=>{let J=await HK.connect({connectionFile:X.connectionFile,handshakeTimeoutMs:X.handshakeTimeoutMs});return vq(J,Y)}}function vq(Y,X){return{getCredential:(J,Q)=>Y.getCredential(J,Q),statusCredential:(J)=>Y.statusCredential(J),reportAuthFailure:(J)=>Y.reportAuthFailure({handle:J.handle,providerStatus:J.providerStatus,recordVersion:J.recordVersion,reporterSource:J.reporterSource}),close:()=>Y.close()}}function hq(Y){if(Y.status!=="available")return Y.path??"";return ZK()}var uq=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),cq=new Set(["gpt-5.6","gpt-6"]),pq="Refusing to send a request with no access token. This is a defect in the plugin, not a problem with the provider or the account; the transport log names the account and the path that produced it.",lq=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-6-astra","gpt-6-sol","gpt-6-luna"]),dq="opencode-oauth-dummy-key",iq="terminal_resize_reflow",UJ="0.155.0",oq=`codex_exec/${UJ} (Debian 12.0.0; aarch64) unknown (codex_exec; ${UJ})`,nq="seccomp",bM=()=>u1,QJ=120000,rq=90000,sq=4000,BK=50,qK=3,aq=25,tq=60000,eq="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",ZJ=!1;function vM(){ZJ=!1}var FK=B0("models"),OK=!1,jK=!1;class HJ 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 W1 extends Error{code;constructor(Y,X){super(X);this.name="ResetTargetResolutionError",this.code=Y}}function DK(Y,X,J,Q){let $=(J?.refresh?.refreshBeforeExpiryMinutes??240)*60000;return!Y||!X||X-Q<=$}function YF(Y){return async(X)=>{if(X==="main"){let Z=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),U=await Y.getAuth();if(U.type!=="oauth")throw new W1("non_oauth_account","Main OpenAI account is not authenticated with OAuth.");if(DK(U.access,U.expires,Z,Y.now()))U={type:"oauth",...await Y.refreshMainWithLease()};if(!U.access)throw new W1("token_unavailable","Main OpenAI account has no usable access token.");let L=Q1(U.access),F=L?$1(L):void 0,N=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath});return{accountKey:X,label:"Main account",accessToken:U.access,chatgptAccountId:F??N?.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 W1("unknown_account",`Fallback account ${X} was not found.`);if(Q.enabled===!1)throw new W1("disabled_account",`Fallback account ${X} is disabled.`);if(!V0(Q))throw new W1("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);let $=Q;if(!await Y.isFallbackRefreshInert?.($,J)&&DK($.access,$.expires,J,Y.now()))$=await Y.refreshFallbackAccount($,J);let G=Y.resolveFallbackAccess?await Y.resolveFallbackAccess($,J):$.access?{token:$.access,provenance:"local"}:h1;if(G===h1||G===r1)throw new W1("token_unavailable",`Fallback account ${X} has no usable access token.`);let W=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),K=W?.accounts.find((Z)=>Z.id===X);if(!W||!K)throw new W1("unknown_account",`Fallback account ${X} was not found.`);if(K.enabled===!1)throw new W1("disabled_account",`Fallback account ${X} is disabled.`);if(!V0(K))throw new W1("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);return{accountKey:X,label:$.label??X,accessToken:G.token,chatgptAccountId:K.accountId,onAuthFailure:G.provenance==="local"?void 0:async(Z)=>{await Y.reportAuthFailure?.({handle:G.provenance.handle,providerStatus:Z,recordVersion:G.provenance.recordVersion})}}}}function XF(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function $J(Y){return Y instanceof HJ}function PK(){throw Error(eq)}function JF(Y){return Math.floor(Math.random()*Y)}function QF(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 $F(Y,X,J){let Q=Y.get(X);if(Q)return Q;let $=c1(),G={threadID:$,turnID:c1(),windowID:`${$}:0`};return Y.set(X,G),J?.(),G}function oK(){return KJ(OY(),"openai-auth-sessions.json")}function GF(){let Y=new Map;try{let X=JSON.parse(iK(oK(),"utf8"));if(!h(X.sessions))return Y;for(let[J,Q]of Object.entries(X.sessions)){if(!h(Q)||typeof Q.threadID!=="string")continue;Y.set(J,{threadID:Q.threadID,turnID:c1(),windowID:`${Q.threadID}:0`})}}catch{}return Y}function WF(Y){let X=oK(),J=`${X}.tmp-${process.pid}`;try{gq(OY(),{recursive:!0});let Q={version:1,sessions:Object.fromEntries([...Y.entries()].map(([$,G])=>[$,{threadID:G.threadID}]))};mq(J,`${JSON.stringify(Q,null,2)}
123
+ `,"utf8"),yq(J,X)}catch{}}function EK(Y,X){return h(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===X}function zF(Y,X){if(Y.length>X.length)return!1;for(let J=0;J<Y.length;J++)if(B1(Y[J])!==B1(X[J]))return!1;return!0}function KF(Y,X){if(!Y.input)return X.length>0;if(!zF(Y.input,X))return!0;return X.slice(Y.input.length).some((Q)=>EK(Q,"user")||EK(Q,"developer"))}function UF(Y,X){let J=Array.isArray(X?.input)?X.input:void 0;if(J&&(KF(Y,J)||!Y.turnID))Y.turnID=c1(),Y.turnStartedAt=Date.now();else if(!Y.turnStartedAt)Y.turnStartedAt=Date.now();if(J)Y.input=J}function ZF(Y){if(!Y.metadata)return{init:Y.init};let X=QF(Y.init?.body);if(!Y.websocket)UF(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:nq,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",iq),Y.headers.set("x-codex-turn-metadata",J),Y.headers.set("user-agent",oq),Y.headers.set("version",UJ),Y.dumpSessionID)Y.headers.set(w1,Y.dumpSessionID);let Q=X;if(!Q)return{init:Y.init};let $=Y.responsesLite&&typeof Q.model==="string"&&lq.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(jF);if(FF(Q),OF(Q),V5(Q),VF(Q),BF(Q,Y.metadata),$)qF(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(e9(Q))}}}function LF(Y,X){return Y.find((J)=>J.enabled!==!1&&V0(J)&&(J.id===X||J.accountId===X))}function MK(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]=$}if(J.spendControl===void 0&&X.spendControl!==void 0)J.spendControl=X.spendControl;return J}function ZX(Y,X){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:X}}function LX(Y,X){return y0(Y).get(X)}function nK(Y,X,J=Date.now(),Q=X.mainAccountId,$){let G=Y.getMain(),W=G?.quota;return{main:{quota:W?{...W,checkedAt:G.checkedAt,primary:ZX(W.primary,G.checkedAt),secondary:ZX(W.secondary,G.checkedAt)}:null,...typeof Q==="string"?{mainAccountId:Q}:{},killed:!1,...W?.resetCreditsAvailable!==void 0?{resetCredits:W.resetCreditsAvailable}:{}},fallbacks:X.accounts.filter((K)=>K.enabled).map((K)=>{let Z=Y.getFallback(K.id),U=Z?.quota,L=$?.(K,J);return{id:K.id,label:K.label,accountId:Z?.accountId??K.accountId,quota:U?{...U,checkedAt:Z.checkedAt,primary:ZX(U.primary,Z.checkedAt),secondary:ZX(U.secondary,Z.checkedAt)}:null,killed:!1,enabled:!0,...U?.resetCreditsAvailable!==void 0?{resetCredits:U.resetCreditsAvailable}:{},...L?{custody:L}:{}}}),route:X.routing?.mode??"main-first",lastUpdated:J}}function gM(Y,X,J,Q=Date.now()){return{...nK(Y,X,Q),activeId:J}}function wK(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 HF(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 AK(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}function VF(Y){if(!g0().webSearch)return;if(!Array.isArray(Y.tools)||Y.tools.length===0)return;if(Y.tools.some((X)=>h(X)&&X.type==="web_search"))return;Y.tools=[...Y.tools,{type:"web_search",external_web_access:!1,search_content_types:["text","image"]}]}function LJ(Y){if(Array.isArray(Y)){for(let X of Y)LJ(X);return}if(!h(Y))return;if(Y.type==="input_image")delete Y.detail;for(let X of Object.values(Y))LJ(X)}var NF=new Set(["gpt-6-astra","gpt-6-sol","gpt-6-luna"]);function BF(Y,X){let J=typeof Y.model==="string"?Y.model:"";if(!NF.has(J))return;let Q=h(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 qF(Y){let X=h(Y.reasoning)?{...Y.reasoning}:{};X.context="all_turns",Y.reasoning=X,Y.parallel_tool_calls=!1;let J=Array.isArray(Y.input)?Y.input:[];LJ(J);let $=[{type:"additional_tools",role:"developer",tools:Array.isArray(Y.tools)?Y.tools.filter((G)=>!(h(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 FF(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(h(X)&&X.type==="function"&&X.name==="web_search"))}function OF(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(h(X)&&X.type==="function"&&X.name==="websearch_web_search_exa"))}function jF(Y){if(!h(Y))return Y;if(Y.type!=="function")return Y;let X=h(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:Z,...U}=Y.parameters;return U})():Y.parameters,{type:J,name:Q,description:$,strict:G,parameters:W,...K}=Y;return{type:J,name:Q,description:$,strict:G??!1,parameters:X,...K}}async function DF(Y,X={}){let J=X.codexApiEndpoint??g0().codexApiEndpoint,Q=crypto.randomUUID(),$=GF(),G=()=>WF($),W=!1,K=[],Z=null,U=Y.client.auth,L=new Map,F=new Map,N,V,j,R={},S=X.custody,u=B0("custody"),I=(M,A="")=>M?async()=>{let B=await M();return{url:B.url,instructions:B.instructions??A,method:"auto",callback:async()=>{try{let D=await B.tokens;return{type:"success",refresh:D.refresh_token,access:D.access_token,expires:Date.now()+(D.expires_in??3600)*1000,accountId:Y9(D)}}finally{B.cleanup?.()}}}}:void 0;function E(M,A){return JJ({storage:M,configPath:e(),loadAccounts:P0,mutateAccounts:q0,withAccountStoreTransaction:VX,readCustodyManifest:s0,acquireRefreshFileLock:H1,auth:A,...S?{detectClaustrumConnection:async()=>S.detection==="absent"?{status:"absent",path:"test"}:{status:"available",schema:1,wireVersion:1,endpoints:[]},cacheConnector:async()=>S.transport}:{},logger:{info:(B,D)=>u.info(B,D??{}),warn:(B,D)=>u.warn(B,D??{}),debug:(B,D)=>u.debug(B,D??{}),error:(B,D)=>u.error(B,D??{})},now:S?.now})}let b=await P0(s(e())),f=await s0(),o=Y.client.auth;if(o.get&&o.all){if(f1(b??{})==="claustrum")j=E(b,{all:o.all,get:o.get,set:o.set}),S?.onRuntime?.(j),await j.boot();let M=j?.getCache();if(M)R.cache=M;if(R.mainVerdict=await yQ({client:{auth:o},mode:f1(b??{}),manifest:f,mainAccountId:b?.mainAccountId,getCredential:M?async(A)=>{return{access:(await M.get(A,v1(b))).payload.access}}:void 0,isReauth:M?(A)=>M.isReauth(A):void 0,now:Date.now,sleep:(A)=>new Promise((B)=>setTimeout(B,A))}),R.mainVerdict){let A=await n1();await zJ({...A,main:{...A.main,custody:YY(R.mainVerdict)}})}}let t=new MX,N0,W0={},F0=BQ({client:Y.client,getAuth:async()=>N0?.(),fetchImpl:fetch,dependencies:{...S?.authorize?{authorizeBrowser:I(S.authorize.browser,"Complete authorization in your browser. This window will close automatically."),authorizeHeadless:I(S.authorize.headless)}:{},custodyQuotaDeps:W0}}),u0=(M)=>async(A)=>{let B=await kX();try{let D=await M(A);if(D.method!=="auto")return await B.release(),D;return{...D,callback:async()=>{try{let w=await D.callback();if(w.type!=="success"||!("refresh"in w))return await B.release(),w;return iQ({accessToken:w.access??"",refreshToken:w.refresh,getAuth:async()=>{let m=await U.get({path:{id:"openai"}});return h(m)&&typeof m.access==="string"&&typeof m.refresh==="string"?{access:m.access,refresh:m.refresh}:void 0},onObserved:({access:m,refresh:p})=>hQ({type:"oauth",access:m,refresh:p}),release:()=>B.release(),warn:(m)=>S?.warn?.(m)??u.warn(m),now:S?.now??Date.now,sleep:S?.sleep??((m)=>Bun.sleep(m))}).catch(()=>B.release()),w}catch(w){throw await B.release(),w}}}}catch(D){throw await B.release(),D}},z1=F0.map((M)=>M.type==="oauth"?{...M,authorize:u0(M.authorize)}:M);async function c(M,A){let B=Y.client.session;if(typeof B?.promptAsync==="function"){let D=await P5(Y.client,M),w={noReply:!0,parts:[{type:"text",text:A,ignored:!0}]};if(D?.agent)w.agent=D.agent;if(D?.model)w.model=D.model;if(D?.variant)w.variant=D.variant;await B.promptAsync({path:{id:M},body:w});return}}return{async dispose(){t.stop(),j?.dispose(),N?.stopBackgroundRefresh(),N=void 0;for(let B of K)B.close();K.length=0;let M=globalThis;for(let[B,D]of L)if(M.__openaiAuthCacheKeepManagers?.get(B)===D)D.stop(),M.__openaiAuthCacheKeepManagers.delete(B);L.clear();let A=globalThis;for(let[B,D]of F)if(A.__openaiAuthRpcServers?.get(B)===D)await D.stop().catch(()=>{}),A.__openaiAuthRpcServers.delete(B);F.clear()},async event(M){if(M.event.type!=="session.deleted")return;let A=M.event.properties.info,B=$.get(A.id);if(B)Z?.cacheKeepManager?.remove(B.threadID);if($.delete(A.id))G();if(V){let D=(await P0(s(e())))?.accounts;await cK(A.id,D,V)}for(let D of K)D.remove(A.id)},provider:{id:"openai",async models(M,A){if(A.auth?.type!=="oauth")return M.models;let B=await P0(s(e())),D=!B||xK(B),w=D?null:await F5();if(!D&&w&&!OK)OK=!0,FK.debug("restoring OAuth model costs from models.dev catalog");if(!D&&!w&&!jK)jK=!0,FK.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(M.models).filter(([,m])=>{if(m.options.reasoningMode==="pro")return!1;if(uq.has(m.api.id))return!0;if(cq.has(m.api.id))return!1;let n=m.api.id.match(/^gpt-(\d+(?:\.\d+)?)/)?.[1];return n?parseFloat(n)>5.4:!1}).map(([m,p])=>[m,{...p,cost:D?{input:0,output:0,cache:{read:0,write:0}}:w?.[p.api.id]??w?.[m]??p.cost,limit:p.id.includes("gpt-5.5")?{context:400000,input:272000,output:128000}:p.id.includes("gpt-6-astra")?{context:872000,input:744000,output:128000}:p.id.includes("gpt-5.6")||p.id.includes("gpt-6-sol")||p.id.includes("gpt-6-luna")?{context:372000,input:244000,output:128000}:p.limit}]))}},tool:{web_search:L5},auth:{provider:"openai",async loader(M){N0=M;let A=await M();if(A.type!=="oauth")return{};let B=_Y(A),D=B.kind==="tombstone"||B.kind==="empty",w=Y.directory?await dK(Y.directory):void 0,m=w?.dir??e();if(!D)await vK({type:"oauth",access:A.access??"",refresh:A.refresh??"",expires:A.expires??0},s(e()));let p=await P0(s(e())).catch((H)=>{let q=e();throw Error(`OpenAI auth store at ${q} is corrupt or unreadable: ${H instanceof Error?H.message:String(H)}. Fix or remove it to continue.`,{cause:H})}),n;async function z0(){let H=e();try{let q=fq(H);if(n?.path===H&&n.mtimeMs===q.mtimeMs&&n.size===q.size)return n.storage;let O=await P0(s(H));return n={path:H,mtimeMs:q.mtimeMs,size:q.size,storage:O},O}catch{return n=void 0,P0(s(H))}}function r(){n=void 0}if(p&&A.access&&!D){let H=Y9({id_token:"",access_token:A.access,refresh_token:A.refresh??""});if(H&&H!==p.mainAccountId)await q0((q)=>{return q.mainAccountId=H,q},s(e())),p.mainAccountId=H,r()}let v0=p?.logging?.level;if(v0&&typeof v0==="string")CY(v0);let K1=B0("transport"),A0=B0("quota"),s1=B0("refresh"),X1=B0("accounts");K1.info("codex auth loader ready",{codexApiEndpoint:J,transport:g0().rawWebSocket?"raw-websocket":g0().webSockets?"websocket":"http",webSearch:g0().webSearch});let J0=new RY({storage:p,configPath:e(),fetchQuotaFn:void 0}),o0,V9=0,Q0=new hK({paths:s(e()),refreshFn:(H)=>HX({refreshToken:H.refreshToken,fetchImpl:H.fetchImpl,now:H.now}),quotaManager:J0,custody:{readManifest:s0},onFallbackStorageChanged:r}),T0=j??E(p);if(!j)S?.onRuntime?.(T0),await T0.boot(),j=T0;if(D){let H=await s0(),q=LX(H,"main"),O=T0.getCache();if(q&&O)try{let C=await O.get(q,v1(p)),_=k9(C.payload.access);if(_&&_!==p?.mainAccountId){if(await q0((k)=>{return k.mainAccountId=_,k},s(e())),p)p.mainAccountId=_;R.mainAccountId=_,r()}}catch{}}if(T0.runTick().catch((H)=>u.warn("custody first tick failed",{error:H instanceof Error?H.message:String(H)})),j=T0,p&&p.accounts.length>0)Q0.startBackgroundRefresh();let g1=T0;async function WY(H,q){let O=await s0();return KX(H,O,E0)}async function a1(H,q){let O=await s0(),C=g1.getCache(),_=LX(O,H.id);if(!C||!_)return GJ(H,q,O);return GJ(H,q,O,{cache:C,manifestHandle:_,requestPath:!0,now:S?.now??Date.now,refreshBeforeExpiryMs:(q.refresh?.refreshBeforeExpiryMinutes??240)*60000,completeEnrollmentDeps:{loadAccounts:P0,readCustodyManifest:s0,acquireRefreshFileLock:H1,configPath:e(),paths:s(e()),cache:C,minTtlMs:v1(q),mutateAccounts:q0,provider:E0,now:Date.now}})}async function VJ(H){if(f1(H)!=="claustrum")return r1;let q=await s0(),O=LX(q,"main"),C=g1.getCache(),_=(v)=>{return u.warn("custody main request refused",{reason:v}),h1};if(!O||!C)return _("no-handle");let k=(S?.now??Date.now)();if(C.isBlocked(O))return _("blocked");if(C.isReauth(O,k))return _("reauth");let x=await C.peek(O);if(!x||x.expiresAtMs<=k)return _("cache-miss");return{token:x.payload.access,provenance:{handle:O,recordVersion:x.recordVersion}}}async function N9(H){let q=g1.getCache();if(!q)return;await q.reportAuthFailure({handle:H.handle,providerStatus:H.providerStatus,recordVersion:H.recordVersion})}Object.assign(W0,{isFallbackRefreshInert:WY,resolveFallbackAccess:a1,reportCustodyAuthFailure:N9});function zY(H={}){let{readSidebarState:q,respectBackoff:O,skipFresherThanMs:C}=H;return{getAuth:M,codexRefreshFn:HX,refreshMainWithLease:ZY,fallbackManager:Q0,quotaManager:J0,loadAccounts:P0,writeSidebarState:LY,client:Y.client,fetchImpl:fetch,now:Date.now,paths:s(e()),readSidebarState:q??(()=>n1(c0)),storageMainAccountId:p?.mainAccountId,isOAuthAccountFn:V0,whamFn:TY,isFallbackRefreshInert:WY,resolveFallbackAccess:a1,resolveMainAccess:VJ,reportCustodyAuthFailure:N9,...O===void 0?{}:{respectBackoff:O},...C===void 0?{}:{skipFresherThanMs:C}}}let NJ=B0("cachekeep"),BJ=p?.cachekeep?.enabled===!0,qJ=p?.cachekeep?.subagents===!0,FJ=p?.cachekeep?.sustain===!0,OJ=EQ(p),KY;async function rK(H){await new Promise((q)=>setTimeout(q,H))}async function sK(H){let q;for(let O=1;O<=qK;O++)try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:H.refresh,access:H.access,expires:H.expires}});return}catch(C){if(q=C,O<qK)await rK(aq*O)}throw new HJ(q)}async function UY(H){await q0((q)=>{return q.refresh=q.refresh??{},H(q),q},s(e())),r()}async function jJ(H){let q=Date.now()+sq;while(Date.now()<q){await new Promise((_)=>setTimeout(_,BK+JF(BK)));let O=await M();if(O.type!=="oauth"||!O.access)continue;if((O.access!==H.access||O.refresh!==H.refresh||(O.expires??0)>(H.expires??0)+60000)&&(!O.expires||O.expires>Date.now()))return s1.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:O.expires?O.expires-Date.now():void 0}),{access:O.access,refresh:O.refresh??H.refresh??"",expires:O.expires??0}}return null}async function ZY(){if(!KY)KY=(async()=>{let H=await M();if(H.type!=="oauth")throw Error("not oauth");if(k0({id:"main",type:"oauth",access:H.access??"",refresh:H.refresh??"",expires:H.expires??0,addedAt:0},E0))throw new SK(E0);if(!H.refresh)throw Error("Token refresh failed: missing refresh token");let q=TK(H.refresh),O=await P0(s(e())),C=O?.refresh?.mainLastRefreshError;if(C&&EY(C,H.refresh,Date.now()))throw Error(CK(C,Date.now()));if(O?.refresh?.mainRefreshLeaseUntil&&O.refresh.mainRefreshLeaseUntil>Date.now()&&O.refresh.mainRefreshLeaseTokenHash===q){let v=await jJ(H);if(v)return v;throw Error("Codex OAuth refresh is already in progress")}let _=await H1({name:u1,ttlMs:QJ,path:e(),renew:!0});if(!_){let v=await jJ(H);if(v)return v;throw Error("Codex OAuth refresh is already in progress")}let k=crypto.randomUUID(),x=q;try{await UY((l)=>{l.refresh=l.refresh??{},l.refresh.mainRefreshLeaseId=k,l.refresh.mainRefreshLeaseUntil=Date.now()+rq,l.refresh.mainRefreshLeaseTokenHash=q});let v=await P0(s(e()));if(v?.refresh?.mainRefreshLeaseId!==k||v.refresh.mainRefreshLeaseTokenHash!==q)throw Error("Codex OAuth refresh is already in progress");let y=await HX({refreshToken:H.refresh,fetchImpl:fetch,now:Date.now});return await sK(y),await UY((l)=>{if(l.refresh=l.refresh??{},l.refresh.mainLastRefreshError=void 0,l.refresh.mainRefreshLeaseId===k)l.refresh.mainRefreshLeaseId=void 0,l.refresh.mainRefreshLeaseUntil=void 0,l.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),x=void 0,y}catch(v){if(H.refresh&&!$J(v))await UY((y)=>{y.refresh=y.refresh??{},y.refresh.mainLastRefreshError=RK({error:v,now:Date.now(),refreshToken:H.refresh??"",previous:y.refresh.mainLastRefreshError})}).catch(()=>{});throw v}finally{if(x)await UY((v)=>{if(v.refresh?.mainRefreshLeaseId===k&&v.refresh.mainRefreshLeaseTokenHash===x)v.refresh.mainRefreshLeaseId=void 0,v.refresh.mainRefreshLeaseUntil=void 0,v.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await _.release().catch(()=>{})}})().finally(()=>{KY=void 0});return KY}let DJ=globalThis,BX=DJ.__openaiAuthCacheKeepManagers??new Map;DJ.__openaiAuthCacheKeepManagers=BX,BX.get(m)?.stop();let B9=new CX({fetchImpl:fetch,getMainToken:async()=>{let H=await M();if(H.type!=="oauth")throw Error("not oauth");if(!H.access||(H.expires??0)<Date.now())try{return(await ZY()).access}catch(q){if($J(q))throw q;if(H.access)return H.access;throw Error("main token refresh failed")}return H.access},refreshFallback:async(H)=>{let q=await z0(),O=q?LF(q.accounts,H):void 0;if(!O)throw Error(`fallback account ${H} not found`);let C=q??{version:1,accounts:[O]},_=O;if(!await WY(O,C))_=await Q0.refreshAccount(O,C);let k=await a1(_,C);if(k===h1||k===r1)throw Error(`no access token for ${H}`);return{token:k.token,onAuthFailure:k.provenance==="local"?void 0:async(x)=>{await N9({handle:k.provenance.handle,providerStatus:x,recordVersion:k.provenance.recordVersion})}}},codexResponsesUrl:J,logger:NJ,now:Date.now,getWindow:()=>OJ,getSustain:()=>FJ});BX.set(m,B9),L.set(m,B9);async function q9(H,q,O,C,_=!1){if(Object.keys(H).length===0&&!_)return;let k=Date.now(),x=H,v={quota:x,refreshAfter:k+300000,checkedAt:k},y;if(O&&O!=="main"){let d=q?Q1(q):null,U0=d?$1(d):void 0,p0=J0.peekFallbackForPolicy(O)?.quota,R0=MK(x,p0);v={...v,quota:R0},J0.setFallback(O,v,q,_,U0)}else{if(y=C,!y&&q){let p0=Q1(q);y=p0?$1(p0):void 0}if(y&&o0&&y!==o0){A0.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:y,currentMainIdentity:o0});return}let d=J0.peekMainForPolicy(y)?.quota,U0=MK(x,d);v={...v,quota:U0},J0.setMain(q,v,y,_)}A0.debug("quota pushed",{pid:process.pid,accountId:O??"main",snapshot:v.quota});let l=await z0();await LY(J0,l,O&&O!=="main"?l?.mainAccountId:y)}function aK(H,q,O){let C=H==="main"?J0.peekMainForPolicy()?.quota:J0.peekFallbackForPolicy(H)?.quota;return kK(C,q,Date.now(),tq,O)}let F9=X.experimentalWebSockets?x1.createWebSocketFetch({httpFetch:fetch,rawWebSocket:g0().rawWebSocket,onQuota:(H,q,O,C)=>{q9(H,q,O,!O||O==="main"?C:void 0,!0)},onRateLimitReached:(H,q,O)=>{if(!q)A0.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:H});let C=q??"main",_=aK(C,H,O);J0.markRateLimited(C,_),A0.debug("mid-stream rate limit mark",{pid:process.pid,accountId:C,window:H})}}):void 0;if(F9)K.push(F9),W=!0;let c0=gK();V=c0;async function LY(H,q,O=q?.mainAccountId){if(!q)return;await zJ(nK(H,q,Date.now(),O,tK),c0)}function tK(H,q){if(!V0(H))return;return g1.getCustodyProjection(H,q)}async function PJ(H,q,O,C,_){let k={activeId:O,route:C,updatedAt:Date.now()};if(H){if(await NX({sessionId:H,...k},_,c0),q&&q!==H){if(C==="sticky-balanced"){let x=(await n1(c0)).stickyAssignments?.[GY(q)]?.accountId,v=_===void 0||x==="main"||_.some((y)=>y.enabled!==!1&&y.id===x);if(!x||!v)return;await NX({sessionId:q,activeId:x,route:C,updatedAt:Date.now()},_,c0);return}await NX({sessionId:q,...k},_,c0)}return}await uK(k,c0)}let eK=async(H,q)=>{let O=await H1({name:M1(H),ttlMs:b1,path:e(),renew:!0});if(!O)throw Error("Fallback account lock unavailable");try{return await q()}finally{await O.release()}},YU=S?.withFallbackAccountLock??eK,XU=async(H)=>{let q=await s0();if(!q.ok)return{ready:!1,reason:"manifest-unreadable"};let O=LX(q,H.id);if(!O)return{ready:!1,reason:"no-handle"};let C=T0.getCache();if(!C)return{ready:!1,reason:"vault-cold"};if(C.isReauth(O,S?.now?.()??Date.now()))return{ready:!1,reason:"vault-reauth"};if(C.isBlocked(O))return{ready:!1,reason:"vault-cold"};try{let _=await C.get(O,v1(p)),k=k9(_.payload.access);if(!k||H.accountId&&H.accountId!==k)return{ready:!1,reason:"identity-mismatch"};return{ready:!0,accountId:k}}catch{return{ready:!1,reason:C.isReauth(O,S?.now?.()??Date.now())?"vault-reauth":"vault-cold"}}};N?.stopBackgroundRefresh(),N=Q0,Z={accountStoragePath:e(),accountStatePath:PY(e()),packageVersion:P9,quotaManager:J0,loadAccounts:P0,client:Y.client,beginAccountLogin:AY,withFallbackAccountLock:YU,checkUsableCustodyBinding:XU,enterClaustrumMode:async()=>{let H=await P0(s(e())),q=(H?.accounts??[]).filter((O)=>O.type==="oauth"&&O.enabled!==!1).map((O)=>O.id);return oQ({accountIds:q,acquireLock:({name:O,renew:C})=>H1({name:O,ttlMs:O===u1?QJ:b1,path:e(),renew:C}),withStoreTransaction:(O)=>VX(O,s(e())),readManifest:s0,preflight:async({accountId:O,handle:C})=>{u.info("preflight probing participant",{accountId:O,hasHandle:C.length>0});let _=await T0.ensureCache(),k=_?.isBlocked(C);if(!_||k)return u.warn("preflight vault-cold",{accountId:O,hasCache:_!==void 0,blocked:k}),"vault-cold";if(_.isReauth(C,S?.now?.()??Date.now()))return"vault-reauth";try{let x=await _.get(C,v1(H)),v=k9(x.payload.access);if(!v||O&&O!==v)return"identity-mismatch";return"ready"}catch{return _.isReauth(C,S?.now?.()??Date.now())?"vault-reauth":"vault-cold"}},auth:{all:async()=>{if(typeof U.all==="function")return U.all();let O=process.env.XDG_DATA_HOME??KJ(UX.homedir(),".local","share"),C=KJ(O,"opencode","auth.json");try{let _=JSON.parse(iK(C,"utf8"));return h(_)?_:{}}catch{return{}}},get:async(O)=>{if(typeof U.get==="function")return U.get(O);if(O.path.id!=="openai"||!N0){u.warn("auth.get unavailable for slot",{id:O.path.id,hasLoaderGetAuth:N0!==void 0});return}return N0()},set:async(O)=>{await U.set(O)}},warn:(O)=>u.warn(O)})},leaveClaustrumMode:()=>nQ({acquireLock:({name:H,renew:q})=>H1({name:H,ttlMs:QJ,path:e(),renew:q}),withStoreTransaction:(H)=>VX(H,s(e()))}),resolveResetTarget:YF({getAuth:M,refreshMainWithLease:ZY,refreshFallbackAccount:(H,q)=>Q0.refreshAccount(H,q),loadAccounts:P0,accountStoragePath:e(),accountStatePath:PY(e()),now:Date.now,isFallbackRefreshInert:WY,resolveFallbackAccess:a1,reportAuthFailure:N9}),...XF(),cacheKeepManager:B9,setCacheKeepEnabled:(H)=>{BJ=H},setCacheKeepSubagents:(H)=>{qJ=H},setCacheKeepSustain:(H)=>{FJ=H},setCacheKeepWindow:(H)=>{OJ=H},clearStickyRouting:(H)=>lK(H,c0),getStickyRouting:async(H)=>mK(await n1(c0),H),refreshSidebar:async()=>{let H=await P0(s(e()));await LY(J0,H)},refreshAllQuota:async()=>E1(zY()),refreshResetTargetQuota:async(H)=>{return(await E1(zY({respectBackoff:!1}),{accountKey:H})).find((O)=>O.account===H)??{account:H,ok:!1,error:"targeted quota refresh returned no result"}}};let qX=null;if(w){let H=globalThis,q=H.__openaiAuthRpcServers??new Map;H.__openaiAuthRpcServers=q;let O=q.get(w.dir);if(O)await O.stop().catch(()=>{}),q.delete(w.dir);try{qX=await R5({dir:w.dir,secureDir:w.secureDir,sweepRoot:w.sweepRoot,drain:M5,apply:async(C)=>{let _={...Z,sessionId:C.sessionId},k=await EX(C.command,C.arguments,_);return{text:k.text,knobs:k.knobs}}}),q.set(w.dir,qX),F.set(w.dir,qX)}catch{}}let EJ=new WeakMap;function JU(H,q){let O=EJ.get(H);if(!O||q.hostname!=="chatgpt.com"||!q.pathname.startsWith("/backend-api/codex/"))return;if(H.status>=200&&H.status<300){g1.getCache()?.markVaultSuccess(O.handle);return}if(H.status!==401)return;N9({handle:O.handle,providerStatus:H.status,recordVersion:O.recordVersion}).catch(()=>{})}async function O9(H,q,O,C,_="main",k){if(!O.trim())throw K1.warn("refusing to send a request with no access token",{account:_,accountId:C,hasProvenance:Boolean(k&&k!=="local")}),Error(pq);let x=wK(H,q);if(x.delete("x-api-key"),x.delete("api-key"),x.set("authorization",`Bearer ${O}`),C)x.set("ChatGPT-Account-Id",C);x.set(x1.QUOTA_ACCOUNT_HEADER,_);let v=AK(x),y=v?$F($,v,G):void 0,l=H instanceof URL?H:new URL(typeof H==="string"?H:H.url),d=l.pathname.includes("/v1/responses")||l.pathname.includes("/chat/completions")?new URL(J):l,U0=(I0)=>{let t1=_K(I0,k,EJ);return JU(t1,d),t1},R0=ZF({init:{...q,headers:x},headers:x,metadata:y,installationID:Q,websocket:Boolean(F9&&l.pathname.endsWith("/responses")),responsesLite:X.responsesLite??!1,dumpSessionID:v}).init,U1=BJ,P1=new Headers(R0?.headers),l0=PQ({enabled:U1,includeSubagents:qJ,headers:P1,body:R0?.body});if(U1)NJ.trace("cachekeep headers",{pid:process.pid,hasParent:P1.has("x-parent-session-id"),sessionKey:l0?.sessionKey,captured:Boolean(l0),affinity:P1.get("x-session-affinity"),opencodeSession:P1.get("x-opencode-session"),sessionId:P1.get("session-id")});if(F9&&l.pathname.endsWith("/responses")){if(K1.debug("WS transport",{pid:process.pid,pathname:l.pathname,accountId:_}),l0)B9.track(l0.sessionKey,l0.bodyText,_,C,l0.replayHeaders,l0.isSubagent);return U0(await F9(d,R0))}let C0=x1.withoutInternalHeaders(R0);if(typeof C0?.body!=="string")return U0(await fetch(d,C0));if(l0)B9.track(l0.sessionKey,l0.bodyText,_,C,l0.replayHeaders,l0.isSubagent);K1.debug("HTTP transport",{pid:process.pid,pathname:l.pathname,accountId:_});try{let I0=await fetch(d,C0);return await $9({sessionID:v,transport:"http",phase:"http",bodyText:C0.body,accountId:_,url:d.toString(),method:C0.method,headers:C0.headers,status:I0.status}),U0(H5(I0))}catch(I0){throw await $9({sessionID:v,transport:"http",phase:"http",bodyText:C0.body,accountId:_,url:d.toString(),method:C0.method,headers:C0.headers,error:I0 instanceof Error?I0.message:String(I0)}),I0}}function HY(H,q){if((q?.method??(H instanceof Request?H.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof q?.body!=="string")return!1;try{let C=H instanceof URL?H.toString():typeof H==="string"?H:H.url;return new URL(C).pathname.endsWith("/responses")}catch{return!1}}function QU(H){return J0.peekMainForPolicy(H)?.quota}function MJ(H,q){for(let O of[H?.primary?.checkedAt,H?.secondary?.checkedAt,H?.checkedAt,q])if(typeof O==="number"&&Number.isFinite(O))return O;return}function j9(H,q,O,C,_){let k=MJ(H,q),x=MJ(O),v=C===_&&O!=null&&(H===void 0||x!==void 0&&(k===void 0||x>k));return{quota:v?O:H,quotaCheckedAt:v?x:k,source:v?"file":"memory"}}function wJ(H,q,O,C,_){let k=H?.quota,x=j9(k,H?.checkedAt,q,C,_),v=x.source,y=x.quota;if(!fK(y,O))return{exhausted:!1};let l=yK(y,O);if(!l)return{exhausted:!1};return{exhausted:!0,source:v,...l}}function AJ(H,q){A0.debug("admission skip: exhausted account",{accountId:H,source:q.source,resetsAt:q.resetsAt})}function $U(H,q="killswitch",O){let C=Date.now(),_=J0.getMain()?.quota,k=(H?.accounts??[]).filter((d)=>d.enabled!==!1&&V0(d)).map((d)=>({accountId:d.id,quota:J0.getFallback(d.id)?.quota})),x=bK(_,k,C,H);if(q==="quota-exhausted"&&O!==void 0)x=Math.max(1,Math.ceil((O-C)/1000));else if(q==="mid-stream-rate-limit"&&O!==void 0){let d=Math.max(1,Math.ceil((O-C)/1000));x=Math.min(x,d)}let v=Math.floor(x/60),y=x%60,l=q==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${v}m ${y}s.`:q==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${v}m ${y}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${v}m ${y}s.`;return new Response(JSON.stringify({error:{message:l,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(x)}})}function TJ(H){let q=H?.resetCreditsAvailable;return typeof q==="number"&&Number.isFinite(q)?q:void 0}async function GU(H){let q=QY(H.storage),O=Date.now(),C=J0.peekMainForPolicy(H.mainAccountIdentity),_=j9(C?.quota,C?.checkedAt,H.sidebarState.main.quota,H.sidebarState.main.mainAccountId,H.mainAccountIdentity),k=q?$Y(C?.quota,H.storage,void 0,O):void 0,x=H.mainCustodyRefused?[]:[{accountId:"main",wireAccountId:H.mainAccountIdentity,access:H.primaryAccess,provenance:H.primaryProvenance,keepwarmAccountKey:"main",quota:_.quota,quotaCheckedAt:_.quotaCheckedAt,reservePercent:WJ(H.storage),configuredOrder:0,resetCreditsApplicable:TJ(_.quota),killswitchPasses:k}],v=await Q0.getUsableFallbackAccounts(H.storage);if(!H.storage)return x;for(let y of v){let l=await a1(y,H.storage);if(l===h1||l===r1)continue;let d=H.sidebarState.fallbacks.find((U1)=>U1.id===y.id),U0=J0.peekFallbackForPolicy(y.id,y.accountId),p0=j9(U0?.quota,U0?.checkedAt,d?.quota,d?.accountId,y.accountId),R0=q?$Y(U0?.quota,H.storage,y.id,O):void 0;x.push({accountId:y.id,wireAccountId:y.accountId,access:l.token,provenance:l.provenance,keepwarmAccountKey:y.id,fallback:y,quota:p0.quota,quotaCheckedAt:p0.quotaCheckedAt,reservePercent:WJ(H.storage,y.id),configuredOrder:x.length,resetCreditsApplicable:TJ(p0.quota),killswitchPasses:R0})}return x}function RJ(H,q,O,C,_){let k=QY(_)?H.killswitchPasses:void 0;if(H.accountId==="main"){let l=J0.peekMainForPolicy(H.wireAccountId),d=j9(l?.quota,l?.checkedAt,q.main.quota,q.main.mainAccountId,H.wireAccountId);return hX({quota:d.quota,quotaCheckedAt:d.quotaCheckedAt,status:O,now:C,killswitchPasses:k})}let x=q.fallbacks.find((l)=>l.id===H.accountId),v=J0.peekFallbackForPolicy(H.accountId,H.wireAccountId),y=j9(v?.quota,v?.checkedAt,x?.quota,x?.accountId,H.wireAccountId);return hX({quota:y.quota,quotaCheckedAt:y.quotaCheckedAt,status:O,now:C,killswitchPasses:k})}function WU(H){return H.accountId==="main"?"main":H.keepwarmAccountKey}function CJ(H){return J0.isRateLimited(WU(H))}async function FX(H){let q=H.candidates.filter((y)=>!CJ(y)),O=new Map(q.map((y)=>[y.accountId,y])),C=Object.fromEntries(q.map((y)=>[y.accountId,y.quotaCheckedAt])),_=Object.fromEntries(q.map((y)=>[y.accountId,y.wireAccountId])),k=new Set(H.excludeAccountIds),x,v=await pK({sessionId:H.sessionId,requestBytes:H.requestBytes,now:H.now,validPinnedAccountIds:[...O.keys()],excludeAccountIds:H.excludeAccountIds,quotaCheckedAtByAccount:C,wireAccountIdByAccount:_,choose:(y)=>{let l=q.filter((U0)=>!k.has(U0.accountId));if(l.length===0)return;let d=Y5({candidates:l,pendingBytes:y,requestBytes:H.requestBytes,now:H.now,onEmptyWeightedSet:()=>{X1.debug("sticky routing: no fresh weighted candidates; using configured order")}});if(!d)return;return x={accountId:d.accountId,source:d.source,pendingBytes:y.get(d.accountId)??0},d}},c0);if(x&&v?.accountId===x.accountId)X1.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:GY(H.sessionId),accountId:x.accountId,source:x.source,requestBytes:H.requestBytes,pendingBytes:x.pendingBytes});return v?O.get(v.accountId):void 0}async function zU(H,q){let O=await Q0.getUsableFallbackAccounts(H),C=[];if(!H)return{current:[],retained:[],skipped:[]};for(let d of O){let U0=await a1(d,H);if(U0===h1||U0===r1)continue;C.push({access:U0.token,provenance:U0.provenance,accountId:d.accountId,keepwarmAccountKey:d.id,quotaAccountId:d.id,fallback:d})}let _=C.filter((d)=>!J0.isRateLimited(d.quotaAccountId)),k=QY(H)?_.filter((d)=>$Y(J0.peekFallbackForPolicy(d.quotaAccountId,d.accountId)?.quota,H,d.quotaAccountId,Date.now())):_,x=new Map(q.fallbacks.map((d)=>[d.id,{quota:d.quota,accountId:d.accountId}])),v=[],y=[],l=Date.now();for(let d of k){let U0=x.get(d.quotaAccountId),p0=wJ(J0.peekFallbackForPolicy(d.quotaAccountId,d.accountId),U0?.quota,l,U0?.accountId,d.accountId);if(p0.exhausted)y.push({candidate:d,decision:p0});else v.push(d)}return{current:k,retained:v,skipped:y}}function IJ(H,q){if(H.retained.length===0&&!q)return H.current;for(let{candidate:O,decision:C}of H.skipped)AJ(O.quotaAccountId,C);return H.retained}async function _J(H,q){try{let O=X9(H.headers);await q9(O,q.access,q.quotaAccountId,void 0,XY(H.headers))}catch{}}async function KU(H,q,O,C){for(let _ of C){let k;try{k=await O9(H,q,_.access,_.accountId,_.keepwarmAccountKey,_.provenance)}catch(x){if(x instanceof DOMException&&x.name==="AbortError")throw x;if(q?.signal?.aborted)throw x;throw X1.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:_.quotaAccountId}),x}if(!JY(k.status,O))return Q0.markUsed(_.fallback),{response:k,accessToken:_.access,quotaAccountId:_.quotaAccountId,activeId:_.keepwarmAccountKey};await _J(k,_),k.body?.cancel().catch(()=>{})}return}async function UU(H,q,O,C,_){if(!HY(H,q))return{response:O};if(!_.length)return{response:O};let k=O,x;for(let v of _){let y;try{y=await O9(H,q,v.access,v.accountId,v.keepwarmAccountKey,v.provenance)}catch(l){if(l instanceof DOMException&&l.name==="AbortError")throw l;if(q?.signal?.aborted)throw l;return X1.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:v.quotaAccountId}),{response:k,...x}}if(k.body?.cancel().catch(()=>{}),k=y,x={accessToken:v.access,accountId:v.quotaAccountId},!JY(y.status,C))return Q0.markUsed(v.fallback),{response:y,...x};await _J(y,v)}return{response:k,...x}}if(p){let H=[];for(let q of p.accounts)if(V0(q))H.push(q);J0.seedFallbacksFromAccounts(H)}if(!ZJ)ZJ=!0,LY(J0,p).catch(()=>{}),E1(zY({respectBackoff:!0})).catch((H)=>A0.warn("boot quota seed failed",{pid:process.pid,error:t9(H)}));return t.start(async()=>{let q=(await qQ(zY({readSidebarState:()=>n1(c0)}))).filter((O)=>!O.ok);if(q.length>0)A0.warn("background quota refresh completed with failures",{pid:process.pid,failures:q})},(H)=>{A0.warn("background quota refresh failed",{pid:process.pid,error:H instanceof Error?H.message:String(H)})}),{apiKey:dq,async fetch(H,q){let O=wK(H,q),C=AK(O),_=O.get("x-parent-session-id")?.trim()||void 0,k=await z0(),x=await M(),v=++V9;if(x.type!=="oauth")return fetch(H,q);q=await HF(H,q);let y=D&&f1(k)==="claustrum",l="",d,U0=!1;if(y){let $0=await VJ(k);if($0===h1||$0===r1)U0=!0;else l=$0.token,d=$0.provenance==="local"?void 0:$0.provenance}else{if(!x.access||(x.expires??0)<Date.now()){s1.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(x.access),expiresInMs:x.expires?x.expires-Date.now():void 0});try{let $0=await ZY();x.access=$0.access,x.refresh=$0.refresh,x.expires=$0.expires}catch($0){if($J($0))throw $0}}l=x.access??""}let R0=x.accountId??(l?$1(Q1(l)??{}):void 0);if(v===V9)o0=R0;let U1=k?.routing?.mode??"main-first",P1,C0=await(()=>{return P1??=n1(c0),P1})();if(U1==="sticky-balanced"&&C&&HY(H,q)&&typeof q?.body==="string"){let $0=Buffer.byteLength(q.body,"utf8"),M0=await GU({storage:k,sidebarState:C0,primaryAccess:l,mainAccountIdentity:R0,mainCustodyRefused:U0,primaryProvenance:d}),j0=await FX({sessionId:C,requestBytes:$0,candidates:M0,now:Date.now()});if(j0){let gJ=CJ(j0)?{action:"migrate",reason:"exhausted"}:RJ(j0,C0,void 0,Date.now(),k);if(gJ.action==="migrate"){let h0=await FX({sessionId:C,requestBytes:$0,candidates:M0,excludeAccountIds:[j0.accountId],now:Date.now()});if(h0)X1.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:GY(C),fromAccountId:j0.accountId,toAccountId:h0.accountId,reason:gJ.reason}),j0=h0}let J1=await O9(H,q,j0.access,j0.wireAccountId,j0.keepwarmAccountKey,j0.provenance),yJ=async(h0,y1)=>{try{let ZU=X9(h0.headers);await q9(ZU,y1.access,y1.accountId==="main"?void 0:y1.accountId,y1.accountId==="main"?y1.wireAccountId:void 0,XY(h0.headers))}catch{}};await yJ(J1,j0);let fJ=RJ(j0,C0,J1.status,Date.now(),k);if((J1.status===401||J1.status===403||J1.status===429)&&fJ.action==="migrate"){let h0=await FX({sessionId:C,requestBytes:$0,candidates:M0,excludeAccountIds:[j0.accountId],now:Date.now()});if(h0){X1.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:GY(C),fromAccountId:j0.accountId,toAccountId:h0.accountId,reason:fJ.reason});let y1=J1;J1=await O9(H,q,h0.access,h0.wireAccountId,h0.keepwarmAccountKey,h0.provenance),y1.body?.cancel().catch(()=>{}),j0=h0,await yJ(J1,j0)}}if(j0.fallback&&!JY(J1.status,k))Q0.markUsed(j0.fallback);return await PJ(C,_,j0.accountId,U1,k?.accounts).catch(()=>{}),J1}}let I0=wJ(J0.peekMainForPolicy(R0),C0.main.quota,Date.now(),C0.main.mainAccountId,R0),t1=QY(k)&&!$Y(QU(R0),k,void 0,Date.now()),VY=J0.isRateLimited("main"),SJ,OX=()=>{return SJ??=zU(k,C0),SJ},Z1,e1,kJ=!1,NY;if(U1==="fallback-first"&&HY(H,q)){kJ=!0;let $0=await OX();NY=IJ($0,!t1&&!VY&&!I0.exhausted);let M0=await KU(H,q,k,NY);if(M0)Z1=M0.response,e1={accessToken:M0.accessToken,accountId:M0.quotaAccountId,activeId:M0.activeId}}if(!Z1){let $0=I0.exhausted&&HY(H,q)&&(await OX()).retained.length>0;if(t1||VY||$0){let M0=t1?"killswitch":VY?"mid-stream-rate-limit":"quota-exhausted";if(M0==="quota-exhausted"&&I0.exhausted)AJ("main",I0);X1.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:M0}),Z1=$U(k,M0,M0==="quota-exhausted"&&I0.exhausted?I0.resetAtMs:VY?J0.rateLimitedUntil("main"):void 0)}else Z1=U0?new Response(null,{status:401}):await O9(H,q,l,R0,"main",d)}let xJ=Boolean(e1),D9=Z1,bJ=e1?.accessToken??l,vJ=e1?.accountId,hJ=e1?.activeId??"main";if(!e1&&!kJ&&JY(Z1.status,k)){X1.debug("reactive fallback triggered",{pid:process.pid,status:Z1.status}),NY??=IJ(await OX(),!1);let $0=await UU(H,q,Z1,k,NY),M0=$0.response;if(M0!==Z1){if(xJ=!0,D9=M0,bJ=$0.accessToken??l,vJ=$0.accountId,$0.accountId)hJ=$0.accountId}}try{let $0=X9(D9.headers);if(xJ)await q9($0,bJ,vJ,void 0,XY(D9.headers));else await q9($0,l,void 0,R0,XY(D9.headers))}catch{}return await PJ(C,_,hJ,U1,k?.accounts).catch(()=>{}),D9}}},methods:z1},"chat.headers":async(M,A)=>{if(M.model.providerID!=="openai")return;if(A.headers.originator="opencode",A.headers["User-Agent"]=`${IK(P9)} (${UX.platform()} ${UX.release()}; ${UX.arch()})`,A.headers["session-id"]=M.sessionID,W&&M.agent==="title")A.headers[x1.TITLE_HEADER]="true"},"chat.params":async(M,A)=>{if(M.model.providerID!=="openai")return;A.maxOutputTokens=void 0},config:async(M)=>{B0("commands").info("registering commands",{existing:Object.keys(M.command??{}).length,pid:process.pid}),M.command={...M.command??{},[E9]:{template:E9,description:"Show current OpenAI Codex OAuth quota usage for all accounts."},[M9]:{template:M9,description:"Manage OpenAI accounts — add, switch, remove, or reorder."},[w9]:{template:w9,description:"Show or change OpenAI account routing between main-first, fallback-first, and sticky-balanced."},[A9]:{template:A9,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."},[T9]:{template:T9,description:"Show or toggle OpenAI Codex request dump capture for debugging."},[R9]:{template:R9,description:"Show or change the plugin log level (error, warn, info, debug, trace)."},[C9]:{template:C9,description:"Keep Codex prompt cache alive during idle by shadow-replaying the last request."},[I9]:{template:I9,description:"Spend one reset credit on an exhausted Codex account."}}},"command.execute.before":async(M)=>{if(B0("commands").info("command hook entered",{command:M.command,arguments:M.arguments,modal:_9.includes(M.command),hasCmdCtx:Z!==null,pid:process.pid}),!_9.includes(M.command))return;if(!Z)B0("commands").warn("command rejected: context not loaded",{command:M.command,pid:process.pid}),await c(M.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),PK();let A=M.command,B={...Z,sessionId:M.sessionID,notify:(w)=>{iX(w,M.sessionID)}},D=await EX(A,M.arguments,B);if(w5(M.sessionID))iX(D,M.sessionID);else await c(M.sessionID,D.text);PK()}}}var PF=async(Y)=>{let X=g0();return DF(Y,{codexApiEndpoint:X.codexApiEndpoint,experimentalWebSockets:X.webSockets,responsesLite:X.responsesLite})},yM={id:"cortexkit-openai-auth",server:PF};export{AK as resolveSidebarSessionId,Q1 as parseJwtClaims,MK as mergePushedQuotaMetadata,bM as getMainRefreshLockName,LF as findCachekeepFallbackAccount,$1 as extractAccountIdFromClaims,yM as default,YF as createResetTargetResolver,gM as buildSidebarState,nK as buildSidebarMachineState,XF as buildResetRedemptionDeps,kq as __resetSweepFailureLogDedupeForTest,vM as __resetBootQuotaSeedForTest,JJ as __createCustodyRuntimeForTest,W1 as ResetTargetResolutionError,PF as OpenAIAuthPlugin,QJ as MAIN_REFRESH_LOCK_TTL_MS,rq as MAIN_REFRESH_LEASE_TTL_MS,pq as EMPTY_BEARER_MESSAGE,DF as CodexAuthPlugin,HJ as AuthPersistError};