@cortexkit/opencode-openai-auth 0.5.1 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,14 +1,14 @@
1
- import{d as E1,e as WY,f as DG}from"./index-2ng03cby.js";import{A as o0,B as b1,C as Y8,D as GW,E as WW,G as q1,H as zW,I as H1,J as A0,K as X0,L as zY,M as KY,N as h9,O as UY,P as KW,Q as UW,R as HW,h as iG,i as nG,j as oG,k as rG,l as sG,m as aG,n as tG,o as LY,p as NY,q as eY,s as eG,t as YW,u as XW,v as JW,w as QW,x as $W,y as GX,z as WX}from"./index-j1364eag.js";import{T as P8,W as HY,X as LW,_ as L1,ca as NW,da as VW,ea as BW,ja as ZW,ka as X8,la as OW,ma as FW,na as qW,oa as jW}from"./index-wnxfzjfr.js";import{ta as PY}from"./index-vrdc90yd.js";import{ua as lX,va as dX}from"./index-zkzb0twr.js";import{xa as DY,ya as EX,za as L0}from"./index-s5fbqqwx.js";import{Ca as DW}from"./index-rfgyxxxq.js";import{Fa as g8}from"./index-wpd7mg3p.js";import{mkdirSync as wN,readFileSync as EN,renameSync as MN,statSync as AN,writeFileSync as RN}from"node:fs";import x9 from"node:os";import{join as TN}from"node:path";import{readFileSync as SW}from"node:fs";import{homedir as kW,tmpdir as bW}from"node:os";import{join as qY}from"node:path";var xW="https://chatgpt.com/backend-api/codex/responses",vW="openai-auth.json",m0={noWebSearch:"CORTEXKIT_OPENAI_AUTH_NO_WEB_SEARCH",webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",responsesLite:"CORTEXKIT_OPENAI_AUTH_RESPONSES_LITE",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",codexApiEndpoint:"CORTEXKIT_OPENAI_AUTH_CODEX_ENDPOINT",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function jY(){let Y=process.env[m0.configDir]?.trim();if(Y)return Y;return qY(process.env.XDG_CONFIG_HOME||qY(kW(),".config"),"opencode")}function U0(){return process.env[m0.configFile]?.trim()||qY(jY(),vW)}function hW(){try{let Y=JSON.parse(SW(U0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function QX(Y){let X=process.env[Y];if(X===void 0)return;let J=X.trim().toLowerCase();if(J==="1"||J==="true"||J==="yes"||J==="on")return!0;if(J===""||J==="0"||J==="false"||J==="no"||J==="off")return!1;return}function FY(Y,X,J){let Q=QX(Y);if(Q!==void 0)return Q;if(typeof X==="boolean")return X;return J}function gW(){let Y=hW(),X=QX(m0.noWebSearch),J=X!==void 0?!X:typeof Y.webSearch==="boolean"?Y.webSearch:!0,Q;if(Y.dump!==void 0&&Y.dump!==null){if(typeof Y.dump==="object")Q=Y.dump.enabled;else if(typeof Y.dump==="boolean")Q=Y.dump}return{webSearch:J,webSockets:FY(m0.webSockets,Y.webSockets,!1),rawWebSocket:FY(m0.rawWebSocket,Y.rawWebSocket,!1),responsesLite:FY(m0.responsesLite,Y.responsesLite,!1),dump:FY(m0.dump,Q,!1),dumpDir:process.env[m0.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():qY(bW(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[m0.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():xW)}}var W8;function w0(){if(!W8)W8=gW();return W8}var z8="openai-quota",K8="openai-account",U8="openai-routing",H8="openai-killswitch",L8="openai-dump",N8="openai-logging",V8="openai-cachekeep",zX=["openai-quota","openai-account","openai-routing","openai-killswitch","openai-dump","openai-logging","openai-cachekeep"],G0=L0("commands");function $X(Y){if(Y==="fallback-first")return"Try usable fallback accounts before the main account.";if(Y==="sticky-balanced")return"Keep each session on its assigned account while balancing new sessions.";return"Try the main account first. Use fallback accounts only when required."}async function yW(Y){let X=await Y.refreshAllQuota?.(),J=Y.quotaManager.getMain(),Q=["## OpenAI Quota",""];if(J?.quota){let W=J.quota;Q.push("### Main account");for(let K of["primary","secondary"]){let H=W[K];if(H){let U=Math.round(H.usedPercent),N="█".repeat(Math.max(0,Math.min(Math.round(U/10),10)))+"░".repeat(Math.max(0,10-Math.min(Math.round(U/10),10)));Q.push(`- ${K}: ${N} ${U}% used (${Math.round(H.remainingPercent)}% remaining)`)}}if(W.resetCreditsAvailable!==void 0)Q.push(`- resets: ${W.resetCreditsAvailable}`)}else Q.push("No main quota snapshot available. Send a request first.");let G=[...Y.quotaManager.getAllFallbacks().entries()].filter(([,W])=>W);if(G.length>0){Q.push(""),Q.push("### Fallback accounts");for(let[W,K]of G){if(!K?.quota)continue;Q.push(`**${W}**`);for(let H of["primary","secondary"]){let U=K.quota[H];if(U){let N=Math.round(U.usedPercent);Q.push(` - ${H}: ${N}% used (${Math.round(U.remainingPercent)}% remaining)`)}}if(K.quota.resetCreditsAvailable!==void 0)Q.push(` - resets: ${K.quota.resetCreditsAvailable}`)}}if(X?.length){let W=X.filter((K)=>!K.ok);if(W.length>0){Q.push("");for(let K of W)Q.push(`- ${K.account}: fetch failed — Refresh to retry`)}}return{command:"openai-quota",text:Q.join(`
2
- `),knobs:{}}}async function fW(Y,X){let J=Y.trim().split(/\s+/).filter(Boolean),Q=await X.loadAccounts(X.accountStoragePath)??{version:1,accounts:[]},$=Q.accounts??[];if(J.length===0){let G=["## OpenAI Accounts",""];if($.length===0)G.push("No accounts configured. Use `/login openai` to add your main account, or `/openai-account add` to add a fallback account.");else{let W=Q.routing?.mode??"main-first";G.push(`Routing: \`${W}\` (set with \`/openai-routing\`). Modes: main-first, fallback-first, or sticky-balanced. \`/openai-routing reset\` clears this session's pin.`),G.push("");for(let K of $){let H=K.type??"oauth";G.push(`- \`${K.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:$}}}if(J[0]==="remove"&&J[1]){let G=J[1],W=!1,K=await X0((H)=>{let U=H.accounts.findIndex((N)=>N.id===G);if(U===-1)return H;return W=!0,H.accounts.splice(U,1),H},X.accountStoragePath);if(!W)return{command:"openai-account",text:`## Account Not Found
1
+ import{d as M1,e as zY,f as PG}from"./index-2ng03cby.js";import{A as a0,B as x1,C as Y8,D as UW,E as HW,G as j1,H as LW,I as L1,J as M0,K as J0,L as KY,M as UY,N as g9,O as HY,P as NW,Q as VW,R as BW,h as sG,i as aG,j as tG,k as eG,l as YW,m as XW,n as JW,o as NY,p as VY,q as eY,s as QW,t as $W,u as GW,v as WW,w as zW,x as KW,y as WX,z as zX}from"./index-qhvsskdz.js";import{T as P8,W as LY,X as ZW,_ as N1,ca as OW,da as FW,ea as qW,ja as jW,ka as X8,la as DW,ma as PW,na as wW,oa as EW}from"./index-wnxfzjfr.js";import{ta as PY}from"./index-vrdc90yd.js";import{ua as dX,va as iX}from"./index-zkzb0twr.js";import{xa as DY,ya as MX,za as H0}from"./index-s5fbqqwx.js";import{Ca as MW}from"./index-rfgyxxxq.js";import{Fa as g8}from"./index-wpd7mg3p.js";import{mkdirSync as MN,readFileSync as AN,renameSync as RN,statSync as TN,writeFileSync as CN}from"node:fs";import v9 from"node:os";import{join as _N}from"node:path";import{readFileSync as vW}from"node:fs";import{homedir as hW,tmpdir as gW}from"node:os";import{join as qY}from"node:path";var yW="https://chatgpt.com/backend-api/codex/responses",fW="openai-auth.json",u0={noWebSearch:"CORTEXKIT_OPENAI_AUTH_NO_WEB_SEARCH",webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",responsesLite:"CORTEXKIT_OPENAI_AUTH_RESPONSES_LITE",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",codexApiEndpoint:"CORTEXKIT_OPENAI_AUTH_CODEX_ENDPOINT",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function jY(){let Y=process.env[u0.configDir]?.trim();if(Y)return Y;return qY(process.env.XDG_CONFIG_HOME||qY(hW(),".config"),"opencode")}function K0(){return process.env[u0.configFile]?.trim()||qY(jY(),fW)}function mW(){try{let Y=JSON.parse(vW(K0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function $X(Y){let X=process.env[Y];if(X===void 0)return;let J=X.trim().toLowerCase();if(J==="1"||J==="true"||J==="yes"||J==="on")return!0;if(J===""||J==="0"||J==="false"||J==="no"||J==="off")return!1;return}function FY(Y,X,J){let Q=$X(Y);if(Q!==void 0)return Q;if(typeof X==="boolean")return X;return J}function cW(){let Y=mW(),X=$X(u0.noWebSearch),J=X!==void 0?!X:typeof Y.webSearch==="boolean"?Y.webSearch:!0,Q;if(Y.dump!==void 0&&Y.dump!==null){if(typeof Y.dump==="object")Q=Y.dump.enabled;else if(typeof Y.dump==="boolean")Q=Y.dump}return{webSearch:J,webSockets:FY(u0.webSockets,Y.webSockets,!1),rawWebSocket:FY(u0.rawWebSocket,Y.rawWebSocket,!1),responsesLite:FY(u0.responsesLite,Y.responsesLite,!1),dump:FY(u0.dump,Q,!1),dumpDir:process.env[u0.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():qY(gW(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[u0.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():yW)}}var W8;function P0(){if(!W8)W8=cW();return W8}var z8="openai-quota",K8="openai-account",U8="openai-routing",H8="openai-killswitch",L8="openai-dump",N8="openai-logging",V8="openai-cachekeep",KX=["openai-quota","openai-account","openai-routing","openai-killswitch","openai-dump","openai-logging","openai-cachekeep"],G0=H0("commands");function GX(Y){if(Y==="fallback-first")return"Try usable fallback accounts before the main account.";if(Y==="sticky-balanced")return"Keep each session on its assigned account while balancing new sessions.";return"Try the main account first. Use fallback accounts only when required."}async function uW(Y){let X=await Y.refreshAllQuota?.(),J=Y.quotaManager.getMain(),Q=["## OpenAI Quota",""];if(J?.quota){let W=J.quota;Q.push("### Main account");for(let K of["primary","secondary"]){let U=W[K];if(U){let H=Math.round(U.usedPercent),N="█".repeat(Math.max(0,Math.min(Math.round(H/10),10)))+"░".repeat(Math.max(0,10-Math.min(Math.round(H/10),10)));Q.push(`- ${K}: ${N} ${H}% used (${Math.round(U.remainingPercent)}% remaining)`)}}if(W.resetCreditsAvailable!==void 0)Q.push(`- resets: ${W.resetCreditsAvailable}`)}else Q.push("No main quota snapshot available. Send a request first.");let G=[...Y.quotaManager.getAllFallbacks().entries()].filter(([,W])=>W);if(G.length>0){Q.push(""),Q.push("### Fallback accounts");for(let[W,K]of G){if(!K?.quota)continue;Q.push(`**${W}**`);for(let U of["primary","secondary"]){let H=K.quota[U];if(H){let N=Math.round(H.usedPercent);Q.push(` - ${U}: ${N}% used (${Math.round(H.remainingPercent)}% remaining)`)}}if(K.quota.resetCreditsAvailable!==void 0)Q.push(` - resets: ${K.quota.resetCreditsAvailable}`)}}if(X?.length){let W=X.filter((K)=>!K.ok);if(W.length>0){Q.push("");for(let K of W)Q.push(`- ${K.account}: fetch failed — Refresh to retry`)}}return{command:"openai-quota",text:Q.join(`
2
+ `),knobs:{}}}async function pW(Y,X){let J=Y.trim().split(/\s+/).filter(Boolean),Q=await X.loadAccounts(X.accountStoragePath)??{version:1,accounts:[]},$=Q.accounts??[];if(J.length===0){let G=["## OpenAI Accounts",""];if($.length===0)G.push("No accounts configured. Use `/login openai` to add your main account, or `/openai-account add` to add a fallback account.");else{let W=Q.routing?.mode??"main-first";G.push(`Routing: \`${W}\` (set with \`/openai-routing\`). Modes: main-first, fallback-first, or sticky-balanced. \`/openai-routing reset\` clears this session's pin.`),G.push("");for(let K of $){let U=K.type??"oauth";G.push(`- \`${K.id}\` (${U})`)}}return G.push(""),G.push("Commands: `/openai-account add [label]` | `/openai-account remove <id>`"),{command:"openai-account",text:G.join(`
3
+ `),knobs:{accounts:$}}}if(J[0]==="remove"&&J[1]){let G=J[1],W=!1,K=await J0((U)=>{let H=U.accounts.findIndex((N)=>N.id===G);if(H===-1)return U;return W=!0,U.accounts.splice(H,1),U},X.accountStoragePath);if(!W)return{command:"openai-account",text:`## Account Not Found
4
4
 
5
5
  No account with id \`${G}\` exists.`,knobs:{accounts:K.accounts}};return G0.info("account removed",{id:G}),X.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Account Removed
6
6
 
7
- Removed account \`${G}\`.`,knobs:{accounts:K.accounts}}}if(J[0]==="order"&&J.length>=3){let G=!1,W=await X0((K)=>{let H=K.accounts.findIndex((O)=>O.id===J[1]),U=K.accounts.findIndex((O)=>O.id===J[2]);if(H===-1||U===-1)return K;G=!0;let N=K.accounts[H];return K.accounts[H]=K.accounts[U],K.accounts[U]=N,K},X.accountStoragePath);if(!G)return{command:"openai-account",text:`## Invalid Order
7
+ Removed account \`${G}\`.`,knobs:{accounts:K.accounts}}}if(J[0]==="order"&&J.length>=3){let G=!1,W=await J0((K)=>{let U=K.accounts.findIndex((O)=>O.id===J[1]),H=K.accounts.findIndex((O)=>O.id===J[2]);if(U===-1||H===-1)return K;G=!0;let N=K.accounts[U];return K.accounts[U]=K.accounts[H],K.accounts[H]=N,K},X.accountStoragePath);if(!G)return{command:"openai-account",text:`## Invalid Order
8
8
 
9
9
  Both account IDs must exist.`,knobs:{accounts:W.accounts}};return G0.info("accounts reordered",{a:J[1],b:J[2]}),X.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Accounts Reordered
10
10
 
11
- Swapped positions of \`${J[1]}\` and \`${J[2]}\`.`,knobs:{accounts:W.accounts}}}if(J[0]==="add"){let G=J.includes("--headless"),W=J.filter((L)=>L!=="add"&&L!=="--headless"),K=W.length>0?W.join(" "):void 0,{url:H,instructions:U,completion:N}=await WX({label:K,headless:G}),O=X.notify,B=X.sessionId;if(N.then(async(L)=>{let Z=!1;if(await X0((j)=>{if(L.accountId&&j.mainAccountId&&L.accountId===j.mainAccountId)return Z=!0,j;return GX(j.accounts,L),j},X.accountStoragePath),Z){G0.warn("account add rejected (main identity)",{id:L.id,sessionId:B}),O?.({command:"openai-account",text:`## Add Failed
11
+ Swapped positions of \`${J[1]}\` and \`${J[2]}\`.`,knobs:{accounts:W.accounts}}}if(J[0]==="add"){let G=J.includes("--headless"),W=J.filter((L)=>L!=="add"&&L!=="--headless"),K=W.length>0?W.join(" "):void 0,{url:U,instructions:H,completion:N}=await zX({label:K,headless:G}),O=X.notify,B=X.sessionId;if(N.then(async(L)=>{let Z=!1;if(await J0((j)=>{if(L.accountId&&j.mainAccountId&&L.accountId===j.mainAccountId)return Z=!0,j;return WX(j.accounts,L),j},X.accountStoragePath),Z){G0.warn("account add rejected (main identity)",{id:L.id,sessionId:B}),O?.({command:"openai-account",text:`## Add Failed
12
12
 
13
13
  ${"That account is already your main account — not added as a fallback."}`,knobs:{}});return}G0.info("account added",{id:L.id,label:L.label}),X.refreshSidebar?.().catch(()=>{}),O?.({command:"openai-account",text:`## Account Added
14
14
 
@@ -16,153 +16,153 @@ Added account \`${L.id}\`${L.label?` ("${L.label}")`:""}.
16
16
 
17
17
  Run \`/openai-account\` to confirm.`,knobs:{}})}).catch((L)=>{let Z=L instanceof Error?L.message:String(L??"unknown error");G0.warn("account add failed",{error:Z,sessionId:B}),O?.({command:"openai-account",text:`## Add Failed
18
18
 
19
- Account add failed: ${Z}`,knobs:{}})}),G){let L=U.match(/Enter code: (.+)/)?.[1]??U;return{command:"openai-account",text:`## Device Code
19
+ Account add failed: ${Z}`,knobs:{}})}),G){let L=H.match(/Enter code: (.+)/)?.[1]??H;return{command:"openai-account",text:`## Device Code
20
20
 
21
21
  1. Open this verification URL:
22
22
 
23
- ${H}
23
+ ${U}
24
24
 
25
25
  2. Enter the code: **${L}**
26
26
 
27
- ${U}
27
+ ${H}
28
28
 
29
- The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{verificationUrl:H,userCode:L,instructions:U}}}return{command:"openai-account",text:`## Add OpenAI Account
29
+ The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{verificationUrl:U,userCode:L,instructions:H}}}return{command:"openai-account",text:`## Add OpenAI Account
30
30
 
31
31
  Open this URL and complete sign-in:
32
32
 
33
- ${H}
34
-
35
33
  ${U}
36
34
 
37
- The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{url:H,instructions:U}}}return{command:"openai-account",text:"## Account Commands\n\n- `/openai-account` — show accounts\n- `/openai-account add [label]` — add a new account\n- `/openai-account remove <id>` — remove\n- `/openai-account order <a> <b>` — swap fallback positions\n\nRouting modes are `main-first`, `fallback-first`, and `sticky-balanced`. `/openai-routing reset` clears the current session pin.",knobs:{accounts:$}}}async function mW(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
35
+ ${H}
36
+
37
+ The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{url:U,instructions:H}}}return{command:"openai-account",text:"## Account Commands\n\n- `/openai-account` — show accounts\n- `/openai-account add [label]` — add a new account\n- `/openai-account remove <id>` — remove\n- `/openai-account order <a> <b>` — swap fallback positions\n\nRouting modes are `main-first`, `fallback-first`, and `sticky-balanced`. `/openai-routing reset` clears the current session pin.",knobs:{accounts:$}}}async function lW(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),$=(await X.loadAccounts(X.accountStoragePath)??{version:1,accounts:[]}).routing?.mode??"main-first";if(J.length===1&&J[0]==="reset"){if(!X.sessionId)return{command:"openai-routing",text:`## OpenAI Routing Reset
38
38
 
39
39
  No current session is available, so no pin was changed.`,knobs:{mode:$}};if(!X.clearStickyRouting)return{command:"openai-routing",text:`## OpenAI Routing Reset
40
40
 
41
41
  This runtime cannot clear the current session pin.`,knobs:{mode:$}};return await X.clearStickyRouting(X.sessionId),G0.info("routing session pin cleared"),{command:"openai-routing",text:`## OpenAI Routing Reset
42
42
 
43
- This session's pin was cleared. The next request may choose the same account if it remains the best selection.`,knobs:{mode:$}}}if(J.length===1&&(J[0]==="main-first"||J[0]==="fallback-first"||J[0]==="sticky-balanced")){let K=J[0];return await X0((H)=>{return H.routing={...H.routing??{},mode:K},H},X.accountStoragePath),G0.info("routing mode changed",{mode:K}),{command:"openai-routing",text:`## OpenAI Routing Updated
43
+ This session's pin was cleared. The next request may choose the same account if it remains the best selection.`,knobs:{mode:$}}}if(J.length===1&&(J[0]==="main-first"||J[0]==="fallback-first"||J[0]==="sticky-balanced")){let K=J[0];return await J0((U)=>{return U.routing={...U.routing??{},mode:K},U},X.accountStoragePath),G0.info("routing mode changed",{mode:K}),{command:"openai-routing",text:`## OpenAI Routing Updated
44
44
 
45
45
  Mode: \`${K}\`
46
- - ${$X(K)}
46
+ - ${GX(K)}
47
47
 
48
48
  Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:K}}}let G=$==="sticky-balanced"&&X.sessionId?await X.getStickyRouting?.(X.sessionId):void 0,W=$==="sticky-balanced"?G?`
49
49
  - Session pin: \`${G}\`. Use \`/openai-routing reset\` to clear it.`:`
50
50
  - Session pin: none yet. A request will choose one when a usable account is available.`:"";return{command:"openai-routing",text:`## OpenAI Routing
51
51
 
52
52
  - Mode: \`${$}\`
53
- - ${$X($)}${W}
53
+ - ${GX($)}${W}
54
54
 
55
- Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:$}}}async function cW(Y,X){let J=await X.loadAccounts(X.accountStoragePath)??{version:1,accounts:[]},Q=J.killswitch??{},$=(J.accounts??[]).filter((W)=>W.enabled!==!1).map((W)=>W.id),G=Y.trim().toLowerCase().split(/\s+/).filter(Boolean);if(G.length===0){let W=Q.enabled===!0,K=["## Killswitch","",`Status: **${W?"ON":"OFF"}**`];if(W){K.push(""),K.push("| Account | primary threshold | secondary threshold |"),K.push("| ------- | ------------ | ------------ |");let H=Q.main??{},U=H.primary??H["5h"]??H1.primary,N=H.secondary??H["1w"]??H1.secondary;K.push(`| main | ≥ ${U}% | ≥ ${N}% |`);for(let O of $){let B=Q.accounts?.[O]??Q.main??{},L=B.primary??B["5h"]??H1.primary,Z=B.secondary??B["1w"]??H1.secondary;K.push(`| ${O} | ≥ ${L}% | ≥ ${Z}% |`)}}return K.push(""),K.push("Commands: `/openai-killswitch on` | `/openai-killswitch off` | `/openai-killswitch set <acct>:<5h>,<1w> ...`"),{command:"openai-killswitch",text:K.join(`
56
- `),knobs:{config:Q,accountIds:$}}}if(G[0]==="on"){let W={...Q,enabled:!0,main:Q.main??{primary:H1.primary,secondary:H1.secondary}};return await X0((K)=>{return K.killswitch=W,K},X.accountStoragePath),G0.info("killswitch enabled"),{command:"openai-killswitch",text:"## Killswitch Enabled",knobs:{config:W,accountIds:$}}}if(G[0]==="off"){let W={...Q,enabled:!1};return await X0((K)=>{return K.killswitch=W,K},X.accountStoragePath),G0.info("killswitch disabled"),{command:"openai-killswitch",text:"## Killswitch Disabled",knobs:{config:W,accountIds:$}}}if(G[0]==="set"&&G.length>1){let W={...Q,enabled:!0,accounts:{...Q.accounts??{}}};for(let K=1;K<G.length;K++){let H=G[K]?.match(/^([^:]+):(\d+),(\d+)$/);if(!H)continue;let[,U,N,O]=H,B={primary:Number.parseInt(N,10),secondary:Number.parseInt(O,10)};if(U==="main")W.main=B;else if(U==="all"){W.main=B;for(let L of $)W.accounts[L]=B}else W.accounts[U]=B}return await X0((K)=>{return K.killswitch=W,K},X.accountStoragePath),G0.info("killswitch thresholds updated",{count:G.length-1}),{command:"openai-killswitch",text:"## Killswitch Updated",knobs:{config:W,accountIds:$}}}return{command:"openai-killswitch",text:"Usage: `/openai-killswitch`, `/openai-killswitch on`, `/openai-killswitch off`, `/openai-killswitch set <acct>:<5h>,<1w> ...`",knobs:{config:Q,accountIds:$}}}async function uW(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),Q=w0(),$=Q.dump;if(J.length===0)return{command:"openai-dump",text:`## Request Dump
55
+ Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:$}}}async function dW(Y,X){let J=await X.loadAccounts(X.accountStoragePath)??{version:1,accounts:[]},Q=J.killswitch??{},$=(J.accounts??[]).filter((W)=>W.enabled!==!1).map((W)=>W.id),G=Y.trim().toLowerCase().split(/\s+/).filter(Boolean);if(G.length===0){let W=Q.enabled===!0,K=["## Killswitch","",`Status: **${W?"ON":"OFF"}**`];if(W){K.push(""),K.push("| Account | primary threshold | secondary threshold |"),K.push("| ------- | ------------ | ------------ |");let U=Q.main??{},H=U.primary??U["5h"]??L1.primary,N=U.secondary??U["1w"]??L1.secondary;K.push(`| main | ≥ ${H}% | ≥ ${N}% |`);for(let O of $){let B=Q.accounts?.[O]??Q.main??{},L=B.primary??B["5h"]??L1.primary,Z=B.secondary??B["1w"]??L1.secondary;K.push(`| ${O} | ≥ ${L}% | ≥ ${Z}% |`)}}return K.push(""),K.push("Commands: `/openai-killswitch on` | `/openai-killswitch off` | `/openai-killswitch set <acct>:<5h>,<1w> ...`"),{command:"openai-killswitch",text:K.join(`
56
+ `),knobs:{config:Q,accountIds:$}}}if(G[0]==="on"){let W={...Q,enabled:!0,main:Q.main??{primary:L1.primary,secondary:L1.secondary}};return await J0((K)=>{return K.killswitch=W,K},X.accountStoragePath),G0.info("killswitch enabled"),{command:"openai-killswitch",text:"## Killswitch Enabled",knobs:{config:W,accountIds:$}}}if(G[0]==="off"){let W={...Q,enabled:!1};return await J0((K)=>{return K.killswitch=W,K},X.accountStoragePath),G0.info("killswitch disabled"),{command:"openai-killswitch",text:"## Killswitch Disabled",knobs:{config:W,accountIds:$}}}if(G[0]==="set"&&G.length>1){let W={...Q,enabled:!0,accounts:{...Q.accounts??{}}};for(let K=1;K<G.length;K++){let U=G[K]?.match(/^([^:]+):(\d+),(\d+)$/);if(!U)continue;let[,H,N,O]=U,B={primary:Number.parseInt(N,10),secondary:Number.parseInt(O,10)};if(H==="main")W.main=B;else if(H==="all"){W.main=B;for(let L of $)W.accounts[L]=B}else W.accounts[H]=B}return await J0((K)=>{return K.killswitch=W,K},X.accountStoragePath),G0.info("killswitch thresholds updated",{count:G.length-1}),{command:"openai-killswitch",text:"## Killswitch Updated",knobs:{config:W,accountIds:$}}}return{command:"openai-killswitch",text:"Usage: `/openai-killswitch`, `/openai-killswitch on`, `/openai-killswitch off`, `/openai-killswitch set <acct>:<5h>,<1w> ...`",knobs:{config:Q,accountIds:$}}}async function iW(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),Q=P0(),$=Q.dump;if(J.length===0)return{command:"openai-dump",text:`## Request Dump
57
57
 
58
58
  - Enabled: ${$?"ON":"OFF"}
59
59
  - Directory: ${Q.dumpDir}
60
60
 
61
- Usage: \`/openai-dump on\` or \`/openai-dump off\``,knobs:{enabled:$}};if(J[0]==="on")return await X0((G)=>{return G.dump={...G.dump??{},enabled:!0},G},X.accountStoragePath),G0.info("request dump enabled"),{command:"openai-dump",text:`## Request Dump Enabled
61
+ Usage: \`/openai-dump on\` or \`/openai-dump off\``,knobs:{enabled:$}};if(J[0]==="on")return await J0((G)=>{return G.dump={...G.dump??{},enabled:!0},G},X.accountStoragePath),G0.info("request dump enabled"),{command:"openai-dump",text:`## Request Dump Enabled
62
62
 
63
63
  Dump directory: ${Q.dumpDir}
64
64
 
65
- Warning: body dumps may contain prompt/session content. Turn this off after debugging.`,knobs:{enabled:!0}};if(J[0]==="off")return await X0((G)=>{return G.dump={...G.dump??{},enabled:!1},G},X.accountStoragePath),G0.info("request dump disabled"),{command:"openai-dump",text:"## Request Dump Disabled",knobs:{enabled:!1}};return{command:"openai-dump",text:"Usage: `/openai-dump`, `/openai-dump on`, or `/openai-dump off`.",knobs:{enabled:$}}}async function pW(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),Q=["error","warn","info","debug","trace"];if(J.length===0){let W=(await X.loadAccounts(X.accountStoragePath))?.logging?.level??"info";return{command:"openai-logging",text:`## Logging
65
+ Warning: body dumps may contain prompt/session content. Turn this off after debugging.`,knobs:{enabled:!0}};if(J[0]==="off")return await J0((G)=>{return G.dump={...G.dump??{},enabled:!1},G},X.accountStoragePath),G0.info("request dump disabled"),{command:"openai-dump",text:"## Request Dump Disabled",knobs:{enabled:!1}};return{command:"openai-dump",text:"Usage: `/openai-dump`, `/openai-dump on`, or `/openai-dump off`.",knobs:{enabled:$}}}async function nW(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),Q=["error","warn","info","debug","trace"];if(J.length===0){let W=(await X.loadAccounts(X.accountStoragePath))?.logging?.level??"info";return{command:"openai-logging",text:`## Logging
66
66
 
67
67
  - Level: \`${W}\`
68
68
 
69
69
  Valid levels: ${Q.map((K)=>`\`${K}\``).join(", ")}
70
70
 
71
- Usage: \`/openai-logging <level>\``,knobs:{level:W}}}let $=J[0];if($&&Q.includes($)){let G=$;return DY(G),await X0((W)=>{return W.logging={...W.logging??{},level:G},W},X.accountStoragePath),G0.info("log level changed",{level:G}),{command:"openai-logging",text:`## Logging Updated
71
+ Usage: \`/openai-logging <level>\``,knobs:{level:W}}}let $=J[0];if($&&Q.includes($)){let G=$;return DY(G),await J0((W)=>{return W.logging={...W.logging??{},level:G},W},X.accountStoragePath),G0.info("log level changed",{level:G}),{command:"openai-logging",text:`## Logging Updated
72
72
 
73
73
  Level set to \`${G}\`.`,knobs:{level:G}}}return{command:"openai-logging",text:`## Invalid Level
74
74
 
75
- Valid levels: ${Q.map((G)=>`\`${G}\``).join(", ")}`,knobs:{level:"info"}}}function lW(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 dW(Y,X){let J=X.cacheKeepManager,Q=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),$=await X.loadAccounts(X.accountStoragePath),G=$?.cachekeep?.enabled===!0;if(Q.length===0||Q[0]==="status"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
75
+ Valid levels: ${Q.map((G)=>`\`${G}\``).join(", ")}`,knobs:{level:"info"}}}function oW(Y){let X=/^(\d{1,2})-(\d{1,2})$/.exec(Y.trim());if(!X)return{ok:!1,reason:"expected HH-HH, e.g. 9-18 or 22-6"};let J=Number(X[1]),Q=Number(X[2]);if(!Number.isInteger(J)||!Number.isInteger(Q)||J<0||J>23||Q<0||Q>23||J===Q)return{ok:!1,reason:"hours must be integers 0-23 and start ≠ end"};return{ok:!0,startHour:J,endHour:Q}}async function rW(Y,X){let J=X.cacheKeepManager,Q=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),$=await X.loadAccounts(X.accountStoragePath),G=$?.cachekeep?.enabled===!0;if(Q.length===0||Q[0]==="status"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
76
76
 
77
- Status: **not available** (manager not wired)`,knobs:{}};let K=J.status(),H=K.window,U=H?`${String(H.startHour).padStart(2,"0")}-${String(H.endHour).padStart(2,"0")}`:"always (no window)",N=["## Cachekeep","",`Status: **${G?"ON":"OFF"}**`,`Timer: **${K.running?"armed":"idle"}**`,`Subagent warming: **${$?.cachekeep?.subagents===!0?"ON":"OFF"}**`,`Idle policy: **sustain ${K.sustain?"ON":"OFF"} (main only)**`,`Window: **${U}**`];if(N.push(`Tracked sessions: **${K.tracked}**`),K.targets.length>0){N.push("");for(let B of K.targets){let L=B.sessionKey.length>12?`${B.sessionKey.slice(0,12)}…`:B.sessionKey,Z=Math.ceil((B.cacheExpiresAt-K.generatedAt)/1000);N.push(`- \`${L}\` (${B.accountId??"main"}) — expires in ${Z}s`+(B.lastWarmedAt?`, last warm ${Math.ceil((K.generatedAt-B.lastWarmedAt)/1000)}s ago`:"")+(B.backoffUntil&&B.backoffUntil>K.generatedAt?`, backoff ${Math.ceil((B.backoffUntil-K.generatedAt)/1000)}s`:""))}}N.push(""),N.push(`TTL: ${Math.round(K.ttlMs/1000)}s | Lead: ${Math.round(K.leadMs/1000)}s | Max idle warm: ${Math.round(K.maxIdleWarmMs/60000)}min`),N.push(""),N.push("Commands: `/openai-cachekeep on` | `/openai-cachekeep off` | `/openai-cachekeep sustain on` | `/openai-cachekeep sustain off` | `/openai-cachekeep HH-HH` | `/openai-cachekeep window clear` | `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off` | `/openai-cachekeep`");let O=Math.max(0,...K.targets.map((B)=>B.lastWarmedAt??0));return{command:"openai-cachekeep",text:N.join(`
78
- `),knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:K.sustain,window:H,running:K.running,tracked:K.tracked,lastWarmAt:O||void 0,generatedAt:K.generatedAt,maxIdleWarmMs:K.maxIdleWarmMs,maxSubagentIdleMs:K.maxSubagentIdleMs}}}if(Q[0]==="on"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
77
+ Status: **not available** (manager not wired)`,knobs:{}};let K=J.status(),U=K.window,H=U?`${String(U.startHour).padStart(2,"0")}-${String(U.endHour).padStart(2,"0")}`:"always (no window)",N=["## Cachekeep","",`Status: **${G?"ON":"OFF"}**`,`Timer: **${K.running?"armed":"idle"}**`,`Subagent warming: **${$?.cachekeep?.subagents===!0?"ON":"OFF"}**`,`Idle policy: **sustain ${K.sustain?"ON":"OFF"} (main only)**`,`Window: **${H}**`];if(N.push(`Tracked sessions: **${K.tracked}**`),K.targets.length>0){N.push("");for(let B of K.targets){let L=B.sessionKey.length>12?`${B.sessionKey.slice(0,12)}…`:B.sessionKey,Z=Math.ceil((B.cacheExpiresAt-K.generatedAt)/1000);N.push(`- \`${L}\` (${B.accountId??"main"}) — expires in ${Z}s`+(B.lastWarmedAt?`, last warm ${Math.ceil((K.generatedAt-B.lastWarmedAt)/1000)}s ago`:"")+(B.backoffUntil&&B.backoffUntil>K.generatedAt?`, backoff ${Math.ceil((B.backoffUntil-K.generatedAt)/1000)}s`:""))}}N.push(""),N.push(`TTL: ${Math.round(K.ttlMs/1000)}s | Lead: ${Math.round(K.leadMs/1000)}s | Max idle warm: ${Math.round(K.maxIdleWarmMs/60000)}min`),N.push(""),N.push("Commands: `/openai-cachekeep on` | `/openai-cachekeep off` | `/openai-cachekeep sustain on` | `/openai-cachekeep sustain off` | `/openai-cachekeep HH-HH` | `/openai-cachekeep window clear` | `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off` | `/openai-cachekeep`");let O=Math.max(0,...K.targets.map((B)=>B.lastWarmedAt??0));return{command:"openai-cachekeep",text:N.join(`
78
+ `),knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:K.sustain,window:U,running:K.running,tracked:K.tracked,lastWarmAt:O||void 0,generatedAt:K.generatedAt,maxIdleWarmMs:K.maxIdleWarmMs,maxSubagentIdleMs:K.maxSubagentIdleMs}}}if(Q[0]==="on"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
79
79
 
80
- Cannot start: manager not wired.`,knobs:{}};await X0((U)=>{return U.cachekeep={...U.cachekeep??{},enabled:!0},U},X.accountStoragePath),G0.info("cachekeep enabled"),X.setCacheKeepEnabled?.(!0),J.start();let K=J.status(),H=Math.max(0,...K.targets.map((U)=>U.lastWarmedAt??0));return{command:"openai-cachekeep",text:`## Cachekeep Enabled
80
+ Cannot start: manager not wired.`,knobs:{}};await J0((H)=>{return H.cachekeep={...H.cachekeep??{},enabled:!0},H},X.accountStoragePath),G0.info("cachekeep enabled"),X.setCacheKeepEnabled?.(!0),J.start();let K=J.status(),U=Math.max(0,...K.targets.map((H)=>H.lastWarmedAt??0));return{command:"openai-cachekeep",text:`## Cachekeep Enabled
81
81
 
82
- TTL: ${Math.round(K.ttlMs/1000)}s | Max idle warm ${Math.round(K.maxIdleWarmMs/60000)}min`,knobs:{enabled:!0,subagents:$?.cachekeep?.subagents===!0,sustain:K.sustain,window:K.window,running:K.running,tracked:K.tracked,lastWarmAt:H||void 0,generatedAt:K.generatedAt,maxIdleWarmMs:K.maxIdleWarmMs,maxSubagentIdleMs:K.maxSubagentIdleMs}}}if(Q[0]==="off")return await X0((K)=>{return K.cachekeep={...K.cachekeep??{},enabled:!1},K},X.accountStoragePath),G0.info("cachekeep disabled"),X.setCacheKeepEnabled?.(!1),J?.stop(),{command:"openai-cachekeep",text:"## Cachekeep Disabled",knobs:{enabled:!1,sustain:$?.cachekeep?.sustain===!0,running:!1,tracked:0}};if(Q[0]==="sustain"){let K=Q[1];if(Q.length!==2||K!=="on"&&K!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep sustain on` | `/openai-cachekeep sustain off`",knobs:{}};let H=K==="on";await X0((N)=>{return N.cachekeep={...N.cachekeep??{},sustain:H},N},X.accountStoragePath),G0.info(`cachekeep sustain ${H?"enabled":"disabled"}`),X.setCacheKeepSustain?.(H);let U=J?.status();return{command:"openai-cachekeep",text:H?`## Cachekeep Sustain Enabled
82
+ TTL: ${Math.round(K.ttlMs/1000)}s | Max idle warm ${Math.round(K.maxIdleWarmMs/60000)}min`,knobs:{enabled:!0,subagents:$?.cachekeep?.subagents===!0,sustain:K.sustain,window:K.window,running:K.running,tracked:K.tracked,lastWarmAt:U||void 0,generatedAt:K.generatedAt,maxIdleWarmMs:K.maxIdleWarmMs,maxSubagentIdleMs:K.maxSubagentIdleMs}}}if(Q[0]==="off")return await J0((K)=>{return K.cachekeep={...K.cachekeep??{},enabled:!1},K},X.accountStoragePath),G0.info("cachekeep disabled"),X.setCacheKeepEnabled?.(!1),J?.stop(),{command:"openai-cachekeep",text:"## Cachekeep Disabled",knobs:{enabled:!1,sustain:$?.cachekeep?.sustain===!0,running:!1,tracked:0}};if(Q[0]==="sustain"){let K=Q[1];if(Q.length!==2||K!=="on"&&K!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep sustain on` | `/openai-cachekeep sustain off`",knobs:{}};let U=K==="on";await J0((N)=>{return N.cachekeep={...N.cachekeep??{},sustain:U},N},X.accountStoragePath),G0.info(`cachekeep sustain ${U?"enabled":"disabled"}`),X.setCacheKeepSustain?.(U);let H=J?.status();return{command:"openai-cachekeep",text:U?`## Cachekeep Sustain Enabled
83
83
 
84
84
  Sustain keeps main-agent sessions warming past the idle cap for this process. Clock windows still apply.
85
85
 
86
86
  Before enabling sustain with Magic Context, set a non-expiring \`cache_ttl\` for models used by main sessions; elapsed-time cold-cache assumptions are no longer valid.`:`## Cachekeep Sustain Disabled
87
87
 
88
- Main-agent sessions again stop warming at the configured idle cap.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:H,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 H=K==="on";await X0((N)=>{return N.cachekeep={...N.cachekeep??{},subagents:H},N},X.accountStoragePath),G0.info(H?"cachekeep subagent warming enabled":"cachekeep subagent warming disabled"),X.setCacheKeepSubagents?.(H);let U=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Subagent Warming
88
+ Main-agent sessions again stop warming at the configured idle cap.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:U,window:H?.window,running:H?.running??!1,tracked:H?.tracked??0,generatedAt:H?.generatedAt??Date.now(),maxIdleWarmMs:H?.maxIdleWarmMs??3600000,maxSubagentIdleMs:H?.maxSubagentIdleMs??1800000}}}if(Q[0]==="subagents"){let K=Q[1];if(!K||K!=="on"&&K!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off`",knobs:{}};let U=K==="on";await J0((N)=>{return N.cachekeep={...N.cachekeep??{},subagents:U},N},X.accountStoragePath),G0.info(U?"cachekeep subagent warming enabled":"cachekeep subagent warming disabled"),X.setCacheKeepSubagents?.(U);let H=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Subagent Warming
89
89
 
90
- Subagent warming: **${H?"ON":"OFF"}**`,knobs:{enabled:G,subagents:H,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 X0((U)=>{if(U.cachekeep)delete U.cachekeep.startHour,delete U.cachekeep.endHour;return U},X.accountStoragePath),X.setCacheKeepWindow?.(void 0),G0.info("cachekeep window cleared");let H=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Cleared
90
+ Subagent warming: **${U?"ON":"OFF"}**`,knobs:{enabled:G,subagents:U,sustain:H?.sustain??$?.cachekeep?.sustain===!0,window:H?.window,running:H?.running??!1,tracked:H?.tracked??0,generatedAt:H?.generatedAt??Date.now(),maxIdleWarmMs:H?.maxIdleWarmMs??3600000,maxSubagentIdleMs:H?.maxSubagentIdleMs??1800000}}}if(Q[0]==="window"){let K=Q[1];if(K==="clear"||K==="off"){await J0((H)=>{if(H.cachekeep)delete H.cachekeep.startHour,delete H.cachekeep.endHour;return H},X.accountStoragePath),X.setCacheKeepWindow?.(void 0),G0.info("cachekeep window cleared");let U=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Cleared
91
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 K=lW(W);if(!K.ok)return{command:"openai-cachekeep",text:`## Cachekeep Window Invalid
92
+ Cachekeep will now warm on every tick (within idle caps).`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:U?.sustain??$?.cachekeep?.sustain===!0,window:void 0,running:U?.running??!1,tracked:U?.tracked??0,generatedAt:U?.generatedAt??Date.now(),maxIdleWarmMs:U?.maxIdleWarmMs??3600000,maxSubagentIdleMs:U?.maxSubagentIdleMs??1800000}}}return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep window clear`",knobs:{}}}let W=Q[0];if(W&&/^\d{1,2}-\d{1,2}$/.test(W)){let K=oW(W);if(!K.ok)return{command:"openai-cachekeep",text:`## Cachekeep Window Invalid
93
93
 
94
- ${K.reason}`,knobs:{}};let{startHour:H,endHour:U}=K;await X0((B)=>{return B.cachekeep={...B.cachekeep??{},startHour:H,endHour:U},B},X.accountStoragePath),X.setCacheKeepWindow?.({startHour:H,endHour:U}),G0.info("cachekeep window set",{startHour:H,endHour:U});let N=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Set
94
+ ${K.reason}`,knobs:{}};let{startHour:U,endHour:H}=K;await J0((B)=>{return B.cachekeep={...B.cachekeep??{},startHour:U,endHour:H},B},X.accountStoragePath),X.setCacheKeepWindow?.({startHour:U,endHour:H}),G0.info("cachekeep window set",{startHour:U,endHour:H});let N=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Set
95
95
 
96
- Warming limited to **${`${String(H).padStart(2,"0")}-${String(U).padStart(2,"0")}`}** local hours.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:N?.sustain??$?.cachekeep?.sustain===!0,window:{startHour:H,endHour:U},running:N?.running??!1,tracked:N?.tracked??0,generatedAt:N?.generatedAt??Date.now(),maxIdleWarmMs:N?.maxIdleWarmMs??3600000,maxSubagentIdleMs:N?.maxSubagentIdleMs??1800000}}}return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep`, `/openai-cachekeep on`, `/openai-cachekeep off`, `/openai-cachekeep sustain on`, `/openai-cachekeep sustain off`, `/openai-cachekeep HH-HH`, `/openai-cachekeep window clear`, `/openai-cachekeep subagents on`, `/openai-cachekeep subagents off`",knobs:{}}}async function B8(Y,X,J){switch(Y){case"openai-quota":return yW(J);case"openai-account":return fW(X,J);case"openai-routing":return mW(X,J);case"openai-killswitch":return cW(X,J);case"openai-dump":return uW(X,J);case"openai-logging":return pW(X,J);case"openai-cachekeep":return dW(X,J);default:throw Error(`unhandled command: ${Y}`)}}var iW=L0("quota");async function y1(Y,X={}){let J=Y.whamFn;if(!J)throw Error("whamFn is required for refreshAllQuota");let Q=[],$=Y.logger??iW,G=(L)=>{Q.push(L);let Z={pid:process.pid,accountId:L.account,status:L.ok?"ok":"error",...L.error?{error:L.error}:{}};if(L.ok)$.debug("quota refresh succeeded",Z);else $.warn("quota refresh failed",Z)},W=Y.skipFresherThanMs,K=!1,H;if(W!==void 0)try{H=await(Y.readSidebarState??L1)()}catch{}let U=new Map(H?.fallbacks.map((L)=>[L.id,L])??[]),N=(...L)=>W!==void 0&&L.some((Z)=>typeof Z==="number"&&Number.isFinite(Z)&&Z<=Y.now()&&Y.now()-Z<W),O=await Y.loadAccounts(Y.configPath).catch(()=>{return}),B=O?.mainAccountId??Y.storageMainAccountId;if(!X.accountKey||X.accountKey==="main")try{let L=await Y.getAuth();if(L.type==="oauth"){let Z=H&&B!==void 0&&H.main.mainAccountId===B?H.main.quota:void 0;if(N(Y.quotaManager.peekMainForPolicy(B)?.checkedAt,Z?.primary?.checkedAt,Z?.secondary?.checkedAt,Z?.checkedAt))G({account:"main",ok:!0});else{if(!L.access||(L.expires??0)<Y.now()){let w=await Y.refreshMainWithLease();L={...L,access:w.access,expires:w.expires}}if(L.access)if(Y.respectBackoff&&Y.quotaManager.isBackedOff())G({account:"main",ok:!0});else{let w=await J({accessToken:L.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:B,accountKey:"main"});Y.quotaManager.setMain(L.access,{quota:w,refreshAfter:Y.now()+300000,checkedAt:Y.now()},B,!0),K=!0,G({account:"main",ok:!0})}else G({account:"main",ok:!1,error:"no access token"})}}else G({account:"main",ok:!1,error:"auth type is not oauth"})}catch(L){G({account:"main",ok:!1,error:o0(L)})}if(O)for(let L of O.accounts){if(X.accountKey&&(X.accountKey==="main"||L.id!==X.accountKey))continue;if(L.enabled===!1||!Y.isOAuthAccountFn(L)){if(X.accountKey)G({account:L.id,ok:!1,error:"account is not an enabled OAuth fallback"});continue}try{let Z=U.get(L.id),j=L.accountId,w=Z&&j!==void 0&&Z.accountId===j?Z.quota:void 0;if(N(Y.quotaManager.peekFallbackForPolicy(L.id,j)?.checkedAt,w?.primary?.checkedAt,w?.secondary?.checkedAt,w?.checkedAt)){G({account:L.id,ok:!0});continue}if(Y.respectBackoff&&Y.quotaManager.isFallbackBackedOff(L.id,L.access)){G({account:L.id,ok:!0});continue}let P;try{P=await Y.fallbackManager.refreshAccount(L,O)}catch{P=L}if(!P.access){G({account:L.id,ok:!1,error:"no access token"});continue}let k=await J({accessToken:P.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:P.accountId,accountKey:L.id});Y.quotaManager.setFallback(L.id,{quota:k,refreshAfter:Y.now()+300000,checkedAt:Y.now()},P.access,!0,P.accountId),K=!0,G({account:L.id,ok:!0})}catch(Z){G({account:L.id,ok:!1,error:o0(Z)})}}if(X.accountKey&&X.accountKey!=="main"&&!Q.some((L)=>L.account===X.accountKey))Q.push({account:X.accountKey,ok:!1,error:"account not found"});if(W===void 0||K){let L=await Y.loadAccounts(Y.configPath);await Y.writeSidebarState(Y.quotaManager,L)}return Q}var nW=300000,oW=30000,rW=240000,sW="bg-quota-refresh",aW=120000;function tW(Y,X){return PY({name:sW,ttlMs:aW,path:Y,renew:!0,...X})}function KX(Y,X=y1,J=()=>tW(Y.configPath)){return eW(Y,X,J)}async function eW(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:rW})}finally{await Q?.release().catch(()=>{})}}class Z8{setIntervalFn;clearIntervalFn;random;onError;run;timer;tickPromise;stopped=!1;constructor(Y={}){this.setIntervalFn=Y.setIntervalFn??setInterval,this.clearIntervalFn=Y.clearIntervalFn??clearInterval,this.random=Y.random??Math.random,this.onError=Y.onError}start(Y,X=this.onError){if(this.run=Y,this.onError=X,this.stopped=!1,this.timer)return;let J=Math.round((this.random()*2-1)*oW);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=$},nW+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 _(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}function O8(Y){if(typeof Y!=="string")return!1;try{let X=JSON.parse(Y);return _(X)&&_(X.client_metadata)&&X.client_metadata.ws_request_header_x_openai_internal_codex_responses_lite==="true"}catch{return!1}}function F8(Y){if(typeof Y!=="string")return Y;try{let X=JSON.parse(Y);if(!_(X)||!_(X.client_metadata))return Y;if(!(("x-codex-turn-metadata"in X.client_metadata)||("x-codex-ws-stream-request-start-ms"in X.client_metadata)||("ws_request_header_x_openai_internal_codex_responses_lite"in X.client_metadata)))return Y;let J={...X.client_metadata};return delete J["x-codex-turn-metadata"],delete J["x-codex-ws-stream-request-start-ms"],delete J.ws_request_header_x_openai_internal_codex_responses_lite,JSON.stringify({...X,client_metadata:J})}catch{return Y}}function wY(Y){if(Y?.method?.toUpperCase()!=="POST")return Y;let X=new Headers(Y.headers);if(X.set("accept","text/event-stream"),X.set("content-type","application/json"),O8(Y.body))X.set("x-openai-internal-codex-responses-lite","true");return{...Y,headers:X,body:F8(Y.body)}}function VX(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 BX(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 UX(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 Y5=300000,ZX=1800000,HX=2*ZX+900000,X5=3600000,LX=1800000,NX=60000,J5=32,Q5=8388608,q8=600000;function OX(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 $5(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 G5(Y,X){return OX(Y)?ZX:X}function j8(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function FX(Y){if(!Y||typeof Y!=="object")return j8();let X=Y,J=Number(X.input_tokens)||Number(X.prompt_tokens)||0,Q=Number(X.output_tokens)||Number(X.completion_tokens)||0,$=X.input_tokens_details??X.prompt_tokens_details,G=Number($?.cached_tokens)||Number(X.cached_tokens)||0,W=J>0?G/J:null;return{input_tokens:J,output_tokens:Q,cached_tokens:G,hit_rate:W}}function W5(Y){try{let X=JSON.parse(Y);return FX(X.usage)}catch{return j8()}}function z5(Y){let X,J=[],Q,$=()=>{if(!J.length)return;let G=J.join(`
97
- `).trim();J=[];let W=X;if(X=void 0,!G||G==="[DONE]")return;try{let K=JSON.parse(G),H=K.type??W;if(H!=="response.completed"&&H!=="response.done")return;let U=K.response;Q=FX(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??j8()}class D8{targets=new Map;fetchImpl;getMainToken;refreshFallback;codexResponsesUrl;log;now;ttlMs;leadMs;maxIdleWarmMs;maxSubagentIdleMs;tickIntervalMs;maxTargets;maxBytes;getWindow;getSustain;timer=null;startedAt=null;totalBytes=0;tickInFlight=!1;disposed=!1;abortController=new AbortController;logPayload(Y={}){return{pid:process.pid,...Y}}constructor(Y){this.fetchImpl=Y.fetchImpl,this.getMainToken=Y.getMainToken,this.refreshFallback=Y.refreshFallback,this.codexResponsesUrl=Y.codexResponsesUrl,this.log=Y.logger,this.now=Y.now,this.ttlMs=Y.ttlMs??Y5,this.tickIntervalMs=Y.tickIntervalMs??NX,this.leadMs=Y.leadMs??this.tickIntervalMs+15000;let X=Y.maxIdleWarmMs??Y.maxDurationMs;this.maxIdleWarmMs=typeof X==="number"&&Number.isFinite(X)&&X>0?X:X5;let J=Y.maxSubagentIdleMs??LX;this.maxSubagentIdleMs=typeof J==="number"&&Number.isFinite(J)&&J>0?J:LX,this.tickIntervalMs=Y.tickIntervalMs??NX,this.maxTargets=Y.maxTargets??J5,this.maxBytes=Y.maxBytes??Q5,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&&!UX(K,new Date(this.now()))){this.log.debug("cachekeep track skipped (outside window)",this.logPayload({sessionKey:Y,startHour:K.startHour,endHour:K.endHour}));return}if(this.targets.has(Y)){let N=this.targets.get(Y);if(N)this.totalBytes-=N.bodyText.length;this.targets.delete(Y)}else this.log.debug("cachekeep captured target",this.logPayload({sessionKey:Y,accountId:J}));while(this.targets.size>=this.maxTargets||this.totalBytes+W>this.maxBytes&&this.targets.size>0){let N,O=Number.POSITIVE_INFINITY;for(let[L,Z]of this.targets){let j=Math.max(Z.lastRealRequestAt,Z.lastWarmedAt??0);if(j<O)N=L,O=j}if(N===void 0)break;let B=this.targets.get(N);if(B)this.totalBytes-=B.bodyText.length;this.targets.delete(N)}let H=G5(X,this.ttlMs),U={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:OX(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-HX;for(let[$,G]of this.targets){let W,K;if(this.isGpt56Subagent(G))W=Q,K=HX;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&&!UX(Y,new Date(this.now())))return;let X=this.now(),J=X+this.leadMs;for(let[Q,$]of this.targets)if($.backoffUntil&&X>=$.backoffUntil&&$.cacheExpiresAt<=J)await this.prewarm(Q,$);for(let[Q,$]of this.targets){if($.backoffUntil&&X<$.backoffUntil)continue;if($.cacheExpiresAt<=J)await this.prewarm(Q,$)}}finally{this.tickInFlight=!1}}async prewarm(Y,X){let J;try{if(X.accountId&&X.accountId!=="main")J=await this.refreshFallback(X.accountId);else J=await this.getMainToken()}catch($){if(!this.disposed&&this.targets.get(Y)===X)X.backoffUntil=this.now()+q8;this.log.debug("cachekeep skip (no token)",this.logPayload({sessionKey:Y,accountId:X.accountId??"main",error:$ instanceof Error?$.message:String($)}));return}if(this.disposed||this.targets.get(Y)!==X)return;let Q={...X.replayHeaders,authorization:`Bearer ${J}`,"content-type":"application/json"};if(X.chatgptAccountId)Q["ChatGPT-Account-Id"]=X.chatgptAccountId;else delete Q["ChatGPT-Account-Id"];try{let $=$5(X.bodyText),G;try{let j=JSON.parse($);G={warmBodyKeys:Object.keys(j),stream:j.stream,max_output_tokens:j.max_output_tokens,store:j.store,has_stream_options:"stream_options"in j,has_max_tokens:"max_tokens"in j,model:j.model}}catch{}this.log.debug("cachekeep warm request",this.logPayload({...G,headerKeys:Object.keys(Q),hasChatGptAccountId:"ChatGPT-Account-Id"in Q}));let W=wY({method:"POST",headers:Q,body:$,signal:AbortSignal.any([AbortSignal.timeout(30000),this.abortController.signal])}),K=await this.fetchImpl(this.codexResponsesUrl,W),H="";try{H=await K.text()}catch{}if(this.disposed||this.targets.get(Y)!==X)return;if(!K.ok){X.backoffUntil=this.now()+q8,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",status:K.status,error:`HTTP ${K.status}`,responseBody:H.slice(0,600)}));return}let U=K.headers.get("content-type")??"",N=U.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(H.slice(0,200));this.log.debug("cachekeep warm response",this.logPayload({status:K.status,contentType:U,bodyLen:H.length,isSse:N}));let O=N?z5(H):W5(H),B=E1(K.headers),L=B.primary?.usedPercent??null,Z=B.secondary?.usedPercent??null;if(this.log.debug("cachekeep fired",this.logPayload({session:Y,accountId:X.accountId??"main",input_tokens:O.input_tokens,cached_tokens:O.cached_tokens,hit_rate:O.hit_rate,output_tokens:O.output_tokens,quota_primary_pct:L,quota_secondary_pct:Z})),X.cacheExpiresAt=this.now()+X.ttlMs,X.lastWarmedAt=this.now(),X.backoffUntil=void 0,X.warmCount+=1,this.isGpt56Subagent(X)&&X.warmCount>=2){if(this.targets.get(Y)===X)this.totalBytes-=X.bodyText.length,this.targets.delete(Y);return}}catch($){if(this.disposed||this.targets.get(Y)!==X)return;X.backoffUntil=this.now()+q8,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",error:$ instanceof Error?$.message:String($)}))}}}var DX=900000,K5=0.016666666666666666,qX=0.000001;function w8(Y,X){for(let J of[Y?.primary?.checkedAt,Y?.checkedAt,X])if(typeof J==="number"&&Number.isFinite(J))return J;return}function E8(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let X=w8(Y.quota,Y.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||Y.now-X>DX)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let J=P8(Y.quota).sort((Q,$)=>{let G=Q.windowMs,W=$.windowMs,K=typeof G==="number"&&Number.isFinite(G),H=typeof W==="number"&&Number.isFinite(W);if(K!==H)return K?-1:1;if(K&&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 U5(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,K5);return Q/G}function jX(Y,X){if(Y<X)return-1;if(Y>X)return 1;return 0}function H5(Y,X){if(!Y.quota)return;let J=w8(Y.quota,Y.quotaCheckedAt);if(J===void 0||X-J>DX)return;let Q=P8(Y.quota).map(({key:G,window:W})=>{return U5(W,Y.reservePercent[G]??0,X)}),$=Q.length>0?Math.min(...Q):0;return $>0?{candidate:Y,quotaCheckedAt:J,weight:$}:void 0}function PX(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(($)=>H5($,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,qX),H=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,qX);return K-H||G.candidate.configuredOrder-W.candidate.configuredOrder||jX(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||jX($.accountId,G.accountId)})[0];if(!Q)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Q.accountId,quotaCheckedAt:w8(Q.quota,Q.quotaCheckedAt),source:"mode-fallback"}}import{createHash as L5}from"node:crypto";import{chmod as N5,mkdir as V5,writeFile as M8}from"node:fs/promises";import{join as B5}from"node:path";var T8=L0("dump"),r0="x-cortexkit-openai-auth-dump-session",wX=0,M1=new Map,Z5=100;function A8(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function O5(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 MX(Y){return L5("sha256").update(Y).digest("hex")}function R8(Y){return MX(JSON.stringify(Y))}function AX(Y){try{let X=JSON.parse(Y);return X!=null&&typeof X==="object"&&!Array.isArray(X)?X:void 0}catch{return}}function F5(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 q5(Y,X){if(!M1.has(Y))while(M1.size>=Z5){let J=M1.keys().next().value;if(J===void 0)break;M1.delete(J)}M1.set(Y,X)}function j5(Y){if(Y===void 0)return;return Object.fromEntries(new Headers(Y).entries())}function C8(Y){if(Array.isArray(Y))return Y.map(C8);if(Y==null||typeof Y!=="object")return Y;let X={};for(let[J,Q]of Object.entries(Y)){let $=J.toLowerCase();if($==="authorization"||$==="chatgpt-account-id"||$==="cookie"||$==="set-cookie"){X[J]="[redacted]";continue}X[J]=C8(Q)}return X}function D5(Y){let X=AX(Y);if(X===void 0)return Y;let J=EX(X),Q=JSON.stringify(J);if(Q===void 0)return Y;return JSON.stringify(X)===Q?Y:Q}function P5(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function w5(Y){let X=AX(Y);if(!X)return{parseable:!1};let J=Array.isArray(X.input)?X.input:[],Q=Array.isArray(X.tools)?X.tools:[],$=Q.map(P5),G=X.client_metadata!=null&&typeof X.client_metadata==="object"&&!Array.isArray(X.client_metadata)?X.client_metadata:void 0;return{parseable:!0,model:typeof X.model==="string"?X.model:void 0,stream:X.stream,generate:X.generate,store:X.store,previousResponseID:typeof X.previous_response_id==="string"?X.previous_response_id:void 0,promptCacheKey:typeof X.prompt_cache_key==="string"?X.prompt_cache_key:void 0,reasoning:X.reasoning,inputCount:J.length,inputHash:R8(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:R8(J[0]),toolsCount:Q.length,toolTypes:$,toolsHash:R8(Q),hasWebSearch:$.includes("web_search"),clientMetadataKeys:G?Object.keys(G).sort():[]}}async function A1(Y){let X=w0();if(!X.dump)return;wX++;let J=Y.sessionID?.trim()||"session-unknown",Q=`${new Date().toISOString().replace(/[:.]/g,"-")}-${String(wX).padStart(5,"0")}-${O5(J)}-${Y.transport}-${Y.phase}`,$=B5(X.dumpDir,Q),G={body:`${$}.body.json`,metadata:`${$}.meta.json`,request:`${$}.request.json`},W=`${Y.transport}:${J}`,K=M1.get(W);try{await V5(X.dumpDir,{recursive:!0,mode:448}),await N5(X.dumpDir,448).catch(()=>{});let H=D5(Y.bodyText),U={id:Q,createdAt:new Date().toISOString(),session:A8(J),transport:Y.transport,phase:Y.phase,accountId:Y.accountId,status:Y.status,error:Y.error,bodyBytes:Y.bodyText.length,bodyHash:MX(Y.bodyText),diff:F5(K,Y.bodyText),body:w5(Y.bodyText),files:G};await Promise.all([M8(G.body,H,{encoding:"utf8",mode:384}),M8(G.metadata,`${JSON.stringify(U,null,2)}
98
- `,{encoding:"utf8",mode:384}),M8(G.request,`${JSON.stringify(C8({url:Y.url,method:Y.method,accountId:Y.accountId,headers:j5(Y.headers)}),null,2)}
99
- `,{encoding:"utf8",mode:384})]),T8.debug("dumped request",{id:Q,session:A8(J),body:G.body,meta:G.metadata}),q5(W,Y.bodyText)}catch(H){T8.warn("request dump failed",{session:A8(J),error:H instanceof Error?H.message:String(H)})}}async function c0(Y){if(!w0().dump)return;T8.debug("diagnostic",Y)}import{tool as f1}from"@opencode-ai/plugin";var EY="ws_",CX=new Map,_X=f1({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:f1.schema.string().optional(),query:f1.schema.string().optional(),queries:f1.schema.array(f1.schema.string()).optional()},async execute(Y){return{title:"OpenAI Web Search",output:JSON.stringify({action:Y}),metadata:{action:Y}}}});function I8(Y){if(E5(Y))return;if(!A5(Y))return Y;let X=Y.item;return CX.set(X.id,X),{...Y,item:{type:"function_call",id:X.id,call_id:X.id,name:"web_search",arguments:JSON.stringify(_(X.action)?X.action:{})}}}function IX(Y){if(!Y.body)return Y;if(!(Y.headers.get("content-type")??"").includes("text/event-stream"))return Y;return new Response(M5(Y.body),{status:Y.status,statusText:Y.statusText,headers:Y.headers})}function SX(Y){if(!Array.isArray(Y.input))return!1;let X=!1,J=new Map,Q=[],$=new Map,G=new Map;for(let W of Y.input)if(_(W)&&typeof W.call_id==="string"&&W.call_id.startsWith(EY)){if(W.type==="function_call")$.set(W.call_id,W);else if(W.type==="function_call_output"&&typeof W.output==="string")G.set(W.call_id,W.output)}for(let W of Y.input){if(R5(W)){J.set(W.call_id,W),X=!0;continue}if(T5(W,J)){Q.push(_8(W.call_id,W.output,J.get(W.call_id))),X=!0;continue}if(C5(W)){let K=CX.get(W.id);if(K)Q.push(_8(W.id,K));else{let H=$.get(W.id),U=G.get(W.id);if(H||U)Q.push(_8(W.id,U,H));else Q.push(W)}X=!0;continue}Q.push(W)}if(X)Y.input=Q;return X}function E5(Y){if(typeof Y.type==="string"&&Y.type.startsWith("response.web_search_call."))return!0;return Y.type==="response.output_item.added"&&_(Y.item)&&Y.item.type==="web_search_call"}function M5(Y){let X=new TextDecoder,J=new TextEncoder,Q="";return Y.pipeThrough(new TransformStream({transform($,G){Q+=X.decode($,{stream:!0});let W=RX(Q);while(W){let K=Q.slice(0,W.index);Q=Q.slice(W.index+W.length);let H=TX(K);if(H)G.enqueue(J.encode(H));W=RX(Q)}},flush($){if(Q+=X.decode(),!Q)return;let G=TX(Q);if(G)$.enqueue(J.encode(G))}}))}function RX(Y){let X=Y.indexOf(`
96
+ Warming limited to **${`${String(U).padStart(2,"0")}-${String(H).padStart(2,"0")}`}** local hours.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:N?.sustain??$?.cachekeep?.sustain===!0,window:{startHour:U,endHour:H},running:N?.running??!1,tracked:N?.tracked??0,generatedAt:N?.generatedAt??Date.now(),maxIdleWarmMs:N?.maxIdleWarmMs??3600000,maxSubagentIdleMs:N?.maxSubagentIdleMs??1800000}}}return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep`, `/openai-cachekeep on`, `/openai-cachekeep off`, `/openai-cachekeep sustain on`, `/openai-cachekeep sustain off`, `/openai-cachekeep HH-HH`, `/openai-cachekeep window clear`, `/openai-cachekeep subagents on`, `/openai-cachekeep subagents off`",knobs:{}}}async function B8(Y,X,J){switch(Y){case"openai-quota":return uW(J);case"openai-account":return pW(X,J);case"openai-routing":return lW(X,J);case"openai-killswitch":return dW(X,J);case"openai-dump":return iW(X,J);case"openai-logging":return nW(X,J);case"openai-cachekeep":return rW(X,J);default:throw Error(`unhandled command: ${Y}`)}}var sW=H0("quota");async function f1(Y,X={}){let J=Y.whamFn;if(!J)throw Error("whamFn is required for refreshAllQuota");let Q=[],$=Y.logger??sW,G=(L)=>{Q.push(L);let Z={pid:process.pid,accountId:L.account,status:L.ok?"ok":"error",...L.error?{error:L.error}:{}};if(L.ok)$.debug("quota refresh succeeded",Z);else $.warn("quota refresh failed",Z)},W=Y.skipFresherThanMs,K=!1,U;if(W!==void 0)try{U=await(Y.readSidebarState??N1)()}catch{}let H=new Map(U?.fallbacks.map((L)=>[L.id,L])??[]),N=(...L)=>W!==void 0&&L.some((Z)=>typeof Z==="number"&&Number.isFinite(Z)&&Z<=Y.now()&&Y.now()-Z<W),O=await Y.loadAccounts(Y.configPath).catch(()=>{return}),B=O?.mainAccountId??Y.storageMainAccountId;if(!X.accountKey||X.accountKey==="main")try{let L=await Y.getAuth();if(L.type==="oauth"){let Z=U&&B!==void 0&&U.main.mainAccountId===B?U.main.quota:void 0;if(N(Y.quotaManager.peekMainForPolicy(B)?.checkedAt,Z?.primary?.checkedAt,Z?.secondary?.checkedAt,Z?.checkedAt))G({account:"main",ok:!0});else{if(!L.access||(L.expires??0)<Y.now()){let P=await Y.refreshMainWithLease();L={...L,access:P.access,expires:P.expires}}if(L.access)if(Y.respectBackoff&&Y.quotaManager.isBackedOff())G({account:"main",ok:!0});else{let P=await J({accessToken:L.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:B,accountKey:"main"});Y.quotaManager.setMain(L.access,{quota:P,refreshAfter:Y.now()+300000,checkedAt:Y.now()},B,!0),K=!0,G({account:"main",ok:!0})}else G({account:"main",ok:!1,error:"no access token"})}}else G({account:"main",ok:!1,error:"auth type is not oauth"})}catch(L){G({account:"main",ok:!1,error:a0(L)})}if(O)for(let L of O.accounts){if(X.accountKey&&(X.accountKey==="main"||L.id!==X.accountKey))continue;if(L.enabled===!1||!Y.isOAuthAccountFn(L)){if(X.accountKey)G({account:L.id,ok:!1,error:"account is not an enabled OAuth fallback"});continue}try{let Z=H.get(L.id),j=L.accountId,P=Z&&j!==void 0&&Z.accountId===j?Z.quota:void 0;if(N(Y.quotaManager.peekFallbackForPolicy(L.id,j)?.checkedAt,P?.primary?.checkedAt,P?.secondary?.checkedAt,P?.checkedAt)){G({account:L.id,ok:!0});continue}if(Y.respectBackoff&&Y.quotaManager.isFallbackBackedOff(L.id,L.access)){G({account:L.id,ok:!0});continue}let S;try{S=await Y.fallbackManager.refreshAccount(L,O)}catch{S=L}if(!S.access){G({account:L.id,ok:!1,error:"no access token"});continue}let E=await J({accessToken:S.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:S.accountId,accountKey:L.id});Y.quotaManager.setFallback(L.id,{quota:E,refreshAfter:Y.now()+300000,checkedAt:Y.now()},S.access,!0,S.accountId),K=!0,G({account:L.id,ok:!0})}catch(Z){G({account:L.id,ok:!1,error:a0(Z)})}}if(X.accountKey&&X.accountKey!=="main"&&!Q.some((L)=>L.account===X.accountKey))Q.push({account:X.accountKey,ok:!1,error:"account not found"});if(W===void 0||K){let L=await Y.loadAccounts(Y.configPath);await Y.writeSidebarState(Y.quotaManager,L)}return Q}var aW=300000,tW=30000,eW=240000,Y5="bg-quota-refresh",X5=120000;function J5(Y,X){return PY({name:Y5,ttlMs:X5,path:Y,renew:!0,...X})}function UX(Y,X=f1,J=()=>J5(Y.configPath)){return Q5(Y,X,J)}async function Q5(Y,X,J){let Q;try{Q=await J()}catch{Q=void 0}if(Q===null)return[];try{return await X({...Y,respectBackoff:!0,skipFresherThanMs:eW})}finally{await Q?.release().catch(()=>{})}}class Z8{setIntervalFn;clearIntervalFn;random;onError;run;timer;tickPromise;stopped=!1;constructor(Y={}){this.setIntervalFn=Y.setIntervalFn??setInterval,this.clearIntervalFn=Y.clearIntervalFn??clearInterval,this.random=Y.random??Math.random,this.onError=Y.onError}start(Y,X=this.onError){if(this.run=Y,this.onError=X,this.stopped=!1,this.timer)return;let J=Math.round((this.random()*2-1)*tW);if(this.timer=this.setIntervalFn(()=>{let Q=this.run;if(this.stopped||!Q||this.tickPromise)return;let $=Q().catch((G)=>{try{this.onError?.(G)}catch{}}).finally(()=>{if(this.tickPromise===$)this.tickPromise=void 0});this.tickPromise=$},aW+J),"unref"in this.timer)this.timer.unref()}stop(){if(this.stopped=!0,this.run=void 0,!this.timer)return;this.clearIntervalFn(this.timer),this.timer=void 0}isStopped(){return this.stopped}}function I(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}function O8(Y){if(typeof Y!=="string")return!1;try{let X=JSON.parse(Y);return I(X)&&I(X.client_metadata)&&X.client_metadata.ws_request_header_x_openai_internal_codex_responses_lite==="true"}catch{return!1}}function F8(Y){if(typeof Y!=="string")return Y;try{let X=JSON.parse(Y);if(!I(X)||!I(X.client_metadata))return Y;if(!(("x-codex-turn-metadata"in X.client_metadata)||("x-codex-ws-stream-request-start-ms"in X.client_metadata)||("ws_request_header_x_openai_internal_codex_responses_lite"in X.client_metadata)))return Y;let J={...X.client_metadata};return delete J["x-codex-turn-metadata"],delete J["x-codex-ws-stream-request-start-ms"],delete J.ws_request_header_x_openai_internal_codex_responses_lite,JSON.stringify({...X,client_metadata:J})}catch{return Y}}function wY(Y){if(Y?.method?.toUpperCase()!=="POST")return Y;let X=new Headers(Y.headers);if(X.set("accept","text/event-stream"),X.set("content-type","application/json"),O8(Y.body))X.set("x-openai-internal-codex-responses-lite","true");return{...Y,headers:X,body:F8(Y.body)}}function BX(Y){if(!Y.enabled||typeof Y.body!=="string")return;let X=Y.headers.has("x-parent-session-id");if(X&&!Y.includeSubagents)return;let J=Y.headers.get("session-id")??Y.headers.get("x-opencode-session")??Y.headers.get("x-session-affinity")??void 0;if(!J)return;let Q={};for(let $ of["session-id","x-session-affinity","x-parent-session-id","user-agent","version","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-client-request-id","thread-id","x-openai-internal-codex-responses-lite"]){let G=Y.headers.get($);if(G)Q[$]=G}return{sessionKey:J,bodyText:Y.body,replayHeaders:Q,isSubagent:X}}function ZX(Y){let X=Number(Y?.cachekeep?.startHour),J=Number(Y?.cachekeep?.endHour);if(!Number.isInteger(X)||!Number.isInteger(J)||X<0||X>23||J<0||J>23||X===J)return;return{startHour:X,endHour:J}}function HX(Y,X=new Date){if(!Y)return!1;let J=X.getHours();if(Y.startHour<Y.endHour)return J>=Y.startHour&&J<Y.endHour;return J>=Y.startHour||J<Y.endHour}var $5=300000,OX=1800000,LX=2*OX+900000,G5=3600000,NX=1800000,VX=60000,W5=32,z5=8388608,q8=600000;function FX(Y){try{let J=JSON.parse(Y).model;if(typeof J!=="string")return!1;return J==="gpt-5.6"||J.startsWith("gpt-5.6-")}catch{return!1}}function K5(Y){let J=JSON.parse(Y);return J.store=!1,delete J.max_output_tokens,delete J.max_tokens,delete J.max_completion_tokens,JSON.stringify(J)}function U5(Y,X){return FX(Y)?OX:X}function j8(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function qX(Y){if(!Y||typeof Y!=="object")return j8();let X=Y,J=Number(X.input_tokens)||Number(X.prompt_tokens)||0,Q=Number(X.output_tokens)||Number(X.completion_tokens)||0,$=X.input_tokens_details??X.prompt_tokens_details,G=Number($?.cached_tokens)||Number(X.cached_tokens)||0,W=J>0?G/J:null;return{input_tokens:J,output_tokens:Q,cached_tokens:G,hit_rate:W}}function H5(Y){try{let X=JSON.parse(Y);return qX(X.usage)}catch{return j8()}}function L5(Y){let X,J=[],Q,$=()=>{if(!J.length)return;let G=J.join(`
97
+ `).trim();J=[];let W=X;if(X=void 0,!G||G==="[DONE]")return;try{let K=JSON.parse(G),U=K.type??W;if(U!=="response.completed"&&U!=="response.done")return;let H=K.response;Q=qX(H?.usage??K.usage)}catch{}};for(let G of Y.split(/\r?\n/)){if(G===""){$();continue}if(G.startsWith("event:")){X=G.slice(6).trim();continue}if(G.startsWith("data:"))J.push(G.slice(5).trim())}return $(),Q??j8()}class D8{targets=new Map;fetchImpl;getMainToken;refreshFallback;codexResponsesUrl;log;now;ttlMs;leadMs;maxIdleWarmMs;maxSubagentIdleMs;tickIntervalMs;maxTargets;maxBytes;getWindow;getSustain;timer=null;startedAt=null;totalBytes=0;tickInFlight=!1;disposed=!1;abortController=new AbortController;logPayload(Y={}){return{pid:process.pid,...Y}}constructor(Y){this.fetchImpl=Y.fetchImpl,this.getMainToken=Y.getMainToken,this.refreshFallback=Y.refreshFallback,this.codexResponsesUrl=Y.codexResponsesUrl,this.log=Y.logger,this.now=Y.now,this.ttlMs=Y.ttlMs??$5,this.tickIntervalMs=Y.tickIntervalMs??VX,this.leadMs=Y.leadMs??this.tickIntervalMs+15000;let X=Y.maxIdleWarmMs??Y.maxDurationMs;this.maxIdleWarmMs=typeof X==="number"&&Number.isFinite(X)&&X>0?X:G5;let J=Y.maxSubagentIdleMs??NX;this.maxSubagentIdleMs=typeof J==="number"&&Number.isFinite(J)&&J>0?J:NX,this.tickIntervalMs=Y.tickIntervalMs??VX,this.maxTargets=Y.maxTargets??W5,this.maxBytes=Y.maxBytes??z5,this.getWindow=Y.getWindow,this.getSustain=Y.getSustain}track(Y,X,J,Q,$={},G=!1){this.pruneStale();let W=X.length;if(W>this.maxBytes){this.log.debug("cachekeep track skipped (body exceeds maxBytes)",this.logPayload({sessionKey:Y,bodyBytes:W,maxBytes:this.maxBytes}));return}let K=this.getWindow?.();if(K&&!HX(K,new Date(this.now()))){this.log.debug("cachekeep track skipped (outside window)",this.logPayload({sessionKey:Y,startHour:K.startHour,endHour:K.endHour}));return}if(this.targets.has(Y)){let N=this.targets.get(Y);if(N)this.totalBytes-=N.bodyText.length;this.targets.delete(Y)}else this.log.debug("cachekeep captured target",this.logPayload({sessionKey:Y,accountId:J}));while(this.targets.size>=this.maxTargets||this.totalBytes+W>this.maxBytes&&this.targets.size>0){let N,O=Number.POSITIVE_INFINITY;for(let[L,Z]of this.targets){let j=Math.max(Z.lastRealRequestAt,Z.lastWarmedAt??0);if(j<O)N=L,O=j}if(N===void 0)break;let B=this.targets.get(N);if(B)this.totalBytes-=B.bodyText.length;this.targets.delete(N)}let U=U5(X,this.ttlMs),H={bodyText:X,accountId:J||void 0,chatgptAccountId:Q,route:"main",ttlMs:U,cacheExpiresAt:this.now()+U,warmCount:0,lastRealRequestAt:this.now(),replayHeaders:$,isSubagent:G,is56:FX(X)};this.targets.set(Y,H),this.totalBytes+=W,this.start()}isGpt56Subagent(Y){return Y.isSubagent===!0&&Y.is56}pruneStale(){let Y=this.now(),X=Y-this.maxIdleWarmMs,J=Y-this.maxSubagentIdleMs,Q=Y-LX;for(let[$,G]of this.targets){let W,K;if(this.isGpt56Subagent(G))W=Q,K=LX;else W=G.isSubagent?J:X,K=G.isSubagent?this.maxSubagentIdleMs:this.maxIdleWarmMs;if(!(G.isSubagent!==!0&&this.getSustain?.()===!0)&&G.lastRealRequestAt<W)this.log.debug("cachekeep pruned idle target",this.logPayload({sessionKey:$,accountId:G.accountId??"main",lastRealRequestAt:G.lastRealRequestAt,maxIdleWarmMs:K})),this.totalBytes-=G.bodyText.length,this.targets.delete($)}}start(){if(this.disposed=!1,this.timer)return;if(this.startedAt=this.now(),this.log.debug("cachekeep started",this.logPayload({ttlMs:this.ttlMs,leadMs:this.leadMs,maxIdleWarmMs:this.maxIdleWarmMs})),this.timer=setInterval(()=>{this.tick().catch(()=>{})},this.tickIntervalMs),"unref"in this.timer)this.timer.unref()}stop(){if(this.disposed=!0,this.abortController.abort(),this.abortController=new AbortController,this.timer)clearInterval(this.timer),this.timer=null;this.startedAt=null,this.targets.clear(),this.totalBytes=0,this.log.debug("cachekeep stopped",this.logPayload())}remove(Y){let X=this.targets.get(Y);if(X)this.totalBytes-=X.bodyText.length,this.targets.delete(Y),this.log.debug("cachekeep removed target",this.logPayload({sessionKey:Y}))}status(){let Y=this.now(),X=Array.from(this.targets.entries()).map(([J,Q])=>({sessionKey:J,accountId:Q.accountId,route:Q.route,cacheExpiresAt:Q.cacheExpiresAt,lastRealRequestAt:Q.lastRealRequestAt,lastWarmedAt:Q.lastWarmedAt,backoffUntil:Q.backoffUntil,bodyBytes:Q.bodyText.length}));return{running:this.timer!=null,tracked:this.targets.size,generatedAt:Y,startedAt:this.startedAt,maxIdleWarmMs:this.maxIdleWarmMs,maxSubagentIdleMs:this.maxSubagentIdleMs,ttlMs:this.ttlMs,leadMs:this.leadMs,sustain:this.getSustain?.()===!0,window:this.getWindow?.(),targets:X}}async tick(){if(this.tickInFlight)return;this.tickInFlight=!0;try{this.pruneStale();let Y=this.getWindow?.();if(Y&&!HX(Y,new Date(this.now())))return;let X=this.now(),J=X+this.leadMs;for(let[Q,$]of this.targets)if($.backoffUntil&&X>=$.backoffUntil&&$.cacheExpiresAt<=J)await this.prewarm(Q,$);for(let[Q,$]of this.targets){if($.backoffUntil&&X<$.backoffUntil)continue;if($.cacheExpiresAt<=J)await this.prewarm(Q,$)}}finally{this.tickInFlight=!1}}async prewarm(Y,X){let J;try{if(X.accountId&&X.accountId!=="main")J=await this.refreshFallback(X.accountId);else J=await this.getMainToken()}catch($){if(!this.disposed&&this.targets.get(Y)===X)X.backoffUntil=this.now()+q8;this.log.debug("cachekeep skip (no token)",this.logPayload({sessionKey:Y,accountId:X.accountId??"main",error:$ instanceof Error?$.message:String($)}));return}if(this.disposed||this.targets.get(Y)!==X)return;let Q={...X.replayHeaders,authorization:`Bearer ${J}`,"content-type":"application/json"};if(X.chatgptAccountId)Q["ChatGPT-Account-Id"]=X.chatgptAccountId;else delete Q["ChatGPT-Account-Id"];try{let $=K5(X.bodyText),G;try{let j=JSON.parse($);G={warmBodyKeys:Object.keys(j),stream:j.stream,max_output_tokens:j.max_output_tokens,store:j.store,has_stream_options:"stream_options"in j,has_max_tokens:"max_tokens"in j,model:j.model}}catch{}this.log.debug("cachekeep warm request",this.logPayload({...G,headerKeys:Object.keys(Q),hasChatGptAccountId:"ChatGPT-Account-Id"in Q}));let W=wY({method:"POST",headers:Q,body:$,signal:AbortSignal.any([AbortSignal.timeout(30000),this.abortController.signal])}),K=await this.fetchImpl(this.codexResponsesUrl,W),U="";try{U=await K.text()}catch{}if(this.disposed||this.targets.get(Y)!==X)return;if(!K.ok){X.backoffUntil=this.now()+q8,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",status:K.status,error:`HTTP ${K.status}`,responseBody:U.slice(0,600)}));return}let H=K.headers.get("content-type")??"",N=H.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(U.slice(0,200));this.log.debug("cachekeep warm response",this.logPayload({status:K.status,contentType:H,bodyLen:U.length,isSse:N}));let O=N?L5(U):H5(U),B=M1(K.headers),L=B.primary?.usedPercent??null,Z=B.secondary?.usedPercent??null;if(this.log.debug("cachekeep fired",this.logPayload({session:Y,accountId:X.accountId??"main",input_tokens:O.input_tokens,cached_tokens:O.cached_tokens,hit_rate:O.hit_rate,output_tokens:O.output_tokens,quota_primary_pct:L,quota_secondary_pct:Z})),X.cacheExpiresAt=this.now()+X.ttlMs,X.lastWarmedAt=this.now(),X.backoffUntil=void 0,X.warmCount+=1,this.isGpt56Subagent(X)&&X.warmCount>=2){if(this.targets.get(Y)===X)this.totalBytes-=X.bodyText.length,this.targets.delete(Y);return}}catch($){if(this.disposed||this.targets.get(Y)!==X)return;X.backoffUntil=this.now()+q8,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",error:$ instanceof Error?$.message:String($)}))}}}var PX=900000,N5=0.016666666666666666,jX=0.000001;function w8(Y,X){for(let J of[Y?.primary?.checkedAt,Y?.checkedAt,X])if(typeof J==="number"&&Number.isFinite(J))return J;return}function E8(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let X=w8(Y.quota,Y.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||Y.now-X>PX)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let J=P8(Y.quota).sort((Q,$)=>{let G=Q.windowMs,W=$.windowMs,K=typeof G==="number"&&Number.isFinite(G),U=typeof W==="number"&&Number.isFinite(W);if(K!==U)return K?-1:1;if(K&&U)return W-G;return 0});for(let{key:Q,window:$}of J)if(Number.isFinite($.remainingPercent)&&$.remainingPercent<=0)return{action:"migrate",reason:"exhausted",windowKey:Q,...typeof $.resetsAt==="string"?{resetsAt:$.resetsAt}:{}};if(Y.status===void 0||Y.status===0||!Number.isFinite(Y.status)||Y.status>=500&&Y.status<=599||Y.status===429)return{action:"retain",reason:"transient"};return{action:"retain",reason:"healthy"}}function V5(Y,X,J){let Q=Math.max(0,Y.remainingPercent-X);if(Q<=0)return 0;if(!Y.resetsAt)return Q;let $=Date.parse(Y.resetsAt);if(!Number.isFinite($)||$<=J)return Q;let G=Math.max(($-J)/3600000,N5);return Q/G}function DX(Y,X){if(Y<X)return-1;if(Y>X)return 1;return 0}function B5(Y,X){if(!Y.quota)return;let J=w8(Y.quota,Y.quotaCheckedAt);if(J===void 0||X-J>PX)return;let Q=P8(Y.quota).map(({key:G,window:W})=>{return V5(W,Y.reservePercent[G]??0,X)}),$=Q.length>0?Math.min(...Q):0;return $>0?{candidate:Y,quotaCheckedAt:J,weight:$}:void 0}function wX(Y){let X=Y.candidates.filter(($)=>$.killswitchPasses!==!1);if(Y.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if(X.length===0)return;let J=X.map(($)=>B5($,Y.now)).filter(($)=>$!==void 0);if(J.length>0){J.sort((G,W)=>{let K=((Y.pendingBytes.get(G.candidate.accountId)??0)+Y.requestBytes)/Math.max(G.weight,jX),U=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,jX);return K-U||G.candidate.configuredOrder-W.candidate.configuredOrder||DX(G.candidate.accountId,W.candidate.accountId)});let $=J[0];if($)return{accountId:$.candidate.accountId,quotaCheckedAt:$.quotaCheckedAt,source:"weighted"}}Y.onEmptyWeightedSet?.();let Q=[...X].sort(($,G)=>{let W=($.resetCreditsApplicable??0)>0?1:0;return((G.resetCreditsApplicable??0)>0?1:0)-W||$.configuredOrder-G.configuredOrder||DX($.accountId,G.accountId)})[0];if(!Q)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Q.accountId,quotaCheckedAt:w8(Q.quota,Q.quotaCheckedAt),source:"mode-fallback"}}import{createHash as Z5}from"node:crypto";import{chmod as O5,mkdir as F5,writeFile as M8}from"node:fs/promises";import{join as q5}from"node:path";var T8=H0("dump"),t0="x-cortexkit-openai-auth-dump-session",EX=0,A1=new Map,j5=100;function A8(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function D5(Y){let X=Y.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!X)return"session-unknown";return X.length<=80?X:X.slice(0,80)}function AX(Y){return Z5("sha256").update(Y).digest("hex")}function R8(Y){return AX(JSON.stringify(Y))}function RX(Y){try{let X=JSON.parse(Y);return X!=null&&typeof X==="object"&&!Array.isArray(X)?X:void 0}catch{return}}function P5(Y,X){if(Y===void 0)return null;if(Y===X)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:Y.length,currentBytes:X.length};let J=0;while(J<Y.length&&J<X.length&&Y[J]===X[J])J++;let Q=Y.length-1,$=X.length-1;while(Q>=J&&$>=J&&Y[Q]===X[$])Q--,$--;return{changed:!0,firstByte:J,lastPreviousByte:Q,lastCurrentByte:$,changedPreviousBytes:Q-J+1,changedCurrentBytes:$-J+1,previousBytes:Y.length,currentBytes:X.length}}function w5(Y,X){if(!A1.has(Y))while(A1.size>=j5){let J=A1.keys().next().value;if(J===void 0)break;A1.delete(J)}A1.set(Y,X)}function E5(Y){if(Y===void 0)return;return Object.fromEntries(new Headers(Y).entries())}function C8(Y){if(Array.isArray(Y))return Y.map(C8);if(Y==null||typeof Y!=="object")return Y;let X={};for(let[J,Q]of Object.entries(Y)){let $=J.toLowerCase();if($==="authorization"||$==="chatgpt-account-id"||$==="cookie"||$==="set-cookie"){X[J]="[redacted]";continue}X[J]=C8(Q)}return X}function M5(Y){let X=RX(Y);if(X===void 0)return Y;let J=MX(X),Q=JSON.stringify(J);if(Q===void 0)return Y;return JSON.stringify(X)===Q?Y:Q}function A5(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function R5(Y){let X=RX(Y);if(!X)return{parseable:!1};let J=Array.isArray(X.input)?X.input:[],Q=Array.isArray(X.tools)?X.tools:[],$=Q.map(A5),G=X.client_metadata!=null&&typeof X.client_metadata==="object"&&!Array.isArray(X.client_metadata)?X.client_metadata:void 0;return{parseable:!0,model:typeof X.model==="string"?X.model:void 0,stream:X.stream,generate:X.generate,store:X.store,previousResponseID:typeof X.previous_response_id==="string"?X.previous_response_id:void 0,promptCacheKey:typeof X.prompt_cache_key==="string"?X.prompt_cache_key:void 0,reasoning:X.reasoning,inputCount:J.length,inputHash:R8(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:R8(J[0]),toolsCount:Q.length,toolTypes:$,toolsHash:R8(Q),hasWebSearch:$.includes("web_search"),clientMetadataKeys:G?Object.keys(G).sort():[]}}async function R1(Y){let X=P0();if(!X.dump)return;EX++;let J=Y.sessionID?.trim()||"session-unknown",Q=`${new Date().toISOString().replace(/[:.]/g,"-")}-${String(EX).padStart(5,"0")}-${D5(J)}-${Y.transport}-${Y.phase}`,$=q5(X.dumpDir,Q),G={body:`${$}.body.json`,metadata:`${$}.meta.json`,request:`${$}.request.json`},W=`${Y.transport}:${J}`,K=A1.get(W);try{await F5(X.dumpDir,{recursive:!0,mode:448}),await O5(X.dumpDir,448).catch(()=>{});let U=M5(Y.bodyText),H={id:Q,createdAt:new Date().toISOString(),session:A8(J),transport:Y.transport,phase:Y.phase,accountId:Y.accountId,status:Y.status,error:Y.error,bodyBytes:Y.bodyText.length,bodyHash:AX(Y.bodyText),diff:P5(K,Y.bodyText),body:R5(Y.bodyText),files:G};await Promise.all([M8(G.body,U,{encoding:"utf8",mode:384}),M8(G.metadata,`${JSON.stringify(H,null,2)}
98
+ `,{encoding:"utf8",mode:384}),M8(G.request,`${JSON.stringify(C8({url:Y.url,method:Y.method,accountId:Y.accountId,headers:E5(Y.headers)}),null,2)}
99
+ `,{encoding:"utf8",mode:384})]),T8.debug("dumped request",{id:Q,session:A8(J),body:G.body,meta:G.metadata}),w5(W,Y.bodyText)}catch(U){T8.warn("request dump failed",{session:A8(J),error:U instanceof Error?U.message:String(U)})}}async function p0(Y){if(!P0().dump)return;T8.debug("diagnostic",Y)}import{tool as m1}from"@opencode-ai/plugin";var EY="ws_",_X=new Map,IX=m1({description:"Provider-executed OpenAI web search. This tool is handled server-side by OpenAI; the local plugin records the hosted action for deterministic replay.",args:{type:m1.schema.string().optional(),query:m1.schema.string().optional(),queries:m1.schema.array(m1.schema.string()).optional()},async execute(Y){return{title:"OpenAI Web Search",output:JSON.stringify({action:Y}),metadata:{action:Y}}}});function I8(Y){if(T5(Y))return;if(!_5(Y))return Y;let X=Y.item;return _X.set(X.id,X),{...Y,item:{type:"function_call",id:X.id,call_id:X.id,name:"web_search",arguments:JSON.stringify(I(X.action)?X.action:{})}}}function SX(Y){if(!Y.body)return Y;if(!(Y.headers.get("content-type")??"").includes("text/event-stream"))return Y;return new Response(C5(Y.body),{status:Y.status,statusText:Y.statusText,headers:Y.headers})}function kX(Y){if(!Array.isArray(Y.input))return!1;let X=!1,J=new Map,Q=[],$=new Map,G=new Map;for(let W of Y.input)if(I(W)&&typeof W.call_id==="string"&&W.call_id.startsWith(EY)){if(W.type==="function_call")$.set(W.call_id,W);else if(W.type==="function_call_output"&&typeof W.output==="string")G.set(W.call_id,W.output)}for(let W of Y.input){if(I5(W)){J.set(W.call_id,W),X=!0;continue}if(S5(W,J)){Q.push(_8(W.call_id,W.output,J.get(W.call_id))),X=!0;continue}if(k5(W)){let K=_X.get(W.id);if(K)Q.push(_8(W.id,K));else{let U=$.get(W.id),H=G.get(W.id);if(U||H)Q.push(_8(W.id,H,U));else Q.push(W)}X=!0;continue}Q.push(W)}if(X)Y.input=Q;return X}function T5(Y){if(typeof Y.type==="string"&&Y.type.startsWith("response.web_search_call."))return!0;return Y.type==="response.output_item.added"&&I(Y.item)&&Y.item.type==="web_search_call"}function C5(Y){let X=new TextDecoder,J=new TextEncoder,Q="";return Y.pipeThrough(new TransformStream({transform($,G){Q+=X.decode($,{stream:!0});let W=TX(Q);while(W){let K=Q.slice(0,W.index);Q=Q.slice(W.index+W.length);let U=CX(K);if(U)G.enqueue(J.encode(U));W=TX(Q)}},flush($){if(Q+=X.decode(),!Q)return;let G=CX(Q);if(G)$.enqueue(J.encode(G))}}))}function TX(Y){let X=Y.indexOf(`
100
100
 
101
101
  `),J=Y.indexOf(`\r
102
102
  \r
103
- `);if(X===-1)return J===-1?void 0:{index:J,length:4};if(J===-1||X<J)return{index:X,length:2};return{index:J,length:4}}function TX(Y){let X=Y.split(/\r?\n/).filter((J)=>J.startsWith("data:")).map((J)=>J.slice(5).trimStart()).join(`
103
+ `);if(X===-1)return J===-1?void 0:{index:J,length:4};if(J===-1||X<J)return{index:X,length:2};return{index:J,length:4}}function CX(Y){let X=Y.split(/\r?\n/).filter((J)=>J.startsWith("data:")).map((J)=>J.slice(5).trimStart()).join(`
104
104
  `);if(!X)return`${Y}
105
105
 
106
106
  `;if(X==="[DONE]")return`data: [DONE]
107
107
 
108
- `;try{let J=JSON.parse(X);if(!_(J))return`${Y}
108
+ `;try{let J=JSON.parse(X);if(!I(J))return`${Y}
109
109
 
110
110
  `;let Q=I8(J);if(!Q)return"";return`data: ${JSON.stringify(Q)}
111
111
 
112
112
  `}catch{return`${Y}
113
113
 
114
- `}}function A5(Y){return Y.type==="response.output_item.done"&&_(Y.item)&&Y.item.type==="web_search_call"&&typeof Y.item.id==="string"}function R5(Y){return _(Y)&&Y.type==="function_call"&&Y.name==="web_search"&&typeof Y.call_id==="string"&&Y.call_id.startsWith(EY)}function T5(Y,X){return _(Y)&&Y.type==="function_call_output"&&typeof Y.call_id==="string"&&typeof Y.output==="string"&&Y.call_id.startsWith(EY)&&X.has(Y.call_id)}function C5(Y){return _(Y)&&Y.type==="item_reference"&&typeof Y.id==="string"&&Y.id.startsWith(EY)}function _8(Y,X,J){let Q=_5(X),$=_(Q?.action)?Q.action:I5(J?.arguments);return{type:"web_search_call",status:"completed",...$?{action:$}:{}}}function _5(Y){if(_(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return _(X)?X:void 0}catch{return}}function I5(Y){if(_(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return _(X)?X:void 0}catch{return}}import{readFile as S5}from"node:fs/promises";import{homedir as k5}from"node:os";import{join as kX}from"node:path";var b5="https://models.dev/api.json",x5="OPENCODE_OPENAI_AUTH_MODELS_CACHE",v5="OPENCODE_MODELS_PATH",h5="OPENCODE_DISABLE_MODELS_FETCH",g5=1e4,y5=300000;function s0(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function bX(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function S8(Y){let{input:X,output:J}=Y;if(typeof X!=="number"||!Number.isFinite(X)||X<0)return null;if(typeof J!=="number"||!Number.isFinite(J)||J<0)return null;let Q=bX(Y.cache_read),$=bX(Y.cache_write);if(Q===null||$===null)return null;return{input:X,output:J,cache:{read:Q,write:$}}}function f5(Y){let X=s0(Y);if(!X)return null;let J=S8(X);if(!J)return null;let Q=J;if(Array.isArray(X.tiers)){let W=[];for(let K of X.tiers){let H=s0(K);if(!H)continue;let U=s0(H.tier),N=U?.size;if(U?.type!=="context")continue;if(typeof N!=="number"||!Number.isFinite(N)||N<=0)continue;let O=S8(H);if(!O)continue;W.push({...O,tier:{type:"context",size:N}})}if(W.length>0)Q.tiers=W}let $=s0(X.context_over_200k),G=$?S8($):null;if(G)Q.experimentalOver200K=G;return Q}function xX(Y){let X=s0(Y),J=s0(X?.openai),Q=s0(J?.models);if(!Q)return null;let $={};for(let[G,W]of Object.entries(Q)){let K=s0(W),H=f5(K?.cost);if(H)$[G]=H}return Object.keys($).length>0?$:null}function m5(){let Y=process.env[x5]?.trim();if(Y)return Y;let X=process.env[v5]?.trim();if(X)return X;let J=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||kX(k5(),".cache");return kX(J,"opencode","models.json")}function c5(){let Y=process.env[h5]?.toLowerCase();return Y==="true"||Y==="1"}async function u5(){try{let Y=xX(JSON.parse(await S5(m5(),"utf8")));if(Y)return Y}catch{}if(c5())return null;try{let Y=await fetch(b5,{signal:AbortSignal.timeout(g5)});if(!Y.ok)return null;return xX(await Y.json())}catch{return null}}var R1;function vX(){let Y=Date.now();if(R1&&R1.expiresAt>Y)return R1.promise;let X={expiresAt:Y+y5,promise:u5()};return R1=X,X.promise.then((J)=>{if(J===null&&R1===X)R1=void 0}),X.promise}function T1(Y){return typeof Y==="object"&&Y!==null}function p5(Y){if(Array.isArray(Y))return Y;if(T1(Y)&&Array.isArray(Y.data))return Y.data;return[]}function l5(Y){if(!T1(Y)||!T1(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function hX(Y){if(!T1(Y)||!T1(Y.info))return null;let X=Y.info,J=T1(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 gX(Y,X){return{agent:Y.agent??X.agent,model:Y.model??X.model,variant:Y.variant??X.variant}}function yX(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function fX(Y,X){if(!Y||!X)return null;let J=Y;if(typeof J.session?.messages!=="function")return null;let Q=[];try{Q=p5(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(l5(Q[G])!=="assistant")continue;let W=hX(Q[G]);if(!W)continue;if($=gX($,W),yX($))return $}for(let G=Q.length-1;G>=0;G--){let W=hX(Q[G]);if(!W)continue;if($=gX($,W),yX($))return $}if(!$.agent&&!$.model&&!$.variant)return null;return $}var a0=[],d5=1,k8=0,mX=new Map;function b8(Y,X){if(a0.push({id:d5++,type:"open-dialog",payload:Y,sessionId:X}),a0.length>100)a0=a0.slice(a0.length-100)}function cX(Y=0,X){let J=Date.now();if(k8=J,X!==void 0)mX.set(X,J);let Q=($)=>X===void 0||$.sessionId===void 0||$.sessionId===X;if(Y>0)a0=a0.filter(($)=>{if($.id>Y)return!0;if(X===void 0)return!1;return $.sessionId!==X});return a0.filter(($)=>$.id>Y&&Q($))}function uX(Y){let X=Date.now();if(Y!==void 0){let J=mX.get(Y)??0;return J>0&&X-J<3000}return k8>0&&X-k8<3000}import{randomBytes as i5,timingSafeEqual as n5}from"node:crypto";import{unlink as o5}from"node:fs/promises";import{createServer as r5}from"node:http";import{join as s5}from"node:path";var pX=L0("rpc");function a5(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 t5(Y,X){if(!Y?.startsWith("Bearer "))return!1;let J=Buffer.from(Y.slice(7)),Q=Buffer.from(X);return J.length===Q.length&&n5(J,Q)}async function iX(Y){let X=i5(32).toString("hex"),J=Y.timeoutMs??2000,Q=r5((W,K)=>{W.setTimeout(J,()=>{W.socket.destroy()}),$(W,K)});Q.requestTimeout=J,Q.headersTimeout=J;async function $(W,K){let H=(U,N)=>{if(K.headersSent||K.writableEnded||K.destroyed)return;K.writeHead(U,{"content-type":"application/json"}),K.end(JSON.stringify(N))};try{let U=W.url??"";if(W.method==="GET"&&U==="/health")return H(200,{ok:!0});if(W.method!=="POST"||!U.startsWith("/rpc/"))return H(404,{error:"not found"});if(!t5(W.headers.authorization,X))return H(401,{error:"unauthorized"});let N=U.slice(5),O=await a5(W),B=JSON.parse(O||"{}");if(N==="pending-notifications"){let L=Y.drain(Number(B.lastReceivedId??0),typeof B.sessionId==="string"?B.sessionId:void 0);return H(200,{messages:L})}if(N==="apply"){let L=await Y.apply(B);return H(200,L)}return H(404,{error:"unknown method"})}catch(U){H(500,{error:U instanceof Error?U.message:String(U)})}}let G=await new Promise((W,K)=>{Q.on("error",K),Q.listen(0,"127.0.0.1",()=>{let H=Q.address();if(H&&typeof H==="object")W(H.port);else K(Error("no port"))})});if(Q.unref(),Y.sweepRoot)try{await dX(Y.sweepRoot,Y.dir)}catch(W){pX.warn("rpc state sweep failed",{pid:process.pid,error:W instanceof Error?W.message:String(W)})}try{await lX(Y.dir,{port:G,token:X,pid:process.pid},{secureDir:Y.secureDir}),pX.debug("rpc server pid",{pid:process.pid,rpcPort:G})}catch(W){throw await new Promise((K)=>Q.close(()=>K())),W}return{port:G,token:X,async stop(){await new Promise((W)=>Q.close(()=>W())),await o5(s5(Y.dir,`port-${process.pid}.json`)).catch(()=>{})}}}function u0(Y){return JSON.stringify(x8(Y))??"undefined"}function x8(Y){if(Array.isArray(Y))return Y.map(x8);if(!_(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((X)=>[X,x8(Y[X])]))}function N1(){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 $1={};g8($1,{withoutInternalHeaders:()=>xG,sanitizeHttpFallbackBody:()=>F8,orderCodexBody:()=>GY,hasWebSocketResponsesLiteMetadata:()=>O8,createWebSocketFetch:()=>GN,applyTurnId:()=>SG,TITLE_HEADER:()=>k9,QUOTA_ACCOUNT_HEADER:()=>aY,OpenAIWebSocketPool:()=>$1,CODEX_BODY_KEY_ORDER:()=>_G});import{createHash as YN}from"node:crypto";var EJ="vercel.ai.error",e5=Symbol.for(EJ),nX,oX,f=class Y extends(oX=Error,nX=e5,oX){constructor({name:X,message:J,cause:Q}){super(J);this[nX]=!0,this.name=X,this.cause=Q}static isInstance(X){return Y.hasMarker(X,EJ)}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}},MJ="AI_APICallError",AJ=`vercel.ai.error.${MJ}`,Y2=Symbol.for(AJ),rX,sX,m1=class extends(sX=f,rX=Y2,sX){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:H}){super({name:MJ,message:Y,cause:W});this[rX]=!0,this.url=X,this.requestBodyValues=J,this.statusCode=Q,this.responseHeaders=$,this.responseBody=G,this.isRetryable=K,this.data=H}static isInstance(Y){return f.hasMarker(Y,AJ)}},RJ="AI_EmptyResponseBodyError",TJ=`vercel.ai.error.${RJ}`,X2=Symbol.for(TJ),aX,tX,J2=class extends(tX=f,aX=X2,tX){constructor({message:Y="Empty response body"}={}){super({name:RJ,message:Y});this[aX]=!0}static isInstance(Y){return f.hasMarker(Y,TJ)}};function v8(Y){if(Y==null)return"unknown error";if(typeof Y==="string")return Y;if(Y instanceof Error)return Y.toString();return JSON.stringify(Y)}var CJ="AI_InvalidArgumentError",_J=`vercel.ai.error.${CJ}`,Q2=Symbol.for(_J),eX,YJ,IJ=class extends(YJ=f,eX=Q2,YJ){constructor({message:Y,cause:X,argument:J}){super({name:CJ,message:Y,cause:X});this[eX]=!0,this.argument=J}static isInstance(Y){return f.hasMarker(Y,_J)}},SJ="AI_InvalidPromptError",kJ=`vercel.ai.error.${SJ}`,$2=Symbol.for(kJ),XJ,JJ,G2=class extends(JJ=f,XJ=$2,JJ){constructor({prompt:Y,message:X,cause:J}){super({name:SJ,message:`Invalid prompt: ${X}`,cause:J});this[XJ]=!0,this.prompt=Y}static isInstance(Y){return f.hasMarker(Y,kJ)}},bJ="AI_InvalidResponseDataError",xJ=`vercel.ai.error.${bJ}`,W2=Symbol.for(xJ),QJ,$J,z2=class extends($J=f,QJ=W2,$J){constructor({data:Y,message:X=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:bJ,message:X});this[QJ]=!0,this.data=Y}static isInstance(Y){return f.hasMarker(Y,xJ)}},vJ="AI_JSONParseError",hJ=`vercel.ai.error.${vJ}`,K2=Symbol.for(hJ),GJ,WJ,MY=class extends(WJ=f,GJ=K2,WJ){constructor({text:Y,cause:X}){super({name:vJ,message:`JSON parsing failed: Text: ${Y}.
115
- Error message: ${v8(X)}`,cause:X});this[GJ]=!0,this.text=Y}static isInstance(Y){return f.hasMarker(Y,hJ)}},gJ="AI_LoadAPIKeyError",yJ=`vercel.ai.error.${gJ}`,U2=Symbol.for(yJ),zJ,KJ,H2=class extends(KJ=f,zJ=U2,KJ){constructor({message:Y}){super({name:gJ,message:Y});this[zJ]=!0}static isInstance(Y){return f.hasMarker(Y,yJ)}},fJ="AI_LoadSettingError",mJ=`vercel.ai.error.${fJ}`,L2=Symbol.for(mJ),UJ,HJ,N2=class extends(HJ=f,UJ=L2,HJ){constructor({message:Y}){super({name:fJ,message:Y});this[UJ]=!0}static isInstance(Y){return f.hasMarker(Y,mJ)}},cJ="AI_NoContentGeneratedError",uJ=`vercel.ai.error.${cJ}`,V2=Symbol.for(uJ),LJ,NJ,B2=class extends(NJ=f,LJ=V2,NJ){constructor({message:Y="No content generated."}={}){super({name:cJ,message:Y});this[LJ]=!0}static isInstance(Y){return f.hasMarker(Y,uJ)}},pJ="AI_NoSuchModelError",lJ=`vercel.ai.error.${pJ}`,Z2=Symbol.for(lJ),VJ,BJ,O2=class extends(BJ=f,VJ=Z2,BJ){constructor({errorName:Y=pJ,modelId:X,modelType:J,message:Q=`No such ${J}: ${X}`}){super({name:Y,message:Q});this[VJ]=!0,this.modelId=X,this.modelType=J}static isInstance(Y){return f.hasMarker(Y,lJ)}},dJ="AI_NoSuchProviderReferenceError",iJ=`vercel.ai.error.${dJ}`,F2=Symbol.for(iJ),ZJ,OJ,q2=class extends(OJ=f,ZJ=F2,OJ){constructor({provider:Y,reference:X,message:J=`No provider reference found for provider '${Y}'. Available providers: ${Object.keys(X).join(", ")}`}){super({name:dJ,message:J});this[ZJ]=!0,this.provider=Y,this.reference=X}static isInstance(Y){return f.hasMarker(Y,iJ)}},nJ="AI_TooManyEmbeddingValuesForCallError",oJ=`vercel.ai.error.${nJ}`,j2=Symbol.for(oJ),FJ,qJ,D2=class extends(qJ=f,FJ=j2,qJ){constructor(Y){super({name:nJ,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[FJ]=!0,this.provider=Y.provider,this.modelId=Y.modelId,this.maxEmbeddingsPerCall=Y.maxEmbeddingsPerCall,this.values=Y.values}static isInstance(Y){return f.hasMarker(Y,oJ)}},rJ="AI_TypeValidationError",sJ=`vercel.ai.error.${rJ}`,P2=Symbol.for(sJ),jJ,DJ,v0=class Y extends(DJ=f,jJ=P2,DJ){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:rJ,message:`${$}: Value: ${JSON.stringify(X)}.
116
- Error message: ${v8(J)}`,cause:J});this[jJ]=!0,this.value=X,this.context=Q}static isInstance(X){return f.hasMarker(X,sJ)}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})}},aJ="AI_UnsupportedFunctionalityError",tJ=`vercel.ai.error.${aJ}`,w2=Symbol.for(tJ),PJ,wJ,E2=class extends(wJ=f,PJ=w2,wJ){constructor({functionality:Y,message:X=`'${Y}' functionality not supported.`}){super({name:aJ,message:X});this[PJ]=!0,this.functionality=Y}static isInstance(Y){return f.hasMarker(Y,tJ)}};var OB=Object.freeze({status:"aborted"});function q(Y,X,J){function Q(K,H){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,H);for(let N in W.prototype)if(!(N in K))Object.defineProperty(K,N,{value:W.prototype[N].bind(K)});K._zod.constr=W,K._zod.def=H}let $=J?.Parent??Object;class G extends ${}Object.defineProperty(G,"name",{value:Y});function W(K){var H;let U=J?.Parent?new G:this;Q(U,K),(H=U._zod).deferred??(H.deferred=[]);for(let N of U._zod.deferred)N();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 FB=Symbol("zod_brand");class p0 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class c1 extends Error{constructor(Y){super(`Encountered unidirectional transform during encode: ${Y}`);this.name="ZodEncodeError"}}var AY={};function h0(Y){if(Y)Object.assign(AY,Y);return AY}var c={};g8(c,{unwrapMessage:()=>u1,uint8ArrayToHex:()=>r2,uint8ArrayToBase64url:()=>n2,uint8ArrayToBase64:()=>W6,stringifyPrimitive:()=>J6,shallowClone:()=>Y6,safeExtend:()=>c2,required:()=>l2,randomString:()=>x2,propertyKeyTypes:()=>m8,promiseAllObject:()=>b2,primitiveTypes:()=>X6,prefixIssues:()=>d0,pick:()=>y2,partial:()=>p2,optionalKeys:()=>c8,omit:()=>f2,objectClone:()=>I2,numKeys:()=>v2,nullish:()=>l1,normalizeParams:()=>v,mergeDefs:()=>e0,merge:()=>u2,jsonStringifyReplacer:()=>C1,joinValues:()=>_2,issue:()=>I1,isPlainObject:()=>Y1,isObject:()=>V1,hexToUint8Array:()=>o2,getSizableOrigin:()=>$6,getParsedType:()=>h2,getLengthableOrigin:()=>i1,getEnumValues:()=>p1,getElementAtPath:()=>k2,floatSafeRemainder:()=>y8,finalizeIssue:()=>_0,extend:()=>m2,escapeRegex:()=>l0,esc:()=>RY,defineLazy:()=>p,createTransparentProxy:()=>g2,cloneDef:()=>S2,clone:()=>C0,cleanRegex:()=>d1,cleanEnum:()=>d2,captureStackTrace:()=>TY,cached:()=>_1,base64urlToUint8Array:()=>i2,base64ToUint8Array:()=>G6,assignProp:()=>t0,assertNotEqual:()=>A2,assertNever:()=>T2,assertIs:()=>R2,assertEqual:()=>M2,assert:()=>C2,allowsEval:()=>f8,aborted:()=>X1,NUMBER_FORMAT_RANGES:()=>u8,Class:()=>z6,BIGINT_FORMAT_RANGES:()=>Q6});function M2(Y){return Y}function A2(Y){return Y}function R2(Y){}function T2(Y){throw Error()}function C2(Y){}function p1(Y){let X=Object.values(Y).filter((Q)=>typeof Q==="number");return Object.entries(Y).filter(([Q,$])=>X.indexOf(+Q)===-1).map(([Q,$])=>$)}function _2(Y,X="|"){return Y.map((J)=>J6(J)).join(X)}function C1(Y,X){if(typeof X==="bigint")return X.toString();return X}function _1(Y){return{get value(){{let J=Y();return Object.defineProperty(this,"value",{value:J}),J}throw Error("cached value already set")}}}function l1(Y){return Y===null||Y===void 0}function d1(Y){let X=Y.startsWith("^")?1:0,J=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(X,J)}function y8(Y,X){let J=(Y.toString().split(".")[1]||"").length,Q=X.toString(),$=(Q.split(".")[1]||"").length;if($===0&&/\d?e-\d?/.test(Q)){let H=Q.match(/\d?e-(\d?)/);if(H?.[1])$=Number.parseInt(H[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 eJ=Symbol("evaluating");function p(Y,X,J){let Q=void 0;Object.defineProperty(Y,X,{get(){if(Q===eJ)return;if(Q===void 0)Q=eJ,Q=J();return Q},set($){Object.defineProperty(Y,X,{value:$})},configurable:!0})}function I2(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function t0(Y,X,J){Object.defineProperty(Y,X,{value:J,writable:!0,enumerable:!0,configurable:!0})}function e0(...Y){let X={};for(let J of Y){let Q=Object.getOwnPropertyDescriptors(J);Object.assign(X,Q)}return Object.defineProperties({},X)}function S2(Y){return e0(Y._zod.def)}function k2(Y,X){if(!X)return Y;return X.reduce((J,Q)=>J?.[Q],Y)}function b2(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 x2(Y=10){let J="";for(let Q=0;Q<Y;Q++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function RY(Y){return JSON.stringify(Y)}var TY="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function V1(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var f8=_1(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function Y1(Y){if(V1(Y)===!1)return!1;let X=Y.constructor;if(X===void 0)return!0;let J=X.prototype;if(V1(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function Y6(Y){if(Y1(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function v2(Y){let X=0;for(let J in Y)if(Object.prototype.hasOwnProperty.call(Y,J))X++;return X}var h2=(Y)=>{let X=typeof Y;switch(X){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(Y)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(Y))return"array";if(Y===null)return"null";if(Y.then&&typeof Y.then==="function"&&Y.catch&&typeof Y.catch==="function")return"promise";if(typeof Map<"u"&&Y instanceof Map)return"map";if(typeof Set<"u"&&Y instanceof Set)return"set";if(typeof Date<"u"&&Y instanceof Date)return"date";if(typeof File<"u"&&Y instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${X}`)}},m8=new Set(["string","number","symbol"]),X6=new Set(["string","number","bigint","boolean","symbol","undefined"]);function l0(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function C0(Y,X,J){let Q=new Y._zod.constr(X??Y._zod.def);if(!X||J?.parent)Q._zod.parent=Y;return Q}function v(Y){let X=Y;if(!X)return{};if(typeof X==="string")return{error:()=>X};if(X?.message!==void 0){if(X?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");X.error=X.message}if(delete X.message,typeof X.error==="string")return{...X,error:()=>X.error};return X}function g2(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 J6(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function c8(Y){return Object.keys(Y).filter((X)=>{return Y[X]._zod.optin==="optional"&&Y[X]._zod.optout==="optional"})}var u8={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Q6={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function y2(Y,X){let J=Y._zod.def,Q=e0(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 t0(this,"shape",$),$},checks:[]});return C0(Y,Q)}function f2(Y,X){let J=Y._zod.def,Q=e0(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 t0(this,"shape",$),$},checks:[]});return C0(Y,Q)}function m2(Y,X){if(!Y1(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 $=e0(Y._zod.def,{get shape(){let G={...Y._zod.def.shape,...X};return t0(this,"shape",G),G},checks:[]});return C0(Y,$)}function c2(Y,X){if(!Y1(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 t0(this,"shape",Q),Q},checks:Y._zod.def.checks};return C0(Y,J)}function u2(Y,X){let J=e0(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape,...X._zod.def.shape};return t0(this,"shape",Q),Q},get catchall(){return X._zod.def.catchall},checks:[]});return C0(Y,J)}function p2(Y,X,J){let Q=e0(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 t0(this,"shape",G),G},checks:[]});return C0(X,Q)}function l2(Y,X,J){let Q=e0(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 t0(this,"shape",G),G},checks:[]});return C0(X,Q)}function X1(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 d0(Y,X){return X.map((J)=>{var Q;return(Q=J).path??(Q.path=[]),J.path.unshift(Y),J})}function u1(Y){return typeof Y==="string"?Y:Y?.message}function _0(Y,X,J){let Q={...Y,path:Y.path??[]};if(!Y.message){let $=u1(Y.inst?._zod.def?.error?.(Y))??u1(X?.error?.(Y))??u1(J.customError?.(Y))??u1(J.localeError?.(Y))??"Invalid input";Q.message=$}if(delete Q.inst,delete Q.continue,!X?.reportInput)delete Q.input;return Q}function $6(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function i1(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 d2(Y){return Object.entries(Y).filter(([X,J])=>{return Number.isNaN(Number.parseInt(X,10))}).map((X)=>X[1])}function G6(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 W6(Y){let X="";for(let J=0;J<Y.length;J++)X+=String.fromCharCode(Y[J]);return btoa(X)}function i2(Y){let X=Y.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-X.length%4)%4);return G6(X+J)}function n2(Y){return W6(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function o2(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 r2(Y){return Array.from(Y).map((X)=>X.toString(16).padStart(2,"0")).join("")}class z6{constructor(...Y){}}var K6=(Y,X)=>{Y.name="$ZodError",Object.defineProperty(Y,"_zod",{value:Y._zod,enumerable:!1}),Object.defineProperty(Y,"issues",{value:X,enumerable:!1}),Y.message=JSON.stringify(X,C1,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},CY=q("$ZodError",K6),p8=q("$ZodError",K6,{Parent:Error});function U6(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 H6(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,H=0;while(H<W.path.length){let U=W.path[H];if(H!==W.path.length-1)K[U]=K[U]||{_errors:[]};else K[U]=K[U]||{_errors:[]},K[U]._errors.push(J(W));K=K[U],H++}}};return $(Y),Q}var _Y=(Y)=>(X,J,Q,$)=>{let G=Q?Object.assign(Q,{async:!1}):{async:!1},W=X._zod.run({value:J,issues:[]},G);if(W instanceof Promise)throw new p0;if(W.issues.length){let K=new($?.Err??Y)(W.issues.map((H)=>_0(H,G,h0())));throw TY(K,$?.callee),K}return W.value};var IY=(Y)=>async(X,J,Q,$)=>{let G=Q?Object.assign(Q,{async:!0}):{async:!0},W=X._zod.run({value:J,issues:[]},G);if(W instanceof Promise)W=await W;if(W.issues.length){let K=new($?.Err??Y)(W.issues.map((H)=>_0(H,G,h0())));throw TY(K,$?.callee),K}return W.value};var n1=(Y)=>(X,J,Q)=>{let $=Q?{...Q,async:!1}:{async:!1},G=X._zod.run({value:J,issues:[]},$);if(G instanceof Promise)throw new p0;return G.issues.length?{success:!1,error:new(Y??CY)(G.issues.map((W)=>_0(W,$,h0())))}:{success:!0,data:G.value}},L6=n1(p8),o1=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{async:!0}):{async:!0},G=X._zod.run({value:J,issues:[]},$);if(G instanceof Promise)G=await G;return G.issues.length?{success:!1,error:new Y(G.issues.map((W)=>_0(W,$,h0())))}:{success:!0,data:G.value}},N6=o1(p8),V6=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return _Y(Y)(X,J,$)};var B6=(Y)=>(X,J,Q)=>{return _Y(Y)(X,J,Q)};var Z6=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return IY(Y)(X,J,$)};var O6=(Y)=>async(X,J,Q)=>{return IY(Y)(X,J,Q)};var F6=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return n1(Y)(X,J,$)};var q6=(Y)=>(X,J,Q)=>{return n1(Y)(X,J,Q)};var j6=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return o1(Y)(X,J,$)};var D6=(Y)=>async(X,J,Q)=>{return o1(Y)(X,J,Q)};var P6=/^[cC][^\s-]{8,}$/,w6=/^[0-9a-z]+$/,E6=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,M6=/^[0-9a-vA-V]{20}$/,A6=/^[A-Za-z0-9]{27}$/,R6=/^[a-zA-Z0-9_-]{21}$/,T6=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var C6=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,l8=(Y)=>{if(!Y)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${Y}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var _6=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function I6(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var S6=/^(?:(?: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])$/,k6=/^(([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}|:))$/,b6=/^((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])$/,x6=/^(([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])$/,v6=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,d8=/^[A-Za-z0-9_-]*$/,h6=/^(?=.{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 g6=/^\+(?:[0-9]){6,14}[0-9]$/,y6="(?:(?:\\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])))",f6=new RegExp(`^${y6}$`);function m6(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 c6(Y){return new RegExp(`^${m6(Y)}$`)}function u6(Y){let X=m6({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(`^${y6}T(?:${Q})$`)}var p6=(Y)=>{let X=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${X}$`)};var l6=/^-?\d+$/,d6=/^-?\d+(?:\.\d+)?/,i6=/^(?:true|false)$/i,n6=/^null$/i;var o6=/^[^A-Z]*$/,r6=/^[^a-z]*$/;var N0=q("$ZodCheck",(Y,X)=>{var J;Y._zod??(Y._zod={}),Y._zod.def=X,(J=Y._zod).onattach??(J.onattach=[])}),s6={number:"number",bigint:"bigint",object:"date"},i8=q("$ZodCheckLessThan",(Y,X)=>{N0.init(Y,X);let J=s6[typeof X.value];Y._zod.onattach.push((Q)=>{let $=Q._zod.bag,G=(X.inclusive?$.maximum:$.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(X.value<G)if(X.inclusive)$.maximum=X.value;else $.exclusiveMaximum=X.value}),Y._zod.check=(Q)=>{if(X.inclusive?Q.value<=X.value:Q.value<X.value)return;Q.issues.push({origin:J,code:"too_big",maximum:X.value,input:Q.value,inclusive:X.inclusive,inst:Y,continue:!X.abort})}}),n8=q("$ZodCheckGreaterThan",(Y,X)=>{N0.init(Y,X);let J=s6[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})}}),a6=q("$ZodCheckMultipleOf",(Y,X)=>{N0.init(Y,X),Y._zod.onattach.push((J)=>{var Q;(Q=J._zod.bag).multipleOf??(Q.multipleOf=X.value)}),Y._zod.check=(J)=>{if(typeof J.value!==typeof X.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof J.value==="bigint"?J.value%X.value===BigInt(0):y8(J.value,X.value)===0)return;J.issues.push({origin:typeof J.value,code:"not_multiple_of",divisor:X.value,input:J.value,inst:Y,continue:!X.abort})}}),t6=q("$ZodCheckNumberFormat",(Y,X)=>{N0.init(Y,X),X.format=X.format||"float64";let J=X.format?.includes("int"),Q=J?"int":"number",[$,G]=u8[X.format];Y._zod.onattach.push((W)=>{let K=W._zod.bag;if(K.format=X.format,K.minimum=$,K.maximum=G,J)K.pattern=l6}),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 e6=q("$ZodCheckMaxLength",(Y,X)=>{var J;N0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!l1($)&&$.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=i1($);Q.issues.push({origin:W,code:"too_big",maximum:X.maximum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),YQ=q("$ZodCheckMinLength",(Y,X)=>{var J;N0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!l1($)&&$.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=i1($);Q.issues.push({origin:W,code:"too_small",minimum:X.minimum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),XQ=q("$ZodCheckLengthEquals",(Y,X)=>{var J;N0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!l1($)&&$.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=i1($),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})}}),r1=q("$ZodCheckStringFormat",(Y,X)=>{var J,Q;if(N0.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=()=>{})}),JQ=q("$ZodCheckRegex",(Y,X)=>{r1.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})}}),QQ=q("$ZodCheckLowerCase",(Y,X)=>{X.pattern??(X.pattern=o6),r1.init(Y,X)}),$Q=q("$ZodCheckUpperCase",(Y,X)=>{X.pattern??(X.pattern=r6),r1.init(Y,X)}),GQ=q("$ZodCheckIncludes",(Y,X)=>{N0.init(Y,X);let J=l0(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})}}),WQ=q("$ZodCheckStartsWith",(Y,X)=>{N0.init(Y,X);let J=new RegExp(`^${l0(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})}}),zQ=q("$ZodCheckEndsWith",(Y,X)=>{N0.init(Y,X);let J=new RegExp(`.*${l0(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 KQ=q("$ZodCheckOverwrite",(Y,X)=>{N0.init(Y,X),Y._zod.check=(J)=>{J.value=X.tx(J.value)}});class o8{constructor(Y=[]){if(this.content=[],this.indent=0,this)this.args=Y}indented(Y){this.indent+=1,Y(this),this.indent-=1}write(Y){if(typeof Y==="function"){Y(this,{execution:"sync"}),Y(this,{execution:"async"});return}let J=Y.split(`
114
+ `}}function _5(Y){return Y.type==="response.output_item.done"&&I(Y.item)&&Y.item.type==="web_search_call"&&typeof Y.item.id==="string"}function I5(Y){return I(Y)&&Y.type==="function_call"&&Y.name==="web_search"&&typeof Y.call_id==="string"&&Y.call_id.startsWith(EY)}function S5(Y,X){return I(Y)&&Y.type==="function_call_output"&&typeof Y.call_id==="string"&&typeof Y.output==="string"&&Y.call_id.startsWith(EY)&&X.has(Y.call_id)}function k5(Y){return I(Y)&&Y.type==="item_reference"&&typeof Y.id==="string"&&Y.id.startsWith(EY)}function _8(Y,X,J){let Q=b5(X),$=I(Q?.action)?Q.action:x5(J?.arguments);return{type:"web_search_call",status:"completed",...$?{action:$}:{}}}function b5(Y){if(I(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return I(X)?X:void 0}catch{return}}function x5(Y){if(I(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return I(X)?X:void 0}catch{return}}import{readFile as v5}from"node:fs/promises";import{homedir as h5}from"node:os";import{join as bX}from"node:path";var g5="https://models.dev/api.json",y5="OPENCODE_OPENAI_AUTH_MODELS_CACHE",f5="OPENCODE_MODELS_PATH",m5="OPENCODE_DISABLE_MODELS_FETCH",c5=1e4,u5=300000;function e0(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function xX(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function S8(Y){let{input:X,output:J}=Y;if(typeof X!=="number"||!Number.isFinite(X)||X<0)return null;if(typeof J!=="number"||!Number.isFinite(J)||J<0)return null;let Q=xX(Y.cache_read),$=xX(Y.cache_write);if(Q===null||$===null)return null;return{input:X,output:J,cache:{read:Q,write:$}}}function p5(Y){let X=e0(Y);if(!X)return null;let J=S8(X);if(!J)return null;let Q=J;if(Array.isArray(X.tiers)){let W=[];for(let K of X.tiers){let U=e0(K);if(!U)continue;let H=e0(U.tier),N=H?.size;if(H?.type!=="context")continue;if(typeof N!=="number"||!Number.isFinite(N)||N<=0)continue;let O=S8(U);if(!O)continue;W.push({...O,tier:{type:"context",size:N}})}if(W.length>0)Q.tiers=W}let $=e0(X.context_over_200k),G=$?S8($):null;if(G)Q.experimentalOver200K=G;return Q}function vX(Y){let X=e0(Y),J=e0(X?.openai),Q=e0(J?.models);if(!Q)return null;let $={};for(let[G,W]of Object.entries(Q)){let K=e0(W),U=p5(K?.cost);if(U)$[G]=U}return Object.keys($).length>0?$:null}function l5(){let Y=process.env[y5]?.trim();if(Y)return Y;let X=process.env[f5]?.trim();if(X)return X;let J=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||bX(h5(),".cache");return bX(J,"opencode","models.json")}function d5(){let Y=process.env[m5]?.toLowerCase();return Y==="true"||Y==="1"}async function i5(){try{let Y=vX(JSON.parse(await v5(l5(),"utf8")));if(Y)return Y}catch{}if(d5())return null;try{let Y=await fetch(g5,{signal:AbortSignal.timeout(c5)});if(!Y.ok)return null;return vX(await Y.json())}catch{return null}}var T1;function hX(){let Y=Date.now();if(T1&&T1.expiresAt>Y)return T1.promise;let X={expiresAt:Y+u5,promise:i5()};return T1=X,X.promise.then((J)=>{if(J===null&&T1===X)T1=void 0}),X.promise}function C1(Y){return typeof Y==="object"&&Y!==null}function n5(Y){if(Array.isArray(Y))return Y;if(C1(Y)&&Array.isArray(Y.data))return Y.data;return[]}function o5(Y){if(!C1(Y)||!C1(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function gX(Y){if(!C1(Y)||!C1(Y.info))return null;let X=Y.info,J=C1(X.model)?X.model:void 0,Q=typeof X.agent==="string"?X.agent:void 0,$=typeof J?.providerID==="string"?J.providerID:typeof X.providerID==="string"?X.providerID:void 0,G=typeof J?.modelID==="string"?J.modelID:typeof X.modelID==="string"?X.modelID:void 0,W=typeof J?.variant==="string"?J.variant:typeof X.variant==="string"?X.variant:void 0;if(!Q&&(!$||!G)&&!W)return null;let K={};if(Q)K.agent=Q;if($&&G)K.model={providerID:$,modelID:G};if(W)K.variant=W;return K}function yX(Y,X){return{agent:Y.agent??X.agent,model:Y.model??X.model,variant:Y.variant??X.variant}}function fX(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function mX(Y,X){if(!Y||!X)return null;let J=Y;if(typeof J.session?.messages!=="function")return null;let Q=[];try{Q=n5(await Promise.resolve(J.session.messages({path:{id:X},query:{limit:100}})))}catch{return null}if(Q.length===0)return null;let $={};for(let G=Q.length-1;G>=0;G--){if(o5(Q[G])!=="assistant")continue;let W=gX(Q[G]);if(!W)continue;if($=yX($,W),fX($))return $}for(let G=Q.length-1;G>=0;G--){let W=gX(Q[G]);if(!W)continue;if($=yX($,W),fX($))return $}if(!$.agent&&!$.model&&!$.variant)return null;return $}var Y1=[],r5=1,k8=0,cX=new Map;function b8(Y,X){if(Y1.push({id:r5++,type:"open-dialog",payload:Y,sessionId:X}),Y1.length>100)Y1=Y1.slice(Y1.length-100)}function uX(Y=0,X){let J=Date.now();if(k8=J,X!==void 0)cX.set(X,J);let Q=($)=>X===void 0||$.sessionId===void 0||$.sessionId===X;if(Y>0)Y1=Y1.filter(($)=>{if($.id>Y)return!0;if(X===void 0)return!1;return $.sessionId!==X});return Y1.filter(($)=>$.id>Y&&Q($))}function pX(Y){let X=Date.now();if(Y!==void 0){let J=cX.get(Y)??0;return J>0&&X-J<3000}return k8>0&&X-k8<3000}import{randomBytes as s5,timingSafeEqual as a5}from"node:crypto";import{unlink as t5}from"node:fs/promises";import{createServer as e5}from"node:http";import{join as Y2}from"node:path";var lX=H0("rpc");function X2(Y){return new Promise((X,J)=>{let Q=[],$=0;Y.on("data",(G)=>{if($+=G.length,$>1e6){Y.destroy(),J(Error("body too large"));return}Q.push(G)}),Y.on("end",()=>X(Buffer.concat(Q).toString("utf8"))),Y.on("error",J)})}function J2(Y,X){if(!Y?.startsWith("Bearer "))return!1;let J=Buffer.from(Y.slice(7)),Q=Buffer.from(X);return J.length===Q.length&&a5(J,Q)}async function nX(Y){let X=s5(32).toString("hex"),J=Y.timeoutMs??2000,Q=e5((W,K)=>{W.setTimeout(J,()=>{W.socket.destroy()}),$(W,K)});Q.requestTimeout=J,Q.headersTimeout=J;async function $(W,K){let U=(H,N)=>{if(K.headersSent||K.writableEnded||K.destroyed)return;K.writeHead(H,{"content-type":"application/json"}),K.end(JSON.stringify(N))};try{let H=W.url??"";if(W.method==="GET"&&H==="/health")return U(200,{ok:!0});if(W.method!=="POST"||!H.startsWith("/rpc/"))return U(404,{error:"not found"});if(!J2(W.headers.authorization,X))return U(401,{error:"unauthorized"});let N=H.slice(5),O=await X2(W),B=JSON.parse(O||"{}");if(N==="pending-notifications"){let L=Y.drain(Number(B.lastReceivedId??0),typeof B.sessionId==="string"?B.sessionId:void 0);return U(200,{messages:L})}if(N==="apply"){let L=await Y.apply(B);return U(200,L)}return U(404,{error:"unknown method"})}catch(H){U(500,{error:H instanceof Error?H.message:String(H)})}}let G=await new Promise((W,K)=>{Q.on("error",K),Q.listen(0,"127.0.0.1",()=>{let U=Q.address();if(U&&typeof U==="object")W(U.port);else K(Error("no port"))})});if(Q.unref(),Y.sweepRoot)try{await iX(Y.sweepRoot,Y.dir)}catch(W){lX.warn("rpc state sweep failed",{pid:process.pid,error:W instanceof Error?W.message:String(W)})}try{await dX(Y.dir,{port:G,token:X,pid:process.pid},{secureDir:Y.secureDir}),lX.debug("rpc server pid",{pid:process.pid,rpcPort:G})}catch(W){throw await new Promise((K)=>Q.close(()=>K())),W}return{port:G,token:X,async stop(){await new Promise((W)=>Q.close(()=>W())),await t5(Y2(Y.dir,`port-${process.pid}.json`)).catch(()=>{})}}}function l0(Y){return JSON.stringify(x8(Y))??"undefined"}function x8(Y){if(Array.isArray(Y))return Y.map(x8);if(!I(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((X)=>[X,x8(Y[X])]))}function V1(){let Y=crypto.getRandomValues(new Uint8Array(16)),X=Date.now();Y[0]=X/1099511627776&255,Y[1]=X/4294967296&255,Y[2]=X/16777216&255,Y[3]=X/65536&255,Y[4]=X/256&255,Y[5]=X&255,Y[6]=(Y[6]??0)&15|112,Y[8]=(Y[8]??0)&63|128;let J=Array.from(Y,(Q)=>Q.toString(16).padStart(2,"0")).join("");return`${J.slice(0,8)}-${J.slice(8,12)}-${J.slice(12,16)}-${J.slice(16,20)}-${J.slice(20)}`}var z1={};g8(z1,{withoutInternalHeaders:()=>yG,sanitizeHttpFallbackBody:()=>F8,orderCodexBody:()=>WY,hasWebSocketResponsesLiteMetadata:()=>O8,createWebSocketFetch:()=>UN,applyTurnId:()=>xG,advanceTurn:()=>b9,TITLE_HEADER:()=>k9,QUOTA_ACCOUNT_HEADER:()=>aY,OpenAIWebSocketPool:()=>z1,CODEX_BODY_KEY_ORDER:()=>kG});import{createHash as $N}from"node:crypto";var MJ="vercel.ai.error",Q2=Symbol.for(MJ),oX,rX,f=class Y extends(rX=Error,oX=Q2,rX){constructor({name:X,message:J,cause:Q}){super(J);this[oX]=!0,this.name=X,this.cause=Q}static isInstance(X){return Y.hasMarker(X,MJ)}static hasMarker(X,J){let Q=Symbol.for(J);return X!=null&&typeof X==="object"&&Q in X&&typeof X[Q]==="boolean"&&X[Q]===!0}},AJ="AI_APICallError",RJ=`vercel.ai.error.${AJ}`,$2=Symbol.for(RJ),sX,aX,c1=class extends(aX=f,sX=$2,aX){constructor({message:Y,url:X,requestBodyValues:J,statusCode:Q,responseHeaders:$,responseBody:G,cause:W,isRetryable:K=Q!=null&&(Q===408||Q===409||Q===429||Q>=500),data:U}){super({name:AJ,message:Y,cause:W});this[sX]=!0,this.url=X,this.requestBodyValues=J,this.statusCode=Q,this.responseHeaders=$,this.responseBody=G,this.isRetryable=K,this.data=U}static isInstance(Y){return f.hasMarker(Y,RJ)}},TJ="AI_EmptyResponseBodyError",CJ=`vercel.ai.error.${TJ}`,G2=Symbol.for(CJ),tX,eX,W2=class extends(eX=f,tX=G2,eX){constructor({message:Y="Empty response body"}={}){super({name:TJ,message:Y});this[tX]=!0}static isInstance(Y){return f.hasMarker(Y,CJ)}};function v8(Y){if(Y==null)return"unknown error";if(typeof Y==="string")return Y;if(Y instanceof Error)return Y.toString();return JSON.stringify(Y)}var _J="AI_InvalidArgumentError",IJ=`vercel.ai.error.${_J}`,z2=Symbol.for(IJ),YJ,XJ,SJ=class extends(XJ=f,YJ=z2,XJ){constructor({message:Y,cause:X,argument:J}){super({name:_J,message:Y,cause:X});this[YJ]=!0,this.argument=J}static isInstance(Y){return f.hasMarker(Y,IJ)}},kJ="AI_InvalidPromptError",bJ=`vercel.ai.error.${kJ}`,K2=Symbol.for(bJ),JJ,QJ,U2=class extends(QJ=f,JJ=K2,QJ){constructor({prompt:Y,message:X,cause:J}){super({name:kJ,message:`Invalid prompt: ${X}`,cause:J});this[JJ]=!0,this.prompt=Y}static isInstance(Y){return f.hasMarker(Y,bJ)}},xJ="AI_InvalidResponseDataError",vJ=`vercel.ai.error.${xJ}`,H2=Symbol.for(vJ),$J,GJ,L2=class extends(GJ=f,$J=H2,GJ){constructor({data:Y,message:X=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:xJ,message:X});this[$J]=!0,this.data=Y}static isInstance(Y){return f.hasMarker(Y,vJ)}},hJ="AI_JSONParseError",gJ=`vercel.ai.error.${hJ}`,N2=Symbol.for(gJ),WJ,zJ,MY=class extends(zJ=f,WJ=N2,zJ){constructor({text:Y,cause:X}){super({name:hJ,message:`JSON parsing failed: Text: ${Y}.
115
+ Error message: ${v8(X)}`,cause:X});this[WJ]=!0,this.text=Y}static isInstance(Y){return f.hasMarker(Y,gJ)}},yJ="AI_LoadAPIKeyError",fJ=`vercel.ai.error.${yJ}`,V2=Symbol.for(fJ),KJ,UJ,B2=class extends(UJ=f,KJ=V2,UJ){constructor({message:Y}){super({name:yJ,message:Y});this[KJ]=!0}static isInstance(Y){return f.hasMarker(Y,fJ)}},mJ="AI_LoadSettingError",cJ=`vercel.ai.error.${mJ}`,Z2=Symbol.for(cJ),HJ,LJ,O2=class extends(LJ=f,HJ=Z2,LJ){constructor({message:Y}){super({name:mJ,message:Y});this[HJ]=!0}static isInstance(Y){return f.hasMarker(Y,cJ)}},uJ="AI_NoContentGeneratedError",pJ=`vercel.ai.error.${uJ}`,F2=Symbol.for(pJ),NJ,VJ,q2=class extends(VJ=f,NJ=F2,VJ){constructor({message:Y="No content generated."}={}){super({name:uJ,message:Y});this[NJ]=!0}static isInstance(Y){return f.hasMarker(Y,pJ)}},lJ="AI_NoSuchModelError",dJ=`vercel.ai.error.${lJ}`,j2=Symbol.for(dJ),BJ,ZJ,D2=class extends(ZJ=f,BJ=j2,ZJ){constructor({errorName:Y=lJ,modelId:X,modelType:J,message:Q=`No such ${J}: ${X}`}){super({name:Y,message:Q});this[BJ]=!0,this.modelId=X,this.modelType=J}static isInstance(Y){return f.hasMarker(Y,dJ)}},iJ="AI_NoSuchProviderReferenceError",nJ=`vercel.ai.error.${iJ}`,P2=Symbol.for(nJ),OJ,FJ,w2=class extends(FJ=f,OJ=P2,FJ){constructor({provider:Y,reference:X,message:J=`No provider reference found for provider '${Y}'. Available providers: ${Object.keys(X).join(", ")}`}){super({name:iJ,message:J});this[OJ]=!0,this.provider=Y,this.reference=X}static isInstance(Y){return f.hasMarker(Y,nJ)}},oJ="AI_TooManyEmbeddingValuesForCallError",rJ=`vercel.ai.error.${oJ}`,E2=Symbol.for(rJ),qJ,jJ,M2=class extends(jJ=f,qJ=E2,jJ){constructor(Y){super({name:oJ,message:`Too many values for a single embedding call. The ${Y.provider} model "${Y.modelId}" can only embed up to ${Y.maxEmbeddingsPerCall} values per call, but ${Y.values.length} values were provided.`});this[qJ]=!0,this.provider=Y.provider,this.modelId=Y.modelId,this.maxEmbeddingsPerCall=Y.maxEmbeddingsPerCall,this.values=Y.values}static isInstance(Y){return f.hasMarker(Y,rJ)}},sJ="AI_TypeValidationError",aJ=`vercel.ai.error.${sJ}`,A2=Symbol.for(aJ),DJ,PJ,v0=class Y extends(PJ=f,DJ=A2,PJ){constructor({value:X,cause:J,context:Q}){let $="Type validation failed";if(Q==null?void 0:Q.field)$+=` for ${Q.field}`;if((Q==null?void 0:Q.entityName)||(Q==null?void 0:Q.entityId)){$+=" (";let G=[];if(Q.entityName)G.push(Q.entityName);if(Q.entityId)G.push(`id: "${Q.entityId}"`);$+=G.join(", "),$+=")"}super({name:sJ,message:`${$}: Value: ${JSON.stringify(X)}.
116
+ Error message: ${v8(J)}`,cause:J});this[DJ]=!0,this.value=X,this.context=Q}static isInstance(X){return f.hasMarker(X,aJ)}static wrap({value:X,cause:J,context:Q}){var $,G,W;if(Y.isInstance(J)&&J.value===X&&(($=J.context)==null?void 0:$.field)===(Q==null?void 0:Q.field)&&((G=J.context)==null?void 0:G.entityName)===(Q==null?void 0:Q.entityName)&&((W=J.context)==null?void 0:W.entityId)===(Q==null?void 0:Q.entityId))return J;return new Y({value:X,cause:J,context:Q})}},tJ="AI_UnsupportedFunctionalityError",eJ=`vercel.ai.error.${tJ}`,R2=Symbol.for(eJ),wJ,EJ,T2=class extends(EJ=f,wJ=R2,EJ){constructor({functionality:Y,message:X=`'${Y}' functionality not supported.`}){super({name:tJ,message:X});this[wJ]=!0,this.functionality=Y}static isInstance(Y){return f.hasMarker(Y,eJ)}};var qB=Object.freeze({status:"aborted"});function q(Y,X,J){function Q(K,U){var H;Object.defineProperty(K,"_zod",{value:K._zod??{},enumerable:!1}),(H=K._zod).traits??(H.traits=new Set),K._zod.traits.add(Y),X(K,U);for(let N in W.prototype)if(!(N in K))Object.defineProperty(K,N,{value:W.prototype[N].bind(K)});K._zod.constr=W,K._zod.def=U}let $=J?.Parent??Object;class G extends ${}Object.defineProperty(G,"name",{value:Y});function W(K){var U;let H=J?.Parent?new G:this;Q(H,K),(U=H._zod).deferred??(U.deferred=[]);for(let N of H._zod.deferred)N();return H}return Object.defineProperty(W,"init",{value:Q}),Object.defineProperty(W,Symbol.hasInstance,{value:(K)=>{if(J?.Parent&&K instanceof J.Parent)return!0;return K?._zod?.traits?.has(Y)}}),Object.defineProperty(W,"name",{value:Y}),W}var jB=Symbol("zod_brand");class d0 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class u1 extends Error{constructor(Y){super(`Encountered unidirectional transform during encode: ${Y}`);this.name="ZodEncodeError"}}var AY={};function h0(Y){if(Y)Object.assign(AY,Y);return AY}var c={};g8(c,{unwrapMessage:()=>p1,uint8ArrayToHex:()=>e2,uint8ArrayToBase64url:()=>a2,uint8ArrayToBase64:()=>z6,stringifyPrimitive:()=>Q6,shallowClone:()=>X6,safeExtend:()=>d2,required:()=>o2,randomString:()=>y2,propertyKeyTypes:()=>m8,promiseAllObject:()=>g2,primitiveTypes:()=>J6,prefixIssues:()=>n0,pick:()=>u2,partial:()=>n2,optionalKeys:()=>c8,omit:()=>p2,objectClone:()=>x2,numKeys:()=>f2,nullish:()=>d1,normalizeParams:()=>v,mergeDefs:()=>J1,merge:()=>i2,jsonStringifyReplacer:()=>_1,joinValues:()=>b2,issue:()=>S1,isPlainObject:()=>Q1,isObject:()=>B1,hexToUint8Array:()=>t2,getSizableOrigin:()=>G6,getParsedType:()=>m2,getLengthableOrigin:()=>n1,getEnumValues:()=>l1,getElementAtPath:()=>h2,floatSafeRemainder:()=>y8,finalizeIssue:()=>_0,extend:()=>l2,escapeRegex:()=>i0,esc:()=>RY,defineLazy:()=>l,createTransparentProxy:()=>c2,cloneDef:()=>v2,clone:()=>C0,cleanRegex:()=>i1,cleanEnum:()=>r2,captureStackTrace:()=>TY,cached:()=>I1,base64urlToUint8Array:()=>s2,base64ToUint8Array:()=>W6,assignProp:()=>X1,assertNotEqual:()=>_2,assertNever:()=>S2,assertIs:()=>I2,assertEqual:()=>C2,assert:()=>k2,allowsEval:()=>f8,aborted:()=>$1,NUMBER_FORMAT_RANGES:()=>u8,Class:()=>K6,BIGINT_FORMAT_RANGES:()=>$6});function C2(Y){return Y}function _2(Y){return Y}function I2(Y){}function S2(Y){throw Error()}function k2(Y){}function l1(Y){let X=Object.values(Y).filter((Q)=>typeof Q==="number");return Object.entries(Y).filter(([Q,$])=>X.indexOf(+Q)===-1).map(([Q,$])=>$)}function b2(Y,X="|"){return Y.map((J)=>Q6(J)).join(X)}function _1(Y,X){if(typeof X==="bigint")return X.toString();return X}function I1(Y){return{get value(){{let J=Y();return Object.defineProperty(this,"value",{value:J}),J}throw Error("cached value already set")}}}function d1(Y){return Y===null||Y===void 0}function i1(Y){let X=Y.startsWith("^")?1:0,J=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(X,J)}function y8(Y,X){let J=(Y.toString().split(".")[1]||"").length,Q=X.toString(),$=(Q.split(".")[1]||"").length;if($===0&&/\d?e-\d?/.test(Q)){let U=Q.match(/\d?e-(\d?)/);if(U?.[1])$=Number.parseInt(U[1])}let G=J>$?J:$,W=Number.parseInt(Y.toFixed(G).replace(".","")),K=Number.parseInt(X.toFixed(G).replace(".",""));return W%K/10**G}var Y6=Symbol("evaluating");function l(Y,X,J){let Q=void 0;Object.defineProperty(Y,X,{get(){if(Q===Y6)return;if(Q===void 0)Q=Y6,Q=J();return Q},set($){Object.defineProperty(Y,X,{value:$})},configurable:!0})}function x2(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function X1(Y,X,J){Object.defineProperty(Y,X,{value:J,writable:!0,enumerable:!0,configurable:!0})}function J1(...Y){let X={};for(let J of Y){let Q=Object.getOwnPropertyDescriptors(J);Object.assign(X,Q)}return Object.defineProperties({},X)}function v2(Y){return J1(Y._zod.def)}function h2(Y,X){if(!X)return Y;return X.reduce((J,Q)=>J?.[Q],Y)}function g2(Y){let X=Object.keys(Y),J=X.map((Q)=>Y[Q]);return Promise.all(J).then((Q)=>{let $={};for(let G=0;G<X.length;G++)$[X[G]]=Q[G];return $})}function y2(Y=10){let J="";for(let Q=0;Q<Y;Q++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function RY(Y){return JSON.stringify(Y)}var TY="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function B1(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var f8=I1(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function Q1(Y){if(B1(Y)===!1)return!1;let X=Y.constructor;if(X===void 0)return!0;let J=X.prototype;if(B1(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function X6(Y){if(Q1(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function f2(Y){let X=0;for(let J in Y)if(Object.prototype.hasOwnProperty.call(Y,J))X++;return X}var m2=(Y)=>{let X=typeof Y;switch(X){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(Y)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(Y))return"array";if(Y===null)return"null";if(Y.then&&typeof Y.then==="function"&&Y.catch&&typeof Y.catch==="function")return"promise";if(typeof Map<"u"&&Y instanceof Map)return"map";if(typeof Set<"u"&&Y instanceof Set)return"set";if(typeof Date<"u"&&Y instanceof Date)return"date";if(typeof File<"u"&&Y instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${X}`)}},m8=new Set(["string","number","symbol"]),J6=new Set(["string","number","bigint","boolean","symbol","undefined"]);function i0(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function C0(Y,X,J){let Q=new Y._zod.constr(X??Y._zod.def);if(!X||J?.parent)Q._zod.parent=Y;return Q}function v(Y){let X=Y;if(!X)return{};if(typeof X==="string")return{error:()=>X};if(X?.message!==void 0){if(X?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");X.error=X.message}if(delete X.message,typeof X.error==="string")return{...X,error:()=>X.error};return X}function c2(Y){let X;return new Proxy({},{get(J,Q,$){return X??(X=Y()),Reflect.get(X,Q,$)},set(J,Q,$,G){return X??(X=Y()),Reflect.set(X,Q,$,G)},has(J,Q){return X??(X=Y()),Reflect.has(X,Q)},deleteProperty(J,Q){return X??(X=Y()),Reflect.deleteProperty(X,Q)},ownKeys(J){return X??(X=Y()),Reflect.ownKeys(X)},getOwnPropertyDescriptor(J,Q){return X??(X=Y()),Reflect.getOwnPropertyDescriptor(X,Q)},defineProperty(J,Q,$){return X??(X=Y()),Reflect.defineProperty(X,Q,$)}})}function Q6(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function c8(Y){return Object.keys(Y).filter((X)=>{return Y[X]._zod.optin==="optional"&&Y[X]._zod.optout==="optional"})}var u8={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},$6={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function u2(Y,X){let J=Y._zod.def,Q=J1(Y._zod.def,{get shape(){let $={};for(let G in X){if(!(G in J.shape))throw Error(`Unrecognized key: "${G}"`);if(!X[G])continue;$[G]=J.shape[G]}return X1(this,"shape",$),$},checks:[]});return C0(Y,Q)}function p2(Y,X){let J=Y._zod.def,Q=J1(Y._zod.def,{get shape(){let $={...Y._zod.def.shape};for(let G in X){if(!(G in J.shape))throw Error(`Unrecognized key: "${G}"`);if(!X[G])continue;delete $[G]}return X1(this,"shape",$),$},checks:[]});return C0(Y,Q)}function l2(Y,X){if(!Q1(X))throw Error("Invalid input to extend: expected a plain object");let J=Y._zod.def.checks;if(J&&J.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let $=J1(Y._zod.def,{get shape(){let G={...Y._zod.def.shape,...X};return X1(this,"shape",G),G},checks:[]});return C0(Y,$)}function d2(Y,X){if(!Q1(X))throw Error("Invalid input to safeExtend: expected a plain object");let J={...Y._zod.def,get shape(){let Q={...Y._zod.def.shape,...X};return X1(this,"shape",Q),Q},checks:Y._zod.def.checks};return C0(Y,J)}function i2(Y,X){let J=J1(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape,...X._zod.def.shape};return X1(this,"shape",Q),Q},get catchall(){return X._zod.def.catchall},checks:[]});return C0(Y,J)}function n2(Y,X,J){let Q=J1(X._zod.def,{get shape(){let $=X._zod.def.shape,G={...$};if(J)for(let W in J){if(!(W in $))throw Error(`Unrecognized key: "${W}"`);if(!J[W])continue;G[W]=Y?new Y({type:"optional",innerType:$[W]}):$[W]}else for(let W in $)G[W]=Y?new Y({type:"optional",innerType:$[W]}):$[W];return X1(this,"shape",G),G},checks:[]});return C0(X,Q)}function o2(Y,X,J){let Q=J1(X._zod.def,{get shape(){let $=X._zod.def.shape,G={...$};if(J)for(let W in J){if(!(W in G))throw Error(`Unrecognized key: "${W}"`);if(!J[W])continue;G[W]=new Y({type:"nonoptional",innerType:$[W]})}else for(let W in $)G[W]=new Y({type:"nonoptional",innerType:$[W]});return X1(this,"shape",G),G},checks:[]});return C0(X,Q)}function $1(Y,X=0){if(Y.aborted===!0)return!0;for(let J=X;J<Y.issues.length;J++)if(Y.issues[J]?.continue!==!0)return!0;return!1}function n0(Y,X){return X.map((J)=>{var Q;return(Q=J).path??(Q.path=[]),J.path.unshift(Y),J})}function p1(Y){return typeof Y==="string"?Y:Y?.message}function _0(Y,X,J){let Q={...Y,path:Y.path??[]};if(!Y.message){let $=p1(Y.inst?._zod.def?.error?.(Y))??p1(X?.error?.(Y))??p1(J.customError?.(Y))??p1(J.localeError?.(Y))??"Invalid input";Q.message=$}if(delete Q.inst,delete Q.continue,!X?.reportInput)delete Q.input;return Q}function G6(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function n1(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function S1(...Y){let[X,J,Q]=Y;if(typeof X==="string")return{message:X,code:"custom",input:J,inst:Q};return{...X}}function r2(Y){return Object.entries(Y).filter(([X,J])=>{return Number.isNaN(Number.parseInt(X,10))}).map((X)=>X[1])}function W6(Y){let X=atob(Y),J=new Uint8Array(X.length);for(let Q=0;Q<X.length;Q++)J[Q]=X.charCodeAt(Q);return J}function z6(Y){let X="";for(let J=0;J<Y.length;J++)X+=String.fromCharCode(Y[J]);return btoa(X)}function s2(Y){let X=Y.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-X.length%4)%4);return W6(X+J)}function a2(Y){return z6(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function t2(Y){let X=Y.replace(/^0x/,"");if(X.length%2!==0)throw Error("Invalid hex string length");let J=new Uint8Array(X.length/2);for(let Q=0;Q<X.length;Q+=2)J[Q/2]=Number.parseInt(X.slice(Q,Q+2),16);return J}function e2(Y){return Array.from(Y).map((X)=>X.toString(16).padStart(2,"0")).join("")}class K6{constructor(...Y){}}var U6=(Y,X)=>{Y.name="$ZodError",Object.defineProperty(Y,"_zod",{value:Y._zod,enumerable:!1}),Object.defineProperty(Y,"issues",{value:X,enumerable:!1}),Y.message=JSON.stringify(X,_1,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},CY=q("$ZodError",U6),p8=q("$ZodError",U6,{Parent:Error});function H6(Y,X=(J)=>J.message){let J={},Q=[];for(let $ of Y.issues)if($.path.length>0)J[$.path[0]]=J[$.path[0]]||[],J[$.path[0]].push(X($));else Q.push(X($));return{formErrors:Q,fieldErrors:J}}function L6(Y,X){let J=X||function(G){return G.message},Q={_errors:[]},$=(G)=>{for(let W of G.issues)if(W.code==="invalid_union"&&W.errors.length)W.errors.map((K)=>$({issues:K}));else if(W.code==="invalid_key")$({issues:W.issues});else if(W.code==="invalid_element")$({issues:W.issues});else if(W.path.length===0)Q._errors.push(J(W));else{let K=Q,U=0;while(U<W.path.length){let H=W.path[U];if(U!==W.path.length-1)K[H]=K[H]||{_errors:[]};else K[H]=K[H]||{_errors:[]},K[H]._errors.push(J(W));K=K[H],U++}}};return $(Y),Q}var _Y=(Y)=>(X,J,Q,$)=>{let G=Q?Object.assign(Q,{async:!1}):{async:!1},W=X._zod.run({value:J,issues:[]},G);if(W instanceof Promise)throw new d0;if(W.issues.length){let K=new($?.Err??Y)(W.issues.map((U)=>_0(U,G,h0())));throw TY(K,$?.callee),K}return W.value};var IY=(Y)=>async(X,J,Q,$)=>{let G=Q?Object.assign(Q,{async:!0}):{async:!0},W=X._zod.run({value:J,issues:[]},G);if(W instanceof Promise)W=await W;if(W.issues.length){let K=new($?.Err??Y)(W.issues.map((U)=>_0(U,G,h0())));throw TY(K,$?.callee),K}return W.value};var o1=(Y)=>(X,J,Q)=>{let $=Q?{...Q,async:!1}:{async:!1},G=X._zod.run({value:J,issues:[]},$);if(G instanceof Promise)throw new d0;return G.issues.length?{success:!1,error:new(Y??CY)(G.issues.map((W)=>_0(W,$,h0())))}:{success:!0,data:G.value}},N6=o1(p8),r1=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{async:!0}):{async:!0},G=X._zod.run({value:J,issues:[]},$);if(G instanceof Promise)G=await G;return G.issues.length?{success:!1,error:new Y(G.issues.map((W)=>_0(W,$,h0())))}:{success:!0,data:G.value}},V6=r1(p8),B6=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return _Y(Y)(X,J,$)};var Z6=(Y)=>(X,J,Q)=>{return _Y(Y)(X,J,Q)};var O6=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return IY(Y)(X,J,$)};var F6=(Y)=>async(X,J,Q)=>{return IY(Y)(X,J,Q)};var q6=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return o1(Y)(X,J,$)};var j6=(Y)=>(X,J,Q)=>{return o1(Y)(X,J,Q)};var D6=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return r1(Y)(X,J,$)};var P6=(Y)=>async(X,J,Q)=>{return r1(Y)(X,J,Q)};var w6=/^[cC][^\s-]{8,}$/,E6=/^[0-9a-z]+$/,M6=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,A6=/^[0-9a-vA-V]{20}$/,R6=/^[A-Za-z0-9]{27}$/,T6=/^[a-zA-Z0-9_-]{21}$/,C6=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var _6=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,l8=(Y)=>{if(!Y)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${Y}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var I6=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function S6(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var k6=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,b6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,x6=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,v6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,h6=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,d8=/^[A-Za-z0-9_-]*$/,g6=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;var y6=/^\+(?:[0-9]){6,14}[0-9]$/,f6="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",m6=new RegExp(`^${f6}$`);function c6(Y){return typeof Y.precision==="number"?Y.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":Y.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${Y.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function u6(Y){return new RegExp(`^${c6(Y)}$`)}function p6(Y){let X=c6({precision:Y.precision}),J=["Z"];if(Y.local)J.push("");if(Y.offset)J.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let Q=`${X}(?:${J.join("|")})`;return new RegExp(`^${f6}T(?:${Q})$`)}var l6=(Y)=>{let X=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${X}$`)};var d6=/^-?\d+$/,i6=/^-?\d+(?:\.\d+)?/,n6=/^(?:true|false)$/i,o6=/^null$/i;var r6=/^[^A-Z]*$/,s6=/^[^a-z]*$/;var L0=q("$ZodCheck",(Y,X)=>{var J;Y._zod??(Y._zod={}),Y._zod.def=X,(J=Y._zod).onattach??(J.onattach=[])}),a6={number:"number",bigint:"bigint",object:"date"},i8=q("$ZodCheckLessThan",(Y,X)=>{L0.init(Y,X);let J=a6[typeof X.value];Y._zod.onattach.push((Q)=>{let $=Q._zod.bag,G=(X.inclusive?$.maximum:$.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(X.value<G)if(X.inclusive)$.maximum=X.value;else $.exclusiveMaximum=X.value}),Y._zod.check=(Q)=>{if(X.inclusive?Q.value<=X.value:Q.value<X.value)return;Q.issues.push({origin:J,code:"too_big",maximum:X.value,input:Q.value,inclusive:X.inclusive,inst:Y,continue:!X.abort})}}),n8=q("$ZodCheckGreaterThan",(Y,X)=>{L0.init(Y,X);let J=a6[typeof X.value];Y._zod.onattach.push((Q)=>{let $=Q._zod.bag,G=(X.inclusive?$.minimum:$.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(X.value>G)if(X.inclusive)$.minimum=X.value;else $.exclusiveMinimum=X.value}),Y._zod.check=(Q)=>{if(X.inclusive?Q.value>=X.value:Q.value>X.value)return;Q.issues.push({origin:J,code:"too_small",minimum:X.value,input:Q.value,inclusive:X.inclusive,inst:Y,continue:!X.abort})}}),t6=q("$ZodCheckMultipleOf",(Y,X)=>{L0.init(Y,X),Y._zod.onattach.push((J)=>{var Q;(Q=J._zod.bag).multipleOf??(Q.multipleOf=X.value)}),Y._zod.check=(J)=>{if(typeof J.value!==typeof X.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof J.value==="bigint"?J.value%X.value===BigInt(0):y8(J.value,X.value)===0)return;J.issues.push({origin:typeof J.value,code:"not_multiple_of",divisor:X.value,input:J.value,inst:Y,continue:!X.abort})}}),e6=q("$ZodCheckNumberFormat",(Y,X)=>{L0.init(Y,X),X.format=X.format||"float64";let J=X.format?.includes("int"),Q=J?"int":"number",[$,G]=u8[X.format];Y._zod.onattach.push((W)=>{let K=W._zod.bag;if(K.format=X.format,K.minimum=$,K.maximum=G,J)K.pattern=d6}),Y._zod.check=(W)=>{let K=W.value;if(J){if(!Number.isInteger(K)){W.issues.push({expected:Q,format:X.format,code:"invalid_type",continue:!1,input:K,inst:Y});return}if(!Number.isSafeInteger(K)){if(K>0)W.issues.push({input:K,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:Q,continue:!X.abort});else W.issues.push({input:K,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:Q,continue:!X.abort});return}}if(K<$)W.issues.push({origin:"number",input:K,code:"too_small",minimum:$,inclusive:!0,inst:Y,continue:!X.abort});if(K>G)W.issues.push({origin:"number",input:K,code:"too_big",maximum:G,inst:Y})}});var YQ=q("$ZodCheckMaxLength",(Y,X)=>{var J;L0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!d1($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(X.maximum<$)Q._zod.bag.maximum=X.maximum}),Y._zod.check=(Q)=>{let $=Q.value;if($.length<=X.maximum)return;let W=n1($);Q.issues.push({origin:W,code:"too_big",maximum:X.maximum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),XQ=q("$ZodCheckMinLength",(Y,X)=>{var J;L0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!d1($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(X.minimum>$)Q._zod.bag.minimum=X.minimum}),Y._zod.check=(Q)=>{let $=Q.value;if($.length>=X.minimum)return;let W=n1($);Q.issues.push({origin:W,code:"too_small",minimum:X.minimum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),JQ=q("$ZodCheckLengthEquals",(Y,X)=>{var J;L0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!d1($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.minimum=X.length,$.maximum=X.length,$.length=X.length}),Y._zod.check=(Q)=>{let $=Q.value,G=$.length;if(G===X.length)return;let W=n1($),K=G>X.length;Q.issues.push({origin:W,...K?{code:"too_big",maximum:X.length}:{code:"too_small",minimum:X.length},inclusive:!0,exact:!0,input:Q.value,inst:Y,continue:!X.abort})}}),s1=q("$ZodCheckStringFormat",(Y,X)=>{var J,Q;if(L0.init(Y,X),Y._zod.onattach.push(($)=>{let G=$._zod.bag;if(G.format=X.format,X.pattern)G.patterns??(G.patterns=new Set),G.patterns.add(X.pattern)}),X.pattern)(J=Y._zod).check??(J.check=($)=>{if(X.pattern.lastIndex=0,X.pattern.test($.value))return;$.issues.push({origin:"string",code:"invalid_format",format:X.format,input:$.value,...X.pattern?{pattern:X.pattern.toString()}:{},inst:Y,continue:!X.abort})});else(Q=Y._zod).check??(Q.check=()=>{})}),QQ=q("$ZodCheckRegex",(Y,X)=>{s1.init(Y,X),Y._zod.check=(J)=>{if(X.pattern.lastIndex=0,X.pattern.test(J.value))return;J.issues.push({origin:"string",code:"invalid_format",format:"regex",input:J.value,pattern:X.pattern.toString(),inst:Y,continue:!X.abort})}}),$Q=q("$ZodCheckLowerCase",(Y,X)=>{X.pattern??(X.pattern=r6),s1.init(Y,X)}),GQ=q("$ZodCheckUpperCase",(Y,X)=>{X.pattern??(X.pattern=s6),s1.init(Y,X)}),WQ=q("$ZodCheckIncludes",(Y,X)=>{L0.init(Y,X);let J=i0(X.includes),Q=new RegExp(typeof X.position==="number"?`^.{${X.position}}${J}`:J);X.pattern=Q,Y._zod.onattach.push(($)=>{let G=$._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(Q)}),Y._zod.check=($)=>{if($.value.includes(X.includes,X.position))return;$.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:X.includes,input:$.value,inst:Y,continue:!X.abort})}}),zQ=q("$ZodCheckStartsWith",(Y,X)=>{L0.init(Y,X);let J=new RegExp(`^${i0(X.prefix)}.*`);X.pattern??(X.pattern=J),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(J)}),Y._zod.check=(Q)=>{if(Q.value.startsWith(X.prefix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:X.prefix,input:Q.value,inst:Y,continue:!X.abort})}}),KQ=q("$ZodCheckEndsWith",(Y,X)=>{L0.init(Y,X);let J=new RegExp(`.*${i0(X.suffix)}$`);X.pattern??(X.pattern=J),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(J)}),Y._zod.check=(Q)=>{if(Q.value.endsWith(X.suffix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:X.suffix,input:Q.value,inst:Y,continue:!X.abort})}});var UQ=q("$ZodCheckOverwrite",(Y,X)=>{L0.init(Y,X),Y._zod.check=(J)=>{J.value=X.tx(J.value)}});class o8{constructor(Y=[]){if(this.content=[],this.indent=0,this)this.args=Y}indented(Y){this.indent+=1,Y(this),this.indent-=1}write(Y){if(typeof Y==="function"){Y(this,{execution:"sync"}),Y(this,{execution:"async"});return}let J=Y.split(`
117
117
  `).filter((G)=>G),Q=Math.min(...J.map((G)=>G.length-G.trimStart().length)),$=J.map((G)=>G.slice(Q)).map((G)=>" ".repeat(this.indent*2)+G);for(let G of $)this.content.push(G)}compile(){let Y=Function,X=this?.args,Q=[...(this?.content??[""]).map(($)=>` ${$}`)];return new Y(...X,Q.join(`
118
- `))}}var HQ={major:4,minor:1,patch:8};var i=q("$ZodType",(Y,X)=>{var J;Y??(Y={}),Y._zod.def=X,Y._zod.bag=Y._zod.bag||{},Y._zod.version=HQ;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,H)=>{let U=X1(W),N;for(let O of K){if(O._zod.def.when){if(!O._zod.def.when(W))continue}else if(U)continue;let B=W.issues.length,L=O._zod.check(W);if(L instanceof Promise&&H?.async===!1)throw new p0;if(N||L instanceof Promise)N=(N??Promise.resolve()).then(async()=>{if(await L,W.issues.length===B)return;if(!U)U=X1(W,B)});else{if(W.issues.length===B)continue;if(!U)U=X1(W,B)}}if(N)return N.then(()=>{return W});return W},G=(W,K,H)=>{if(X1(W))return W.aborted=!0,W;let U=$(K,Q,H);if(U instanceof Promise){if(H.async===!1)throw new p0;return U.then((N)=>Y._zod.parse(N,H))}return Y._zod.parse(U,H)};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((N)=>{return G(N,W,K)});return G(U,W,K)}let H=Y._zod.parse(W,K);if(H instanceof Promise){if(K.async===!1)throw new p0;return H.then((U)=>$(U,Q,K))}return $(H,Q,K)}}Y["~standard"]={validate:($)=>{try{let G=L6(Y,$);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return N6(Y,$).then((W)=>W.success?{value:W.data}:{issues:W.error?.issues})}},vendor:"zod",version:1}}),xY=q("$ZodString",(Y,X)=>{i.init(Y,X),Y._zod.pattern=[...Y?._zod.bag?.patterns??[]].pop()??p6(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}}),n=q("$ZodStringFormat",(Y,X)=>{r1.init(Y,X),xY.init(Y,X)}),jQ=q("$ZodGUID",(Y,X)=>{X.pattern??(X.pattern=C6),n.init(Y,X)}),DQ=q("$ZodUUID",(Y,X)=>{if(X.version){let Q={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[X.version];if(Q===void 0)throw Error(`Invalid UUID version: "${X.version}"`);X.pattern??(X.pattern=l8(Q))}else X.pattern??(X.pattern=l8());n.init(Y,X)}),PQ=q("$ZodEmail",(Y,X)=>{X.pattern??(X.pattern=_6),n.init(Y,X)}),wQ=q("$ZodURL",(Y,X)=>{n.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:h6.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})}}}),EQ=q("$ZodEmoji",(Y,X)=>{X.pattern??(X.pattern=I6()),n.init(Y,X)}),MQ=q("$ZodNanoID",(Y,X)=>{X.pattern??(X.pattern=R6),n.init(Y,X)}),AQ=q("$ZodCUID",(Y,X)=>{X.pattern??(X.pattern=P6),n.init(Y,X)}),RQ=q("$ZodCUID2",(Y,X)=>{X.pattern??(X.pattern=w6),n.init(Y,X)}),TQ=q("$ZodULID",(Y,X)=>{X.pattern??(X.pattern=E6),n.init(Y,X)}),CQ=q("$ZodXID",(Y,X)=>{X.pattern??(X.pattern=M6),n.init(Y,X)}),_Q=q("$ZodKSUID",(Y,X)=>{X.pattern??(X.pattern=A6),n.init(Y,X)}),IQ=q("$ZodISODateTime",(Y,X)=>{X.pattern??(X.pattern=u6(X)),n.init(Y,X)}),SQ=q("$ZodISODate",(Y,X)=>{X.pattern??(X.pattern=f6),n.init(Y,X)}),kQ=q("$ZodISOTime",(Y,X)=>{X.pattern??(X.pattern=c6(X)),n.init(Y,X)}),bQ=q("$ZodISODuration",(Y,X)=>{X.pattern??(X.pattern=T6),n.init(Y,X)}),xQ=q("$ZodIPv4",(Y,X)=>{X.pattern??(X.pattern=S6),n.init(Y,X),Y._zod.onattach.push((J)=>{let Q=J._zod.bag;Q.format="ipv4"})}),vQ=q("$ZodIPv6",(Y,X)=>{X.pattern??(X.pattern=k6),n.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})}}}),hQ=q("$ZodCIDRv4",(Y,X)=>{X.pattern??(X.pattern=b6),n.init(Y,X)}),gQ=q("$ZodCIDRv6",(Y,X)=>{X.pattern??(X.pattern=x6),n.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 yQ(Y){if(Y==="")return!0;if(Y.length%4!==0)return!1;try{return atob(Y),!0}catch{return!1}}var fQ=q("$ZodBase64",(Y,X)=>{X.pattern??(X.pattern=v6),n.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64"}),Y._zod.check=(J)=>{if(yQ(J.value))return;J.issues.push({code:"invalid_format",format:"base64",input:J.value,inst:Y,continue:!X.abort})}});function a2(Y){if(!d8.test(Y))return!1;let X=Y.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),J=X.padEnd(Math.ceil(X.length/4)*4,"=");return yQ(J)}var mQ=q("$ZodBase64URL",(Y,X)=>{X.pattern??(X.pattern=d8),n.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64url"}),Y._zod.check=(J)=>{if(a2(J.value))return;J.issues.push({code:"invalid_format",format:"base64url",input:J.value,inst:Y,continue:!X.abort})}}),cQ=q("$ZodE164",(Y,X)=>{X.pattern??(X.pattern=g6),n.init(Y,X)});function t2(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 uQ=q("$ZodJWT",(Y,X)=>{n.init(Y,X),Y._zod.check=(J)=>{if(t2(J.value,X.alg))return;J.issues.push({code:"invalid_format",format:"jwt",input:J.value,inst:Y,continue:!X.abort})}});var s8=q("$ZodNumber",(Y,X)=>{i.init(Y,X),Y._zod.pattern=Y._zod.bag.pattern??d6,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}}),pQ=q("$ZodNumber",(Y,X)=>{t6.init(Y,X),s8.init(Y,X)}),lQ=q("$ZodBoolean",(Y,X)=>{i.init(Y,X),Y._zod.pattern=i6,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 dQ=q("$ZodNull",(Y,X)=>{i.init(Y,X),Y._zod.pattern=n6,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 iQ=q("$ZodUnknown",(Y,X)=>{i.init(Y,X),Y._zod.parse=(J)=>J}),nQ=q("$ZodNever",(Y,X)=>{i.init(Y,X),Y._zod.parse=(J,Q)=>{return J.issues.push({expected:"never",code:"invalid_type",input:J.value,inst:Y}),J}});function LQ(Y,X,J){if(Y.issues.length)X.issues.push(...d0(J,Y.issues));X.value[J]=Y.value}var oQ=q("$ZodArray",(Y,X)=>{i.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],H=X.element._zod.run({value:K,issues:[]},Q);if(H instanceof Promise)G.push(H.then((U)=>LQ(U,J,W)));else LQ(H,J,W)}if(G.length)return Promise.all(G).then(()=>J);return J}});function bY(Y,X,J,Q){if(Y.issues.length)X.issues.push(...d0(J,Y.issues));if(Y.value===void 0){if(J in Q)X.value[J]=void 0}else X.value[J]=Y.value}function rQ(Y){let X=Object.keys(Y.shape);for(let Q of X)if(!Y.shape?.[Q]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${Q}": expected a Zod schema`);let J=c8(Y.shape);return{...Y,keys:X,keySet:new Set(X),numKeys:X.length,optionalKeys:new Set(J)}}function sQ(Y,X,J,Q,$,G){let W=[],K=$.keySet,H=$.catchall._zod,U=H.def.type;for(let N of Object.keys(X)){if(K.has(N))continue;if(U==="never"){W.push(N);continue}let O=H.run({value:X[N],issues:[]},Q);if(O instanceof Promise)Y.push(O.then((B)=>bY(B,J,N,X)));else bY(O,J,N,X)}if(W.length)J.issues.push({code:"unrecognized_keys",keys:W,input:X,inst:G});if(!Y.length)return J;return Promise.all(Y).then(()=>{return J})}var e2=q("$ZodObject",(Y,X)=>{i.init(Y,X);let J=_1(()=>rQ(X));p(Y._zod,"propValues",()=>{let W=X.shape,K={};for(let H in W){let U=W[H]._zod;if(U.values){K[H]??(K[H]=new Set);for(let N of U.values)K[H].add(N)}}return K});let Q=V1,$=X.catchall,G;Y._zod.parse=(W,K)=>{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 U=[],N=G.shape;for(let O of G.keys){let L=N[O]._zod.run({value:H[O],issues:[]},K);if(L instanceof Promise)U.push(L.then((Z)=>bY(Z,W,O,H)));else bY(L,W,O,H)}if(!$)return U.length?Promise.all(U).then(()=>W):W;return sQ(U,H,W,K,J.value,Y)}}),aQ=q("$ZodObjectJIT",(Y,X)=>{e2.init(Y,X);let J=Y._zod.parse,Q=_1(()=>rQ(X)),$=(B)=>{let L=new o8(["shape","payload","ctx"]),Z=Q.value,j=(x)=>{let S=RY(x);return`shape[${S}]._zod.run({ value: input[${S}], issues: [] }, ctx)`};L.write("const input = payload.value;");let w=Object.create(null),P=0;for(let x of Z.keys)w[x]=`key_${P++}`;L.write("const newResult = {};");for(let x of Z.keys){let S=w[x],d=RY(x);L.write(`const ${S} = ${j(x)};`),L.write(`
119
- if (${S}.issues.length) {
120
- payload.issues = payload.issues.concat(${S}.issues.map(iss => ({
118
+ `))}}var LQ={major:4,minor:1,patch:8};var n=q("$ZodType",(Y,X)=>{var J;Y??(Y={}),Y._zod.def=X,Y._zod.bag=Y._zod.bag||{},Y._zod.version=LQ;let Q=[...Y._zod.def.checks??[]];if(Y._zod.traits.has("$ZodCheck"))Q.unshift(Y);for(let $ of Q)for(let G of $._zod.onattach)G(Y);if(Q.length===0)(J=Y._zod).deferred??(J.deferred=[]),Y._zod.deferred?.push(()=>{Y._zod.run=Y._zod.parse});else{let $=(W,K,U)=>{let H=$1(W),N;for(let O of K){if(O._zod.def.when){if(!O._zod.def.when(W))continue}else if(H)continue;let B=W.issues.length,L=O._zod.check(W);if(L instanceof Promise&&U?.async===!1)throw new d0;if(N||L instanceof Promise)N=(N??Promise.resolve()).then(async()=>{if(await L,W.issues.length===B)return;if(!H)H=$1(W,B)});else{if(W.issues.length===B)continue;if(!H)H=$1(W,B)}}if(N)return N.then(()=>{return W});return W},G=(W,K,U)=>{if($1(W))return W.aborted=!0,W;let H=$(K,Q,U);if(H instanceof Promise){if(U.async===!1)throw new d0;return H.then((N)=>Y._zod.parse(N,U))}return Y._zod.parse(H,U)};Y._zod.run=(W,K)=>{if(K.skipChecks)return Y._zod.parse(W,K);if(K.direction==="backward"){let H=Y._zod.parse({value:W.value,issues:[]},{...K,skipChecks:!0});if(H instanceof Promise)return H.then((N)=>{return G(N,W,K)});return G(H,W,K)}let U=Y._zod.parse(W,K);if(U instanceof Promise){if(K.async===!1)throw new d0;return U.then((H)=>$(H,Q,K))}return $(U,Q,K)}}Y["~standard"]={validate:($)=>{try{let G=N6(Y,$);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return V6(Y,$).then((W)=>W.success?{value:W.data}:{issues:W.error?.issues})}},vendor:"zod",version:1}}),xY=q("$ZodString",(Y,X)=>{n.init(Y,X),Y._zod.pattern=[...Y?._zod.bag?.patterns??[]].pop()??l6(Y._zod.bag),Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=String(J.value)}catch($){}if(typeof J.value==="string")return J;return J.issues.push({expected:"string",code:"invalid_type",input:J.value,inst:Y}),J}}),r=q("$ZodStringFormat",(Y,X)=>{s1.init(Y,X),xY.init(Y,X)}),DQ=q("$ZodGUID",(Y,X)=>{X.pattern??(X.pattern=_6),r.init(Y,X)}),PQ=q("$ZodUUID",(Y,X)=>{if(X.version){let Q={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[X.version];if(Q===void 0)throw Error(`Invalid UUID version: "${X.version}"`);X.pattern??(X.pattern=l8(Q))}else X.pattern??(X.pattern=l8());r.init(Y,X)}),wQ=q("$ZodEmail",(Y,X)=>{X.pattern??(X.pattern=I6),r.init(Y,X)}),EQ=q("$ZodURL",(Y,X)=>{r.init(Y,X),Y._zod.check=(J)=>{try{let Q=J.value.trim(),$=new URL(Q);if(X.hostname){if(X.hostname.lastIndex=0,!X.hostname.test($.hostname))J.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:g6.source,input:J.value,inst:Y,continue:!X.abort})}if(X.protocol){if(X.protocol.lastIndex=0,!X.protocol.test($.protocol.endsWith(":")?$.protocol.slice(0,-1):$.protocol))J.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:X.protocol.source,input:J.value,inst:Y,continue:!X.abort})}if(X.normalize)J.value=$.href;else J.value=Q;return}catch(Q){J.issues.push({code:"invalid_format",format:"url",input:J.value,inst:Y,continue:!X.abort})}}}),MQ=q("$ZodEmoji",(Y,X)=>{X.pattern??(X.pattern=S6()),r.init(Y,X)}),AQ=q("$ZodNanoID",(Y,X)=>{X.pattern??(X.pattern=T6),r.init(Y,X)}),RQ=q("$ZodCUID",(Y,X)=>{X.pattern??(X.pattern=w6),r.init(Y,X)}),TQ=q("$ZodCUID2",(Y,X)=>{X.pattern??(X.pattern=E6),r.init(Y,X)}),CQ=q("$ZodULID",(Y,X)=>{X.pattern??(X.pattern=M6),r.init(Y,X)}),_Q=q("$ZodXID",(Y,X)=>{X.pattern??(X.pattern=A6),r.init(Y,X)}),IQ=q("$ZodKSUID",(Y,X)=>{X.pattern??(X.pattern=R6),r.init(Y,X)}),SQ=q("$ZodISODateTime",(Y,X)=>{X.pattern??(X.pattern=p6(X)),r.init(Y,X)}),kQ=q("$ZodISODate",(Y,X)=>{X.pattern??(X.pattern=m6),r.init(Y,X)}),bQ=q("$ZodISOTime",(Y,X)=>{X.pattern??(X.pattern=u6(X)),r.init(Y,X)}),xQ=q("$ZodISODuration",(Y,X)=>{X.pattern??(X.pattern=C6),r.init(Y,X)}),vQ=q("$ZodIPv4",(Y,X)=>{X.pattern??(X.pattern=k6),r.init(Y,X),Y._zod.onattach.push((J)=>{let Q=J._zod.bag;Q.format="ipv4"})}),hQ=q("$ZodIPv6",(Y,X)=>{X.pattern??(X.pattern=b6),r.init(Y,X),Y._zod.onattach.push((J)=>{let Q=J._zod.bag;Q.format="ipv6"}),Y._zod.check=(J)=>{try{new URL(`http://[${J.value}]`)}catch{J.issues.push({code:"invalid_format",format:"ipv6",input:J.value,inst:Y,continue:!X.abort})}}}),gQ=q("$ZodCIDRv4",(Y,X)=>{X.pattern??(X.pattern=x6),r.init(Y,X)}),yQ=q("$ZodCIDRv6",(Y,X)=>{X.pattern??(X.pattern=v6),r.init(Y,X),Y._zod.check=(J)=>{let Q=J.value.split("/");try{if(Q.length!==2)throw Error();let[$,G]=Q;if(!G)throw Error();let W=Number(G);if(`${W}`!==G)throw Error();if(W<0||W>128)throw Error();new URL(`http://[${$}]`)}catch{J.issues.push({code:"invalid_format",format:"cidrv6",input:J.value,inst:Y,continue:!X.abort})}}});function fQ(Y){if(Y==="")return!0;if(Y.length%4!==0)return!1;try{return atob(Y),!0}catch{return!1}}var mQ=q("$ZodBase64",(Y,X)=>{X.pattern??(X.pattern=h6),r.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64"}),Y._zod.check=(J)=>{if(fQ(J.value))return;J.issues.push({code:"invalid_format",format:"base64",input:J.value,inst:Y,continue:!X.abort})}});function Xz(Y){if(!d8.test(Y))return!1;let X=Y.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),J=X.padEnd(Math.ceil(X.length/4)*4,"=");return fQ(J)}var cQ=q("$ZodBase64URL",(Y,X)=>{X.pattern??(X.pattern=d8),r.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64url"}),Y._zod.check=(J)=>{if(Xz(J.value))return;J.issues.push({code:"invalid_format",format:"base64url",input:J.value,inst:Y,continue:!X.abort})}}),uQ=q("$ZodE164",(Y,X)=>{X.pattern??(X.pattern=y6),r.init(Y,X)});function Jz(Y,X=null){try{let J=Y.split(".");if(J.length!==3)return!1;let[Q]=J;if(!Q)return!1;let $=JSON.parse(atob(Q));if("typ"in $&&$?.typ!=="JWT")return!1;if(!$.alg)return!1;if(X&&(!("alg"in $)||$.alg!==X))return!1;return!0}catch{return!1}}var pQ=q("$ZodJWT",(Y,X)=>{r.init(Y,X),Y._zod.check=(J)=>{if(Jz(J.value,X.alg))return;J.issues.push({code:"invalid_format",format:"jwt",input:J.value,inst:Y,continue:!X.abort})}});var s8=q("$ZodNumber",(Y,X)=>{n.init(Y,X),Y._zod.pattern=Y._zod.bag.pattern??i6,Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=Number(J.value)}catch(W){}let $=J.value;if(typeof $==="number"&&!Number.isNaN($)&&Number.isFinite($))return J;let G=typeof $==="number"?Number.isNaN($)?"NaN":!Number.isFinite($)?"Infinity":void 0:void 0;return J.issues.push({expected:"number",code:"invalid_type",input:$,inst:Y,...G?{received:G}:{}}),J}}),lQ=q("$ZodNumber",(Y,X)=>{e6.init(Y,X),s8.init(Y,X)}),dQ=q("$ZodBoolean",(Y,X)=>{n.init(Y,X),Y._zod.pattern=n6,Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=Boolean(J.value)}catch(G){}let $=J.value;if(typeof $==="boolean")return J;return J.issues.push({expected:"boolean",code:"invalid_type",input:$,inst:Y}),J}});var iQ=q("$ZodNull",(Y,X)=>{n.init(Y,X),Y._zod.pattern=o6,Y._zod.values=new Set([null]),Y._zod.parse=(J,Q)=>{let $=J.value;if($===null)return J;return J.issues.push({expected:"null",code:"invalid_type",input:$,inst:Y}),J}});var nQ=q("$ZodUnknown",(Y,X)=>{n.init(Y,X),Y._zod.parse=(J)=>J}),oQ=q("$ZodNever",(Y,X)=>{n.init(Y,X),Y._zod.parse=(J,Q)=>{return J.issues.push({expected:"never",code:"invalid_type",input:J.value,inst:Y}),J}});function NQ(Y,X,J){if(Y.issues.length)X.issues.push(...n0(J,Y.issues));X.value[J]=Y.value}var rQ=q("$ZodArray",(Y,X)=>{n.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value;if(!Array.isArray($))return J.issues.push({expected:"array",code:"invalid_type",input:$,inst:Y}),J;J.value=Array($.length);let G=[];for(let W=0;W<$.length;W++){let K=$[W],U=X.element._zod.run({value:K,issues:[]},Q);if(U instanceof Promise)G.push(U.then((H)=>NQ(H,J,W)));else NQ(U,J,W)}if(G.length)return Promise.all(G).then(()=>J);return J}});function bY(Y,X,J,Q){if(Y.issues.length)X.issues.push(...n0(J,Y.issues));if(Y.value===void 0){if(J in Q)X.value[J]=void 0}else X.value[J]=Y.value}function sQ(Y){let X=Object.keys(Y.shape);for(let Q of X)if(!Y.shape?.[Q]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${Q}": expected a Zod schema`);let J=c8(Y.shape);return{...Y,keys:X,keySet:new Set(X),numKeys:X.length,optionalKeys:new Set(J)}}function aQ(Y,X,J,Q,$,G){let W=[],K=$.keySet,U=$.catchall._zod,H=U.def.type;for(let N of Object.keys(X)){if(K.has(N))continue;if(H==="never"){W.push(N);continue}let O=U.run({value:X[N],issues:[]},Q);if(O instanceof Promise)Y.push(O.then((B)=>bY(B,J,N,X)));else bY(O,J,N,X)}if(W.length)J.issues.push({code:"unrecognized_keys",keys:W,input:X,inst:G});if(!Y.length)return J;return Promise.all(Y).then(()=>{return J})}var Qz=q("$ZodObject",(Y,X)=>{n.init(Y,X);let J=I1(()=>sQ(X));l(Y._zod,"propValues",()=>{let W=X.shape,K={};for(let U in W){let H=W[U]._zod;if(H.values){K[U]??(K[U]=new Set);for(let N of H.values)K[U].add(N)}}return K});let Q=B1,$=X.catchall,G;Y._zod.parse=(W,K)=>{G??(G=J.value);let U=W.value;if(!Q(U))return W.issues.push({expected:"object",code:"invalid_type",input:U,inst:Y}),W;W.value={};let H=[],N=G.shape;for(let O of G.keys){let L=N[O]._zod.run({value:U[O],issues:[]},K);if(L instanceof Promise)H.push(L.then((Z)=>bY(Z,W,O,U)));else bY(L,W,O,U)}if(!$)return H.length?Promise.all(H).then(()=>W):W;return aQ(H,U,W,K,J.value,Y)}}),tQ=q("$ZodObjectJIT",(Y,X)=>{Qz.init(Y,X);let J=Y._zod.parse,Q=I1(()=>sQ(X)),$=(B)=>{let L=new o8(["shape","payload","ctx"]),Z=Q.value,j=(b)=>{let _=RY(b);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};L.write("const input = payload.value;");let P=Object.create(null),S=0;for(let b of Z.keys)P[b]=`key_${S++}`;L.write("const newResult = {};");for(let b of Z.keys){let _=P[b],u=RY(b);L.write(`const ${_} = ${j(b)};`),L.write(`
119
+ if (${_}.issues.length) {
120
+ payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
121
121
  ...iss,
122
- path: iss.path ? [${d}, ...iss.path] : [${d}]
122
+ path: iss.path ? [${u}, ...iss.path] : [${u}]
123
123
  })));
124
124
  }
125
125
 
126
126
 
127
- if (${S}.value === undefined) {
128
- if (${d} in input) {
129
- newResult[${d}] = undefined;
127
+ if (${_}.value === undefined) {
128
+ if (${u} in input) {
129
+ newResult[${u}] = undefined;
130
130
  }
131
131
  } else {
132
- newResult[${d}] = ${S}.value;
132
+ newResult[${u}] = ${_}.value;
133
133
  }
134
134
 
135
- `)}L.write("payload.value = newResult;"),L.write("return payload;");let k=L.compile();return(x,S)=>k(B,x,S)},G,W=V1,K=!AY.jitless,U=K&&f8.value,N=X.catchall,O;Y._zod.parse=(B,L)=>{O??(O=Q.value);let Z=B.value;if(!W(Z))return B.issues.push({expected:"object",code:"invalid_type",input:Z,inst:Y}),B;if(K&&U&&L?.async===!1&&L.jitless!==!0){if(!G)G=$(X.shape);if(B=G(B,L),!N)return B;return sQ([],Z,B,L,O,Y)}return J(B,L)}});function NQ(Y,X,J,Q){for(let G of Y)if(G.issues.length===0)return X.value=G.value,X;let $=Y.filter((G)=>!X1(G));if($.length===1)return X.value=$[0].value,$[0];return X.issues.push({code:"invalid_union",input:X.value,inst:J,errors:Y.map((G)=>G.issues.map((W)=>_0(W,Q,h0())))}),X}var a8=q("$ZodUnion",(Y,X)=>{i.init(Y,X),p(Y._zod,"optin",()=>X.options.some(($)=>$._zod.optin==="optional")?"optional":void 0),p(Y._zod,"optout",()=>X.options.some(($)=>$._zod.optout==="optional")?"optional":void 0),p(Y._zod,"values",()=>{if(X.options.every(($)=>$._zod.values))return new Set(X.options.flatMap(($)=>Array.from($._zod.values)));return}),p(Y._zod,"pattern",()=>{if(X.options.every(($)=>$._zod.pattern)){let $=X.options.map((G)=>G._zod.pattern);return new RegExp(`^(${$.map((G)=>d1(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 H of X.options){let U=H._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 NQ(K,$,Y,G);return Promise.all(K).then((H)=>{return NQ(H,$,Y,G)})}}),tQ=q("$ZodDiscriminatedUnion",(Y,X)=>{a8.init(Y,X);let J=Y._zod.parse;p(Y._zod,"propValues",()=>{let $={};for(let G of X.options){let W=G._zod.propValues;if(!W||Object.keys(W).length===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf(G)}"`);for(let[K,H]of Object.entries(W)){if(!$[K])$[K]=new Set;for(let U of H)$[K].add(U)}}return $});let Q=_1(()=>{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 H of K){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(!V1(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}),$}}),eQ=q("$ZodIntersection",(Y,X)=>{i.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,U])=>{return VQ(J,H,U)});return VQ(J,G,W)}});function r8(Y,X){if(Y===X)return{valid:!0,data:Y};if(Y instanceof Date&&X instanceof Date&&+Y===+X)return{valid:!0,data:Y};if(Y1(Y)&&Y1(X)){let J=Object.keys(X),Q=Object.keys(Y).filter((G)=>J.indexOf(G)!==-1),$={...Y,...X};for(let G of Q){let W=r8(Y[G],X[G]);if(!W.valid)return{valid:!1,mergeErrorPath:[G,...W.mergeErrorPath]};$[G]=W.data}return{valid:!0,data:$}}if(Array.isArray(Y)&&Array.isArray(X)){if(Y.length!==X.length)return{valid:!1,mergeErrorPath:[]};let J=[];for(let Q=0;Q<Y.length;Q++){let $=Y[Q],G=X[Q],W=r8($,G);if(!W.valid)return{valid:!1,mergeErrorPath:[Q,...W.mergeErrorPath]};J.push(W.data)}return{valid:!0,data:J}}return{valid:!1,mergeErrorPath:[]}}function VQ(Y,X,J){if(X.issues.length)Y.issues.push(...X.issues);if(J.issues.length)Y.issues.push(...J.issues);if(X1(Y))return Y;let Q=r8(X.value,J.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return Y.value=Q.data,Y}var Y7=q("$ZodRecord",(Y,X)=>{i.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value;if(!Y1($))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 U=X.valueType._zod.run({value:$[H],issues:[]},Q);if(U instanceof Promise)G.push(U.then((N)=>{if(N.issues.length)J.issues.push(...d0(H,N.issues));J.value[H]=N.value}));else{if(U.issues.length)J.issues.push(...d0(H,U.issues));J.value[H]=U.value}}let K;for(let H in $)if(!W.has(H))K=K??[],K.push(H);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)=>_0(U,Q,h0())),input:W,path:[W],inst:Y}),J.value[K.value]=K.value;continue}let H=X.valueType._zod.run({value:$[W],issues:[]},Q);if(H instanceof Promise)G.push(H.then((U)=>{if(U.issues.length)J.issues.push(...d0(W,U.issues));J.value[K.value]=U.value}));else{if(H.issues.length)J.issues.push(...d0(W,H.issues));J.value[K.value]=H.value}}}if(G.length)return Promise.all(G).then(()=>J);return J}});var X7=q("$ZodEnum",(Y,X)=>{i.init(Y,X);let J=p1(X.entries),Q=new Set(J);Y._zod.values=Q,Y._zod.pattern=new RegExp(`^(${J.filter(($)=>m8.has(typeof $)).map(($)=>typeof $==="string"?l0($):$.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}),$}}),J7=q("$ZodLiteral",(Y,X)=>{if(i.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"?l0(J):J?l0(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 Q7=q("$ZodTransform",(Y,X)=>{i.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new c1(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 p0;return J.value=$,J}});function BQ(Y,X){if(Y.issues.length&&X===void 0)return{issues:[],value:void 0};return Y}var $7=q("$ZodOptional",(Y,X)=>{i.init(Y,X),Y._zod.optin="optional",Y._zod.optout="optional",p(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,void 0]):void 0}),p(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${d1(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)=>BQ(G,J.value));return BQ($,J.value)}if(J.value===void 0)return J;return X.innerType._zod.run(J,Q)}}),G7=q("$ZodNullable",(Y,X)=>{i.init(Y,X),p(Y._zod,"optin",()=>X.innerType._zod.optin),p(Y._zod,"optout",()=>X.innerType._zod.optout),p(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${d1(J.source)}|null)$`):void 0}),p(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,null]):void 0}),Y._zod.parse=(J,Q)=>{if(J.value===null)return J;return X.innerType._zod.run(J,Q)}}),W7=q("$ZodDefault",(Y,X)=>{i.init(Y,X),Y._zod.optin="optional",p(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);if(J.value===void 0)return J.value=X.defaultValue,J;let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>ZQ(G,X));return ZQ($,X)}});function ZQ(Y,X){if(Y.value===void 0)Y.value=X.defaultValue;return Y}var z7=q("$ZodPrefault",(Y,X)=>{i.init(Y,X),Y._zod.optin="optional",p(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);if(J.value===void 0)J.value=X.defaultValue;return X.innerType._zod.run(J,Q)}}),K7=q("$ZodNonOptional",(Y,X)=>{i.init(Y,X),p(Y._zod,"values",()=>{let J=X.innerType._zod.values;return J?new Set([...J].filter((Q)=>Q!==void 0)):void 0}),Y._zod.parse=(J,Q)=>{let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>OQ(G,Y));return OQ($,Y)}});function OQ(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 U7=q("$ZodCatch",(Y,X)=>{i.init(Y,X),p(Y._zod,"optin",()=>X.innerType._zod.optin),p(Y._zod,"optout",()=>X.innerType._zod.optout),p(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>{if(J.value=G.value,G.issues.length)J.value=X.catchValue({...J,error:{issues:G.issues.map((W)=>_0(W,Q,h0()))},input:J.value}),J.issues=[];return J});if(J.value=$.value,$.issues.length)J.value=X.catchValue({...J,error:{issues:$.issues.map((G)=>_0(G,Q,h0()))},input:J.value}),J.issues=[];return J}});var H7=q("$ZodPipe",(Y,X)=>{i.init(Y,X),p(Y._zod,"values",()=>X.in._zod.values),p(Y._zod,"optin",()=>X.in._zod.optin),p(Y._zod,"optout",()=>X.out._zod.optout),p(Y._zod,"propValues",()=>X.in._zod.propValues),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward"){let G=X.out._zod.run(J,Q);if(G instanceof Promise)return G.then((W)=>kY(W,X.in,Q));return kY(G,X.in,Q)}let $=X.in._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>kY(G,X.out,Q));return kY($,X.out,Q)}});function kY(Y,X,J){if(Y.issues.length)return Y.aborted=!0,Y;return X._zod.run({value:Y.value,issues:Y.issues},J)}var L7=q("$ZodReadonly",(Y,X)=>{i.init(Y,X),p(Y._zod,"propValues",()=>X.innerType._zod.propValues),p(Y._zod,"values",()=>X.innerType._zod.values),p(Y._zod,"optin",()=>X.innerType._zod.optin),p(Y._zod,"optout",()=>X.innerType._zod.optout),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then(FQ);return FQ($)}});function FQ(Y){return Y.value=Object.freeze(Y.value),Y}var N7=q("$ZodLazy",(Y,X)=>{i.init(Y,X),p(Y._zod,"innerType",()=>X.getter()),p(Y._zod,"pattern",()=>Y._zod.innerType._zod.pattern),p(Y._zod,"propValues",()=>Y._zod.innerType._zod.propValues),p(Y._zod,"optin",()=>Y._zod.innerType._zod.optin??void 0),p(Y._zod,"optout",()=>Y._zod.innerType._zod.optout??void 0),Y._zod.parse=(J,Q)=>{return Y._zod.innerType._zod.run(J,Q)}}),V7=q("$ZodCustom",(Y,X)=>{N0.init(Y,X),i.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)=>qQ(G,J,Q,Y));qQ($,J,Q,Y);return}});function qQ(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 kB=Symbol("ZodOutput"),bB=Symbol("ZodInput");class vY{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Y,...X){let J=X[0];if(this._map.set(Y,J),J&&typeof J==="object"&&"id"in J){if(this._idmap.has(J.id))throw Error(`ID ${J.id} already exists in the registry`);this._idmap.set(J.id,Y)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Y){let X=this._map.get(Y);if(X&&typeof X==="object"&&"id"in X)this._idmap.delete(X.id);return this._map.delete(Y),this}get(Y){let X=Y._zod.parent;if(X){let J={...this.get(X)??{}};delete J.id;let Q={...J,...this._map.get(Y)};return Object.keys(Q).length?Q:void 0}return this._map.get(Y)}has(Y){return this._map.has(Y)}}function Yz(){return new vY}var B1=Yz();function B7(Y,X){return new Y({type:"string",...v(X)})}function Z7(Y,X){return new Y({type:"string",format:"email",check:"string_format",abort:!1,...v(X)})}function t8(Y,X){return new Y({type:"string",format:"guid",check:"string_format",abort:!1,...v(X)})}function O7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...v(X)})}function F7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...v(X)})}function q7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...v(X)})}function j7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...v(X)})}function D7(Y,X){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...v(X)})}function P7(Y,X){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...v(X)})}function w7(Y,X){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...v(X)})}function E7(Y,X){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...v(X)})}function M7(Y,X){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...v(X)})}function A7(Y,X){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...v(X)})}function R7(Y,X){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...v(X)})}function T7(Y,X){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...v(X)})}function C7(Y,X){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...v(X)})}function _7(Y,X){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...v(X)})}function I7(Y,X){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...v(X)})}function S7(Y,X){return new Y({type:"string",format:"cidrv6",check:"string_format",abort:!1,...v(X)})}function k7(Y,X){return new Y({type:"string",format:"base64",check:"string_format",abort:!1,...v(X)})}function b7(Y,X){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...v(X)})}function x7(Y,X){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...v(X)})}function v7(Y,X){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...v(X)})}function h7(Y,X){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...v(X)})}function g7(Y,X){return new Y({type:"string",format:"date",check:"string_format",...v(X)})}function y7(Y,X){return new Y({type:"string",format:"time",check:"string_format",precision:null,...v(X)})}function f7(Y,X){return new Y({type:"string",format:"duration",check:"string_format",...v(X)})}function m7(Y,X){return new Y({type:"number",checks:[],...v(X)})}function c7(Y,X){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...v(X)})}function u7(Y,X){return new Y({type:"boolean",...v(X)})}function p7(Y,X){return new Y({type:"null",...v(X)})}function l7(Y){return new Y({type:"unknown"})}function d7(Y,X){return new Y({type:"never",...v(X)})}function hY(Y,X){return new i8({check:"less_than",...v(X),value:Y,inclusive:!1})}function s1(Y,X){return new i8({check:"less_than",...v(X),value:Y,inclusive:!0})}function gY(Y,X){return new n8({check:"greater_than",...v(X),value:Y,inclusive:!1})}function a1(Y,X){return new n8({check:"greater_than",...v(X),value:Y,inclusive:!0})}function yY(Y,X){return new a6({check:"multiple_of",...v(X),value:Y})}function fY(Y,X){return new e6({check:"max_length",...v(X),maximum:Y})}function S1(Y,X){return new YQ({check:"min_length",...v(X),minimum:Y})}function mY(Y,X){return new XQ({check:"length_equals",...v(X),length:Y})}function e8(Y,X){return new JQ({check:"string_format",format:"regex",...v(X),pattern:Y})}function Y9(Y){return new QQ({check:"string_format",format:"lowercase",...v(Y)})}function X9(Y){return new $Q({check:"string_format",format:"uppercase",...v(Y)})}function J9(Y,X){return new GQ({check:"string_format",format:"includes",...v(X),includes:Y})}function Q9(Y,X){return new WQ({check:"string_format",format:"starts_with",...v(X),prefix:Y})}function $9(Y,X){return new zQ({check:"string_format",format:"ends_with",...v(X),suffix:Y})}function Z1(Y){return new KQ({check:"overwrite",tx:Y})}function G9(Y){return Z1((X)=>X.normalize(Y))}function W9(){return Z1((Y)=>Y.trim())}function z9(){return Z1((Y)=>Y.toLowerCase())}function K9(){return Z1((Y)=>Y.toUpperCase())}function i7(Y,X,J){return new Y({type:"array",element:X,...v(J)})}function n7(Y,X,J){let Q=v(J);return Q.abort??(Q.abort=!0),new Y({type:"custom",check:"custom",fn:X,...Q})}function o7(Y,X,J){return new Y({type:"custom",check:"custom",fn:X,...v(J)})}function r7(Y){let X=Xz((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 Xz(Y,X){let J=new N0({check:"custom",...v(X)});return J._zod.check=Y,J}class U9{constructor(Y){this.counter=0,this.metadataRegistry=Y?.metadata??B1,this.target=Y?.target??"draft-2020-12",this.unrepresentable=Y?.unrepresentable??"throw",this.override=Y?.override??(()=>{}),this.io=Y?.io??"output",this.seen=new Map}process(Y,X={path:[],schemaPath:[]}){var J;let Q=Y._zod.def,$={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},G=this.seen.get(Y);if(G){if(G.count++,X.schemaPath.includes(Y))G.cycle=X.path;return G.schema}let W={schema:{},count:1,cycle:void 0,path:X.path};this.seen.set(Y,W);let K=Y._zod.toJSONSchema?.();if(K)W.schema=K;else{let N={...X,schemaPath:[...X.schemaPath,Y],path:X.path},O=Y._zod.parent;if(O)W.ref=O,this.process(O,N),this.seen.get(O).isParent=!0;else{let B=W.schema;switch(Q.type){case"string":{let L=B;L.type="string";let{minimum:Z,maximum:j,format:w,patterns:P,contentEncoding:k}=Y._zod.bag;if(typeof Z==="number")L.minLength=Z;if(typeof j==="number")L.maxLength=j;if(w){if(L.format=$[w]??w,L.format==="")delete L.format}if(k)L.contentEncoding=k;if(P&&P.size>0){let x=[...P];if(x.length===1)L.pattern=x[0].source;else if(x.length>1)W.schema.allOf=[...x.map((S)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:S.source}))]}break}case"number":{let L=B,{minimum:Z,maximum:j,format:w,multipleOf:P,exclusiveMaximum:k,exclusiveMinimum:x}=Y._zod.bag;if(typeof w==="string"&&w.includes("int"))L.type="integer";else L.type="number";if(typeof x==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")L.minimum=x,L.exclusiveMinimum=!0;else L.exclusiveMinimum=x;if(typeof Z==="number"){if(L.minimum=Z,typeof x==="number"&&this.target!=="draft-4")if(x>=Z)delete L.minimum;else delete L.exclusiveMinimum}if(typeof k==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")L.maximum=k,L.exclusiveMaximum=!0;else L.exclusiveMaximum=k;if(typeof j==="number"){if(L.maximum=j,typeof k==="number"&&this.target!=="draft-4")if(k<=j)delete L.maximum;else delete L.exclusiveMaximum}if(typeof P==="number")L.multipleOf=P;break}case"boolean":{let L=B;L.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema");break}case"null":{if(this.target==="openapi-3.0")B.type="string",B.nullable=!0,B.enum=[null];else B.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema");break}case"never":{B.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let L=B,{minimum:Z,maximum:j}=Y._zod.bag;if(typeof Z==="number")L.minItems=Z;if(typeof j==="number")L.maxItems=j;L.type="array",L.items=this.process(Q.element,{...N,path:[...N.path,"items"]});break}case"object":{let L=B;L.type="object",L.properties={};let Z=Q.shape;for(let P in Z)L.properties[P]=this.process(Z[P],{...N,path:[...N.path,"properties",P]});let j=new Set(Object.keys(Z)),w=new Set([...j].filter((P)=>{let k=Q.shape[P]._zod;if(this.io==="input")return k.optin===void 0;else return k.optout===void 0}));if(w.size>0)L.required=Array.from(w);if(Q.catchall?._zod.def.type==="never")L.additionalProperties=!1;else if(!Q.catchall){if(this.io==="output")L.additionalProperties=!1}else if(Q.catchall)L.additionalProperties=this.process(Q.catchall,{...N,path:[...N.path,"additionalProperties"]});break}case"union":{let L=B,Z=Q.options.map((j,w)=>this.process(j,{...N,path:[...N.path,"anyOf",w]}));L.anyOf=Z;break}case"intersection":{let L=B,Z=this.process(Q.left,{...N,path:[...N.path,"allOf",0]}),j=this.process(Q.right,{...N,path:[...N.path,"allOf",1]}),w=(k)=>("allOf"in k)&&Object.keys(k).length===1,P=[...w(Z)?Z.allOf:[Z],...w(j)?j.allOf:[j]];L.allOf=P;break}case"tuple":{let L=B;L.type="array";let Z=this.target==="draft-2020-12"?"prefixItems":"items",j=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",w=Q.items.map((S,d)=>this.process(S,{...N,path:[...N.path,Z,d]})),P=Q.rest?this.process(Q.rest,{...N,path:[...N.path,j,...this.target==="openapi-3.0"?[Q.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(L.prefixItems=w,P)L.items=P}else if(this.target==="openapi-3.0"){if(L.items={anyOf:w},P)L.items.anyOf.push(P);if(L.minItems=w.length,!P)L.maxItems=w.length}else if(L.items=w,P)L.additionalItems=P;let{minimum:k,maximum:x}=Y._zod.bag;if(typeof k==="number")L.minItems=k;if(typeof x==="number")L.maxItems=x;break}case"record":{let L=B;if(L.type="object",this.target==="draft-7"||this.target==="draft-2020-12")L.propertyNames=this.process(Q.keyType,{...N,path:[...N.path,"propertyNames"]});L.additionalProperties=this.process(Q.valueType,{...N,path:[...N.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let L=B,Z=p1(Q.entries);if(Z.every((j)=>typeof j==="number"))L.type="number";if(Z.every((j)=>typeof j==="string"))L.type="string";L.enum=Z;break}case"literal":{let L=B,Z=[];for(let j of Q.values)if(j===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof j==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else Z.push(Number(j));else Z.push(j);if(Z.length===0);else if(Z.length===1){let j=Z[0];if(L.type=j===null?"null":typeof j,this.target==="draft-4"||this.target==="openapi-3.0")L.enum=[j];else L.const=j}else{if(Z.every((j)=>typeof j==="number"))L.type="number";if(Z.every((j)=>typeof j==="string"))L.type="string";if(Z.every((j)=>typeof j==="boolean"))L.type="string";if(Z.every((j)=>j===null))L.type="null";L.enum=Z}break}case"file":{let L=B,Z={type:"string",format:"binary",contentEncoding:"binary"},{minimum:j,maximum:w,mime:P}=Y._zod.bag;if(j!==void 0)Z.minLength=j;if(w!==void 0)Z.maxLength=w;if(P)if(P.length===1)Z.contentMediaType=P[0],Object.assign(L,Z);else L.anyOf=P.map((k)=>{return{...Z,contentMediaType:k}});else Object.assign(L,Z);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let L=this.process(Q.innerType,N);if(this.target==="openapi-3.0")W.ref=Q.innerType,B.nullable=!0;else B.anyOf=[L,{type:"null"}];break}case"nonoptional":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"success":{let L=B;L.type="boolean";break}case"default":{this.process(Q.innerType,N),W.ref=Q.innerType,B.default=JSON.parse(JSON.stringify(Q.defaultValue));break}case"prefault":{if(this.process(Q.innerType,N),W.ref=Q.innerType,this.io==="input")B._prefault=JSON.parse(JSON.stringify(Q.defaultValue));break}case"catch":{this.process(Q.innerType,N),W.ref=Q.innerType;let L;try{L=Q.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}B.default=L;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let L=B,Z=Y._zod.pattern;if(!Z)throw Error("Pattern not found in template literal");L.type="string",L.pattern=Z.source;break}case"pipe":{let L=this.io==="input"?Q.in._zod.def.type==="transform"?Q.out:Q.in:Q.out;this.process(L,N),W.ref=L;break}case"readonly":{this.process(Q.innerType,N),W.ref=Q.innerType,B.readOnly=!0;break}case"promise":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"optional":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"lazy":{let L=Y._zod.innerType;this.process(L,N),W.ref=L;break}case"custom":{if(this.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema");break}case"function":{if(this.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema");break}default:}}}let H=this.metadataRegistry.get(Y);if(H)Object.assign(W.schema,H);if(this.io==="input"&&W0(Y))delete W.schema.examples,delete W.schema.default;if(this.io==="input"&&W.schema._prefault)(J=W.schema).default??(J.default=W.schema._prefault);return delete W.schema._prefault,this.seen.get(Y).schema}emit(Y,X){let J={cycles:X?.cycles??"ref",reused:X?.reused??"inline",external:X?.external??void 0},Q=this.seen.get(Y);if(!Q)throw Error("Unprocessed schema. This is a bug in Zod.");let $=(U)=>{let N=this.target==="draft-2020-12"?"$defs":"definitions";if(J.external){let Z=J.external.registry.get(U[0])?.id,j=J.external.uri??((P)=>P);if(Z)return{ref:j(Z)};let w=U[1].defId??U[1].schema.id??`schema${this.counter++}`;return U[1].defId=w,{defId:w,ref:`${j("__shared")}#/${N}/${w}`}}if(U[1]===Q)return{ref:"#"};let B=`${"#"}/${N}/`,L=U[1].schema.id??`__schema${this.counter++}`;return{defId:L,ref:B+L}},G=(U)=>{if(U[1].schema.$ref)return;let N=U[1],{ref:O,defId:B}=$(U);if(N.def={...N.schema},B)N.defId=B;let L=N.schema;for(let Z in L)delete L[Z];L.$ref=O};if(J.cycles==="throw")for(let U of this.seen.entries()){let N=U[1];if(N.cycle)throw Error(`Cycle detected: #/${N.cycle?.join("/")}/<root>
135
+ `)}L.write("payload.value = newResult;"),L.write("return payload;");let E=L.compile();return(b,_)=>E(B,b,_)},G,W=B1,K=!AY.jitless,H=K&&f8.value,N=X.catchall,O;Y._zod.parse=(B,L)=>{O??(O=Q.value);let Z=B.value;if(!W(Z))return B.issues.push({expected:"object",code:"invalid_type",input:Z,inst:Y}),B;if(K&&H&&L?.async===!1&&L.jitless!==!0){if(!G)G=$(X.shape);if(B=G(B,L),!N)return B;return aQ([],Z,B,L,O,Y)}return J(B,L)}});function VQ(Y,X,J,Q){for(let G of Y)if(G.issues.length===0)return X.value=G.value,X;let $=Y.filter((G)=>!$1(G));if($.length===1)return X.value=$[0].value,$[0];return X.issues.push({code:"invalid_union",input:X.value,inst:J,errors:Y.map((G)=>G.issues.map((W)=>_0(W,Q,h0())))}),X}var a8=q("$ZodUnion",(Y,X)=>{n.init(Y,X),l(Y._zod,"optin",()=>X.options.some(($)=>$._zod.optin==="optional")?"optional":void 0),l(Y._zod,"optout",()=>X.options.some(($)=>$._zod.optout==="optional")?"optional":void 0),l(Y._zod,"values",()=>{if(X.options.every(($)=>$._zod.values))return new Set(X.options.flatMap(($)=>Array.from($._zod.values)));return}),l(Y._zod,"pattern",()=>{if(X.options.every(($)=>$._zod.pattern)){let $=X.options.map((G)=>G._zod.pattern);return new RegExp(`^(${$.map((G)=>i1(G.source)).join("|")})$`)}return});let J=X.options.length===1,Q=X.options[0]._zod.run;Y._zod.parse=($,G)=>{if(J)return Q($,G);let W=!1,K=[];for(let U of X.options){let H=U._zod.run({value:$.value,issues:[]},G);if(H instanceof Promise)K.push(H),W=!0;else{if(H.issues.length===0)return H;K.push(H)}}if(!W)return VQ(K,$,Y,G);return Promise.all(K).then((U)=>{return VQ(U,$,Y,G)})}}),eQ=q("$ZodDiscriminatedUnion",(Y,X)=>{a8.init(Y,X);let J=Y._zod.parse;l(Y._zod,"propValues",()=>{let $={};for(let G of X.options){let W=G._zod.propValues;if(!W||Object.keys(W).length===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf(G)}"`);for(let[K,U]of Object.entries(W)){if(!$[K])$[K]=new Set;for(let H of U)$[K].add(H)}}return $});let Q=I1(()=>{let $=X.options,G=new Map;for(let W of $){let K=W._zod.propValues?.[X.discriminator];if(!K||K.size===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf(W)}"`);for(let U of K){if(G.has(U))throw Error(`Duplicate discriminator value "${String(U)}"`);G.set(U,W)}}return G});Y._zod.parse=($,G)=>{let W=$.value;if(!B1(W))return $.issues.push({code:"invalid_type",expected:"object",input:W,inst:Y}),$;let K=Q.value.get(W?.[X.discriminator]);if(K)return K._zod.run($,G);if(X.unionFallback)return J($,G);return $.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:X.discriminator,input:W,path:[X.discriminator],inst:Y}),$}}),Y7=q("$ZodIntersection",(Y,X)=>{n.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value,G=X.left._zod.run({value:$,issues:[]},Q),W=X.right._zod.run({value:$,issues:[]},Q);if(G instanceof Promise||W instanceof Promise)return Promise.all([G,W]).then(([U,H])=>{return BQ(J,U,H)});return BQ(J,G,W)}});function r8(Y,X){if(Y===X)return{valid:!0,data:Y};if(Y instanceof Date&&X instanceof Date&&+Y===+X)return{valid:!0,data:Y};if(Q1(Y)&&Q1(X)){let J=Object.keys(X),Q=Object.keys(Y).filter((G)=>J.indexOf(G)!==-1),$={...Y,...X};for(let G of Q){let W=r8(Y[G],X[G]);if(!W.valid)return{valid:!1,mergeErrorPath:[G,...W.mergeErrorPath]};$[G]=W.data}return{valid:!0,data:$}}if(Array.isArray(Y)&&Array.isArray(X)){if(Y.length!==X.length)return{valid:!1,mergeErrorPath:[]};let J=[];for(let Q=0;Q<Y.length;Q++){let $=Y[Q],G=X[Q],W=r8($,G);if(!W.valid)return{valid:!1,mergeErrorPath:[Q,...W.mergeErrorPath]};J.push(W.data)}return{valid:!0,data:J}}return{valid:!1,mergeErrorPath:[]}}function BQ(Y,X,J){if(X.issues.length)Y.issues.push(...X.issues);if(J.issues.length)Y.issues.push(...J.issues);if($1(Y))return Y;let Q=r8(X.value,J.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return Y.value=Q.data,Y}var X7=q("$ZodRecord",(Y,X)=>{n.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value;if(!Q1($))return J.issues.push({expected:"record",code:"invalid_type",input:$,inst:Y}),J;let G=[];if(X.keyType._zod.values){let W=X.keyType._zod.values;J.value={};for(let U of W)if(typeof U==="string"||typeof U==="number"||typeof U==="symbol"){let H=X.valueType._zod.run({value:$[U],issues:[]},Q);if(H instanceof Promise)G.push(H.then((N)=>{if(N.issues.length)J.issues.push(...n0(U,N.issues));J.value[U]=N.value}));else{if(H.issues.length)J.issues.push(...n0(U,H.issues));J.value[U]=H.value}}let K;for(let U in $)if(!W.has(U))K=K??[],K.push(U);if(K&&K.length>0)J.issues.push({code:"unrecognized_keys",input:$,inst:Y,keys:K})}else{J.value={};for(let W of Reflect.ownKeys($)){if(W==="__proto__")continue;let K=X.keyType._zod.run({value:W,issues:[]},Q);if(K instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(K.issues.length){J.issues.push({code:"invalid_key",origin:"record",issues:K.issues.map((H)=>_0(H,Q,h0())),input:W,path:[W],inst:Y}),J.value[K.value]=K.value;continue}let U=X.valueType._zod.run({value:$[W],issues:[]},Q);if(U instanceof Promise)G.push(U.then((H)=>{if(H.issues.length)J.issues.push(...n0(W,H.issues));J.value[K.value]=H.value}));else{if(U.issues.length)J.issues.push(...n0(W,U.issues));J.value[K.value]=U.value}}}if(G.length)return Promise.all(G).then(()=>J);return J}});var J7=q("$ZodEnum",(Y,X)=>{n.init(Y,X);let J=l1(X.entries),Q=new Set(J);Y._zod.values=Q,Y._zod.pattern=new RegExp(`^(${J.filter(($)=>m8.has(typeof $)).map(($)=>typeof $==="string"?i0($):$.toString()).join("|")})$`),Y._zod.parse=($,G)=>{let W=$.value;if(Q.has(W))return $;return $.issues.push({code:"invalid_value",values:J,input:W,inst:Y}),$}}),Q7=q("$ZodLiteral",(Y,X)=>{if(n.init(Y,X),X.values.length===0)throw Error("Cannot create literal schema with no valid values");Y._zod.values=new Set(X.values),Y._zod.pattern=new RegExp(`^(${X.values.map((J)=>typeof J==="string"?i0(J):J?i0(J.toString()):String(J)).join("|")})$`),Y._zod.parse=(J,Q)=>{let $=J.value;if(Y._zod.values.has($))return J;return J.issues.push({code:"invalid_value",values:X.values,input:$,inst:Y}),J}});var $7=q("$ZodTransform",(Y,X)=>{n.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new u1(Y.constructor.name);let $=X.transform(J.value,J);if(Q.async)return($ instanceof Promise?$:Promise.resolve($)).then((W)=>{return J.value=W,J});if($ instanceof Promise)throw new d0;return J.value=$,J}});function ZQ(Y,X){if(Y.issues.length&&X===void 0)return{issues:[],value:void 0};return Y}var G7=q("$ZodOptional",(Y,X)=>{n.init(Y,X),Y._zod.optin="optional",Y._zod.optout="optional",l(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,void 0]):void 0}),l(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${i1(J.source)})?$`):void 0}),Y._zod.parse=(J,Q)=>{if(X.innerType._zod.optin==="optional"){let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>ZQ(G,J.value));return ZQ($,J.value)}if(J.value===void 0)return J;return X.innerType._zod.run(J,Q)}}),W7=q("$ZodNullable",(Y,X)=>{n.init(Y,X),l(Y._zod,"optin",()=>X.innerType._zod.optin),l(Y._zod,"optout",()=>X.innerType._zod.optout),l(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${i1(J.source)}|null)$`):void 0}),l(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,null]):void 0}),Y._zod.parse=(J,Q)=>{if(J.value===null)return J;return X.innerType._zod.run(J,Q)}}),z7=q("$ZodDefault",(Y,X)=>{n.init(Y,X),Y._zod.optin="optional",l(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);if(J.value===void 0)return J.value=X.defaultValue,J;let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>OQ(G,X));return OQ($,X)}});function OQ(Y,X){if(Y.value===void 0)Y.value=X.defaultValue;return Y}var K7=q("$ZodPrefault",(Y,X)=>{n.init(Y,X),Y._zod.optin="optional",l(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);if(J.value===void 0)J.value=X.defaultValue;return X.innerType._zod.run(J,Q)}}),U7=q("$ZodNonOptional",(Y,X)=>{n.init(Y,X),l(Y._zod,"values",()=>{let J=X.innerType._zod.values;return J?new Set([...J].filter((Q)=>Q!==void 0)):void 0}),Y._zod.parse=(J,Q)=>{let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>FQ(G,Y));return FQ($,Y)}});function FQ(Y,X){if(!Y.issues.length&&Y.value===void 0)Y.issues.push({code:"invalid_type",expected:"nonoptional",input:Y.value,inst:X});return Y}var H7=q("$ZodCatch",(Y,X)=>{n.init(Y,X),l(Y._zod,"optin",()=>X.innerType._zod.optin),l(Y._zod,"optout",()=>X.innerType._zod.optout),l(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>{if(J.value=G.value,G.issues.length)J.value=X.catchValue({...J,error:{issues:G.issues.map((W)=>_0(W,Q,h0()))},input:J.value}),J.issues=[];return J});if(J.value=$.value,$.issues.length)J.value=X.catchValue({...J,error:{issues:$.issues.map((G)=>_0(G,Q,h0()))},input:J.value}),J.issues=[];return J}});var L7=q("$ZodPipe",(Y,X)=>{n.init(Y,X),l(Y._zod,"values",()=>X.in._zod.values),l(Y._zod,"optin",()=>X.in._zod.optin),l(Y._zod,"optout",()=>X.out._zod.optout),l(Y._zod,"propValues",()=>X.in._zod.propValues),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward"){let G=X.out._zod.run(J,Q);if(G instanceof Promise)return G.then((W)=>kY(W,X.in,Q));return kY(G,X.in,Q)}let $=X.in._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>kY(G,X.out,Q));return kY($,X.out,Q)}});function kY(Y,X,J){if(Y.issues.length)return Y.aborted=!0,Y;return X._zod.run({value:Y.value,issues:Y.issues},J)}var N7=q("$ZodReadonly",(Y,X)=>{n.init(Y,X),l(Y._zod,"propValues",()=>X.innerType._zod.propValues),l(Y._zod,"values",()=>X.innerType._zod.values),l(Y._zod,"optin",()=>X.innerType._zod.optin),l(Y._zod,"optout",()=>X.innerType._zod.optout),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then(qQ);return qQ($)}});function qQ(Y){return Y.value=Object.freeze(Y.value),Y}var V7=q("$ZodLazy",(Y,X)=>{n.init(Y,X),l(Y._zod,"innerType",()=>X.getter()),l(Y._zod,"pattern",()=>Y._zod.innerType._zod.pattern),l(Y._zod,"propValues",()=>Y._zod.innerType._zod.propValues),l(Y._zod,"optin",()=>Y._zod.innerType._zod.optin??void 0),l(Y._zod,"optout",()=>Y._zod.innerType._zod.optout??void 0),Y._zod.parse=(J,Q)=>{return Y._zod.innerType._zod.run(J,Q)}}),B7=q("$ZodCustom",(Y,X)=>{L0.init(Y,X),n.init(Y,X),Y._zod.parse=(J,Q)=>{return J},Y._zod.check=(J)=>{let Q=J.value,$=X.fn(Q);if($ instanceof Promise)return $.then((G)=>jQ(G,J,Q,Y));jQ($,J,Q,Y);return}});function jQ(Y,X,J,Q){if(!Y){let $={code:"custom",input:J,inst:Q,path:[...Q._zod.def.path??[]],continue:!Q._zod.def.abort};if(Q._zod.def.params)$.params=Q._zod.def.params;X.issues.push(S1($))}}var xB=Symbol("ZodOutput"),vB=Symbol("ZodInput");class vY{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Y,...X){let J=X[0];if(this._map.set(Y,J),J&&typeof J==="object"&&"id"in J){if(this._idmap.has(J.id))throw Error(`ID ${J.id} already exists in the registry`);this._idmap.set(J.id,Y)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Y){let X=this._map.get(Y);if(X&&typeof X==="object"&&"id"in X)this._idmap.delete(X.id);return this._map.delete(Y),this}get(Y){let X=Y._zod.parent;if(X){let J={...this.get(X)??{}};delete J.id;let Q={...J,...this._map.get(Y)};return Object.keys(Q).length?Q:void 0}return this._map.get(Y)}has(Y){return this._map.has(Y)}}function $z(){return new vY}var Z1=$z();function Z7(Y,X){return new Y({type:"string",...v(X)})}function O7(Y,X){return new Y({type:"string",format:"email",check:"string_format",abort:!1,...v(X)})}function t8(Y,X){return new Y({type:"string",format:"guid",check:"string_format",abort:!1,...v(X)})}function F7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...v(X)})}function q7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...v(X)})}function j7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...v(X)})}function D7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...v(X)})}function P7(Y,X){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...v(X)})}function w7(Y,X){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...v(X)})}function E7(Y,X){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...v(X)})}function M7(Y,X){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...v(X)})}function A7(Y,X){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...v(X)})}function R7(Y,X){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...v(X)})}function T7(Y,X){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...v(X)})}function C7(Y,X){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...v(X)})}function _7(Y,X){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...v(X)})}function I7(Y,X){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...v(X)})}function S7(Y,X){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...v(X)})}function k7(Y,X){return new Y({type:"string",format:"cidrv6",check:"string_format",abort:!1,...v(X)})}function b7(Y,X){return new Y({type:"string",format:"base64",check:"string_format",abort:!1,...v(X)})}function x7(Y,X){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...v(X)})}function v7(Y,X){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...v(X)})}function h7(Y,X){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...v(X)})}function g7(Y,X){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...v(X)})}function y7(Y,X){return new Y({type:"string",format:"date",check:"string_format",...v(X)})}function f7(Y,X){return new Y({type:"string",format:"time",check:"string_format",precision:null,...v(X)})}function m7(Y,X){return new Y({type:"string",format:"duration",check:"string_format",...v(X)})}function c7(Y,X){return new Y({type:"number",checks:[],...v(X)})}function u7(Y,X){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...v(X)})}function p7(Y,X){return new Y({type:"boolean",...v(X)})}function l7(Y,X){return new Y({type:"null",...v(X)})}function d7(Y){return new Y({type:"unknown"})}function i7(Y,X){return new Y({type:"never",...v(X)})}function hY(Y,X){return new i8({check:"less_than",...v(X),value:Y,inclusive:!1})}function a1(Y,X){return new i8({check:"less_than",...v(X),value:Y,inclusive:!0})}function gY(Y,X){return new n8({check:"greater_than",...v(X),value:Y,inclusive:!1})}function t1(Y,X){return new n8({check:"greater_than",...v(X),value:Y,inclusive:!0})}function yY(Y,X){return new t6({check:"multiple_of",...v(X),value:Y})}function fY(Y,X){return new YQ({check:"max_length",...v(X),maximum:Y})}function k1(Y,X){return new XQ({check:"min_length",...v(X),minimum:Y})}function mY(Y,X){return new JQ({check:"length_equals",...v(X),length:Y})}function e8(Y,X){return new QQ({check:"string_format",format:"regex",...v(X),pattern:Y})}function Y9(Y){return new $Q({check:"string_format",format:"lowercase",...v(Y)})}function X9(Y){return new GQ({check:"string_format",format:"uppercase",...v(Y)})}function J9(Y,X){return new WQ({check:"string_format",format:"includes",...v(X),includes:Y})}function Q9(Y,X){return new zQ({check:"string_format",format:"starts_with",...v(X),prefix:Y})}function $9(Y,X){return new KQ({check:"string_format",format:"ends_with",...v(X),suffix:Y})}function O1(Y){return new UQ({check:"overwrite",tx:Y})}function G9(Y){return O1((X)=>X.normalize(Y))}function W9(){return O1((Y)=>Y.trim())}function z9(){return O1((Y)=>Y.toLowerCase())}function K9(){return O1((Y)=>Y.toUpperCase())}function n7(Y,X,J){return new Y({type:"array",element:X,...v(J)})}function o7(Y,X,J){let Q=v(J);return Q.abort??(Q.abort=!0),new Y({type:"custom",check:"custom",fn:X,...Q})}function r7(Y,X,J){return new Y({type:"custom",check:"custom",fn:X,...v(J)})}function s7(Y){let X=Gz((J)=>{return J.addIssue=(Q)=>{if(typeof Q==="string")J.issues.push(S1(Q,J.value,X._zod.def));else{let $=Q;if($.fatal)$.continue=!1;$.code??($.code="custom"),$.input??($.input=J.value),$.inst??($.inst=X),$.continue??($.continue=!X._zod.def.abort),J.issues.push(S1($))}},Y(J.value,J)});return X}function Gz(Y,X){let J=new L0({check:"custom",...v(X)});return J._zod.check=Y,J}class U9{constructor(Y){this.counter=0,this.metadataRegistry=Y?.metadata??Z1,this.target=Y?.target??"draft-2020-12",this.unrepresentable=Y?.unrepresentable??"throw",this.override=Y?.override??(()=>{}),this.io=Y?.io??"output",this.seen=new Map}process(Y,X={path:[],schemaPath:[]}){var J;let Q=Y._zod.def,$={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},G=this.seen.get(Y);if(G){if(G.count++,X.schemaPath.includes(Y))G.cycle=X.path;return G.schema}let W={schema:{},count:1,cycle:void 0,path:X.path};this.seen.set(Y,W);let K=Y._zod.toJSONSchema?.();if(K)W.schema=K;else{let N={...X,schemaPath:[...X.schemaPath,Y],path:X.path},O=Y._zod.parent;if(O)W.ref=O,this.process(O,N),this.seen.get(O).isParent=!0;else{let B=W.schema;switch(Q.type){case"string":{let L=B;L.type="string";let{minimum:Z,maximum:j,format:P,patterns:S,contentEncoding:E}=Y._zod.bag;if(typeof Z==="number")L.minLength=Z;if(typeof j==="number")L.maxLength=j;if(P){if(L.format=$[P]??P,L.format==="")delete L.format}if(E)L.contentEncoding=E;if(S&&S.size>0){let b=[...S];if(b.length===1)L.pattern=b[0].source;else if(b.length>1)W.schema.allOf=[...b.map((_)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:_.source}))]}break}case"number":{let L=B,{minimum:Z,maximum:j,format:P,multipleOf:S,exclusiveMaximum:E,exclusiveMinimum:b}=Y._zod.bag;if(typeof P==="string"&&P.includes("int"))L.type="integer";else L.type="number";if(typeof b==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")L.minimum=b,L.exclusiveMinimum=!0;else L.exclusiveMinimum=b;if(typeof Z==="number"){if(L.minimum=Z,typeof b==="number"&&this.target!=="draft-4")if(b>=Z)delete L.minimum;else delete L.exclusiveMinimum}if(typeof E==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")L.maximum=E,L.exclusiveMaximum=!0;else L.exclusiveMaximum=E;if(typeof j==="number"){if(L.maximum=j,typeof E==="number"&&this.target!=="draft-4")if(E<=j)delete L.maximum;else delete L.exclusiveMaximum}if(typeof S==="number")L.multipleOf=S;break}case"boolean":{let L=B;L.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema");break}case"null":{if(this.target==="openapi-3.0")B.type="string",B.nullable=!0,B.enum=[null];else B.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema");break}case"never":{B.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let L=B,{minimum:Z,maximum:j}=Y._zod.bag;if(typeof Z==="number")L.minItems=Z;if(typeof j==="number")L.maxItems=j;L.type="array",L.items=this.process(Q.element,{...N,path:[...N.path,"items"]});break}case"object":{let L=B;L.type="object",L.properties={};let Z=Q.shape;for(let S in Z)L.properties[S]=this.process(Z[S],{...N,path:[...N.path,"properties",S]});let j=new Set(Object.keys(Z)),P=new Set([...j].filter((S)=>{let E=Q.shape[S]._zod;if(this.io==="input")return E.optin===void 0;else return E.optout===void 0}));if(P.size>0)L.required=Array.from(P);if(Q.catchall?._zod.def.type==="never")L.additionalProperties=!1;else if(!Q.catchall){if(this.io==="output")L.additionalProperties=!1}else if(Q.catchall)L.additionalProperties=this.process(Q.catchall,{...N,path:[...N.path,"additionalProperties"]});break}case"union":{let L=B,Z=Q.options.map((j,P)=>this.process(j,{...N,path:[...N.path,"anyOf",P]}));L.anyOf=Z;break}case"intersection":{let L=B,Z=this.process(Q.left,{...N,path:[...N.path,"allOf",0]}),j=this.process(Q.right,{...N,path:[...N.path,"allOf",1]}),P=(E)=>("allOf"in E)&&Object.keys(E).length===1,S=[...P(Z)?Z.allOf:[Z],...P(j)?j.allOf:[j]];L.allOf=S;break}case"tuple":{let L=B;L.type="array";let Z=this.target==="draft-2020-12"?"prefixItems":"items",j=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",P=Q.items.map((_,u)=>this.process(_,{...N,path:[...N.path,Z,u]})),S=Q.rest?this.process(Q.rest,{...N,path:[...N.path,j,...this.target==="openapi-3.0"?[Q.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(L.prefixItems=P,S)L.items=S}else if(this.target==="openapi-3.0"){if(L.items={anyOf:P},S)L.items.anyOf.push(S);if(L.minItems=P.length,!S)L.maxItems=P.length}else if(L.items=P,S)L.additionalItems=S;let{minimum:E,maximum:b}=Y._zod.bag;if(typeof E==="number")L.minItems=E;if(typeof b==="number")L.maxItems=b;break}case"record":{let L=B;if(L.type="object",this.target==="draft-7"||this.target==="draft-2020-12")L.propertyNames=this.process(Q.keyType,{...N,path:[...N.path,"propertyNames"]});L.additionalProperties=this.process(Q.valueType,{...N,path:[...N.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let L=B,Z=l1(Q.entries);if(Z.every((j)=>typeof j==="number"))L.type="number";if(Z.every((j)=>typeof j==="string"))L.type="string";L.enum=Z;break}case"literal":{let L=B,Z=[];for(let j of Q.values)if(j===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof j==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else Z.push(Number(j));else Z.push(j);if(Z.length===0);else if(Z.length===1){let j=Z[0];if(L.type=j===null?"null":typeof j,this.target==="draft-4"||this.target==="openapi-3.0")L.enum=[j];else L.const=j}else{if(Z.every((j)=>typeof j==="number"))L.type="number";if(Z.every((j)=>typeof j==="string"))L.type="string";if(Z.every((j)=>typeof j==="boolean"))L.type="string";if(Z.every((j)=>j===null))L.type="null";L.enum=Z}break}case"file":{let L=B,Z={type:"string",format:"binary",contentEncoding:"binary"},{minimum:j,maximum:P,mime:S}=Y._zod.bag;if(j!==void 0)Z.minLength=j;if(P!==void 0)Z.maxLength=P;if(S)if(S.length===1)Z.contentMediaType=S[0],Object.assign(L,Z);else L.anyOf=S.map((E)=>{return{...Z,contentMediaType:E}});else Object.assign(L,Z);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let L=this.process(Q.innerType,N);if(this.target==="openapi-3.0")W.ref=Q.innerType,B.nullable=!0;else B.anyOf=[L,{type:"null"}];break}case"nonoptional":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"success":{let L=B;L.type="boolean";break}case"default":{this.process(Q.innerType,N),W.ref=Q.innerType,B.default=JSON.parse(JSON.stringify(Q.defaultValue));break}case"prefault":{if(this.process(Q.innerType,N),W.ref=Q.innerType,this.io==="input")B._prefault=JSON.parse(JSON.stringify(Q.defaultValue));break}case"catch":{this.process(Q.innerType,N),W.ref=Q.innerType;let L;try{L=Q.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}B.default=L;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let L=B,Z=Y._zod.pattern;if(!Z)throw Error("Pattern not found in template literal");L.type="string",L.pattern=Z.source;break}case"pipe":{let L=this.io==="input"?Q.in._zod.def.type==="transform"?Q.out:Q.in:Q.out;this.process(L,N),W.ref=L;break}case"readonly":{this.process(Q.innerType,N),W.ref=Q.innerType,B.readOnly=!0;break}case"promise":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"optional":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"lazy":{let L=Y._zod.innerType;this.process(L,N),W.ref=L;break}case"custom":{if(this.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema");break}case"function":{if(this.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema");break}default:}}}let U=this.metadataRegistry.get(Y);if(U)Object.assign(W.schema,U);if(this.io==="input"&&W0(Y))delete W.schema.examples,delete W.schema.default;if(this.io==="input"&&W.schema._prefault)(J=W.schema).default??(J.default=W.schema._prefault);return delete W.schema._prefault,this.seen.get(Y).schema}emit(Y,X){let J={cycles:X?.cycles??"ref",reused:X?.reused??"inline",external:X?.external??void 0},Q=this.seen.get(Y);if(!Q)throw Error("Unprocessed schema. This is a bug in Zod.");let $=(H)=>{let N=this.target==="draft-2020-12"?"$defs":"definitions";if(J.external){let Z=J.external.registry.get(H[0])?.id,j=J.external.uri??((S)=>S);if(Z)return{ref:j(Z)};let P=H[1].defId??H[1].schema.id??`schema${this.counter++}`;return H[1].defId=P,{defId:P,ref:`${j("__shared")}#/${N}/${P}`}}if(H[1]===Q)return{ref:"#"};let B=`${"#"}/${N}/`,L=H[1].schema.id??`__schema${this.counter++}`;return{defId:L,ref:B+L}},G=(H)=>{if(H[1].schema.$ref)return;let N=H[1],{ref:O,defId:B}=$(H);if(N.def={...N.schema},B)N.defId=B;let L=N.schema;for(let Z in L)delete L[Z];L.$ref=O};if(J.cycles==="throw")for(let H of this.seen.entries()){let N=H[1];if(N.cycle)throw Error(`Cycle detected: #/${N.cycle?.join("/")}/<root>
136
136
 
137
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let U of this.seen.entries()){let N=U[1];if(Y===U[0]){G(U);continue}if(J.external){let B=J.external.registry.get(U[0])?.id;if(Y!==U[0]&&B){G(U);continue}}if(this.metadataRegistry.get(U[0])?.id){G(U);continue}if(N.cycle){G(U);continue}if(N.count>1){if(J.reused==="ref"){G(U);continue}}}let W=(U,N)=>{let O=this.seen.get(U),B=O.def??O.schema,L={...B};if(O.ref===null)return;let Z=O.ref;if(O.ref=null,Z){W(Z,N);let j=this.seen.get(Z).schema;if(j.$ref&&(N.target==="draft-7"||N.target==="draft-4"||N.target==="openapi-3.0"))B.allOf=B.allOf??[],B.allOf.push(j);else Object.assign(B,j),Object.assign(B,L)}if(!O.isParent)this.override({zodSchema:U,jsonSchema:B,path:O.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 H=J.external?.defs??{};for(let U of this.seen.entries()){let N=U[1];if(N.def&&N.defId)H[N.defId]=N.def}if(J.external);else if(Object.keys(H).length>0)if(this.target==="draft-2020-12")K.$defs=H;else K.definitions=H;try{return JSON.parse(JSON.stringify(K))}catch(U){throw Error("Error converting schema to JSON.")}}}function s7(Y,X){if(Y instanceof vY){let Q=new U9(X),$={};for(let K of Y._idmap.entries()){let[H,U]=K;Q.process(U)}let G={},W={registry:Y,uri:X?.uri,defs:$};for(let K of Y._idmap.entries()){let[H,U]=K;G[H]=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 U9(X);return J.process(Y),J.emit(Y,X)}function W0(Y,X){let J=X??{seen:new Set};if(J.seen.has(Y))return!1;J.seen.add(Y);let $=Y._zod.def;switch($.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return W0($.element,J);case"object":{for(let G in $.shape)if(W0($.shape[G],J))return!0;return!1}case"union":{for(let G of $.options)if(W0(G,J))return!0;return!1}case"intersection":return W0($.left,J)||W0($.right,J);case"tuple":{for(let G of $.items)if(W0(G,J))return!0;if($.rest&&W0($.rest,J))return!0;return!1}case"record":return W0($.keyType,J)||W0($.valueType,J);case"map":return W0($.keyType,J)||W0($.valueType,J);case"set":return W0($.valueType,J);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return W0($.innerType,J);case"lazy":return W0($.getter(),J);case"default":return W0($.innerType,J);case"prefault":return W0($.innerType,J);case"custom":return!1;case"transform":return!0;case"pipe":return W0($.in,J)||W0($.out,J);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${$.type}`)}var zz=q("ZodISODateTime",(Y,X)=>{IQ.init(Y,X),o.init(Y,X)});function a7(Y){return h7(zz,Y)}var Kz=q("ZodISODate",(Y,X)=>{SQ.init(Y,X),o.init(Y,X)});function t7(Y){return g7(Kz,Y)}var Uz=q("ZodISOTime",(Y,X)=>{kQ.init(Y,X),o.init(Y,X)});function e7(Y){return y7(Uz,Y)}var Hz=q("ZodISODuration",(Y,X)=>{bQ.init(Y,X),o.init(Y,X)});function Y$(Y){return f7(Hz,Y)}var X$=(Y,X)=>{CY.init(Y,X),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(J)=>H6(Y,J)},flatten:{value:(J)=>U6(Y,J)},addIssue:{value:(J)=>{Y.issues.push(J),Y.message=JSON.stringify(Y.issues,C1,2)}},addIssues:{value:(J)=>{Y.issues.push(...J),Y.message=JSON.stringify(Y.issues,C1,2)}},isEmpty:{get(){return Y.issues.length===0}}})},UZ=q("ZodError",X$),E0=q("ZodError",X$,{Parent:Error});var J$=_Y(E0),Q$=IY(E0),$$=n1(E0),uY=o1(E0),G$=V6(E0),W$=B6(E0),z$=Z6(E0),K$=O6(E0),U$=F6(E0),H$=q6(E0),L$=j6(E0),N$=D6(E0);var r=q("ZodType",(Y,X)=>{return i.init(Y,X),Y.def=X,Y.type=X.type,Object.defineProperty(Y,"_def",{value:X}),Y.check=(...J)=>{return Y.clone({...X,checks:[...X.checks??[],...J.map((Q)=>typeof Q==="function"?{_zod:{check:Q,def:{check:"custom"},onattach:[]}}:Q)]})},Y.clone=(J,Q)=>C0(Y,J,Q),Y.brand=()=>Y,Y.register=(J,Q)=>{return J.add(Y,Q),Y},Y.parse=(J,Q)=>J$(Y,J,Q,{callee:Y.parse}),Y.safeParse=(J,Q)=>$$(Y,J,Q),Y.parseAsync=async(J,Q)=>Q$(Y,J,Q,{callee:Y.parseAsync}),Y.safeParseAsync=async(J,Q)=>uY(Y,J,Q),Y.spa=Y.safeParseAsync,Y.encode=(J,Q)=>G$(Y,J,Q),Y.decode=(J,Q)=>W$(Y,J,Q),Y.encodeAsync=async(J,Q)=>z$(Y,J,Q),Y.decodeAsync=async(J,Q)=>K$(Y,J,Q),Y.safeEncode=(J,Q)=>U$(Y,J,Q),Y.safeDecode=(J,Q)=>H$(Y,J,Q),Y.safeEncodeAsync=async(J,Q)=>L$(Y,J,Q),Y.safeDecodeAsync=async(J,Q)=>N$(Y,J,Q),Y.refine=(J,Q)=>Y.check(QK(J,Q)),Y.superRefine=(J)=>Y.check($K(J)),Y.overwrite=(J)=>Y.check(Z1(J)),Y.optional=()=>Z$(Y),Y.nullable=()=>O$(Y),Y.nullish=()=>Z$(O$(Y)),Y.nonoptional=(J)=>sz(Y,J),Y.array=()=>N9(Y),Y.or=(J)=>V9([Y,J]),Y.and=(J)=>mz(Y,J),Y.transform=(J)=>F$(Y,lz(J)),Y.default=(J)=>nz(Y,J),Y.prefault=(J)=>rz(Y,J),Y.catch=(J)=>tz(Y,J),Y.pipe=(J)=>F$(Y,J),Y.readonly=()=>XK(Y),Y.describe=(J)=>{let Q=Y.clone();return B1.add(Q,{description:J}),Q},Object.defineProperty(Y,"description",{get(){return B1.get(Y)?.description},configurable:!0}),Y.meta=(...J)=>{if(J.length===0)return B1.get(Y);let Q=Y.clone();return B1.add(Q,J[0]),Q},Y.isOptional=()=>Y.safeParse(void 0).success,Y.isNullable=()=>Y.safeParse(null).success,Y}),q$=q("_ZodString",(Y,X)=>{xY.init(Y,X),r.init(Y,X);let J=Y._zod.bag;Y.format=J.format??null,Y.minLength=J.minimum??null,Y.maxLength=J.maximum??null,Y.regex=(...Q)=>Y.check(e8(...Q)),Y.includes=(...Q)=>Y.check(J9(...Q)),Y.startsWith=(...Q)=>Y.check(Q9(...Q)),Y.endsWith=(...Q)=>Y.check($9(...Q)),Y.min=(...Q)=>Y.check(S1(...Q)),Y.max=(...Q)=>Y.check(fY(...Q)),Y.length=(...Q)=>Y.check(mY(...Q)),Y.nonempty=(...Q)=>Y.check(S1(1,...Q)),Y.lowercase=(Q)=>Y.check(Y9(Q)),Y.uppercase=(Q)=>Y.check(X9(Q)),Y.trim=()=>Y.check(W9()),Y.normalize=(...Q)=>Y.check(G9(...Q)),Y.toLowerCase=()=>Y.check(z9()),Y.toUpperCase=()=>Y.check(K9())}),Bz=q("ZodString",(Y,X)=>{xY.init(Y,X),q$.init(Y,X),Y.email=(J)=>Y.check(Z7(Zz,J)),Y.url=(J)=>Y.check(D7(Oz,J)),Y.jwt=(J)=>Y.check(v7(Sz,J)),Y.emoji=(J)=>Y.check(P7(Fz,J)),Y.guid=(J)=>Y.check(t8(V$,J)),Y.uuid=(J)=>Y.check(O7(pY,J)),Y.uuidv4=(J)=>Y.check(F7(pY,J)),Y.uuidv6=(J)=>Y.check(q7(pY,J)),Y.uuidv7=(J)=>Y.check(j7(pY,J)),Y.nanoid=(J)=>Y.check(w7(qz,J)),Y.guid=(J)=>Y.check(t8(V$,J)),Y.cuid=(J)=>Y.check(E7(jz,J)),Y.cuid2=(J)=>Y.check(M7(Dz,J)),Y.ulid=(J)=>Y.check(A7(Pz,J)),Y.base64=(J)=>Y.check(k7(Cz,J)),Y.base64url=(J)=>Y.check(b7(_z,J)),Y.xid=(J)=>Y.check(R7(wz,J)),Y.ksuid=(J)=>Y.check(T7(Ez,J)),Y.ipv4=(J)=>Y.check(C7(Mz,J)),Y.ipv6=(J)=>Y.check(_7(Az,J)),Y.cidrv4=(J)=>Y.check(I7(Rz,J)),Y.cidrv6=(J)=>Y.check(S7(Tz,J)),Y.e164=(J)=>Y.check(x7(Iz,J)),Y.datetime=(J)=>Y.check(a7(J)),Y.date=(J)=>Y.check(t7(J)),Y.time=(J)=>Y.check(e7(J)),Y.duration=(J)=>Y.check(Y$(J))});function j$(Y){return B7(Bz,Y)}var o=q("ZodStringFormat",(Y,X)=>{n.init(Y,X),q$.init(Y,X)}),Zz=q("ZodEmail",(Y,X)=>{PQ.init(Y,X),o.init(Y,X)});var V$=q("ZodGUID",(Y,X)=>{jQ.init(Y,X),o.init(Y,X)});var pY=q("ZodUUID",(Y,X)=>{DQ.init(Y,X),o.init(Y,X)});var Oz=q("ZodURL",(Y,X)=>{wQ.init(Y,X),o.init(Y,X)});var Fz=q("ZodEmoji",(Y,X)=>{EQ.init(Y,X),o.init(Y,X)});var qz=q("ZodNanoID",(Y,X)=>{MQ.init(Y,X),o.init(Y,X)});var jz=q("ZodCUID",(Y,X)=>{AQ.init(Y,X),o.init(Y,X)});var Dz=q("ZodCUID2",(Y,X)=>{RQ.init(Y,X),o.init(Y,X)});var Pz=q("ZodULID",(Y,X)=>{TQ.init(Y,X),o.init(Y,X)});var wz=q("ZodXID",(Y,X)=>{CQ.init(Y,X),o.init(Y,X)});var Ez=q("ZodKSUID",(Y,X)=>{_Q.init(Y,X),o.init(Y,X)});var Mz=q("ZodIPv4",(Y,X)=>{xQ.init(Y,X),o.init(Y,X)});var Az=q("ZodIPv6",(Y,X)=>{vQ.init(Y,X),o.init(Y,X)});var Rz=q("ZodCIDRv4",(Y,X)=>{hQ.init(Y,X),o.init(Y,X)});var Tz=q("ZodCIDRv6",(Y,X)=>{gQ.init(Y,X),o.init(Y,X)});var Cz=q("ZodBase64",(Y,X)=>{fQ.init(Y,X),o.init(Y,X)});var _z=q("ZodBase64URL",(Y,X)=>{mQ.init(Y,X),o.init(Y,X)});var Iz=q("ZodE164",(Y,X)=>{cQ.init(Y,X),o.init(Y,X)});var Sz=q("ZodJWT",(Y,X)=>{uQ.init(Y,X),o.init(Y,X)});var D$=q("ZodNumber",(Y,X)=>{s8.init(Y,X),r.init(Y,X),Y.gt=(Q,$)=>Y.check(gY(Q,$)),Y.gte=(Q,$)=>Y.check(a1(Q,$)),Y.min=(Q,$)=>Y.check(a1(Q,$)),Y.lt=(Q,$)=>Y.check(hY(Q,$)),Y.lte=(Q,$)=>Y.check(s1(Q,$)),Y.max=(Q,$)=>Y.check(s1(Q,$)),Y.int=(Q)=>Y.check(B$(Q)),Y.safe=(Q)=>Y.check(B$(Q)),Y.positive=(Q)=>Y.check(gY(0,Q)),Y.nonnegative=(Q)=>Y.check(a1(0,Q)),Y.negative=(Q)=>Y.check(hY(0,Q)),Y.nonpositive=(Q)=>Y.check(s1(0,Q)),Y.multipleOf=(Q,$)=>Y.check(yY(Q,$)),Y.step=(Q,$)=>Y.check(yY(Q,$)),Y.finite=()=>Y;let J=Y._zod.bag;Y.minValue=Math.max(J.minimum??Number.NEGATIVE_INFINITY,J.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Y.maxValue=Math.min(J.maximum??Number.POSITIVE_INFINITY,J.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Y.isInt=(J.format??"").includes("int")||Number.isSafeInteger(J.multipleOf??0.5),Y.isFinite=!0,Y.format=J.format??null});function P$(Y){return m7(D$,Y)}var kz=q("ZodNumberFormat",(Y,X)=>{pQ.init(Y,X),D$.init(Y,X)});function B$(Y){return c7(kz,Y)}var bz=q("ZodBoolean",(Y,X)=>{lQ.init(Y,X),r.init(Y,X)});function w$(Y){return u7(bz,Y)}var xz=q("ZodNull",(Y,X)=>{dQ.init(Y,X),r.init(Y,X)});function E$(Y){return p7(xz,Y)}var vz=q("ZodUnknown",(Y,X)=>{iQ.init(Y,X),r.init(Y,X)});function t1(){return l7(vz)}var hz=q("ZodNever",(Y,X)=>{nQ.init(Y,X),r.init(Y,X)});function L9(Y){return d7(hz,Y)}var gz=q("ZodArray",(Y,X)=>{oQ.init(Y,X),r.init(Y,X),Y.element=X.element,Y.min=(J,Q)=>Y.check(S1(J,Q)),Y.nonempty=(J)=>Y.check(S1(1,J)),Y.max=(J,Q)=>Y.check(fY(J,Q)),Y.length=(J,Q)=>Y.check(mY(J,Q)),Y.unwrap=()=>Y.element});function N9(Y,X){return i7(gz,Y,X)}var M$=q("ZodObject",(Y,X)=>{aQ.init(Y,X),r.init(Y,X),c.defineLazy(Y,"shape",()=>X.shape),Y.keyof=()=>B9(Object.keys(Y._zod.def.shape)),Y.catchall=(J)=>Y.clone({...Y._zod.def,catchall:J}),Y.passthrough=()=>Y.clone({...Y._zod.def,catchall:t1()}),Y.loose=()=>Y.clone({...Y._zod.def,catchall:t1()}),Y.strict=()=>Y.clone({...Y._zod.def,catchall:L9()}),Y.strip=()=>Y.clone({...Y._zod.def,catchall:void 0}),Y.extend=(J)=>{return c.extend(Y,J)},Y.safeExtend=(J)=>{return c.safeExtend(Y,J)},Y.merge=(J)=>c.merge(Y,J),Y.pick=(J)=>c.pick(Y,J),Y.omit=(J)=>c.omit(Y,J),Y.partial=(...J)=>c.partial(S$,Y,J[0]),Y.required=(...J)=>c.required(k$,Y,J[0])});function A$(Y,X){let J={type:"object",get shape(){return c.assignProp(this,"shape",Y?c.objectClone(Y):{}),this.shape},...c.normalizeParams(X)};return new M$(J)}function R$(Y,X){return new M$({type:"object",get shape(){return c.assignProp(this,"shape",c.objectClone(Y)),this.shape},catchall:t1(),...c.normalizeParams(X)})}var T$=q("ZodUnion",(Y,X)=>{a8.init(Y,X),r.init(Y,X),Y.options=X.options});function V9(Y,X){return new T$({type:"union",options:Y,...c.normalizeParams(X)})}var yz=q("ZodDiscriminatedUnion",(Y,X)=>{T$.init(Y,X),tQ.init(Y,X)});function C$(Y,X,J){return new yz({type:"union",options:X,discriminator:Y,...c.normalizeParams(J)})}var fz=q("ZodIntersection",(Y,X)=>{eQ.init(Y,X),r.init(Y,X)});function mz(Y,X){return new fz({type:"intersection",left:Y,right:X})}var cz=q("ZodRecord",(Y,X)=>{Y7.init(Y,X),r.init(Y,X),Y.keyType=X.keyType,Y.valueType=X.valueType});function _$(Y,X,J){return new cz({type:"record",keyType:Y,valueType:X,...c.normalizeParams(J)})}var H9=q("ZodEnum",(Y,X)=>{X7.init(Y,X),r.init(Y,X),Y.enum=X.entries,Y.options=Object.values(X.entries);let J=new Set(Object.keys(X.entries));Y.extract=(Q,$)=>{let G={};for(let W of Q)if(J.has(W))G[W]=X.entries[W];else throw Error(`Key ${W} not found in enum`);return new H9({...X,checks:[],...c.normalizeParams($),entries:G})},Y.exclude=(Q,$)=>{let G={...X.entries};for(let W of Q)if(J.has(W))delete G[W];else throw Error(`Key ${W} not found in enum`);return new H9({...X,checks:[],...c.normalizeParams($),entries:G})}});function B9(Y,X){let J=Array.isArray(Y)?Object.fromEntries(Y.map((Q)=>[Q,Q])):Y;return new H9({type:"enum",entries:J,...c.normalizeParams(X)})}var uz=q("ZodLiteral",(Y,X)=>{J7.init(Y,X),r.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 I$(Y,X){return new uz({type:"literal",values:Array.isArray(Y)?Y:[Y],...c.normalizeParams(X)})}var pz=q("ZodTransform",(Y,X)=>{Q7.init(Y,X),r.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new c1(Y.constructor.name);J.addIssue=(G)=>{if(typeof G==="string")J.issues.push(c.issue(G,J.value,X));else{let W=G;if(W.fatal)W.continue=!1;W.code??(W.code="custom"),W.input??(W.input=J.value),W.inst??(W.inst=Y),J.issues.push(c.issue(W))}};let $=X.transform(J.value,J);if($ instanceof Promise)return $.then((G)=>{return J.value=G,J});return J.value=$,J}});function lz(Y){return new pz({type:"transform",transform:Y})}var S$=q("ZodOptional",(Y,X)=>{$7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function Z$(Y){return new S$({type:"optional",innerType:Y})}var dz=q("ZodNullable",(Y,X)=>{G7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function O$(Y){return new dz({type:"nullable",innerType:Y})}var iz=q("ZodDefault",(Y,X)=>{W7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function nz(Y,X){return new iz({type:"default",innerType:Y,get defaultValue(){return typeof X==="function"?X():c.shallowClone(X)}})}var oz=q("ZodPrefault",(Y,X)=>{z7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function rz(Y,X){return new oz({type:"prefault",innerType:Y,get defaultValue(){return typeof X==="function"?X():c.shallowClone(X)}})}var k$=q("ZodNonOptional",(Y,X)=>{K7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function sz(Y,X){return new k$({type:"nonoptional",innerType:Y,...c.normalizeParams(X)})}var az=q("ZodCatch",(Y,X)=>{U7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function tz(Y,X){return new az({type:"catch",innerType:Y,catchValue:typeof X==="function"?X:()=>X})}var ez=q("ZodPipe",(Y,X)=>{H7.init(Y,X),r.init(Y,X),Y.in=X.in,Y.out=X.out});function F$(Y,X){return new ez({type:"pipe",in:Y,out:X})}var YK=q("ZodReadonly",(Y,X)=>{L7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function XK(Y){return new YK({type:"readonly",innerType:Y})}var JK=q("ZodLazy",(Y,X)=>{N7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.getter()});function b$(Y){return new JK({type:"lazy",getter:Y})}var Z9=q("ZodCustom",(Y,X)=>{V7.init(Y,X),r.init(Y,X)});function x$(Y,X){return n7(Z9,Y??(()=>!0),X)}function QK(Y,X={}){return o7(Z9,Y,X)}function $K(Y){return r7(Y)}function v$(Y,X={error:`Input not instance of ${Y.name}`}){let J=new Z9({type:"custom",check:"custom",fn:(Q)=>Q instanceof Y,abort:!0,...c.normalizeParams(X)});return J._zod.bag.Class=Y,J}var GK=[{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]}],sZ=[...GK,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];var WK=12,zK=131072,aZ=zK+WK;async function lY(Y){var X;try{await((X=Y.body)==null?void 0:X.cancel())}catch(J){}}var d$="AI_DownloadError",i$=`vercel.ai.error.${d$}`,KK=Symbol.for(i$),h$,g$,F0=class extends(g$=f,h$=KK,g$){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:d$,message:$,cause:Q});this[h$]=!0,this.url=Y,this.statusCode=X,this.statusText=J}static isInstance(Y){return f.hasMarker(Y,i$)}};function UK(Y=globalThis){return Y.window!=null}function y$(Y,X){try{return new URL(Y).origin===new URL(X).origin}catch(J){return!1}}function HK(Y){let X;try{X=new URL(Y)}catch(Q){throw new F0({url:Y,message:`Invalid URL: ${Y}`})}if(X.protocol==="data:")return;if(X.protocol!=="http:"&&X.protocol!=="https:")throw new F0({url:Y,message:`URL scheme must be http, https, or data, got ${X.protocol}`});let J=X.hostname.toLowerCase().replace(/\.+$/,"");if(!J)throw new F0({url:Y,message:"URL must have a hostname"});if(J==="localhost"||J.endsWith(".local")||J.endsWith(".localhost"))throw new F0({url:Y,message:`URL with hostname ${J} is not allowed`});if(J.startsWith("[")&&J.endsWith("]")){let Q=J.slice(1,-1);if(n$(Q))throw new F0({url:Y,message:`URL with IPv6 address ${J} is not allowed`});return}if(P9(J)){if(w9(J))throw new F0({url:Y,message:`URL with IP address ${J} is not allowed`});return}}function LK({address:Y,family:X,hostname:J}){if(X===4?!P9(Y)||w9(Y):X===6?n$(Y):!0)throw new F0({url:J,message:`Hostname ${J} resolved to disallowed IP address ${Y}`})}function P9(Y){let X=Y.split(".");if(X.length!==4)return!1;return X.every((J)=>{let Q=Number(J);return Number.isInteger(Q)&&Q>=0&&Q<=255&&String(Q)===J})}function w9(Y){let X=Y.split(".").map(Number),[J,Q,$]=X;if(J===0)return!0;if(J===10)return!0;if(J===100&&Q>=64&&Q<=127)return!0;if(J===127)return!0;if(J===169&&Q===254)return!0;if(J===172&&Q>=16&&Q<=31)return!0;if(J===192&&Q===0&&$===0)return!0;if(J===192&&Q===0&&$===2)return!0;if(J===192&&Q===168)return!0;if(J===198&&(Q===18||Q===19))return!0;if(J===198&&Q===51&&$===100)return!0;if(J===203&&Q===0&&$===113)return!0;if(J>=224)return!0;return!1}function NK(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=[],H=W.split(":");for(let U=0;U<H.length;U++){let N=H[U];if(N.includes(".")){if(U!==H.length-1||!P9(N))return null;let[O,B,L,Z]=N.split(".").map(Number);K.push(O<<8|B,L<<8|Z);continue}if(!/^[0-9a-f]{1,4}$/.test(N))return null;K.push(parseInt(N,16))}return K},G=$(Q[0]);if(G===null)return null;if(Q.length===2){let W=$(Q[1]);if(W===null)return null;let K=8-G.length-W.length;if(K<0)return null;return[...G,...Array(K).fill(0),...W]}return G.length===8?G:null}function n$(Y){let X=NK(Y);if(X===null)return!0;let J=($)=>X.slice(0,$).every((G)=>G===0);if(J(7)&&(X[7]===0||X[7]===1))return!0;if((X[0]&65024)===64512)return!0;if((X[0]&65472)===65152)return!0;if((X[0]&65472)===65216)return!0;if((X[0]&65280)===65280)return!0;if(X[0]===8193&&X[1]===3512)return!0;if(X[0]===16383&&(X[1]&61440)===0)return!0;if(J(6)||J(5)&&X[5]===65535||J(4)&&X[4]===65535&&X[5]===0||X[0]===100&&X[1]===65435&&X[2]===0&&X[3]===0&&X[4]===0&&X[5]===0||X[0]===100&&X[1]===65435&&X[2]===1){let $=X[6]>>8&255,G=X[6]&255,W=X[7]>>8&255,K=X[7]&255;return w9(`${$}.${G}.${W}.${K}`)}return!1}function VK(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:H}of G)LK({address:K,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 O9,o$=globalThis.fetch,BK=FK(o$);function ZK(){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 OK(){if(!ZK()||!BK||globalThis.fetch!==o$)return globalThis.fetch;return O9!=null?O9:O9=Promise.resolve().then(qK)}function FK(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 qK(){let{createRequire:Y}=f$("node:module"),{lookup:X}=f$("node:dns"),{Agent:J,fetch:Q}=Y(r$())("undici"),$=new J({connect:{lookup:VK(X)}});return(G,W)=>Q(G,{...W,dispatcher:$})}function f$(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 r$(){let Y=Error.prepareStackTrace;try{Error.prepareStackTrace=($,G)=>G;let X=Error("Capture current module path");Error.captureStackTrace(X,r$);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 jK=["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 DK(Y){let X=new Headers(Y);for(let J of jK)X.delete(J);return X}var PK=10,wK=new Set([301,302,303,307,308]);async function s$({url:Y,headers:X,abortSignal:J,maxRedirects:Q=PK,fetch:$,trustedOrigin:G}){let W=X===void 0?void 0:DK(X),K=(U)=>{let N={signal:J,redirect:U};if(W!==void 0)N.headers=new Headers(W);return N},H=Y;for(let U=0;U<=Q;U++){let N=G!==void 0&&y$(H,G);if(!N)HK(H);let O=$!=null?$:N?globalThis.fetch:await OK(),B=await O(H,K("manual"));if(B.type==="opaqueredirect"){if(!UK())throw new F0({url:Y,message:`Redirect from ${H} could not be validated and was blocked`});return await O(H,K("follow"))}let L=B.headers.get("location");if(wK.has(B.status)&&L){await lY(B);let Z=new URL(L,H).toString();if(W!==void 0&&!y$(Z,H)){let j=W.get("user-agent");W=new Headers(j==null?void 0:{"user-agent":j})}H=Z;continue}return B}throw new F0({url:Y,message:`Too many redirects (max ${Q})`})}var E9=2147483648;async function a$({response:Y,url:X,maxBytes:J=E9}){let Q=Y.headers.get("content-length");if(Q!=null){let N=parseInt(Q,10);if(!isNaN(N)&&N>J)throw await lY(Y),new F0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes (Content-Length: ${N}).`})}let $=Y.body;if($==null)return new Uint8Array(0);let G=$.getReader(),W=[],K=0;try{while(!0){let{done:N,value:O}=await G.read();if(N)break;if(K+=O.length,K>J)throw new F0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes.`});W.push(O)}}finally{try{await G.cancel()}finally{G.releaseLock()}}let H=new Uint8Array(K),U=0;for(let N of W)H.set(N,U),U+=N.length;return H}var J0=({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 IJ({argument:"separator",message:`The separator "${Q}" must not be part of the alphabet "${J}".`});return()=>`${Y}${Q}${$()}`},YO=J0();function t$(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 EK(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 k1(Y,...X){let J=new Headers(EK(Y)),Q=J.get("user-agent")||"";return J.set("user-agent",[Q,...X].filter(Boolean).join(" ")),Object.fromEntries(J.entries())}function e$(Y){var X,J;return(J=(X=globalThis.Buffer)==null?void 0:X.isBuffer(Y))!=null?J:!1}var MK=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,AK=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function m$(Y){let X=JSON.parse(Y);if(X===null||typeof X!=="object")return X;if(MK.test(Y)===!1&&AK.test(Y)===!1)return X;return RK(X)}function RK(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 TK(Y){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(J){return m$(Y)}try{return m$(Y)}finally{Error.stackTraceLimit=X}}function M9(Y){if(Y.type==="object"||Array.isArray(Y.type)&&Y.type.includes("object")){Y.additionalProperties=!1;let{properties:J}=Y;if(J!=null)for(let Q of Object.keys(J))J[Q]=O1(J[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 M9(Y)}var CK=Symbol("Let zodToJsonSchema decide on which parser to use"),c$={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"},_K=(Y)=>typeof Y==="string"?{...c$,name:Y}:{...c$,...Y};function M0(){return{}}function IK(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=l(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 SK(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 kK(){return{type:"boolean"}}function YG(Y,X){return l(Y.type._def,X)}var bK=(Y,X)=>{return l(Y.innerType._def,X)};function XG(Y,X,J){let Q=J!=null?J:X.dateStrategy;if(Array.isArray(Q))return{anyOf:Q.map(($)=>XG(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 xK(Y)}}var xK=(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 vK(Y,X){return{...l(Y.innerType._def,X),default:Y.defaultValue()}}function hK(Y,X){return X.effectStrategy==="input"?l(Y.schema._def,X):M0()}function gK(Y){return{type:"string",enum:Array.from(Y.values)}}var yK=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function fK(Y,X){let J=[l(Y.left._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),l(Y.right._def,{...X,currentPath:[...X.currentPath,"allOf","1"]})].filter(($)=>!!$),Q=[];return J.forEach(($)=>{if(yK($))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 mK(Y){let X=typeof Y.value;if(X!=="bigint"&&X!=="number"&&X!=="boolean"&&X!=="string")return{type:Array.isArray(Y.value)?"array":"object"};return{type:X==="bigint"?"integer":X,const:Y.value}}var F9=void 0,I0={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(F9===void 0)F9=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return F9},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function JG(Y,X){let J={type:"string"};if(Y.checks)for(let Q of Y.checks)switch(Q.kind){case"min":J.minLength=typeof J.minLength==="number"?Math.max(J.minLength,Q.value):Q.value;break;case"max":J.maxLength=typeof J.maxLength==="number"?Math.min(J.maxLength,Q.value):Q.value;break;case"email":switch(X.emailStrategy){case"format:email":S0(J,"email",Q.message,X);break;case"format:idn-email":S0(J,"idn-email",Q.message,X);break;case"pattern:zod":O0(J,I0.email,Q.message,X);break}break;case"url":S0(J,"uri",Q.message,X);break;case"uuid":S0(J,"uuid",Q.message,X);break;case"regex":O0(J,Q.regex,Q.message,X);break;case"cuid":O0(J,I0.cuid,Q.message,X);break;case"cuid2":O0(J,I0.cuid2,Q.message,X);break;case"startsWith":O0(J,RegExp(`^${q9(Q.value,X)}`),Q.message,X);break;case"endsWith":O0(J,RegExp(`${q9(Q.value,X)}$`),Q.message,X);break;case"datetime":S0(J,"date-time",Q.message,X);break;case"date":S0(J,"date",Q.message,X);break;case"time":S0(J,"time",Q.message,X);break;case"duration":S0(J,"duration",Q.message,X);break;case"length":J.minLength=typeof J.minLength==="number"?Math.max(J.minLength,Q.value):Q.value,J.maxLength=typeof J.maxLength==="number"?Math.min(J.maxLength,Q.value):Q.value;break;case"includes":{O0(J,RegExp(q9(Q.value,X)),Q.message,X);break}case"ip":{if(Q.version!=="v6")S0(J,"ipv4",Q.message,X);if(Q.version!=="v4")S0(J,"ipv6",Q.message,X);break}case"base64url":O0(J,I0.base64url,Q.message,X);break;case"jwt":O0(J,I0.jwt,Q.message,X);break;case"cidr":{if(Q.version!=="v6")O0(J,I0.ipv4Cidr,Q.message,X);if(Q.version!=="v4")O0(J,I0.ipv6Cidr,Q.message,X);break}case"emoji":O0(J,I0.emoji(),Q.message,X);break;case"ulid":{O0(J,I0.ulid,Q.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{S0(J,"binary",Q.message,X);break}case"contentEncoding:base64":{J.contentEncoding="base64";break}case"pattern:zod":{O0(J,I0.base64,Q.message,X);break}}break}case"nanoid":O0(J,I0.nanoid,Q.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return J}function q9(Y,X){return X.patternStrategy==="escape"?uK(Y):Y}var cK=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function uK(Y){let X="";for(let J=0;J<Y.length;J++){if(!cK.has(Y[J]))X+="\\";X+=Y[J]}return X}function S0(Y,X,J,Q){var $;if(Y.format||(($=Y.anyOf)==null?void 0:$.some((G)=>G.format))){if(!Y.anyOf)Y.anyOf=[];if(Y.format)Y.anyOf.push({format:Y.format}),delete Y.format;Y.anyOf.push({format:X,...J&&Q.errorMessages&&{errorMessage:{format:J}}})}else Y.format=X}function O0(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:u$(X,Q),...J&&Q.errorMessages&&{errorMessage:{pattern:J}}})}else Y.pattern=u$(X,Q)}function u$(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,H=!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(H)G+=$[U],G+=`${$[U-2]}-${$[U]}`.toUpperCase(),H=!1;else if($[U+1]==="-"&&((J=$[U+2])==null?void 0:J.match(/[a-z]/)))G+=$[U],H=!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
138
- ]))`;continue}else if($[U]==="$"){G+=`($|(?=[\r
139
- ]))`;continue}}if(Q.s&&$[U]==="."){G+=K?`${$[U]}\r
140
- `:`[${$[U]}\r
141
- ]`;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 QG(Y,X){var J,Q,$,G,W,K;let H={type:"object",additionalProperties:(J=l(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,...N}=JG(Y.keyType._def,X);return{...H,propertyNames:N}}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"&&((K=Y.keyType._def.type._def.checks)==null?void 0:K.length)){let{type:U,...N}=YG(Y.keyType._def,X);return{...H,propertyNames:N}}return H}function pK(Y,X){if(X.mapStrategy==="record")return QG(Y,X);let J=l(Y.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||M0(),Q=l(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||M0();return{type:"array",maxItems:125,items:{type:"array",items:[J,Q],minItems:2,maxItems:2}}}function lK(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 dK(){return{not:M0()}}function iK(){return{type:"null"}}var j9={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function nK(Y,X){let J=Y.options instanceof Map?Array.from(Y.options.values()):Y.options;if(J.every((Q)=>(Q._def.typeName in j9)&&(!Q._def.checks||!Q._def.checks.length))){let Q=J.reduce(($,G)=>{let W=j9[G._def.typeName];return W&&!$.includes(W)?[...$,W]:$},[]);return{type:Q.length>1?Q:Q[0]}}else if(J.every((Q)=>Q._def.typeName==="ZodLiteral"&&!Q.description)){let Q=J.reduce(($,G)=>{let W=typeof G._def.value;switch(W){case"string":case"number":case"boolean":return[...$,W];case"bigint":return[...$,"integer"];case"object":if(G._def.value===null)return[...$,"null"];case"symbol":case"undefined":case"function":default:return $}},[]);if(Q.length===J.length){let $=Q.filter((G,W,K)=>K.indexOf(G)===W);return{type:$.length>1?$:$[0],enum:J.reduce((G,W)=>{return G.includes(W._def.value)?G:[...G,W._def.value]},[])}}}else if(J.every((Q)=>Q._def.typeName==="ZodEnum"))return{type:"string",enum:J.reduce((Q,$)=>[...Q,...$._def.values.filter((G)=>!Q.includes(G))],[])};return oK(Y,X)}var oK=(Y,X)=>{let J=(Y.options instanceof Map?Array.from(Y.options.values()):Y.options).map((Q,$)=>l(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 rK(Y,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Y.innerType._def.typeName)&&(!Y.innerType._def.checks||!Y.innerType._def.checks.length))return{type:[j9[Y.innerType._def.typeName],"null"]};let J=l(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return J&&{anyOf:[J,{type:"null"}]}}function sK(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 aK(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 H=eK(K),U=l(K._def,{...X,currentPath:[...X.currentPath,"properties",W],propertyPath:[...X.currentPath,"properties",W]});if(U===void 0)continue;if(J.properties[W]=U,!H)Q.push(W)}if(Q.length)J.required=Q;let G=tK(Y,X);if(G!==void 0)J.additionalProperties=G;return J}function tK(Y,X){if(Y.catchall._def.typeName!=="ZodNever")return l(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 eK(Y){try{return Y.isOptional()}catch(X){return!0}}var YU=(Y,X)=>{var J;if(X.currentPath.toString()===((J=X.propertyPath)==null?void 0:J.toString()))return l(Y.innerType._def,X);let Q=l(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return Q?{anyOf:[{not:M0()},Q]}:M0()},XU=(Y,X)=>{if(X.pipeStrategy==="input")return l(Y.in._def,X);else if(X.pipeStrategy==="output")return l(Y.out._def,X);let J=l(Y.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),Q=l(Y.out._def,{...X,currentPath:[...X.currentPath,"allOf",J?"1":"0"]});return{allOf:[J,Q].filter(($)=>$!==void 0)}};function JU(Y,X){return l(Y.type._def,X)}function QU(Y,X){let Q={type:"array",uniqueItems:!0,items:l(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 $U(Y,X){if(Y.rest)return{type:"array",minItems:Y.items.length,items:Y.items.map((J,Q)=>l(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[]),additionalItems:l(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)=>l(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[])}}function GU(){return{not:M0()}}function WU(){return M0()}var zU=(Y,X)=>{return l(Y.innerType._def,X)},KU=(Y,X,J)=>{switch(X){case"ZodString":return JG(Y,J);case"ZodNumber":return sK(Y);case"ZodObject":return aK(Y,J);case"ZodBigInt":return SK(Y);case"ZodBoolean":return kK();case"ZodDate":return XG(Y,J);case"ZodUndefined":return GU();case"ZodNull":return iK();case"ZodArray":return IK(Y,J);case"ZodUnion":case"ZodDiscriminatedUnion":return nK(Y,J);case"ZodIntersection":return fK(Y,J);case"ZodTuple":return $U(Y,J);case"ZodRecord":return QG(Y,J);case"ZodLiteral":return mK(Y);case"ZodEnum":return gK(Y);case"ZodNativeEnum":return lK(Y);case"ZodNullable":return rK(Y,J);case"ZodOptional":return YU(Y,J);case"ZodMap":return pK(Y,J);case"ZodSet":return QU(Y,J);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return JU(Y,J);case"ZodNaN":case"ZodNever":return dK();case"ZodEffects":return hK(Y,J);case"ZodAny":return M0();case"ZodUnknown":return WU();case"ZodDefault":return vK(Y,J);case"ZodBranded":return YG(Y,J);case"ZodReadonly":return zU(Y,J);case"ZodCatch":return bK(Y,J);case"ZodPipeline":return XU(Y,J);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Q)=>{return})(X)}},UU=(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 l(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!==CK)return H}if($&&!J){let H=HU($,X);if(H!==void 0)return H}let G={def:Y,path:X.currentPath,jsonSchema:void 0};X.seen.set(Y,G);let W=KU(Y,Y.typeName,X),K=typeof W==="function"?l(W(),X):W;if(K)LU(Y,X,K);if(X.postProcess){let H=X.postProcess(K,Y,X);return G.jsonSchema=K,H}return G.jsonSchema=K,K}var HU=(Y,X)=>{switch(X.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:UU(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`),M0();return X.$refStrategy==="seen"?M0():void 0}}},LU=(Y,X,J)=>{if(Y.description)J.description=Y.description;return J},NU=(Y)=>{let X=_K(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}]))}},VU=(Y,X)=>{var J;let Q=NU(X),$=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((U,[N,O])=>{var B;return{...U,[N]:(B=l(O._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,N]},!0))!=null?B:M0()}},{}):void 0,G=typeof X==="string"?X:(X==null?void 0:X.nameStrategy)==="title"?void 0:X==null?void 0:X.name,W=(J=l(Y._def,G===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,G]},!1))!=null?J:M0(),K=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if(K!==void 0)W.title=K;let H=G===void 0?$?{...W,[Q.definitionPath]:$}:W:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,G].join("/"),[Q.definitionPath]:{...$,[G]:W}};return H.$schema="http://json-schema.org/draft-07/schema#",H},D9=Symbol.for("vercel.ai.schema");function dY(Y){let X;return()=>{if(X==null)X=Y();return X}}function iY(Y,{validate:X}={}){return{[D9]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:X}}function BU(Y){return typeof Y==="object"&&Y!==null&&D9 in Y&&Y[D9]===!0&&"jsonSchema"in Y&&"validate"in Y}function nY(Y){return Y==null?iY({type:"object",properties:{},additionalProperties:!1}):BU(Y)?Y:("~standard"in Y)?Y["~standard"].vendor==="zod"?e1(Y):ZU(Y):Y()}function ZU(Y){return iY(()=>{if(!OU(Y))throw Error(`Standard schema vendor '${Y["~standard"].vendor}' does not support JSON Schema conversion.`);return M9(Y["~standard"].jsonSchema.input({target:"draft-07"}))},{validate:async(X)=>{let J=await Y["~standard"].validate(X);return"value"in J?{success:!0,value:J.value}:{success:!1,error:new v0({value:X,cause:J.issues})}}})}function OU(Y){return Y["~standard"].jsonSchema!=null}function FU(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return iY(()=>VU(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 qU(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return iY(()=>M9(s7(Y,{target:"draft-7",io:"input",reused:Q?"ref":"inline"})),{validate:async($)=>{let G=await uY(Y,$);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function jU(Y){return"_zod"in Y}function e1(Y,X){if(jU(Y))return qU(Y,X);else return FU(Y,X)}async function YY({value:Y,schema:X,context:J}){let Q=nY(X);try{if(Q.validate==null)return{success:!0,value:Y,rawValue:Y};let $=await Q.validate(Y);if($.success)return{success:!0,value:$.value,rawValue:Y};return{success:!1,error:v0.wrap({value:Y,cause:$.error,context:J}),rawValue:Y}}catch($){return{success:!1,error:v0.wrap({value:Y,cause:$,context:J}),rawValue:Y}}}async function J1({text:Y,schema:X}){try{let J=TK(Y);if(X==null)return{success:!0,value:J,rawValue:J};return await YY({value:J,schema:X})}catch(J){return{success:!1,error:MY.isInstance(J)?J:new MY({text:Y,cause:J}),rawValue:void 0}}}async function A9(Y){if(typeof Y==="function")Y=Y();return Promise.resolve(Y)}var $G="AI_SerializationError",GG=`vercel.ai.error.${$G}`,DU=Symbol.for(GG),p$,l$,zO=class extends(l$=f,p$=DU,l$){constructor({message:Y="Failed to serialize value.",cause:X}={}){super({name:$G,message:Y,cause:X});this[p$]=!0}static isInstance(Y){return f.hasMarker(Y,GG)}};var EU=Object.defineProperty,MU=(Y,X)=>{for(var J in X)EU(Y,J,{get:X[J],enumerable:!0})},AU="AI_InvalidArgumentError",RU=`vercel.ai.error.${AU}`,TU=Symbol.for(RU),CU;CU=TU;var _U="AI_InvalidStreamPartError",IU=`vercel.ai.error.${_U}`,SU=Symbol.for(IU),kU;kU=SU;var bU="AI_InvalidToolApprovalError",xU=`vercel.ai.error.${bU}`,vU=Symbol.for(xU),hU;hU=vU;var gU="AI_InvalidToolApprovalSignatureError",yU=`vercel.ai.error.${gU}`,fU=Symbol.for(yU),mU;mU=fU;var cU="AI_InvalidToolInputError",uU=`vercel.ai.error.${cU}`,pU=Symbol.for(uU),lU;lU=pU;var dU="AI_ToolCallNotFoundForApprovalError",iU=`vercel.ai.error.${dU}`,nU=Symbol.for(iU),oU;oU=nU;var rU="AI_MissingToolResultsError",sU=`vercel.ai.error.${rU}`,aU=Symbol.for(sU),tU;tU=aU;var eU="AI_NoImageGeneratedError",YH=`vercel.ai.error.${eU}`,XH=Symbol.for(YH),JH;JH=XH;var WG="AI_NoObjectGeneratedError",zG=`vercel.ai.error.${WG}`,QH=Symbol.for(zG),KG,Q1=class extends f{constructor({message:Y="No object generated.",cause:X,text:J,response:Q,usage:$,finishReason:G}){super({name:WG,message:Y,cause:X});this[KG]=!0,this.text=J,this.response=Q,this.usage=$,this.finishReason=G}static isInstance(Y){return f.hasMarker(Y,zG)}};KG=QH;var $H="AI_NoOutputGeneratedError",GH=`vercel.ai.error.${$H}`,WH=Symbol.for(GH),zH;zH=WH;var KH="AI_NoSpeechGeneratedError",UH=`vercel.ai.error.${KH}`,HH=Symbol.for(UH),LH;LH=HH;var NH="AI_NoTranscriptGeneratedError",VH=`vercel.ai.error.${NH}`,BH=Symbol.for(VH),ZH;ZH=BH;var OH="AI_NoTranslationGeneratedError",FH=`vercel.ai.error.${OH}`,qH=Symbol.for(FH),jH;jH=qH;var DH="AI_NoVideoGeneratedError",PH=`vercel.ai.error.${DH}`,wH=Symbol.for(PH),EH;EH=wH;var MH="AI_NoSuchToolError",AH=`vercel.ai.error.${MH}`,RH=Symbol.for(AH),TH;TH=RH;var CH="AI_ToolCallRepairError",_H=`vercel.ai.error.${CH}`,IH=Symbol.for(_H),SH;SH=IH;var kH="AI_UIMessageStreamError",bH=`vercel.ai.error.${kH}`,xH=Symbol.for(bH),vH;vH=xH;var hH="AI_InvalidDataContentError",gH=`vercel.ai.error.${hH}`,yH=Symbol.for(gH),fH;fH=yH;var mH="AI_InvalidMessageRoleError",cH=`vercel.ai.error.${mH}`,uH=Symbol.for(cH),pH;pH=uH;var lH="AI_MessageConversionError",dH=`vercel.ai.error.${lH}`,iH=Symbol.for(dH),nH;nH=iH;var oH="AI_RetryError",rH=`vercel.ai.error.${oH}`,sH=Symbol.for(rH),aH;aH=sH;var tH="7.0.59",eH=async({url:Y,maxBytes:X,abortSignal:J})=>{var Q;let $=Y.toString();try{let G=k1({},`ai-sdk/${tH}`,t$()),W=await s$({url:$,headers:G,abortSignal:J});if(!W.ok)throw await lY(W),new F0({url:$,statusCode:W.status,statusText:W.statusText});return{data:await a$({response:W,url:$,maxBytes:X!=null?X:E9}),mediaType:(Q=W.headers.get("content-type"))!=null?Q:void 0}}catch(G){if(F0.isInstance(G))throw G;throw new F0({url:$,cause:G})}};var z={array:N9,boolean:w$,custom:x$,discriminatedUnion:C$,enum:B9,instanceof:v$,lazy:b$,literal:I$,looseObject:R$,never:L9,null:E$,number:P$,object:A$,record:_$,string:j$,union:V9,unknown:t1},F1=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),F1.optional()),z.array(F1)])),A=z.record(z.string(),z.record(z.string(),F1.optional())),JY=z.union([z.string(),z.instanceof(Uint8Array),z.instanceof(ArrayBuffer),z.custom(e$,{message:"Must be a Buffer"})]),R9=z.record(z.string(),z.string()),UG=z.object({type:z.literal("text"),text:z.string(),providerOptions:A.optional()}),YL=z.object({type:z.literal("image"),image:z.union([JY,z.instanceof(URL),R9]),mediaType:z.string().optional(),providerOptions:A.optional()}),HG=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:JY}),z.object({type:z.literal("url"),url:z.instanceof(URL)}),z.object({type:z.literal("reference"),reference:R9}),z.object({type:z.literal("text"),text:z.string()})]),XL=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:JY}),z.object({type:z.literal("url"),url:z.instanceof(URL)})]),LG=z.object({type:z.literal("file"),data:z.union([HG,JY,z.instanceof(URL),R9]),filename:z.string().optional(),mediaType:z.string(),providerOptions:A.optional()}),JL=z.object({type:z.literal("reasoning"),text:z.string(),providerOptions:A.optional()}),QL=z.object({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerOptions:A.optional()}),$L=z.object({type:z.literal("reasoning-file"),data:z.union([XL,JY,z.instanceof(URL)]),mediaType:z.string(),providerOptions:A.optional()}),GL=z.object({type:z.literal("tool-call"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerOptions:A.optional(),providerExecuted:z.boolean().optional()}),WL=z.discriminatedUnion("type",[z.object({type:z.literal("text"),value:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("json"),value:F1,providerOptions:A.optional()}),z.object({type:z.literal("execution-denied"),reason:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("error-text"),value:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("error-json"),value:F1,providerOptions:A.optional()}),z.object({type:z.literal("content"),value:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("file"),data:HG,mediaType:z.string(),filename:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("file-data"),data:z.string(),mediaType:z.string(),filename:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("file-url"),url:z.string(),mediaType:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:A.optional()}),z.object({type:z.literal("file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:A.optional()}),z.object({type:z.literal("image-data"),data:z.string(),mediaType:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("image-url"),url:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("image-file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:A.optional()}),z.object({type:z.literal("image-file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:A.optional()}),z.object({type:z.literal("custom"),providerOptions:A.optional()})]))})]),NG=z.object({type:z.literal("tool-result"),toolCallId:z.string(),toolName:z.string(),output:WL,providerOptions:A.optional()}),zL=z.object({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string()}),KL=z.object({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional()}),UL=z.object({role:z.literal("system"),content:z.string(),providerOptions:A.optional()}),HL=z.object({role:z.literal("user"),content:z.union([z.string(),z.array(z.union([UG,YL,LG]))]),providerOptions:A.optional()}),LL=z.object({role:z.literal("assistant"),content:z.union([z.string(),z.array(z.union([UG,QL,LG,JL,$L,GL,NG,zL]))]),providerOptions:A.optional()}),NL=z.object({role:z.literal("tool"),content:z.array(z.union([NG,KL])),providerOptions:A.optional()}),PO=z.union([UL,HL,LL,NL]);var VL={};MU(VL,{array:()=>FL,choice:()=>qL,json:()=>jL,object:()=>OL,text:()=>ZL});function BL(Y){let X=["ROOT"],J=-1,Q=null,$=0;function G(N){return N>="0"&&N<="9"||N>="A"&&N<="F"||N>="a"&&N<="f"}function W(N,O,B){switch(N){case'"':{J=O,X.pop(),X.push(B),X.push("INSIDE_STRING");break}case"f":case"t":case"n":{J=O,Q=O,X.pop(),X.push(B),X.push("INSIDE_LITERAL");break}case"-":{X.pop(),X.push(B),X.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=O,X.pop(),X.push(B),X.push("INSIDE_NUMBER");break}case"{":{J=O,X.pop(),X.push(B),X.push("INSIDE_OBJECT_START");break}case"[":{J=O,X.pop(),X.push(B),X.push("INSIDE_ARRAY_START");break}}}function K(N,O){switch(N){case",":{X.pop(),X.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{J=O,X.pop();break}}}function H(N,O){switch(N){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=O,X.pop();break}}}for(let N=0;N<Y.length;N++){let O=Y[N];switch(X[X.length-1]){case"ROOT":W(O,N,"FINISH");break;case"INSIDE_OBJECT_START":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}case"}":{J=N,X.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(O){case":":{X.pop(),X.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{W(O,N,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{K(O,N);break}case"INSIDE_STRING":{switch(O){case'"':{X.pop(),J=N;break}case"\\":{X.push("INSIDE_STRING_ESCAPE");break}default:J=N}break}case"INSIDE_ARRAY_START":{switch(O){case"]":{J=N,X.pop();break}default:{J=N,W(O,N,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(O){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=N,X.pop();break}default:{J=N;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{W(O,N,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{if(X.pop(),O==="u")$=0,X.push("INSIDE_STRING_UNICODE_ESCAPE");else J=N;break}case"INSIDE_STRING_UNICODE_ESCAPE":{if(G(O)){if($++,$===4)X.pop(),J=N}break}case"INSIDE_NUMBER":{switch(O){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=N;break}case"e":case"E":case"-":case".":break;case",":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")H(O,N);if(X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(O,N);break}case"}":{if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(O,N);break}case"]":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")H(O,N);break}default:{X.pop();break}}break}case"INSIDE_LITERAL":{let L=Y.substring(Q,N+1);if(!"false".startsWith(L)&&!"true".startsWith(L)&&!"null".startsWith(L)){if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(O,N);else if(X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")H(O,N)}else J=N;break}}}let U=Y.slice(0,J+1);for(let N=X.length-1;N>=0;N--)switch(X[N]){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 B=Y.substring(Q,Y.length);if("true".startsWith(B))U+="true".slice(B.length);else if("false".startsWith(B))U+="false".slice(B.length);else if("null".startsWith(B))U+="null".slice(B.length)}}return U}async function oY(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:BL(Y)}),X.success)return{value:X.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var ZL=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:Y}){return Y},async parsePartialOutput({text:Y}){return{partial:Y}},createElementStreamTransform(){return}}),OL=({schema:Y,name:X,description:J})=>{let Q=nY(Y);return{name:"object",responseFormat:A9(Q.jsonSchema).then(($)=>({type:"json",schema:$,...X!=null&&{name:X},...J!=null&&{description:J}})),async parseCompleteOutput({text:$},G){let W=await J1({text:$});if(!W.success)throw new Q1({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 YY({value:W.value,schema:Q});if(!K.success)throw new Q1({message:"No object generated: response did not match schema.",cause:K.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});return K.value},async parsePartialOutput({text:$}){let G=await oY($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:G.value}}},createElementStreamTransform(){return}}},FL=({element:Y,name:X,description:J})=>{let Q=nY(Y);return{name:"array",responseFormat:A9(Q.jsonSchema).then(($)=>{let{$schema:G,...W}=$;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:W}},required:["elements"],additionalProperties:!1},...X!=null&&{name:X},...J!=null&&{description:J}}}),async parseCompleteOutput({text:$},G){let W=await J1({text:$});if(!W.success)throw new Q1({message:"No object generated: could not parse the response.",cause:W.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let K=W.value;if(K==null||typeof K!=="object"||!("elements"in K)||!Array.isArray(K.elements))throw new Q1({message:"No object generated: response did not match schema.",cause:new v0({value:K,cause:"response must be an object with an elements array"}),text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let H=[];for(let U of K.elements){let N=await YY({value:U,schema:Q});if(!N.success)throw new Q1({message:"No object generated: response did not match schema.",cause:N.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});H.push(N.value)}return H},async parsePartialOutput({text:$}){let G=await oY($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let W=G.value;if(W==null||typeof W!=="object"||!("elements"in W)||!Array.isArray(W.elements))return;let K=G.state==="repaired-parse"&&W.elements.length>0?W.elements.slice(0,-1):W.elements,H=[];for(let U of K){let N=await YY({value:U,schema:Q});if(N.success)H.push(N.value)}return{partial:H}}}},createElementStreamTransform(){let $=0;return new TransformStream({transform({partialOutput:G},W){if(G!=null)for(;$<G.length;$++)W.enqueue(G[$])}})}}},qL=({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 Q1({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 Q1({message:"No object generated: response did not match schema.",cause:new v0({value:W,cause:"response must be an object that contains a choice value."}),text:Q,response:$.response,usage:$.usage,finishReason:$.finishReason});return W.result},async parsePartialOutput({text:Q}){let $=await oY(Q);switch($.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let G=$.value;if(G==null||typeof G!=="object"||!("result"in G)||typeof G.result!=="string")return;let W=Y.filter((K)=>K.startsWith(G.result));if($.state==="successful-parse")return W.includes(G.result)?{partial:G.result}:void 0;else return W.length===1?{partial:W[0]}:void 0}}},createElementStreamTransform(){return}}},jL=({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 Q1({message:"No object generated: could not parse the response.",cause:$.error,text:J,response:Q.response,usage:Q.usage,finishReason:Q.finishReason});return $.value},async parsePartialOutput({text:J}){let Q=await oY(J);switch(Q.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return Q.value===void 0?void 0:{partial:Q.value}}},createElementStreamTransform(){return}}};var AO=J0({prefix:"aitxt",size:24}),RO=J0({prefix:"call",size:24});var CO=class extends TransformStream{constructor(){super({transform(Y,X){X.enqueue(`data: ${JSON.stringify(Y)}
137
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let H of this.seen.entries()){let N=H[1];if(Y===H[0]){G(H);continue}if(J.external){let B=J.external.registry.get(H[0])?.id;if(Y!==H[0]&&B){G(H);continue}}if(this.metadataRegistry.get(H[0])?.id){G(H);continue}if(N.cycle){G(H);continue}if(N.count>1){if(J.reused==="ref"){G(H);continue}}}let W=(H,N)=>{let O=this.seen.get(H),B=O.def??O.schema,L={...B};if(O.ref===null)return;let Z=O.ref;if(O.ref=null,Z){W(Z,N);let j=this.seen.get(Z).schema;if(j.$ref&&(N.target==="draft-7"||N.target==="draft-4"||N.target==="openapi-3.0"))B.allOf=B.allOf??[],B.allOf.push(j);else Object.assign(B,j),Object.assign(B,L)}if(!O.isParent)this.override({zodSchema:H,jsonSchema:B,path:O.path??[]})};for(let H of[...this.seen.entries()].reverse())W(H[0],{target:this.target});let K={};if(this.target==="draft-2020-12")K.$schema="https://json-schema.org/draft/2020-12/schema";else if(this.target==="draft-7")K.$schema="http://json-schema.org/draft-07/schema#";else if(this.target==="draft-4")K.$schema="http://json-schema.org/draft-04/schema#";else if(this.target==="openapi-3.0");else console.warn(`Invalid target: ${this.target}`);if(J.external?.uri){let H=J.external.registry.get(Y)?.id;if(!H)throw Error("Schema is missing an `id` property");K.$id=J.external.uri(H)}Object.assign(K,Q.def);let U=J.external?.defs??{};for(let H of this.seen.entries()){let N=H[1];if(N.def&&N.defId)U[N.defId]=N.def}if(J.external);else if(Object.keys(U).length>0)if(this.target==="draft-2020-12")K.$defs=U;else K.definitions=U;try{return JSON.parse(JSON.stringify(K))}catch(H){throw Error("Error converting schema to JSON.")}}}function a7(Y,X){if(Y instanceof vY){let Q=new U9(X),$={};for(let K of Y._idmap.entries()){let[U,H]=K;Q.process(H)}let G={},W={registry:Y,uri:X?.uri,defs:$};for(let K of Y._idmap.entries()){let[U,H]=K;G[U]=Q.emit(H,{...X,external:W})}if(Object.keys($).length>0){let K=Q.target==="draft-2020-12"?"$defs":"definitions";G.__shared={[K]:$}}return{schemas:G}}let J=new U9(X);return J.process(Y),J.emit(Y,X)}function W0(Y,X){let J=X??{seen:new Set};if(J.seen.has(Y))return!1;J.seen.add(Y);let $=Y._zod.def;switch($.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return W0($.element,J);case"object":{for(let G in $.shape)if(W0($.shape[G],J))return!0;return!1}case"union":{for(let G of $.options)if(W0(G,J))return!0;return!1}case"intersection":return W0($.left,J)||W0($.right,J);case"tuple":{for(let G of $.items)if(W0(G,J))return!0;if($.rest&&W0($.rest,J))return!0;return!1}case"record":return W0($.keyType,J)||W0($.valueType,J);case"map":return W0($.keyType,J)||W0($.valueType,J);case"set":return W0($.valueType,J);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return W0($.innerType,J);case"lazy":return W0($.getter(),J);case"default":return W0($.innerType,J);case"prefault":return W0($.innerType,J);case"custom":return!1;case"transform":return!0;case"pipe":return W0($.in,J)||W0($.out,J);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${$.type}`)}var Lz=q("ZodISODateTime",(Y,X)=>{SQ.init(Y,X),s.init(Y,X)});function t7(Y){return g7(Lz,Y)}var Nz=q("ZodISODate",(Y,X)=>{kQ.init(Y,X),s.init(Y,X)});function e7(Y){return y7(Nz,Y)}var Vz=q("ZodISOTime",(Y,X)=>{bQ.init(Y,X),s.init(Y,X)});function Y$(Y){return f7(Vz,Y)}var Bz=q("ZodISODuration",(Y,X)=>{xQ.init(Y,X),s.init(Y,X)});function X$(Y){return m7(Bz,Y)}var J$=(Y,X)=>{CY.init(Y,X),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(J)=>L6(Y,J)},flatten:{value:(J)=>H6(Y,J)},addIssue:{value:(J)=>{Y.issues.push(J),Y.message=JSON.stringify(Y.issues,_1,2)}},addIssues:{value:(J)=>{Y.issues.push(...J),Y.message=JSON.stringify(Y.issues,_1,2)}},isEmpty:{get(){return Y.issues.length===0}}})},LZ=q("ZodError",J$),w0=q("ZodError",J$,{Parent:Error});var Q$=_Y(w0),$$=IY(w0),G$=o1(w0),uY=r1(w0),W$=B6(w0),z$=Z6(w0),K$=O6(w0),U$=F6(w0),H$=q6(w0),L$=j6(w0),N$=D6(w0),V$=P6(w0);var a=q("ZodType",(Y,X)=>{return n.init(Y,X),Y.def=X,Y.type=X.type,Object.defineProperty(Y,"_def",{value:X}),Y.check=(...J)=>{return Y.clone({...X,checks:[...X.checks??[],...J.map((Q)=>typeof Q==="function"?{_zod:{check:Q,def:{check:"custom"},onattach:[]}}:Q)]})},Y.clone=(J,Q)=>C0(Y,J,Q),Y.brand=()=>Y,Y.register=(J,Q)=>{return J.add(Y,Q),Y},Y.parse=(J,Q)=>Q$(Y,J,Q,{callee:Y.parse}),Y.safeParse=(J,Q)=>G$(Y,J,Q),Y.parseAsync=async(J,Q)=>$$(Y,J,Q,{callee:Y.parseAsync}),Y.safeParseAsync=async(J,Q)=>uY(Y,J,Q),Y.spa=Y.safeParseAsync,Y.encode=(J,Q)=>W$(Y,J,Q),Y.decode=(J,Q)=>z$(Y,J,Q),Y.encodeAsync=async(J,Q)=>K$(Y,J,Q),Y.decodeAsync=async(J,Q)=>U$(Y,J,Q),Y.safeEncode=(J,Q)=>H$(Y,J,Q),Y.safeDecode=(J,Q)=>L$(Y,J,Q),Y.safeEncodeAsync=async(J,Q)=>N$(Y,J,Q),Y.safeDecodeAsync=async(J,Q)=>V$(Y,J,Q),Y.refine=(J,Q)=>Y.check(zK(J,Q)),Y.superRefine=(J)=>Y.check(KK(J)),Y.overwrite=(J)=>Y.check(O1(J)),Y.optional=()=>O$(Y),Y.nullable=()=>F$(Y),Y.nullish=()=>O$(F$(Y)),Y.nonoptional=(J)=>YK(Y,J),Y.array=()=>N9(Y),Y.or=(J)=>V9([Y,J]),Y.and=(J)=>lz(Y,J),Y.transform=(J)=>q$(Y,oz(J)),Y.default=(J)=>az(Y,J),Y.prefault=(J)=>ez(Y,J),Y.catch=(J)=>JK(Y,J),Y.pipe=(J)=>q$(Y,J),Y.readonly=()=>GK(Y),Y.describe=(J)=>{let Q=Y.clone();return Z1.add(Q,{description:J}),Q},Object.defineProperty(Y,"description",{get(){return Z1.get(Y)?.description},configurable:!0}),Y.meta=(...J)=>{if(J.length===0)return Z1.get(Y);let Q=Y.clone();return Z1.add(Q,J[0]),Q},Y.isOptional=()=>Y.safeParse(void 0).success,Y.isNullable=()=>Y.safeParse(null).success,Y}),j$=q("_ZodString",(Y,X)=>{xY.init(Y,X),a.init(Y,X);let J=Y._zod.bag;Y.format=J.format??null,Y.minLength=J.minimum??null,Y.maxLength=J.maximum??null,Y.regex=(...Q)=>Y.check(e8(...Q)),Y.includes=(...Q)=>Y.check(J9(...Q)),Y.startsWith=(...Q)=>Y.check(Q9(...Q)),Y.endsWith=(...Q)=>Y.check($9(...Q)),Y.min=(...Q)=>Y.check(k1(...Q)),Y.max=(...Q)=>Y.check(fY(...Q)),Y.length=(...Q)=>Y.check(mY(...Q)),Y.nonempty=(...Q)=>Y.check(k1(1,...Q)),Y.lowercase=(Q)=>Y.check(Y9(Q)),Y.uppercase=(Q)=>Y.check(X9(Q)),Y.trim=()=>Y.check(W9()),Y.normalize=(...Q)=>Y.check(G9(...Q)),Y.toLowerCase=()=>Y.check(z9()),Y.toUpperCase=()=>Y.check(K9())}),qz=q("ZodString",(Y,X)=>{xY.init(Y,X),j$.init(Y,X),Y.email=(J)=>Y.check(O7(jz,J)),Y.url=(J)=>Y.check(P7(Dz,J)),Y.jwt=(J)=>Y.check(h7(vz,J)),Y.emoji=(J)=>Y.check(w7(Pz,J)),Y.guid=(J)=>Y.check(t8(B$,J)),Y.uuid=(J)=>Y.check(F7(pY,J)),Y.uuidv4=(J)=>Y.check(q7(pY,J)),Y.uuidv6=(J)=>Y.check(j7(pY,J)),Y.uuidv7=(J)=>Y.check(D7(pY,J)),Y.nanoid=(J)=>Y.check(E7(wz,J)),Y.guid=(J)=>Y.check(t8(B$,J)),Y.cuid=(J)=>Y.check(M7(Ez,J)),Y.cuid2=(J)=>Y.check(A7(Mz,J)),Y.ulid=(J)=>Y.check(R7(Az,J)),Y.base64=(J)=>Y.check(b7(kz,J)),Y.base64url=(J)=>Y.check(x7(bz,J)),Y.xid=(J)=>Y.check(T7(Rz,J)),Y.ksuid=(J)=>Y.check(C7(Tz,J)),Y.ipv4=(J)=>Y.check(_7(Cz,J)),Y.ipv6=(J)=>Y.check(I7(_z,J)),Y.cidrv4=(J)=>Y.check(S7(Iz,J)),Y.cidrv6=(J)=>Y.check(k7(Sz,J)),Y.e164=(J)=>Y.check(v7(xz,J)),Y.datetime=(J)=>Y.check(t7(J)),Y.date=(J)=>Y.check(e7(J)),Y.time=(J)=>Y.check(Y$(J)),Y.duration=(J)=>Y.check(X$(J))});function D$(Y){return Z7(qz,Y)}var s=q("ZodStringFormat",(Y,X)=>{r.init(Y,X),j$.init(Y,X)}),jz=q("ZodEmail",(Y,X)=>{wQ.init(Y,X),s.init(Y,X)});var B$=q("ZodGUID",(Y,X)=>{DQ.init(Y,X),s.init(Y,X)});var pY=q("ZodUUID",(Y,X)=>{PQ.init(Y,X),s.init(Y,X)});var Dz=q("ZodURL",(Y,X)=>{EQ.init(Y,X),s.init(Y,X)});var Pz=q("ZodEmoji",(Y,X)=>{MQ.init(Y,X),s.init(Y,X)});var wz=q("ZodNanoID",(Y,X)=>{AQ.init(Y,X),s.init(Y,X)});var Ez=q("ZodCUID",(Y,X)=>{RQ.init(Y,X),s.init(Y,X)});var Mz=q("ZodCUID2",(Y,X)=>{TQ.init(Y,X),s.init(Y,X)});var Az=q("ZodULID",(Y,X)=>{CQ.init(Y,X),s.init(Y,X)});var Rz=q("ZodXID",(Y,X)=>{_Q.init(Y,X),s.init(Y,X)});var Tz=q("ZodKSUID",(Y,X)=>{IQ.init(Y,X),s.init(Y,X)});var Cz=q("ZodIPv4",(Y,X)=>{vQ.init(Y,X),s.init(Y,X)});var _z=q("ZodIPv6",(Y,X)=>{hQ.init(Y,X),s.init(Y,X)});var Iz=q("ZodCIDRv4",(Y,X)=>{gQ.init(Y,X),s.init(Y,X)});var Sz=q("ZodCIDRv6",(Y,X)=>{yQ.init(Y,X),s.init(Y,X)});var kz=q("ZodBase64",(Y,X)=>{mQ.init(Y,X),s.init(Y,X)});var bz=q("ZodBase64URL",(Y,X)=>{cQ.init(Y,X),s.init(Y,X)});var xz=q("ZodE164",(Y,X)=>{uQ.init(Y,X),s.init(Y,X)});var vz=q("ZodJWT",(Y,X)=>{pQ.init(Y,X),s.init(Y,X)});var P$=q("ZodNumber",(Y,X)=>{s8.init(Y,X),a.init(Y,X),Y.gt=(Q,$)=>Y.check(gY(Q,$)),Y.gte=(Q,$)=>Y.check(t1(Q,$)),Y.min=(Q,$)=>Y.check(t1(Q,$)),Y.lt=(Q,$)=>Y.check(hY(Q,$)),Y.lte=(Q,$)=>Y.check(a1(Q,$)),Y.max=(Q,$)=>Y.check(a1(Q,$)),Y.int=(Q)=>Y.check(Z$(Q)),Y.safe=(Q)=>Y.check(Z$(Q)),Y.positive=(Q)=>Y.check(gY(0,Q)),Y.nonnegative=(Q)=>Y.check(t1(0,Q)),Y.negative=(Q)=>Y.check(hY(0,Q)),Y.nonpositive=(Q)=>Y.check(a1(0,Q)),Y.multipleOf=(Q,$)=>Y.check(yY(Q,$)),Y.step=(Q,$)=>Y.check(yY(Q,$)),Y.finite=()=>Y;let J=Y._zod.bag;Y.minValue=Math.max(J.minimum??Number.NEGATIVE_INFINITY,J.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Y.maxValue=Math.min(J.maximum??Number.POSITIVE_INFINITY,J.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Y.isInt=(J.format??"").includes("int")||Number.isSafeInteger(J.multipleOf??0.5),Y.isFinite=!0,Y.format=J.format??null});function w$(Y){return c7(P$,Y)}var hz=q("ZodNumberFormat",(Y,X)=>{lQ.init(Y,X),P$.init(Y,X)});function Z$(Y){return u7(hz,Y)}var gz=q("ZodBoolean",(Y,X)=>{dQ.init(Y,X),a.init(Y,X)});function E$(Y){return p7(gz,Y)}var yz=q("ZodNull",(Y,X)=>{iQ.init(Y,X),a.init(Y,X)});function M$(Y){return l7(yz,Y)}var fz=q("ZodUnknown",(Y,X)=>{nQ.init(Y,X),a.init(Y,X)});function e1(){return d7(fz)}var mz=q("ZodNever",(Y,X)=>{oQ.init(Y,X),a.init(Y,X)});function L9(Y){return i7(mz,Y)}var cz=q("ZodArray",(Y,X)=>{rQ.init(Y,X),a.init(Y,X),Y.element=X.element,Y.min=(J,Q)=>Y.check(k1(J,Q)),Y.nonempty=(J)=>Y.check(k1(1,J)),Y.max=(J,Q)=>Y.check(fY(J,Q)),Y.length=(J,Q)=>Y.check(mY(J,Q)),Y.unwrap=()=>Y.element});function N9(Y,X){return n7(cz,Y,X)}var A$=q("ZodObject",(Y,X)=>{tQ.init(Y,X),a.init(Y,X),c.defineLazy(Y,"shape",()=>X.shape),Y.keyof=()=>B9(Object.keys(Y._zod.def.shape)),Y.catchall=(J)=>Y.clone({...Y._zod.def,catchall:J}),Y.passthrough=()=>Y.clone({...Y._zod.def,catchall:e1()}),Y.loose=()=>Y.clone({...Y._zod.def,catchall:e1()}),Y.strict=()=>Y.clone({...Y._zod.def,catchall:L9()}),Y.strip=()=>Y.clone({...Y._zod.def,catchall:void 0}),Y.extend=(J)=>{return c.extend(Y,J)},Y.safeExtend=(J)=>{return c.safeExtend(Y,J)},Y.merge=(J)=>c.merge(Y,J),Y.pick=(J)=>c.pick(Y,J),Y.omit=(J)=>c.omit(Y,J),Y.partial=(...J)=>c.partial(k$,Y,J[0]),Y.required=(...J)=>c.required(b$,Y,J[0])});function R$(Y,X){let J={type:"object",get shape(){return c.assignProp(this,"shape",Y?c.objectClone(Y):{}),this.shape},...c.normalizeParams(X)};return new A$(J)}function T$(Y,X){return new A$({type:"object",get shape(){return c.assignProp(this,"shape",c.objectClone(Y)),this.shape},catchall:e1(),...c.normalizeParams(X)})}var C$=q("ZodUnion",(Y,X)=>{a8.init(Y,X),a.init(Y,X),Y.options=X.options});function V9(Y,X){return new C$({type:"union",options:Y,...c.normalizeParams(X)})}var uz=q("ZodDiscriminatedUnion",(Y,X)=>{C$.init(Y,X),eQ.init(Y,X)});function _$(Y,X,J){return new uz({type:"union",options:X,discriminator:Y,...c.normalizeParams(J)})}var pz=q("ZodIntersection",(Y,X)=>{Y7.init(Y,X),a.init(Y,X)});function lz(Y,X){return new pz({type:"intersection",left:Y,right:X})}var dz=q("ZodRecord",(Y,X)=>{X7.init(Y,X),a.init(Y,X),Y.keyType=X.keyType,Y.valueType=X.valueType});function I$(Y,X,J){return new dz({type:"record",keyType:Y,valueType:X,...c.normalizeParams(J)})}var H9=q("ZodEnum",(Y,X)=>{J7.init(Y,X),a.init(Y,X),Y.enum=X.entries,Y.options=Object.values(X.entries);let J=new Set(Object.keys(X.entries));Y.extract=(Q,$)=>{let G={};for(let W of Q)if(J.has(W))G[W]=X.entries[W];else throw Error(`Key ${W} not found in enum`);return new H9({...X,checks:[],...c.normalizeParams($),entries:G})},Y.exclude=(Q,$)=>{let G={...X.entries};for(let W of Q)if(J.has(W))delete G[W];else throw Error(`Key ${W} not found in enum`);return new H9({...X,checks:[],...c.normalizeParams($),entries:G})}});function B9(Y,X){let J=Array.isArray(Y)?Object.fromEntries(Y.map((Q)=>[Q,Q])):Y;return new H9({type:"enum",entries:J,...c.normalizeParams(X)})}var iz=q("ZodLiteral",(Y,X)=>{Q7.init(Y,X),a.init(Y,X),Y.values=new Set(X.values),Object.defineProperty(Y,"value",{get(){if(X.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return X.values[0]}})});function S$(Y,X){return new iz({type:"literal",values:Array.isArray(Y)?Y:[Y],...c.normalizeParams(X)})}var nz=q("ZodTransform",(Y,X)=>{$7.init(Y,X),a.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new u1(Y.constructor.name);J.addIssue=(G)=>{if(typeof G==="string")J.issues.push(c.issue(G,J.value,X));else{let W=G;if(W.fatal)W.continue=!1;W.code??(W.code="custom"),W.input??(W.input=J.value),W.inst??(W.inst=Y),J.issues.push(c.issue(W))}};let $=X.transform(J.value,J);if($ instanceof Promise)return $.then((G)=>{return J.value=G,J});return J.value=$,J}});function oz(Y){return new nz({type:"transform",transform:Y})}var k$=q("ZodOptional",(Y,X)=>{G7.init(Y,X),a.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function O$(Y){return new k$({type:"optional",innerType:Y})}var rz=q("ZodNullable",(Y,X)=>{W7.init(Y,X),a.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function F$(Y){return new rz({type:"nullable",innerType:Y})}var sz=q("ZodDefault",(Y,X)=>{z7.init(Y,X),a.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function az(Y,X){return new sz({type:"default",innerType:Y,get defaultValue(){return typeof X==="function"?X():c.shallowClone(X)}})}var tz=q("ZodPrefault",(Y,X)=>{K7.init(Y,X),a.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function ez(Y,X){return new tz({type:"prefault",innerType:Y,get defaultValue(){return typeof X==="function"?X():c.shallowClone(X)}})}var b$=q("ZodNonOptional",(Y,X)=>{U7.init(Y,X),a.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function YK(Y,X){return new b$({type:"nonoptional",innerType:Y,...c.normalizeParams(X)})}var XK=q("ZodCatch",(Y,X)=>{H7.init(Y,X),a.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function JK(Y,X){return new XK({type:"catch",innerType:Y,catchValue:typeof X==="function"?X:()=>X})}var QK=q("ZodPipe",(Y,X)=>{L7.init(Y,X),a.init(Y,X),Y.in=X.in,Y.out=X.out});function q$(Y,X){return new QK({type:"pipe",in:Y,out:X})}var $K=q("ZodReadonly",(Y,X)=>{N7.init(Y,X),a.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function GK(Y){return new $K({type:"readonly",innerType:Y})}var WK=q("ZodLazy",(Y,X)=>{V7.init(Y,X),a.init(Y,X),Y.unwrap=()=>Y._zod.def.getter()});function x$(Y){return new WK({type:"lazy",getter:Y})}var Z9=q("ZodCustom",(Y,X)=>{B7.init(Y,X),a.init(Y,X)});function v$(Y,X){return o7(Z9,Y??(()=>!0),X)}function zK(Y,X={}){return r7(Z9,Y,X)}function KK(Y){return s7(Y)}function h$(Y,X={error:`Input not instance of ${Y.name}`}){let J=new Z9({type:"custom",check:"custom",fn:(Q)=>Q instanceof Y,abort:!0,...c.normalizeParams(X)});return J._zod.bag.Class=Y,J}var UK=[{mediaType:"audio/mpeg",bytesPrefix:[255,251]},{mediaType:"audio/mpeg",bytesPrefix:[255,250]},{mediaType:"audio/mpeg",bytesPrefix:[255,243]},{mediaType:"audio/mpeg",bytesPrefix:[255,242]},{mediaType:"audio/mpeg",bytesPrefix:[255,227]},{mediaType:"audio/mpeg",bytesPrefix:[255,226]},{mediaType:"audio/wav",bytesPrefix:[82,73,70,70,null,null,null,null,87,65,86,69]},{mediaType:"audio/ogg",bytesPrefix:[79,103,103,83]},{mediaType:"audio/flac",bytesPrefix:[102,76,97,67]},{mediaType:"audio/aac",bytesPrefix:[64,21,0,0]},{mediaType:"audio/webm",bytesPrefix:[26,69,223,163]}],tZ=[...UK,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];var HK=12,LK=131072,eZ=LK+HK;async function lY(Y){var X;try{await((X=Y.body)==null?void 0:X.cancel())}catch(J){}}var i$="AI_DownloadError",n$=`vercel.ai.error.${i$}`,NK=Symbol.for(n$),g$,y$,O0=class extends(y$=f,g$=NK,y$){constructor({url:Y,statusCode:X,statusText:J,cause:Q,message:$=Q==null?`Failed to download ${Y}: ${X} ${J}`:`Failed to download ${Y}: ${Q}`}){super({name:i$,message:$,cause:Q});this[g$]=!0,this.url=Y,this.statusCode=X,this.statusText=J}static isInstance(Y){return f.hasMarker(Y,n$)}};function VK(Y=globalThis){return Y.window!=null}function f$(Y,X){try{return new URL(Y).origin===new URL(X).origin}catch(J){return!1}}function BK(Y){let X;try{X=new URL(Y)}catch(Q){throw new O0({url:Y,message:`Invalid URL: ${Y}`})}if(X.protocol==="data:")return;if(X.protocol!=="http:"&&X.protocol!=="https:")throw new O0({url:Y,message:`URL scheme must be http, https, or data, got ${X.protocol}`});let J=X.hostname.toLowerCase().replace(/\.+$/,"");if(!J)throw new O0({url:Y,message:"URL must have a hostname"});if(J==="localhost"||J.endsWith(".local")||J.endsWith(".localhost"))throw new O0({url:Y,message:`URL with hostname ${J} is not allowed`});if(J.startsWith("[")&&J.endsWith("]")){let Q=J.slice(1,-1);if(o$(Q))throw new O0({url:Y,message:`URL with IPv6 address ${J} is not allowed`});return}if(P9(J)){if(w9(J))throw new O0({url:Y,message:`URL with IP address ${J} is not allowed`});return}}function ZK({address:Y,family:X,hostname:J}){if(X===4?!P9(Y)||w9(Y):X===6?o$(Y):!0)throw new O0({url:J,message:`Hostname ${J} resolved to disallowed IP address ${Y}`})}function P9(Y){let X=Y.split(".");if(X.length!==4)return!1;return X.every((J)=>{let Q=Number(J);return Number.isInteger(Q)&&Q>=0&&Q<=255&&String(Q)===J})}function w9(Y){let X=Y.split(".").map(Number),[J,Q,$]=X;if(J===0)return!0;if(J===10)return!0;if(J===100&&Q>=64&&Q<=127)return!0;if(J===127)return!0;if(J===169&&Q===254)return!0;if(J===172&&Q>=16&&Q<=31)return!0;if(J===192&&Q===0&&$===0)return!0;if(J===192&&Q===0&&$===2)return!0;if(J===192&&Q===168)return!0;if(J===198&&(Q===18||Q===19))return!0;if(J===198&&Q===51&&$===100)return!0;if(J===203&&Q===0&&$===113)return!0;if(J>=224)return!0;return!1}function OK(Y){let X=Y.toLowerCase(),J=X.indexOf("%");if(J!==-1)X=X.slice(0,J);let Q=X.split("::");if(Q.length>2)return null;let $=(W)=>{if(W==="")return[];let K=[],U=W.split(":");for(let H=0;H<U.length;H++){let N=U[H];if(N.includes(".")){if(H!==U.length-1||!P9(N))return null;let[O,B,L,Z]=N.split(".").map(Number);K.push(O<<8|B,L<<8|Z);continue}if(!/^[0-9a-f]{1,4}$/.test(N))return null;K.push(parseInt(N,16))}return K},G=$(Q[0]);if(G===null)return null;if(Q.length===2){let W=$(Q[1]);if(W===null)return null;let K=8-G.length-W.length;if(K<0)return null;return[...G,...Array(K).fill(0),...W]}return G.length===8?G:null}function o$(Y){let X=OK(Y);if(X===null)return!0;let J=($)=>X.slice(0,$).every((G)=>G===0);if(J(7)&&(X[7]===0||X[7]===1))return!0;if((X[0]&65024)===64512)return!0;if((X[0]&65472)===65152)return!0;if((X[0]&65472)===65216)return!0;if((X[0]&65280)===65280)return!0;if(X[0]===8193&&X[1]===3512)return!0;if(X[0]===16383&&(X[1]&61440)===0)return!0;if(J(6)||J(5)&&X[5]===65535||J(4)&&X[4]===65535&&X[5]===0||X[0]===100&&X[1]===65435&&X[2]===0&&X[3]===0&&X[4]===0&&X[5]===0||X[0]===100&&X[1]===65435&&X[2]===1){let $=X[6]>>8&255,G=X[6]&255,W=X[7]>>8&255,K=X[7]&255;return w9(`${$}.${G}.${W}.${K}`)}return!1}function FK(Y){return(X,J,Q)=>{Y(X,{...J,all:!0},($,G)=>{if($){Q($);return}try{let[W]=G;if(W==null)throw Error(`Hostname ${X} did not resolve to an address`);for(let{address:K,family:U}of G)ZK({address:K,family:U,hostname:X});if(J.all===!0)Q(null,G);else Q(null,W.address,W.family)}catch(W){Q(W instanceof Error?W:Error(String(W)))}})}}var O9,r$=globalThis.fetch,qK=PK(r$);function jK(){var Y,X;let J=globalThis.process;return((Y=J==null?void 0:J.release)==null?void 0:Y.name)==="node"&&((X=J.versions)==null?void 0:X.bun)==null}async function DK(){if(!jK()||!qK||globalThis.fetch!==r$)return globalThis.fetch;return O9!=null?O9:O9=Promise.resolve().then(wK)}function PK(Y){if(typeof Y!=="function")return!1;let X=Function.prototype.toString.call(Y);return X.includes("internal/deps/undici")||X.includes("lazy loading of undici")}function wK(){let{createRequire:Y}=m$("node:module"),{lookup:X}=m$("node:dns"),{Agent:J,fetch:Q}=Y(s$())("undici"),$=new J({connect:{lookup:FK(X)}});return(G,W)=>Q(G,{...W,dispatcher:$})}function m$(Y){var X;let J=globalThis.process,Q=(X=J==null?void 0:J.getBuiltinModule)==null?void 0:X.call(J,Y);if(Q==null)throw Error(`Node.js built-in module ${Y} is unavailable`);return Q}function s$(){let Y=Error.prepareStackTrace;try{Error.prepareStackTrace=($,G)=>G;let X=Error("Capture current module path");Error.captureStackTrace(X,s$);let[J]=X.stack,Q=J==null?void 0:J.getFileName();if(Q==null)throw Error("Unable to determine the current module path");return Q}finally{Error.prepareStackTrace=Y}}var EK=["connection","keep-alive","te","trailer","transfer-encoding","upgrade","host","forwarded","proxy-authorization","via","x-forwarded-for","x-forwarded-host","x-forwarded-proto","x-real-ip","metadata","metadata-flavor","x-aws-ec2-metadata-token","x-metadata-token","cookie","set-cookie"];function MK(Y){let X=new Headers(Y);for(let J of EK)X.delete(J);return X}var AK=10,RK=new Set([301,302,303,307,308]);async function a$({url:Y,headers:X,abortSignal:J,maxRedirects:Q=AK,fetch:$,trustedOrigin:G}){let W=X===void 0?void 0:MK(X),K=(H)=>{let N={signal:J,redirect:H};if(W!==void 0)N.headers=new Headers(W);return N},U=Y;for(let H=0;H<=Q;H++){let N=G!==void 0&&f$(U,G);if(!N)BK(U);let O=$!=null?$:N?globalThis.fetch:await DK(),B=await O(U,K("manual"));if(B.type==="opaqueredirect"){if(!VK())throw new O0({url:Y,message:`Redirect from ${U} could not be validated and was blocked`});return await O(U,K("follow"))}let L=B.headers.get("location");if(RK.has(B.status)&&L){await lY(B);let Z=new URL(L,U).toString();if(W!==void 0&&!f$(Z,U)){let j=W.get("user-agent");W=new Headers(j==null?void 0:{"user-agent":j})}U=Z;continue}return B}throw new O0({url:Y,message:`Too many redirects (max ${Q})`})}var E9=2147483648;async function t$({response:Y,url:X,maxBytes:J=E9}){let Q=Y.headers.get("content-length");if(Q!=null){let N=parseInt(Q,10);if(!isNaN(N)&&N>J)throw await lY(Y),new O0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes (Content-Length: ${N}).`})}let $=Y.body;if($==null)return new Uint8Array(0);let G=$.getReader(),W=[],K=0;try{while(!0){let{done:N,value:O}=await G.read();if(N)break;if(K+=O.length,K>J)throw new O0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes.`});W.push(O)}}finally{try{await G.cancel()}finally{G.releaseLock()}}let U=new Uint8Array(K),H=0;for(let N of W)U.set(N,H),H+=N.length;return U}var Q0=({prefix:Y,size:X=16,alphabet:J="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:Q="-"}={})=>{let $=()=>{let G=J.length,W=Array(X);for(let K=0;K<X;K++)W[K]=J[Math.random()*G|0];return W.join("")};if(Y==null)return $;if(J.includes(Q))throw new SJ({argument:"separator",message:`The separator "${Q}" must not be part of the alphabet "${J}".`});return()=>`${Y}${Q}${$()}`},JO=Q0();function e$(Y=globalThis){var X,J,Q;if(Y.window)return"runtime/browser";if((X=Y.navigator)==null?void 0:X.userAgent)return`runtime/${Y.navigator.userAgent.toLowerCase()}`;if((Q=(J=Y.process)==null?void 0:J.versions)==null?void 0:Q.node)return`runtime/node.js/${Y.process.version.substring(0)}`;if(Y.EdgeRuntime)return"runtime/vercel-edge";return"runtime/unknown"}function TK(Y){if(Y==null)return{};let X={};if(Y instanceof Headers)Y.forEach((J,Q)=>{X[Q.toLowerCase()]=J});else{if(!Array.isArray(Y))Y=Object.entries(Y);for(let[J,Q]of Y)if(Q!=null)X[J.toLowerCase()]=Q}return X}function b1(Y,...X){let J=new Headers(TK(Y)),Q=J.get("user-agent")||"";return J.set("user-agent",[Q,...X].filter(Boolean).join(" ")),Object.fromEntries(J.entries())}function YG(Y){var X,J;return(J=(X=globalThis.Buffer)==null?void 0:X.isBuffer(Y))!=null?J:!1}var CK=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,_K=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function c$(Y){let X=JSON.parse(Y);if(X===null||typeof X!=="object")return X;if(CK.test(Y)===!1&&_K.test(Y)===!1)return X;return IK(X)}function IK(Y){let X=[Y];while(X.length){let J=X;X=[];for(let Q of J){if(Object.prototype.hasOwnProperty.call(Q,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(Q,"constructor")&&Q.constructor!==null&&typeof Q.constructor==="object"&&Object.prototype.hasOwnProperty.call(Q.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let $ in Q){let G=Q[$];if(G&&typeof G==="object")X.push(G)}}}return Y}function SK(Y){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(J){return c$(Y)}try{return c$(Y)}finally{Error.stackTraceLimit=X}}function M9(Y){if(Y.type==="object"||Array.isArray(Y.type)&&Y.type.includes("object")){Y.additionalProperties=!1;let{properties:J}=Y;if(J!=null)for(let Q of Object.keys(J))J[Q]=F1(J[Q])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(F1):F1(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(F1);if(Y.allOf!=null)Y.allOf=Y.allOf.map(F1);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(F1);let{definitions:X}=Y;if(X!=null)for(let J of Object.keys(X))X[J]=F1(X[J]);return Y}function F1(Y){if(typeof Y==="boolean")return Y;return M9(Y)}var kK=Symbol("Let zodToJsonSchema decide on which parser to use"),u$={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},bK=(Y)=>typeof Y==="string"?{...u$,name:Y}:{...u$,...Y};function E0(){return{}}function xK(Y,X){var J,Q,$;let G={type:"array"};if(((J=Y.type)==null?void 0:J._def)&&(($=(Q=Y.type)==null?void 0:Q._def)==null?void 0:$.typeName)!=="ZodAny")G.items=i(Y.type._def,{...X,currentPath:[...X.currentPath,"items"]});if(Y.minLength)G.minItems=Y.minLength.value;if(Y.maxLength)G.maxItems=Y.maxLength.value;if(Y.exactLength)G.minItems=Y.exactLength.value,G.maxItems=Y.exactLength.value;return G}function vK(Y){let X={type:"integer",format:"int64"};if(!Y.checks)return X;for(let J of Y.checks)switch(J.kind){case"min":if(J.inclusive)X.minimum=J.value;else X.exclusiveMinimum=J.value;break;case"max":if(J.inclusive)X.maximum=J.value;else X.exclusiveMaximum=J.value;break;case"multipleOf":X.multipleOf=J.value;break}return X}function hK(){return{type:"boolean"}}function XG(Y,X){return i(Y.type._def,X)}var gK=(Y,X)=>{return i(Y.innerType._def,X)};function JG(Y,X,J){let Q=J!=null?J:X.dateStrategy;if(Array.isArray(Q))return{anyOf:Q.map(($)=>JG(Y,X,$))};switch(Q){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return yK(Y)}}var yK=(Y)=>{let X={type:"integer",format:"unix-time"};for(let J of Y.checks)switch(J.kind){case"min":X.minimum=J.value;break;case"max":X.maximum=J.value;break}return X};function fK(Y,X){return{...i(Y.innerType._def,X),default:Y.defaultValue()}}function mK(Y,X){return X.effectStrategy==="input"?i(Y.schema._def,X):E0()}function cK(Y){return{type:"string",enum:Array.from(Y.values)}}var uK=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function pK(Y,X){let J=[i(Y.left._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),i(Y.right._def,{...X,currentPath:[...X.currentPath,"allOf","1"]})].filter(($)=>!!$),Q=[];return J.forEach(($)=>{if(uK($))Q.push(...$.allOf);else{let G=$;if("additionalProperties"in $&&$.additionalProperties===!1){let{additionalProperties:W,...K}=$;G=K}Q.push(G)}}),Q.length?{allOf:Q}:void 0}function lK(Y){let X=typeof Y.value;if(X!=="bigint"&&X!=="number"&&X!=="boolean"&&X!=="string")return{type:Array.isArray(Y.value)?"array":"object"};return{type:X==="bigint"?"integer":X,const:Y.value}}var F9=void 0,I0={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(F9===void 0)F9=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return F9},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function QG(Y,X){let J={type:"string"};if(Y.checks)for(let Q of Y.checks)switch(Q.kind){case"min":J.minLength=typeof J.minLength==="number"?Math.max(J.minLength,Q.value):Q.value;break;case"max":J.maxLength=typeof J.maxLength==="number"?Math.min(J.maxLength,Q.value):Q.value;break;case"email":switch(X.emailStrategy){case"format:email":S0(J,"email",Q.message,X);break;case"format:idn-email":S0(J,"idn-email",Q.message,X);break;case"pattern:zod":Z0(J,I0.email,Q.message,X);break}break;case"url":S0(J,"uri",Q.message,X);break;case"uuid":S0(J,"uuid",Q.message,X);break;case"regex":Z0(J,Q.regex,Q.message,X);break;case"cuid":Z0(J,I0.cuid,Q.message,X);break;case"cuid2":Z0(J,I0.cuid2,Q.message,X);break;case"startsWith":Z0(J,RegExp(`^${q9(Q.value,X)}`),Q.message,X);break;case"endsWith":Z0(J,RegExp(`${q9(Q.value,X)}$`),Q.message,X);break;case"datetime":S0(J,"date-time",Q.message,X);break;case"date":S0(J,"date",Q.message,X);break;case"time":S0(J,"time",Q.message,X);break;case"duration":S0(J,"duration",Q.message,X);break;case"length":J.minLength=typeof J.minLength==="number"?Math.max(J.minLength,Q.value):Q.value,J.maxLength=typeof J.maxLength==="number"?Math.min(J.maxLength,Q.value):Q.value;break;case"includes":{Z0(J,RegExp(q9(Q.value,X)),Q.message,X);break}case"ip":{if(Q.version!=="v6")S0(J,"ipv4",Q.message,X);if(Q.version!=="v4")S0(J,"ipv6",Q.message,X);break}case"base64url":Z0(J,I0.base64url,Q.message,X);break;case"jwt":Z0(J,I0.jwt,Q.message,X);break;case"cidr":{if(Q.version!=="v6")Z0(J,I0.ipv4Cidr,Q.message,X);if(Q.version!=="v4")Z0(J,I0.ipv6Cidr,Q.message,X);break}case"emoji":Z0(J,I0.emoji(),Q.message,X);break;case"ulid":{Z0(J,I0.ulid,Q.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{S0(J,"binary",Q.message,X);break}case"contentEncoding:base64":{J.contentEncoding="base64";break}case"pattern:zod":{Z0(J,I0.base64,Q.message,X);break}}break}case"nanoid":Z0(J,I0.nanoid,Q.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return J}function q9(Y,X){return X.patternStrategy==="escape"?iK(Y):Y}var dK=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function iK(Y){let X="";for(let J=0;J<Y.length;J++){if(!dK.has(Y[J]))X+="\\";X+=Y[J]}return X}function S0(Y,X,J,Q){var $;if(Y.format||(($=Y.anyOf)==null?void 0:$.some((G)=>G.format))){if(!Y.anyOf)Y.anyOf=[];if(Y.format)Y.anyOf.push({format:Y.format}),delete Y.format;Y.anyOf.push({format:X,...J&&Q.errorMessages&&{errorMessage:{format:J}}})}else Y.format=X}function Z0(Y,X,J,Q){var $;if(Y.pattern||(($=Y.allOf)==null?void 0:$.some((G)=>G.pattern))){if(!Y.allOf)Y.allOf=[];if(Y.pattern)Y.allOf.push({pattern:Y.pattern}),delete Y.pattern;Y.allOf.push({pattern:p$(X,Q),...J&&Q.errorMessages&&{errorMessage:{pattern:J}}})}else Y.pattern=p$(X,Q)}function p$(Y,X){var J;if(!X.applyRegexFlags||!Y.flags)return Y.source;let Q={i:Y.flags.includes("i"),m:Y.flags.includes("m"),s:Y.flags.includes("s")},$=Q.i?Y.source.toLowerCase():Y.source,G="",W=!1,K=!1,U=!1;for(let H=0;H<$.length;H++){if(W){G+=$[H],W=!1;continue}if(Q.i){if(K){if($[H].match(/[a-z]/)){if(U)G+=$[H],G+=`${$[H-2]}-${$[H]}`.toUpperCase(),U=!1;else if($[H+1]==="-"&&((J=$[H+2])==null?void 0:J.match(/[a-z]/)))G+=$[H],U=!0;else G+=`${$[H]}${$[H].toUpperCase()}`;continue}}else if($[H].match(/[a-z]/)){G+=`[${$[H]}${$[H].toUpperCase()}]`;continue}}if(Q.m){if($[H]==="^"){G+=`(^|(?<=[\r
138
+ ]))`;continue}else if($[H]==="$"){G+=`($|(?=[\r
139
+ ]))`;continue}}if(Q.s&&$[H]==="."){G+=K?`${$[H]}\r
140
+ `:`[${$[H]}\r
141
+ ]`;continue}if(G+=$[H],$[H]==="\\")W=!0;else if(K&&$[H]==="]")K=!1;else if(!K&&$[H]==="[")K=!0}try{new RegExp(G)}catch(H){return console.warn(`Could not convert regex pattern at ${X.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Y.source}return G}function $G(Y,X){var J,Q,$,G,W,K;let U={type:"object",additionalProperties:(J=i(Y.valueType._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]}))!=null?J:X.allowedAdditionalProperties};if(((Q=Y.keyType)==null?void 0:Q._def.typeName)==="ZodString"&&(($=Y.keyType._def.checks)==null?void 0:$.length)){let{type:H,...N}=QG(Y.keyType._def,X);return{...U,propertyNames:N}}else if(((G=Y.keyType)==null?void 0:G._def.typeName)==="ZodEnum")return{...U,propertyNames:{enum:Y.keyType._def.values}};else if(((W=Y.keyType)==null?void 0:W._def.typeName)==="ZodBranded"&&Y.keyType._def.type._def.typeName==="ZodString"&&((K=Y.keyType._def.type._def.checks)==null?void 0:K.length)){let{type:H,...N}=XG(Y.keyType._def,X);return{...U,propertyNames:N}}return U}function nK(Y,X){if(X.mapStrategy==="record")return $G(Y,X);let J=i(Y.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||E0(),Q=i(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||E0();return{type:"array",maxItems:125,items:{type:"array",items:[J,Q],minItems:2,maxItems:2}}}function oK(Y){let X=Y.values,Q=Object.keys(Y.values).filter((G)=>{return typeof X[X[G]]!=="number"}).map((G)=>X[G]),$=Array.from(new Set(Q.map((G)=>typeof G)));return{type:$.length===1?$[0]==="string"?"string":"number":["string","number"],enum:Q}}function rK(){return{not:E0()}}function sK(){return{type:"null"}}var j9={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function aK(Y,X){let J=Y.options instanceof Map?Array.from(Y.options.values()):Y.options;if(J.every((Q)=>(Q._def.typeName in j9)&&(!Q._def.checks||!Q._def.checks.length))){let Q=J.reduce(($,G)=>{let W=j9[G._def.typeName];return W&&!$.includes(W)?[...$,W]:$},[]);return{type:Q.length>1?Q:Q[0]}}else if(J.every((Q)=>Q._def.typeName==="ZodLiteral"&&!Q.description)){let Q=J.reduce(($,G)=>{let W=typeof G._def.value;switch(W){case"string":case"number":case"boolean":return[...$,W];case"bigint":return[...$,"integer"];case"object":if(G._def.value===null)return[...$,"null"];case"symbol":case"undefined":case"function":default:return $}},[]);if(Q.length===J.length){let $=Q.filter((G,W,K)=>K.indexOf(G)===W);return{type:$.length>1?$:$[0],enum:J.reduce((G,W)=>{return G.includes(W._def.value)?G:[...G,W._def.value]},[])}}}else if(J.every((Q)=>Q._def.typeName==="ZodEnum"))return{type:"string",enum:J.reduce((Q,$)=>[...Q,...$._def.values.filter((G)=>!Q.includes(G))],[])};return tK(Y,X)}var tK=(Y,X)=>{let J=(Y.options instanceof Map?Array.from(Y.options.values()):Y.options).map((Q,$)=>i(Q._def,{...X,currentPath:[...X.currentPath,"anyOf",`${$}`]})).filter((Q)=>!!Q&&(!X.strictUnions||typeof Q==="object"&&Object.keys(Q).length>0));return J.length?{anyOf:J}:void 0};function eK(Y,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Y.innerType._def.typeName)&&(!Y.innerType._def.checks||!Y.innerType._def.checks.length))return{type:[j9[Y.innerType._def.typeName],"null"]};let J=i(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return J&&{anyOf:[J,{type:"null"}]}}function YU(Y){let X={type:"number"};if(!Y.checks)return X;for(let J of Y.checks)switch(J.kind){case"int":X.type="integer";break;case"min":if(J.inclusive)X.minimum=J.value;else X.exclusiveMinimum=J.value;break;case"max":if(J.inclusive)X.maximum=J.value;else X.exclusiveMaximum=J.value;break;case"multipleOf":X.multipleOf=J.value;break}return X}function XU(Y,X){let J={type:"object",properties:{}},Q=[],$=Y.shape();for(let W in $){let K=$[W];if(K===void 0||K._def===void 0)continue;let U=QU(K),H=i(K._def,{...X,currentPath:[...X.currentPath,"properties",W],propertyPath:[...X.currentPath,"properties",W]});if(H===void 0)continue;if(J.properties[W]=H,!U)Q.push(W)}if(Q.length)J.required=Q;let G=JU(Y,X);if(G!==void 0)J.additionalProperties=G;return J}function JU(Y,X){if(Y.catchall._def.typeName!=="ZodNever")return i(Y.catchall._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]});switch(Y.unknownKeys){case"passthrough":return X.allowedAdditionalProperties;case"strict":return X.rejectedAdditionalProperties;case"strip":return X.removeAdditionalStrategy==="strict"?X.allowedAdditionalProperties:X.rejectedAdditionalProperties}}function QU(Y){try{return Y.isOptional()}catch(X){return!0}}var $U=(Y,X)=>{var J;if(X.currentPath.toString()===((J=X.propertyPath)==null?void 0:J.toString()))return i(Y.innerType._def,X);let Q=i(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return Q?{anyOf:[{not:E0()},Q]}:E0()},GU=(Y,X)=>{if(X.pipeStrategy==="input")return i(Y.in._def,X);else if(X.pipeStrategy==="output")return i(Y.out._def,X);let J=i(Y.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),Q=i(Y.out._def,{...X,currentPath:[...X.currentPath,"allOf",J?"1":"0"]});return{allOf:[J,Q].filter(($)=>$!==void 0)}};function WU(Y,X){return i(Y.type._def,X)}function zU(Y,X){let Q={type:"array",uniqueItems:!0,items:i(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items"]})};if(Y.minSize)Q.minItems=Y.minSize.value;if(Y.maxSize)Q.maxItems=Y.maxSize.value;return Q}function KU(Y,X){if(Y.rest)return{type:"array",minItems:Y.items.length,items:Y.items.map((J,Q)=>i(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[]),additionalItems:i(Y.rest._def,{...X,currentPath:[...X.currentPath,"additionalItems"]})};else return{type:"array",minItems:Y.items.length,maxItems:Y.items.length,items:Y.items.map((J,Q)=>i(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[])}}function UU(){return{not:E0()}}function HU(){return E0()}var LU=(Y,X)=>{return i(Y.innerType._def,X)},NU=(Y,X,J)=>{switch(X){case"ZodString":return QG(Y,J);case"ZodNumber":return YU(Y);case"ZodObject":return XU(Y,J);case"ZodBigInt":return vK(Y);case"ZodBoolean":return hK();case"ZodDate":return JG(Y,J);case"ZodUndefined":return UU();case"ZodNull":return sK();case"ZodArray":return xK(Y,J);case"ZodUnion":case"ZodDiscriminatedUnion":return aK(Y,J);case"ZodIntersection":return pK(Y,J);case"ZodTuple":return KU(Y,J);case"ZodRecord":return $G(Y,J);case"ZodLiteral":return lK(Y);case"ZodEnum":return cK(Y);case"ZodNativeEnum":return oK(Y);case"ZodNullable":return eK(Y,J);case"ZodOptional":return $U(Y,J);case"ZodMap":return nK(Y,J);case"ZodSet":return zU(Y,J);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return WU(Y,J);case"ZodNaN":case"ZodNever":return rK();case"ZodEffects":return mK(Y,J);case"ZodAny":return E0();case"ZodUnknown":return HU();case"ZodDefault":return fK(Y,J);case"ZodBranded":return XG(Y,J);case"ZodReadonly":return LU(Y,J);case"ZodCatch":return gK(Y,J);case"ZodPipeline":return GU(Y,J);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Q)=>{return})(X)}},VU=(Y,X)=>{let J=0;for(;J<Y.length&&J<X.length;J++)if(Y[J]!==X[J])break;return[(Y.length-J).toString(),...X.slice(J)].join("/")};function i(Y,X,J=!1){var Q;let $=X.seen.get(Y);if(X.override){let U=(Q=X.override)==null?void 0:Q.call(X,Y,X,$,J);if(U!==kK)return U}if($&&!J){let U=BU($,X);if(U!==void 0)return U}let G={def:Y,path:X.currentPath,jsonSchema:void 0};X.seen.set(Y,G);let W=NU(Y,Y.typeName,X),K=typeof W==="function"?i(W(),X):W;if(K)ZU(Y,X,K);if(X.postProcess){let U=X.postProcess(K,Y,X);return G.jsonSchema=K,U}return G.jsonSchema=K,K}var BU=(Y,X)=>{switch(X.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:VU(X.currentPath,Y.path)};case"none":case"seen":{if(Y.path.length<X.currentPath.length&&Y.path.every((J,Q)=>X.currentPath[Q]===J))return console.warn(`Recursive reference detected at ${X.currentPath.join("/")}! Defaulting to any`),E0();return X.$refStrategy==="seen"?E0():void 0}}},ZU=(Y,X,J)=>{if(Y.description)J.description=Y.description;return J},OU=(Y)=>{let X=bK(Y),J=X.name!==void 0?[...X.basePath,X.definitionPath,X.name]:X.basePath;return{...X,currentPath:J,propertyPath:void 0,seen:new Map(Object.entries(X.definitions).map(([Q,$])=>[$._def,{def:$._def,path:[...X.basePath,X.definitionPath,Q],jsonSchema:void 0}]))}},FU=(Y,X)=>{var J;let Q=OU(X),$=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((H,[N,O])=>{var B;return{...H,[N]:(B=i(O._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,N]},!0))!=null?B:E0()}},{}):void 0,G=typeof X==="string"?X:(X==null?void 0:X.nameStrategy)==="title"?void 0:X==null?void 0:X.name,W=(J=i(Y._def,G===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,G]},!1))!=null?J:E0(),K=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if(K!==void 0)W.title=K;let U=G===void 0?$?{...W,[Q.definitionPath]:$}:W:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,G].join("/"),[Q.definitionPath]:{...$,[G]:W}};return U.$schema="http://json-schema.org/draft-07/schema#",U},D9=Symbol.for("vercel.ai.schema");function dY(Y){let X;return()=>{if(X==null)X=Y();return X}}function iY(Y,{validate:X}={}){return{[D9]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:X}}function qU(Y){return typeof Y==="object"&&Y!==null&&D9 in Y&&Y[D9]===!0&&"jsonSchema"in Y&&"validate"in Y}function nY(Y){return Y==null?iY({type:"object",properties:{},additionalProperties:!1}):qU(Y)?Y:("~standard"in Y)?Y["~standard"].vendor==="zod"?YY(Y):jU(Y):Y()}function jU(Y){return iY(()=>{if(!DU(Y))throw Error(`Standard schema vendor '${Y["~standard"].vendor}' does not support JSON Schema conversion.`);return M9(Y["~standard"].jsonSchema.input({target:"draft-07"}))},{validate:async(X)=>{let J=await Y["~standard"].validate(X);return"value"in J?{success:!0,value:J.value}:{success:!1,error:new v0({value:X,cause:J.issues})}}})}function DU(Y){return Y["~standard"].jsonSchema!=null}function PU(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return iY(()=>FU(Y,{$refStrategy:Q?"root":"none"}),{validate:async($)=>{let G=await Y.safeParseAsync($);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function wU(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return iY(()=>M9(a7(Y,{target:"draft-7",io:"input",reused:Q?"ref":"inline"})),{validate:async($)=>{let G=await uY(Y,$);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function EU(Y){return"_zod"in Y}function YY(Y,X){if(EU(Y))return wU(Y,X);else return PU(Y,X)}async function XY({value:Y,schema:X,context:J}){let Q=nY(X);try{if(Q.validate==null)return{success:!0,value:Y,rawValue:Y};let $=await Q.validate(Y);if($.success)return{success:!0,value:$.value,rawValue:Y};return{success:!1,error:v0.wrap({value:Y,cause:$.error,context:J}),rawValue:Y}}catch($){return{success:!1,error:v0.wrap({value:Y,cause:$,context:J}),rawValue:Y}}}async function G1({text:Y,schema:X}){try{let J=SK(Y);if(X==null)return{success:!0,value:J,rawValue:J};return await XY({value:J,schema:X})}catch(J){return{success:!1,error:MY.isInstance(J)?J:new MY({text:Y,cause:J}),rawValue:void 0}}}async function A9(Y){if(typeof Y==="function")Y=Y();return Promise.resolve(Y)}var GG="AI_SerializationError",WG=`vercel.ai.error.${GG}`,MU=Symbol.for(WG),l$,d$,UO=class extends(d$=f,l$=MU,d$){constructor({message:Y="Failed to serialize value.",cause:X}={}){super({name:GG,message:Y,cause:X});this[l$]=!0}static isInstance(Y){return f.hasMarker(Y,WG)}};var TU=Object.defineProperty,CU=(Y,X)=>{for(var J in X)TU(Y,J,{get:X[J],enumerable:!0})},_U="AI_InvalidArgumentError",IU=`vercel.ai.error.${_U}`,SU=Symbol.for(IU),kU;kU=SU;var bU="AI_InvalidStreamPartError",xU=`vercel.ai.error.${bU}`,vU=Symbol.for(xU),hU;hU=vU;var gU="AI_InvalidToolApprovalError",yU=`vercel.ai.error.${gU}`,fU=Symbol.for(yU),mU;mU=fU;var cU="AI_InvalidToolApprovalSignatureError",uU=`vercel.ai.error.${cU}`,pU=Symbol.for(uU),lU;lU=pU;var dU="AI_InvalidToolInputError",iU=`vercel.ai.error.${dU}`,nU=Symbol.for(iU),oU;oU=nU;var rU="AI_ToolCallNotFoundForApprovalError",sU=`vercel.ai.error.${rU}`,aU=Symbol.for(sU),tU;tU=aU;var eU="AI_MissingToolResultsError",YH=`vercel.ai.error.${eU}`,XH=Symbol.for(YH),JH;JH=XH;var QH="AI_NoImageGeneratedError",$H=`vercel.ai.error.${QH}`,GH=Symbol.for($H),WH;WH=GH;var zG="AI_NoObjectGeneratedError",KG=`vercel.ai.error.${zG}`,zH=Symbol.for(KG),UG,W1=class extends f{constructor({message:Y="No object generated.",cause:X,text:J,response:Q,usage:$,finishReason:G}){super({name:zG,message:Y,cause:X});this[UG]=!0,this.text=J,this.response=Q,this.usage=$,this.finishReason=G}static isInstance(Y){return f.hasMarker(Y,KG)}};UG=zH;var KH="AI_NoOutputGeneratedError",UH=`vercel.ai.error.${KH}`,HH=Symbol.for(UH),LH;LH=HH;var NH="AI_NoSpeechGeneratedError",VH=`vercel.ai.error.${NH}`,BH=Symbol.for(VH),ZH;ZH=BH;var OH="AI_NoTranscriptGeneratedError",FH=`vercel.ai.error.${OH}`,qH=Symbol.for(FH),jH;jH=qH;var DH="AI_NoTranslationGeneratedError",PH=`vercel.ai.error.${DH}`,wH=Symbol.for(PH),EH;EH=wH;var MH="AI_NoVideoGeneratedError",AH=`vercel.ai.error.${MH}`,RH=Symbol.for(AH),TH;TH=RH;var CH="AI_NoSuchToolError",_H=`vercel.ai.error.${CH}`,IH=Symbol.for(_H),SH;SH=IH;var kH="AI_ToolCallRepairError",bH=`vercel.ai.error.${kH}`,xH=Symbol.for(bH),vH;vH=xH;var hH="AI_UIMessageStreamError",gH=`vercel.ai.error.${hH}`,yH=Symbol.for(gH),fH;fH=yH;var mH="AI_InvalidDataContentError",cH=`vercel.ai.error.${mH}`,uH=Symbol.for(cH),pH;pH=uH;var lH="AI_InvalidMessageRoleError",dH=`vercel.ai.error.${lH}`,iH=Symbol.for(dH),nH;nH=iH;var oH="AI_MessageConversionError",rH=`vercel.ai.error.${oH}`,sH=Symbol.for(rH),aH;aH=sH;var tH="AI_RetryError",eH=`vercel.ai.error.${tH}`,YL=Symbol.for(eH),XL;XL=YL;var JL="7.0.59",QL=async({url:Y,maxBytes:X,abortSignal:J})=>{var Q;let $=Y.toString();try{let G=b1({},`ai-sdk/${JL}`,e$()),W=await a$({url:$,headers:G,abortSignal:J});if(!W.ok)throw await lY(W),new O0({url:$,statusCode:W.status,statusText:W.statusText});return{data:await t$({response:W,url:$,maxBytes:X!=null?X:E9}),mediaType:(Q=W.headers.get("content-type"))!=null?Q:void 0}}catch(G){if(O0.isInstance(G))throw G;throw new O0({url:$,cause:G})}};var z={array:N9,boolean:E$,custom:v$,discriminatedUnion:_$,enum:B9,instanceof:h$,lazy:x$,literal:S$,looseObject:T$,never:L9,null:M$,number:w$,object:R$,record:I$,string:D$,union:V9,unknown:e1},q1=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),q1.optional()),z.array(q1)])),A=z.record(z.string(),z.record(z.string(),q1.optional())),QY=z.union([z.string(),z.instanceof(Uint8Array),z.instanceof(ArrayBuffer),z.custom(YG,{message:"Must be a Buffer"})]),R9=z.record(z.string(),z.string()),HG=z.object({type:z.literal("text"),text:z.string(),providerOptions:A.optional()}),$L=z.object({type:z.literal("image"),image:z.union([QY,z.instanceof(URL),R9]),mediaType:z.string().optional(),providerOptions:A.optional()}),LG=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:QY}),z.object({type:z.literal("url"),url:z.instanceof(URL)}),z.object({type:z.literal("reference"),reference:R9}),z.object({type:z.literal("text"),text:z.string()})]),GL=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:QY}),z.object({type:z.literal("url"),url:z.instanceof(URL)})]),NG=z.object({type:z.literal("file"),data:z.union([LG,QY,z.instanceof(URL),R9]),filename:z.string().optional(),mediaType:z.string(),providerOptions:A.optional()}),WL=z.object({type:z.literal("reasoning"),text:z.string(),providerOptions:A.optional()}),zL=z.object({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerOptions:A.optional()}),KL=z.object({type:z.literal("reasoning-file"),data:z.union([GL,QY,z.instanceof(URL)]),mediaType:z.string(),providerOptions:A.optional()}),UL=z.object({type:z.literal("tool-call"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerOptions:A.optional(),providerExecuted:z.boolean().optional()}),HL=z.discriminatedUnion("type",[z.object({type:z.literal("text"),value:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("json"),value:q1,providerOptions:A.optional()}),z.object({type:z.literal("execution-denied"),reason:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("error-text"),value:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("error-json"),value:q1,providerOptions:A.optional()}),z.object({type:z.literal("content"),value:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("file"),data:LG,mediaType:z.string(),filename:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("file-data"),data:z.string(),mediaType:z.string(),filename:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("file-url"),url:z.string(),mediaType:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:A.optional()}),z.object({type:z.literal("file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:A.optional()}),z.object({type:z.literal("image-data"),data:z.string(),mediaType:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("image-url"),url:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("image-file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:A.optional()}),z.object({type:z.literal("image-file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:A.optional()}),z.object({type:z.literal("custom"),providerOptions:A.optional()})]))})]),VG=z.object({type:z.literal("tool-result"),toolCallId:z.string(),toolName:z.string(),output:HL,providerOptions:A.optional()}),LL=z.object({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string()}),NL=z.object({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional()}),VL=z.object({role:z.literal("system"),content:z.string(),providerOptions:A.optional()}),BL=z.object({role:z.literal("user"),content:z.union([z.string(),z.array(z.union([HG,$L,NG]))]),providerOptions:A.optional()}),ZL=z.object({role:z.literal("assistant"),content:z.union([z.string(),z.array(z.union([HG,zL,NG,WL,KL,UL,VG,LL]))]),providerOptions:A.optional()}),OL=z.object({role:z.literal("tool"),content:z.array(z.union([VG,NL])),providerOptions:A.optional()}),EO=z.union([VL,BL,ZL,OL]);var FL={};CU(FL,{array:()=>PL,choice:()=>wL,json:()=>EL,object:()=>DL,text:()=>jL});function qL(Y){let X=["ROOT"],J=-1,Q=null,$=0;function G(N){return N>="0"&&N<="9"||N>="A"&&N<="F"||N>="a"&&N<="f"}function W(N,O,B){switch(N){case'"':{J=O,X.pop(),X.push(B),X.push("INSIDE_STRING");break}case"f":case"t":case"n":{J=O,Q=O,X.pop(),X.push(B),X.push("INSIDE_LITERAL");break}case"-":{X.pop(),X.push(B),X.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=O,X.pop(),X.push(B),X.push("INSIDE_NUMBER");break}case"{":{J=O,X.pop(),X.push(B),X.push("INSIDE_OBJECT_START");break}case"[":{J=O,X.pop(),X.push(B),X.push("INSIDE_ARRAY_START");break}}}function K(N,O){switch(N){case",":{X.pop(),X.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{J=O,X.pop();break}}}function U(N,O){switch(N){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=O,X.pop();break}}}for(let N=0;N<Y.length;N++){let O=Y[N];switch(X[X.length-1]){case"ROOT":W(O,N,"FINISH");break;case"INSIDE_OBJECT_START":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}case"}":{J=N,X.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(O){case":":{X.pop(),X.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{W(O,N,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{K(O,N);break}case"INSIDE_STRING":{switch(O){case'"':{X.pop(),J=N;break}case"\\":{X.push("INSIDE_STRING_ESCAPE");break}default:J=N}break}case"INSIDE_ARRAY_START":{switch(O){case"]":{J=N,X.pop();break}default:{J=N,W(O,N,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(O){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=N,X.pop();break}default:{J=N;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{W(O,N,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{if(X.pop(),O==="u")$=0,X.push("INSIDE_STRING_UNICODE_ESCAPE");else J=N;break}case"INSIDE_STRING_UNICODE_ESCAPE":{if(G(O)){if($++,$===4)X.pop(),J=N}break}case"INSIDE_NUMBER":{switch(O){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=N;break}case"e":case"E":case"-":case".":break;case",":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")U(O,N);if(X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(O,N);break}case"}":{if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(O,N);break}case"]":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")U(O,N);break}default:{X.pop();break}}break}case"INSIDE_LITERAL":{let L=Y.substring(Q,N+1);if(!"false".startsWith(L)&&!"true".startsWith(L)&&!"null".startsWith(L)){if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(O,N);else if(X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")U(O,N)}else J=N;break}}}let H=Y.slice(0,J+1);for(let N=X.length-1;N>=0;N--)switch(X[N]){case"INSIDE_STRING":{H+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{H+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{H+="]";break}case"INSIDE_LITERAL":{let B=Y.substring(Q,Y.length);if("true".startsWith(B))H+="true".slice(B.length);else if("false".startsWith(B))H+="false".slice(B.length);else if("null".startsWith(B))H+="null".slice(B.length)}}return H}async function oY(Y){if(Y===void 0)return{value:void 0,state:"undefined-input"};let X=await G1({text:Y});if(X.success)return{value:X.value,state:"successful-parse"};if(X=await G1({text:qL(Y)}),X.success)return{value:X.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var jL=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:Y}){return Y},async parsePartialOutput({text:Y}){return{partial:Y}},createElementStreamTransform(){return}}),DL=({schema:Y,name:X,description:J})=>{let Q=nY(Y);return{name:"object",responseFormat:A9(Q.jsonSchema).then(($)=>({type:"json",schema:$,...X!=null&&{name:X},...J!=null&&{description:J}})),async parseCompleteOutput({text:$},G){let W=await G1({text:$});if(!W.success)throw new W1({message:"No object generated: could not parse the response.",cause:W.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let K=await XY({value:W.value,schema:Q});if(!K.success)throw new W1({message:"No object generated: response did not match schema.",cause:K.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});return K.value},async parsePartialOutput({text:$}){let G=await oY($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:G.value}}},createElementStreamTransform(){return}}},PL=({element:Y,name:X,description:J})=>{let Q=nY(Y);return{name:"array",responseFormat:A9(Q.jsonSchema).then(($)=>{let{$schema:G,...W}=$;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:W}},required:["elements"],additionalProperties:!1},...X!=null&&{name:X},...J!=null&&{description:J}}}),async parseCompleteOutput({text:$},G){let W=await G1({text:$});if(!W.success)throw new W1({message:"No object generated: could not parse the response.",cause:W.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let K=W.value;if(K==null||typeof K!=="object"||!("elements"in K)||!Array.isArray(K.elements))throw new W1({message:"No object generated: response did not match schema.",cause:new v0({value:K,cause:"response must be an object with an elements array"}),text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let U=[];for(let H of K.elements){let N=await XY({value:H,schema:Q});if(!N.success)throw new W1({message:"No object generated: response did not match schema.",cause:N.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});U.push(N.value)}return U},async parsePartialOutput({text:$}){let G=await oY($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let W=G.value;if(W==null||typeof W!=="object"||!("elements"in W)||!Array.isArray(W.elements))return;let K=G.state==="repaired-parse"&&W.elements.length>0?W.elements.slice(0,-1):W.elements,U=[];for(let H of K){let N=await XY({value:H,schema:Q});if(N.success)U.push(N.value)}return{partial:U}}}},createElementStreamTransform(){let $=0;return new TransformStream({transform({partialOutput:G},W){if(G!=null)for(;$<G.length;$++)W.enqueue(G[$])}})}}},wL=({options:Y,name:X,description:J})=>{return{name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:Y}},required:["result"],additionalProperties:!1},...X!=null&&{name:X},...J!=null&&{description:J}}),async parseCompleteOutput({text:Q},$){let G=await G1({text:Q});if(!G.success)throw new W1({message:"No object generated: could not parse the response.",cause:G.error,text:Q,response:$.response,usage:$.usage,finishReason:$.finishReason});let W=G.value;if(W==null||typeof W!=="object"||!("result"in W)||typeof W.result!=="string"||!Y.includes(W.result))throw new W1({message:"No object generated: response did not match schema.",cause:new v0({value:W,cause:"response must be an object that contains a choice value."}),text:Q,response:$.response,usage:$.usage,finishReason:$.finishReason});return W.result},async parsePartialOutput({text:Q}){let $=await oY(Q);switch($.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let G=$.value;if(G==null||typeof G!=="object"||!("result"in G)||typeof G.result!=="string")return;let W=Y.filter((K)=>K.startsWith(G.result));if($.state==="successful-parse")return W.includes(G.result)?{partial:G.result}:void 0;else return W.length===1?{partial:W[0]}:void 0}}},createElementStreamTransform(){return}}},EL=({name:Y,description:X}={})=>{return{name:"json",responseFormat:Promise.resolve({type:"json",...Y!=null&&{name:Y},...X!=null&&{description:X}}),async parseCompleteOutput({text:J},Q){let $=await G1({text:J});if(!$.success)throw new W1({message:"No object generated: could not parse the response.",cause:$.error,text:J,response:Q.response,usage:Q.usage,finishReason:Q.finishReason});return $.value},async parsePartialOutput({text:J}){let Q=await oY(J);switch(Q.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return Q.value===void 0?void 0:{partial:Q.value}}},createElementStreamTransform(){return}}};var TO=Q0({prefix:"aitxt",size:24}),CO=Q0({prefix:"call",size:24});var IO=class extends TransformStream{constructor(){super({transform(Y,X){X.enqueue(`data: ${JSON.stringify(Y)}
142
142
 
143
143
  `)},flush(Y){Y.enqueue(`data: [DONE]
144
144
 
145
- `)}})}};var XY=z.record(z.string(),F1.optional()),IO=dY(()=>e1(z.union([z.looseObject({type:z.literal("text-start"),id:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("text-delta"),id:z.string(),delta:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("text-end"),id:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("error"),errorText:z.string()}),z.looseObject({type:z.literal("tool-input-start"),toolCallId:z.string(),toolName:z.string(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional(),toolMetadata:XY.optional(),dynamic:z.boolean().optional(),title:z.string().optional()}),z.looseObject({type:z.literal("tool-input-delta"),toolCallId:z.string(),inputTextDelta:z.string()}),z.looseObject({type:z.literal("tool-input-available"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional(),toolMetadata:XY.optional(),dynamic:z.boolean().optional(),title:z.string().optional()}),z.looseObject({type:z.literal("tool-input-error"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional(),toolMetadata:XY.optional(),dynamic:z.boolean().optional(),errorText:z.string(),title:z.string().optional()}),z.looseObject({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}),z.looseObject({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("tool-output-available"),toolCallId:z.string(),output:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional(),toolMetadata:XY.optional(),dynamic:z.boolean().optional(),preliminary:z.boolean().optional()}),z.looseObject({type:z.literal("tool-output-error"),toolCallId:z.string(),errorText:z.string(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional(),toolMetadata:XY.optional(),dynamic:z.boolean().optional()}),z.looseObject({type:z.literal("tool-output-denied"),toolCallId:z.string()}),z.looseObject({type:z.literal("reasoning-start"),id:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("reasoning-delta"),id:z.string(),delta:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("reasoning-end"),id:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerMetadata:A.optional()}),z.looseObject({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("file"),url:z.string(),mediaType:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("reasoning-file"),url:z.string(),mediaType:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.custom((Y)=>typeof Y==="string"&&Y.startsWith("data-"),{message:'Type must start with "data-"'}),id:z.string().optional(),data:z.unknown(),transient:z.boolean().optional()}),z.looseObject({type:z.literal("start-step")}),z.looseObject({type:z.literal("finish-step")}),z.looseObject({type:z.literal("start"),messageId:z.string().optional(),messageMetadata:z.unknown().optional()}),z.looseObject({type:z.literal("finish"),finishReason:z.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:z.unknown().optional()}),z.looseObject({type:z.literal("abort"),reason:z.string().optional()}),z.looseObject({type:z.literal("message-metadata"),messageMetadata:z.unknown()})])));var kO=J0({prefix:"aitxt",size:24}),bO=J0({prefix:"call",size:24});var xO=J0({prefix:"aitxt",size:24}),vO=J0({prefix:"call",size:24});var j0=z.record(z.string(),F1.optional()),DL=z.record(z.string(),z.string()),gO=dY(()=>e1(z.array(z.object({id:z.string(),role:z.enum(["system","user","assistant"]),metadata:z.unknown().optional(),parts:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:A.optional()}),z.object({type:z.literal("reasoning"),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:A.optional()}),z.object({type:z.literal("custom"),kind:z.string(),providerMetadata:A.optional()}),z.object({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:A.optional()}),z.object({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:A.optional()}),z.object({type:z.literal("file"),mediaType:z.string(),filename:z.string().optional(),url:z.string(),providerReference:DL.optional(),providerMetadata:A.optional()}),z.object({type:z.literal("reasoning-file"),mediaType:z.string(),url:z.string(),providerMetadata:A.optional()}),z.object({type:z.literal("step-start")}),z.object({type:z.string().startsWith("data-"),id:z.string().optional(),data:z.unknown()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("input-streaming"),input:z.unknown().optional(),providerExecuted:z.boolean().optional(),callProviderMetadata:A.optional(),output:z.never().optional(),errorText:z.never().optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("input-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),reason:z.never().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.boolean(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("output-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("output-error"),input:z.unknown().optional(),rawInput:z.unknown().optional(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.string(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("output-denied"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("input-streaming"),providerExecuted:z.boolean().optional(),callProviderMetadata:A.optional(),input:z.unknown().optional(),output:z.never().optional(),errorText:z.never().optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("input-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),reason:z.never().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.boolean(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("output-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("output-error"),providerExecuted:z.boolean().optional(),input:z.unknown().optional(),rawInput:z.unknown().optional(),output:z.never().optional(),errorText:z.string(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("output-denied"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})})]))}).superRefine((Y,X)=>{if(Y.role!=="assistant"&&Y.parts.length===0)X.addIssue({origin:"array",code:"too_small",minimum:1,inclusive:!0,input:Y.parts,path:["parts"],message:"Message must contain at least one part"})})).nonempty("Messages array must not be empty")));var fO=J0({prefix:"call",size:24});var cO=J0({prefix:"call",size:24});var pO=J0({prefix:"aiobj",size:24});function VG(Y){return({url:X,abortSignal:J})=>eH({url:X,maxBytes:Y==null?void 0:Y.maxBytes,abortSignal:J})}var dO=J0({prefix:"aiobj",size:24});var iO=VG();var PL="AI_NoSuchProviderError",wL=`vercel.ai.error.${PL}`,EL=Symbol.for(wL),ML;ML=EL;var oO=J0({prefix:"call",size:24});var rO=VG();class R0 extends m1{name="ProviderResponseStreamError";constructor(Y,X){super({message:Y,url:"",requestBodyValues:void 0,cause:X?.cause,isRetryable:!0})}}var D0={};g8(D0,{toWebSocketUrl:()=>uL,streamResponsesWebSocket:()=>iL,parseRateLimitSignal:()=>$Y,normalizeHeaders:()=>pL,isUpgradeFailure:()=>lL,isAbortError:()=>I9,connectResponsesWebSocket:()=>dL,PROTOCOL_HEADER:()=>PG,OpenAIWebSocket:()=>D0});function QY(Y){let X=Number(Y.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(X)?X:void 0}function rY(Y,X,J=!1){let $=Buffer.from(Y.slice(0,X)).toString("latin1").split(`\r
146
- `),G=$[0]??"",W=QY(G);if(W===void 0||W===101)return;let K=Object.fromEntries($.slice(1).flatMap((L)=>{let Z=L.indexOf(":");return Z===-1?[]:[[L.slice(0,Z).trim().toLowerCase(),L.slice(Z+1).trim()]]})),H=Y.slice(X+4),U=K["content-length"],N=Number(U);if(!J&&(U===void 0||Number.isFinite(N)&&H.length<N))return;let O=Buffer.from(H).toString("utf8"),B=(()=>{try{let L=JSON.parse(O);return _(L)?L:void 0}catch{return}})();return{message:`WS upgrade failed: ${G}`,status:W,status_code:W,headers:K,body:O,..._(B?.error)?{error:B.error}:{}}}var AL="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",BG=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class T9{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];writeQueue=[];constructor(Y,X,J){this.url=Y,this.sessionID=J?.sessionID,this.connect(Y,X)}addEventListener(Y,X,J){this.listeners[Y]?.add(X)}removeEventListener(Y,X){this.listeners[Y]?.delete(X)}emit(Y,X){for(let J of[...this.listeners[Y]??[]])try{J(X)}catch{}}async connect(Y,X){let J=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),Q=J.hostname,$=J.port?Number(J.port):J.protocol==="https:"?443:80,G=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),K=Buffer.from(W).toString("base64"),H=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(K+AL));this.expectedAccept=Buffer.from(new Uint8Array(H)).toString("base64");let U={};for(let[B,L]of Object.entries(X))U[B.toLowerCase()]=L;let N=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${K}`];for(let B of BG)if(U[B]!==void 0)N.push(`${RL(B)}: ${U[B]}`);for(let[B,L]of Object.entries(X))if(!BG.includes(B.toLowerCase())&&B.toLowerCase()!=="content-length")N.push(`${B}: ${L}`);let O=`${N.join(`\r
145
+ `)}})}};var JY=z.record(z.string(),q1.optional()),kO=dY(()=>YY(z.union([z.looseObject({type:z.literal("text-start"),id:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("text-delta"),id:z.string(),delta:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("text-end"),id:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("error"),errorText:z.string()}),z.looseObject({type:z.literal("tool-input-start"),toolCallId:z.string(),toolName:z.string(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional(),toolMetadata:JY.optional(),dynamic:z.boolean().optional(),title:z.string().optional()}),z.looseObject({type:z.literal("tool-input-delta"),toolCallId:z.string(),inputTextDelta:z.string()}),z.looseObject({type:z.literal("tool-input-available"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional(),toolMetadata:JY.optional(),dynamic:z.boolean().optional(),title:z.string().optional()}),z.looseObject({type:z.literal("tool-input-error"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional(),toolMetadata:JY.optional(),dynamic:z.boolean().optional(),errorText:z.string(),title:z.string().optional()}),z.looseObject({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}),z.looseObject({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("tool-output-available"),toolCallId:z.string(),output:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional(),toolMetadata:JY.optional(),dynamic:z.boolean().optional(),preliminary:z.boolean().optional()}),z.looseObject({type:z.literal("tool-output-error"),toolCallId:z.string(),errorText:z.string(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional(),toolMetadata:JY.optional(),dynamic:z.boolean().optional()}),z.looseObject({type:z.literal("tool-output-denied"),toolCallId:z.string()}),z.looseObject({type:z.literal("reasoning-start"),id:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("reasoning-delta"),id:z.string(),delta:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("reasoning-end"),id:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerMetadata:A.optional()}),z.looseObject({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("file"),url:z.string(),mediaType:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("reasoning-file"),url:z.string(),mediaType:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.custom((Y)=>typeof Y==="string"&&Y.startsWith("data-"),{message:'Type must start with "data-"'}),id:z.string().optional(),data:z.unknown(),transient:z.boolean().optional()}),z.looseObject({type:z.literal("start-step")}),z.looseObject({type:z.literal("finish-step")}),z.looseObject({type:z.literal("start"),messageId:z.string().optional(),messageMetadata:z.unknown().optional()}),z.looseObject({type:z.literal("finish"),finishReason:z.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:z.unknown().optional()}),z.looseObject({type:z.literal("abort"),reason:z.string().optional()}),z.looseObject({type:z.literal("message-metadata"),messageMetadata:z.unknown()})])));var xO=Q0({prefix:"aitxt",size:24}),vO=Q0({prefix:"call",size:24});var hO=Q0({prefix:"aitxt",size:24}),gO=Q0({prefix:"call",size:24});var q0=z.record(z.string(),q1.optional()),ML=z.record(z.string(),z.string()),fO=dY(()=>YY(z.array(z.object({id:z.string(),role:z.enum(["system","user","assistant"]),metadata:z.unknown().optional(),parts:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:A.optional()}),z.object({type:z.literal("reasoning"),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:A.optional()}),z.object({type:z.literal("custom"),kind:z.string(),providerMetadata:A.optional()}),z.object({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:A.optional()}),z.object({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:A.optional()}),z.object({type:z.literal("file"),mediaType:z.string(),filename:z.string().optional(),url:z.string(),providerReference:ML.optional(),providerMetadata:A.optional()}),z.object({type:z.literal("reasoning-file"),mediaType:z.string(),url:z.string(),providerMetadata:A.optional()}),z.object({type:z.literal("step-start")}),z.object({type:z.string().startsWith("data-"),id:z.string().optional(),data:z.unknown()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:q0.optional(),state:z.literal("input-streaming"),input:z.unknown().optional(),providerExecuted:z.boolean().optional(),callProviderMetadata:A.optional(),output:z.never().optional(),errorText:z.never().optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:q0.optional(),state:z.literal("input-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:q0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),reason:z.never().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:q0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.boolean(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:q0.optional(),state:z.literal("output-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:q0.optional(),state:z.literal("output-error"),input:z.unknown().optional(),rawInput:z.unknown().optional(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.string(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:q0.optional(),state:z.literal("output-denied"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:q0.optional(),state:z.literal("input-streaming"),providerExecuted:z.boolean().optional(),callProviderMetadata:A.optional(),input:z.unknown().optional(),output:z.never().optional(),errorText:z.never().optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:q0.optional(),state:z.literal("input-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:q0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),reason:z.never().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:q0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.boolean(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:q0.optional(),state:z.literal("output-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:q0.optional(),state:z.literal("output-error"),providerExecuted:z.boolean().optional(),input:z.unknown().optional(),rawInput:z.unknown().optional(),output:z.never().optional(),errorText:z.string(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:q0.optional(),state:z.literal("output-denied"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})})]))}).superRefine((Y,X)=>{if(Y.role!=="assistant"&&Y.parts.length===0)X.addIssue({origin:"array",code:"too_small",minimum:1,inclusive:!0,input:Y.parts,path:["parts"],message:"Message must contain at least one part"})})).nonempty("Messages array must not be empty")));var cO=Q0({prefix:"call",size:24});var pO=Q0({prefix:"call",size:24});var dO=Q0({prefix:"aiobj",size:24});function BG(Y){return({url:X,abortSignal:J})=>QL({url:X,maxBytes:Y==null?void 0:Y.maxBytes,abortSignal:J})}var nO=Q0({prefix:"aiobj",size:24});var oO=BG();var AL="AI_NoSuchProviderError",RL=`vercel.ai.error.${AL}`,TL=Symbol.for(RL),CL;CL=TL;var sO=Q0({prefix:"call",size:24});var aO=BG();class R0 extends c1{name="ProviderResponseStreamError";constructor(Y,X){super({message:Y,url:"",requestBodyValues:void 0,cause:X?.cause,isRetryable:!0})}}var j0={};g8(j0,{toWebSocketUrl:()=>iL,streamResponsesWebSocket:()=>sL,parseRateLimitSignal:()=>GY,normalizeHeaders:()=>nL,isUpgradeFailure:()=>oL,isAbortError:()=>I9,connectResponsesWebSocket:()=>rL,PROTOCOL_HEADER:()=>wG,OpenAIWebSocket:()=>j0});function $Y(Y){let X=Number(Y.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(X)?X:void 0}function rY(Y,X,J=!1){let $=Buffer.from(Y.slice(0,X)).toString("latin1").split(`\r
146
+ `),G=$[0]??"",W=$Y(G);if(W===void 0||W===101)return;let K=Object.fromEntries($.slice(1).flatMap((L)=>{let Z=L.indexOf(":");return Z===-1?[]:[[L.slice(0,Z).trim().toLowerCase(),L.slice(Z+1).trim()]]})),U=Y.slice(X+4),H=K["content-length"],N=Number(H);if(!J&&(H===void 0||Number.isFinite(N)&&U.length<N))return;let O=Buffer.from(U).toString("utf8"),B=(()=>{try{let L=JSON.parse(O);return I(L)?L:void 0}catch{return}})();return{message:`WS upgrade failed: ${G}`,status:W,status_code:W,headers:K,body:O,...I(B?.error)?{error:B.error}:{}}}var _L="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",ZG=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class T9{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];writeQueue=[];constructor(Y,X,J){this.url=Y,this.sessionID=J?.sessionID,this.connect(Y,X)}addEventListener(Y,X,J){this.listeners[Y]?.add(X)}removeEventListener(Y,X){this.listeners[Y]?.delete(X)}emit(Y,X){for(let J of[...this.listeners[Y]??[]])try{J(X)}catch{}}async connect(Y,X){let J=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),Q=J.hostname,$=J.port?Number(J.port):J.protocol==="https:"?443:80,G=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),K=Buffer.from(W).toString("base64"),U=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(K+_L));this.expectedAccept=Buffer.from(new Uint8Array(U)).toString("base64");let H={};for(let[B,L]of Object.entries(X))H[B.toLowerCase()]=L;let N=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${K}`];for(let B of ZG)if(H[B]!==void 0)N.push(`${IL(B)}: ${H[B]}`);for(let[B,L]of Object.entries(X))if(!ZG.includes(B.toLowerCase())&&B.toLowerCase()!=="content-length")N.push(`${B}: ${L}`);let O=`${N.join(`\r
147
147
  `)}\r
148
148
  \r
149
- `;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let B=globalThis.Bun?.connect;if(!B)throw Error("Bun.connect is not available");this.socket=await B({hostname:Q,port:$,tls:J.protocol==="https:"?{serverName:Q}:void 0,socket:{open:(L)=>{this.socket=L,this.enqueueWrite(new TextEncoder().encode(O))},data:(L,Z)=>this.onData(Z),drain:()=>this.flushWrites(),error:(L,Z)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let j=Z instanceof Error?Z.message:String(Z);this.log("socket_error",{message:j}),this.emit("error",{message:j})},close:()=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close"),this.emit("close",{code:1006,reason:"socket closed"})}}})}catch(B){this.readyState=3;let L=B instanceof Error?B.message:String(B);this.log("connect_exception",{message:L}),this.emit("error",{message:L})}}onData(Y){if(this.rxBuffer=TL(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
149
+ `;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let B=globalThis.Bun?.connect;if(!B)throw Error("Bun.connect is not available");this.socket=await B({hostname:Q,port:$,tls:J.protocol==="https:"?{serverName:Q}:void 0,socket:{open:(L)=>{this.socket=L,this.enqueueWrite(new TextEncoder().encode(O))},data:(L,Z)=>this.onData(Z),drain:()=>this.flushWrites(),error:(L,Z)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let j=Z instanceof Error?Z.message:String(Z);this.log("socket_error",{message:j}),this.emit("error",{message:j})},close:()=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close"),this.emit("close",{code:1006,reason:"socket closed"})}}})}catch(B){this.readyState=3;let L=B instanceof Error?B.message:String(B);this.log("connect_exception",{message:L}),this.emit("error",{message:L})}}onData(Y){if(this.rxBuffer=SL(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
150
150
  \r
151
151
  `);if(J===-1)return;let Q=X.slice(0,J),$=Q.split(`\r
152
- `)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=QY($);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
152
+ `)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=$Y($);if(W!==101){if(W===void 0){this.readyState=3;try{this.socket?.end()}catch{}this.log("upgrade_failed",{statusLine:$}),this.emit("error",{message:`WS upgrade failed: ${$}`});return}if(!this.emitRejectedUpgrade())return;try{this.socket?.end()}catch{}return}if(!G||G[1]!==this.expectedAccept){this.readyState=3;try{this.socket?.end()}catch{}this.log("accept_mismatch",{statusLine:$}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(J+4),this.log("open",{statusLine:$}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let X=Buffer.from(this.rxBuffer).indexOf(`\r
153
153
  \r
154
- `);if(X===-1)return!1;let J=rY(this.rxBuffer,X,Y);if(!J)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:J.status,partial:Y}),this.emit("error",J),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let X=Y[0],J=Y[1],Q=(X&128)!==0,$=X&15,G=(J&128)!==0,W=J&127,K=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],K=4}else if(W===127){if(Y.length<10)return;W=0;for(let U=0;U<8;U++)W=W*256+Y[2+U];K=10}if(G)K+=4;if(Y.length<K+W)return;let H=Y.slice(K,K+W);this.rxBuffer=Y.slice(K+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;try{this.socket?.end()}catch{}this.log("close_frame",{code:$,reason:G}),this.emit("close",{code:$,reason:G});return}if(X===1||X===2)this.fragOpcode=X,this.fragChunks=[J];else if(X===0)this.fragChunks.push(J);if(!Y)return;let Q=CL(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 c0({component:"raw-ws-bun",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function RL(Y){return Y}function TL(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function CL(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 _L}from"node:net";import{connect as IL}from"node:tls";var SL="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",ZG=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class C9{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];constructor(Y,X,J){this.url=Y,this.sessionID=J?.sessionID,this.connect(Y,X)}addEventListener(Y,X,J){this.listeners[Y]?.add(X)}removeEventListener(Y,X){this.listeners[Y]?.delete(X)}emit(Y,X){for(let J of[...this.listeners[Y]??[]])try{J(X)}catch{}}async connect(Y,X){let J=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),Q=J.hostname,$=J.port?Number(J.port):J.protocol==="https:"?443:80,G=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),K=Buffer.from(W).toString("base64"),H=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(K+SL));this.expectedAccept=Buffer.from(new Uint8Array(H)).toString("base64");let U={};for(let[B,L]of Object.entries(X))U[B.toLowerCase()]=L;let N=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${K}`];for(let B of ZG)if(U[B]!==void 0)N.push(`${kL(B)}: ${U[B]}`);for(let[B,L]of Object.entries(X))if(!ZG.includes(B.toLowerCase())&&B.toLowerCase()!=="content-length")N.push(`${B}: ${L}`);let O=`${N.join(`\r
154
+ `);if(X===-1)return!1;let J=rY(this.rxBuffer,X,Y);if(!J)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:J.status,partial:Y}),this.emit("error",J),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let X=Y[0],J=Y[1],Q=(X&128)!==0,$=X&15,G=(J&128)!==0,W=J&127,K=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],K=4}else if(W===127){if(Y.length<10)return;W=0;for(let H=0;H<8;H++)W=W*256+Y[2+H];K=10}if(G)K+=4;if(Y.length<K+W)return;let U=Y.slice(K,K+W);this.rxBuffer=Y.slice(K+W),this.handleFrame(Q,$,U)}}handleFrame(Y,X,J){if(X===9){this.writeFrame(10,J);return}if(X===10)return;if(X===8){let $=1005,G="";if(J.length>=2)$=J[0]<<8|J[1],G=Buffer.from(J.slice(2)).toString("utf-8");this.readyState=3;try{this.socket?.end()}catch{}this.log("close_frame",{code:$,reason:G}),this.emit("close",{code:$,reason:G});return}if(X===1||X===2)this.fragOpcode=X,this.fragChunks=[J];else if(X===0)this.fragChunks.push(J);if(!Y)return;let Q=kL(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let $=Buffer.from(Q).toString("utf-8");this.emit("message",{data:$})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),$;if(J<126)$=[128|Y,128|J];else if(J<65536)$=[128|Y,254,J>>8&255,J&255];else{$=[128|Y,255];for(let K=7;K>=0;K--)$.push(J/2**(8*K)&255)}let G=new Uint8Array(J);for(let K=0;K<J;K++)G[K]=X[K]^Q[K%4];let W=new Uint8Array($.length+4+J);W.set($,0),W.set(Q,$.length),W.set(G,$.length+4);try{this.enqueueWrite(W)}catch{}}enqueueWrite(Y){this.writeQueue.push(Y),this.flushWrites()}flushWrites(){let Y=this.socket;if(!Y)return;while(this.writeQueue.length>0){let X=this.writeQueue[0],J=Y.write(X);if(J<X.length){this.writeQueue[0]=X.slice(J),this.log("write_backpressure",{written:J,remaining:X.length-J});return}this.writeQueue.shift()}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return p0({component:"raw-ws-bun",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function IL(Y){return Y}function SL(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function kL(Y){let X=0;for(let $ of Y)X+=$.length;let J=new Uint8Array(X),Q=0;for(let $ of Y)J.set($,Q),Q+=$.length;return J}import{connect as bL}from"node:net";import{connect as xL}from"node:tls";var vL="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",OG=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class C9{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];constructor(Y,X,J){this.url=Y,this.sessionID=J?.sessionID,this.connect(Y,X)}addEventListener(Y,X,J){this.listeners[Y]?.add(X)}removeEventListener(Y,X){this.listeners[Y]?.delete(X)}emit(Y,X){for(let J of[...this.listeners[Y]??[]])try{J(X)}catch{}}async connect(Y,X){let J=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),Q=J.hostname,$=J.port?Number(J.port):J.protocol==="https:"?443:80,G=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),K=Buffer.from(W).toString("base64"),U=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(K+vL));this.expectedAccept=Buffer.from(new Uint8Array(U)).toString("base64");let H={};for(let[B,L]of Object.entries(X))H[B.toLowerCase()]=L;let N=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${K}`];for(let B of OG)if(H[B]!==void 0)N.push(`${hL(B)}: ${H[B]}`);for(let[B,L]of Object.entries(X))if(!OG.includes(B.toLowerCase())&&B.toLowerCase()!=="content-length")N.push(`${B}: ${L}`);let O=`${N.join(`\r
155
155
  `)}\r
156
156
  \r
157
- `;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let B=()=>{this.socket?.write(O)},L=J.protocol==="https:"?IL({host:Q,port:$,servername:Q},B):_L({host:Q,port:$},B);this.socket=L,L.on("data",(Z)=>{this.onData(typeof Z==="string"?Buffer.from(Z,"binary"):Z)}),L.on("error",(Z)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let j=Z instanceof Error?Z.message:String(Z);this.log("socket_error",{message:j}),this.emit("error",{message:j})}),L.on("close",(Z)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close",{hadError:Z}),this.emit("close",{code:1006,reason:"socket closed"})})}catch(B){this.readyState=3,this.log("connect_exception",{message:B instanceof Error?B.message:String(B)}),this.emit("error",{message:B instanceof Error?B.message:String(B)})}}onData(Y){if(this.rxBuffer=bL(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
157
+ `;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let B=()=>{this.socket?.write(O)},L=J.protocol==="https:"?xL({host:Q,port:$,servername:Q},B):bL({host:Q,port:$},B);this.socket=L,L.on("data",(Z)=>{this.onData(typeof Z==="string"?Buffer.from(Z,"binary"):Z)}),L.on("error",(Z)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let j=Z instanceof Error?Z.message:String(Z);this.log("socket_error",{message:j}),this.emit("error",{message:j})}),L.on("close",(Z)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close",{hadError:Z}),this.emit("close",{code:1006,reason:"socket closed"})})}catch(B){this.readyState=3,this.log("connect_exception",{message:B instanceof Error?B.message:String(B)}),this.emit("error",{message:B instanceof Error?B.message:String(B)})}}onData(Y){if(this.rxBuffer=gL(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
158
158
  \r
159
159
  `);if(J===-1)return;let Q=X.slice(0,J),$=Q.split(`\r
160
- `)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=QY($);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
160
+ `)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=$Y($);if(W!==101){if(W===void 0){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:$}),this.emit("error",{message:`WS upgrade failed: ${$}`});return}if(!this.emitRejectedUpgrade())return;this.socket?.destroy?.();return}if(!G||G[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:$}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(J+4),this.log("open",{statusLine:$}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let X=Buffer.from(this.rxBuffer).indexOf(`\r
161
161
  \r
162
- `);if(X===-1)return!1;let J=rY(this.rxBuffer,X,Y);if(!J)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:J.status,partial:Y}),this.emit("error",J),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let X=Y[0],J=Y[1],Q=(X&128)!==0,$=X&15,G=(J&128)!==0,W=J&127,K=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],K=4}else if(W===127){if(Y.length<10)return;W=0;for(let U=0;U<8;U++)W=W*256+Y[2+U];K=10}if(G)K+=4;if(Y.length<K+W)return;let H=Y.slice(K,K+W);this.rxBuffer=Y.slice(K+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;try{this.socket?.end()}catch{}this.emit("close",{code:$,reason:G});return}if(X===1||X===2)this.fragOpcode=X,this.fragChunks=[J];else if(X===0)this.fragChunks.push(J);if(!Y)return;let Q=xL(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 c0({component:"raw-ws-node",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function kL(Y){return Y}function bL(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function xL(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 vL(){return typeof globalThis.Bun?.connect==="function"}var OG=vL()?T9:C9;function sY(Y){return process.env[Y]??process.env[Y.toLowerCase()]}function hL(Y){let X=sY("NO_PROXY");if(!X)return!1;let J=Y.hostname.toLowerCase(),Q=X.split(",").map(($)=>$.trim().toLowerCase()).filter(Boolean);for(let $ of Q){if($==="*")return!0;if($.startsWith(".")){if(J===$.slice(1)||J.endsWith($))return!0}else if(J===$||J.endsWith(`.${$}`))return!0}return!1}function gL(Y){let X=new URL(Y);if(hL(X))return;if(X.protocol==="http:")return sY("HTTP_PROXY");if(X.protocol==="https:")return sY("HTTPS_PROXY")??sY("HTTP_PROXY");return}var FG={getProxyForUrl:gL};var yL=L0("quota"),PG="responses_websockets=2026-02-06",qG=["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"],fL=new Set([r0,"x-opencode-title"]);function mL(Y){let X=new Map;for(let Q of Object.keys(Y))X.set(Q.toLowerCase(),Q);let J={};for(let Q of qG){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(!qG.includes(Q.toLowerCase()))J[Q]=$;return J}function cL(Y){let X={};for(let[J,Q]of Object.entries(Y)){if(fL.has(J.toLowerCase()))continue;X[J]=Q}return X}function uL(Y){return Y.replace(/^http/,"ws")}function pL(Y){let X={};if(!Y)return X;if(Y instanceof Headers)return Y.forEach((J,Q)=>{X[Q.toLowerCase()]=J}),X;if(Array.isArray(Y)){for(let[J,Q]of Y)X[J.toLowerCase()]=Q;return X}for(let[J,Q]of Object.entries(Y))if(Q!=null)X[J.toLowerCase()]=String(Q);return X}function I9(Y){return Y instanceof DOMException&&Y.name==="AbortError"}var wG=new WeakSet;function lL(Y){return typeof Y==="object"&&Y!==null&&wG.has(Y)}function jG(Y,X){let J=Error(Y,X===void 0?void 0:{cause:X});return wG.add(J),J}function dL(Y){return new Promise((X,J)=>{if(Y.signal?.aborted){J(_9(Y.signal));return}let Q={...Y.headers,"openai-beta":Y.headers["openai-beta"]??PG},$=Q[r0]??Q["session-id"];delete Q["content-length"],Q=mL(cL(Q));let G=typeof Bun>"u"?void 0:FG.getProxyForUrl(Y.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),W=!0,K=Y.rawWebSocket?new OG(Y.url,Q,{sessionID:$}):new globalThis.WebSocket(Y.url,{headers:Q,...G?{proxy:G}:{},perMessageDeflate:W}),H=Y.timeout?setTimeout(()=>{U(),K.close(),J(Error("WebSocket connect timed out"))},Y.timeout):void 0;function U(){if(H)clearTimeout(H);K.removeEventListener("open",N),K.removeEventListener("error",O),K.removeEventListener("close",B),Y.signal?.removeEventListener("abort",L)}function N(){U(),X(K)}function O(Z){U(),J(jG(o0(Z),Z))}function B(Z){U(),J(jG(MG("WebSocket closed before open",Z.code,Z.reason)))}function L(){U(),K.close(),J(_9(Y.signal))}K.addEventListener("open",N,{once:!0}),K.addEventListener("error",O,{once:!0}),K.addEventListener("close",B,{once:!0}),Y.signal?.addEventListener("abort",L,{once:!0})})}function iL(Y){let X=new TextEncoder,J=Y.socket,Q,$=()=>{},G=!1,W=!1,K,H=new Set;function U(){if(K)clearTimeout(K);$(),Y.signal?.removeEventListener("abort",P)}function N(S=J){S.close()}function O(){U(),Q?.enqueue(X.encode(`data: [DONE]
162
+ `);if(X===-1)return!1;let J=rY(this.rxBuffer,X,Y);if(!J)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:J.status,partial:Y}),this.emit("error",J),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let X=Y[0],J=Y[1],Q=(X&128)!==0,$=X&15,G=(J&128)!==0,W=J&127,K=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],K=4}else if(W===127){if(Y.length<10)return;W=0;for(let H=0;H<8;H++)W=W*256+Y[2+H];K=10}if(G)K+=4;if(Y.length<K+W)return;let U=Y.slice(K,K+W);this.rxBuffer=Y.slice(K+W),this.handleFrame(Q,$,U)}}handleFrame(Y,X,J){if(X===9){this.writeFrame(10,J);return}if(X===10)return;if(X===8){let $=1005,G="";if(J.length>=2)$=J[0]<<8|J[1],G=Buffer.from(J.slice(2)).toString("utf-8");this.readyState=3;try{this.socket?.end()}catch{}this.emit("close",{code:$,reason:G});return}if(X===1||X===2)this.fragOpcode=X,this.fragChunks=[J];else if(X===0)this.fragChunks.push(J);if(!Y)return;let Q=yL(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let $=Buffer.from(Q).toString("utf-8");this.emit("message",{data:$})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),$;if(J<126)$=[128|Y,128|J];else if(J<65536)$=[128|Y,254,J>>8&255,J&255];else{$=[128|Y,255];for(let K=7;K>=0;K--)$.push(J/2**(8*K)&255)}let G=new Uint8Array(J);for(let K=0;K<J;K++)G[K]=X[K]^Q[K%4];let W=new Uint8Array($.length+4+J);W.set($,0),W.set(Q,$.length),W.set(G,$.length+4);try{this.socket?.write(W)}catch{}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return p0({component:"raw-ws-node",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function hL(Y){return Y}function gL(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function yL(Y){let X=0;for(let $ of Y)X+=$.length;let J=new Uint8Array(X),Q=0;for(let $ of Y)J.set($,Q),Q+=$.length;return J}function fL(){return typeof globalThis.Bun?.connect==="function"}var FG=fL()?T9:C9;function sY(Y){return process.env[Y]??process.env[Y.toLowerCase()]}function mL(Y){let X=sY("NO_PROXY");if(!X)return!1;let J=Y.hostname.toLowerCase(),Q=X.split(",").map(($)=>$.trim().toLowerCase()).filter(Boolean);for(let $ of Q){if($==="*")return!0;if($.startsWith(".")){if(J===$.slice(1)||J.endsWith($))return!0}else if(J===$||J.endsWith(`.${$}`))return!0}return!1}function cL(Y){let X=new URL(Y);if(mL(X))return;if(X.protocol==="http:")return sY("HTTP_PROXY");if(X.protocol==="https:")return sY("HTTPS_PROXY")??sY("HTTP_PROXY");return}var qG={getProxyForUrl:cL};var uL=H0("quota"),wG="responses_websockets=2026-02-06",jG=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"],pL=new Set([t0,"x-opencode-title"]);function lL(Y){let X=new Map;for(let Q of Object.keys(Y))X.set(Q.toLowerCase(),Q);let J={};for(let Q of jG){let $=X.get(Q),G=$===void 0?void 0:Y[$];if($!==void 0&&G!==void 0)J[$]=G}for(let[Q,$]of Object.entries(Y))if(!jG.includes(Q.toLowerCase()))J[Q]=$;return J}function dL(Y){let X={};for(let[J,Q]of Object.entries(Y)){if(pL.has(J.toLowerCase()))continue;X[J]=Q}return X}function iL(Y){return Y.replace(/^http/,"ws")}function nL(Y){let X={};if(!Y)return X;if(Y instanceof Headers)return Y.forEach((J,Q)=>{X[Q.toLowerCase()]=J}),X;if(Array.isArray(Y)){for(let[J,Q]of Y)X[J.toLowerCase()]=Q;return X}for(let[J,Q]of Object.entries(Y))if(Q!=null)X[J.toLowerCase()]=String(Q);return X}function I9(Y){return Y instanceof DOMException&&Y.name==="AbortError"}var EG=new WeakSet;function oL(Y){return typeof Y==="object"&&Y!==null&&EG.has(Y)}function DG(Y,X){let J=Error(Y,X===void 0?void 0:{cause:X});return EG.add(J),J}function rL(Y){return new Promise((X,J)=>{if(Y.signal?.aborted){J(_9(Y.signal));return}let Q={...Y.headers,"openai-beta":Y.headers["openai-beta"]??wG},$=Q[t0]??Q["session-id"];delete Q["content-length"],Q=lL(dL(Q));let G=typeof Bun>"u"?void 0:qG.getProxyForUrl(Y.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),W=!0,K=Y.rawWebSocket?new FG(Y.url,Q,{sessionID:$}):new globalThis.WebSocket(Y.url,{headers:Q,...G?{proxy:G}:{},perMessageDeflate:W}),U=Y.timeout?setTimeout(()=>{H(),K.close(),J(Error("WebSocket connect timed out"))},Y.timeout):void 0;function H(){if(U)clearTimeout(U);K.removeEventListener("open",N),K.removeEventListener("error",O),K.removeEventListener("close",B),Y.signal?.removeEventListener("abort",L)}function N(){H(),X(K)}function O(Z){H(),J(DG(a0(Z),Z))}function B(Z){H(),J(DG(AG("WebSocket closed before open",Z.code,Z.reason)))}function L(){H(),K.close(),J(_9(Y.signal))}K.addEventListener("open",N,{once:!0}),K.addEventListener("error",O,{once:!0}),K.addEventListener("close",B,{once:!0}),Y.signal?.addEventListener("abort",L,{once:!0})})}function sL(Y){let X=new TextEncoder,J=Y.socket,Q,$=()=>{},G=!1,W=!1,K,U=new Set;function H(){if(K)clearTimeout(K);$(),Y.signal?.removeEventListener("abort",S)}function N(_=J){_.close()}function O(){H(),Q?.enqueue(X.encode(`data: [DONE]
163
163
 
164
- `)),Q?.close()}function B(S){if(G)return;G=!0,U(),Y.onConnectionInvalid?.(S),Q?.error(S)}function L(S){if(G)return;if(!Y.idleTimeout)return;if(K)clearTimeout(K);K=setTimeout(()=>B(new R0(S)),Y.idleTimeout)}async function Z(S){if(G)return;if(typeof S.data!=="string"){B(new R0("Unexpected binary WebSocket frame"));return}let d=S.data,m=(()=>{try{let u=JSON.parse(d);return typeof u==="object"&&u!==null?u:void 0}catch{return}})();if(m?.type==="codex.rate_limits"){yL.debug("codex.rate_limits frame received",{pid:process.pid}),L("idle timeout waiting for websocket");let u=DG(m);Y.onQuota?.(u);return}let e=!W?$Y(m):void 0;if(e&&m){G=!0,U(),Y.onRateLimitReached?.(e.window,e.resetAt),Y.onTerminal?.(m),Y.onFirstEvent?.(),Q?.error(new R0(`OpenAI account rate limit reached at admission (${e.window})`));return}if(m?.type==="error"&&Y.onRetryableTerminal){if($(),K)clearTimeout(K);K=void 0;try{let u=await Y.onRetryableTerminal(m);if(G){if(u)N(u);return}if(u){x(u);return}}catch(u){B(new R0(u instanceof Error?u.message:String(u),{cause:u}));return}}let y=aL(m,d);if(y&&m){if(!W)Y.onFirstEvent?.(y);G=!0,U(),Y.onTerminal?.(m),Q?.error(new m1({message:y.message,url:J.url,requestBodyValues:Y.body,statusCode:y.status,responseHeaders:y.headers,responseBody:y.body}));return}if(_(m)&&m.type==="response.failed"){let u=_(m.response)?m.response.failed:void 0,g0=_(u)?u.rate_limit_reached_type:void 0;if(typeof g0==="string"){if(G=!0,U(),Y.onRateLimitReached?.(g0),Y.onTerminal?.(m),!W)Y.onFirstEvent?.(),Q?.error(new R0(`OpenAI account rate limit reached mid-stream (${g0})`));else O();return}}if(m)nL(m,Y.sessionID),rL(m,H);let s=m?I8(m):m;if(!s){if(!W)Y.onFirstEvent?.();L("idle timeout waiting for websocket");return}let j1=s===m?d:JSON.stringify(s);if(!W)Y.onFirstEvent?.();if(Q?.enqueue(X.encode(`${j1.split(/\r?\n/).map((u)=>`data: ${u}`).join(`
164
+ `)),Q?.close()}function B(_){if(G)return;G=!0,H(),Y.onConnectionInvalid?.(_),Q?.error(_)}function L(_){if(G)return;if(!Y.idleTimeout)return;if(K)clearTimeout(K);K=setTimeout(()=>B(new R0(_)),Y.idleTimeout)}async function Z(_){if(G)return;if(typeof _.data!=="string"){B(new R0("Unexpected binary WebSocket frame"));return}let u=_.data,m=(()=>{try{let p=JSON.parse(u);return typeof p==="object"&&p!==null?p:void 0}catch{return}})();if(m?.type==="codex.rate_limits"){uL.debug("codex.rate_limits frame received",{pid:process.pid}),L("idle timeout waiting for websocket");let p=PG(m);Y.onQuota?.(p);return}let d=!W?GY(m):void 0;if(d&&m){G=!0,H(),Y.onRateLimitReached?.(d.window,d.resetAt),Y.onTerminal?.(m),Y.onFirstEvent?.(),Q?.error(new R0(`OpenAI account rate limit reached at admission (${d.window})`));return}if(m?.type==="error"&&Y.onRetryableTerminal){if($(),K)clearTimeout(K);K=void 0;try{let p=await Y.onRetryableTerminal(m);if(G){if(p)N(p);return}if(p){b(p);return}}catch(p){B(new R0(p instanceof Error?p.message:String(p),{cause:p}));return}}let y=XN(m,u);if(y&&m){if(!W)Y.onFirstEvent?.(y);G=!0,H(),Y.onTerminal?.(m),Q?.error(new c1({message:y.message,url:J.url,requestBodyValues:Y.body,statusCode:y.status,responseHeaders:y.headers,responseBody:y.body}));return}if(I(m)&&m.type==="response.failed"){let p=I(m.response)?m.response.failed:void 0,r0=I(p)?p.rate_limit_reached_type:void 0;if(typeof r0==="string"){if(G=!0,H(),Y.onRateLimitReached?.(r0),Y.onTerminal?.(m),!W)Y.onFirstEvent?.(),Q?.error(new R0(`OpenAI account rate limit reached mid-stream (${r0})`));else O();return}}if(m)aL(m,Y.sessionID),eL(m,U);let e=m?I8(m):m;if(!e){if(!W)Y.onFirstEvent?.();L("idle timeout waiting for websocket");return}let g0=e===m?u:JSON.stringify(e);if(!W)Y.onFirstEvent?.();if(Q?.enqueue(X.encode(`${g0.split(/\r?\n/).map((p)=>`data: ${p}`).join(`
165
165
  `)}
166
166
 
167
- `)),W=!0,L("idle timeout waiting for websocket"),!s)return;if(s.type==="response.completed"||s.type==="response.done"){G=!0,sL(s,H),Y.onComplete?.(s,H),Y.onTerminal?.(s),O();return}if(s.type==="response.failed"||s.type==="response.incomplete"||s.type==="error")G=!0,Y.onTerminal?.(s),O()}function j(S){B(new R0(o0(S),{cause:S}))}function w(S){if(G)return;B(new R0(MG("WebSocket closed before response.completed",S.code,S.reason)))}function P(){let S=_9(Y.signal);if(G)return;G=!0,U(),N(),Y.onAbort?.(S),Q?.error(S)}function k(S){if(G)return;G=!0,U(),N(),Y.onAbort?.(tL(S))}function x(S){$(),J=S,J.addEventListener("message",Z),J.addEventListener("error",j,{once:!0}),J.addEventListener("close",w,{once:!0}),$=()=>{J.removeEventListener("message",Z),J.removeEventListener("error",j),J.removeEventListener("close",w)};let{background:d,...m}=Y.body;L("idle timeout sending websocket request");try{J.send(JSON.stringify({type:"response.create",...m})),L("idle timeout waiting for websocket")}catch(e){if(G)return;B(new R0(e instanceof Error?e.message:String(e),{cause:e}))}}return new Response(new ReadableStream({start(S){if(Q=S,Y.signal?.addEventListener("abort",P,{once:!0}),Y.signal?.aborted){P();return}x(J)},cancel(S){k(S)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function nL(Y,X){if(!oL(Y))return;await c0({component:"ws",event:"provider_native_web_search_event",sessionID:X,serverEventType:Y.type,itemType:_(Y.item)?Y.item.type:void 0,serverEvent:Y})}function oL(Y){if(typeof Y.type==="string"&&(Y.type.startsWith("response.web_search_call.")||Y.type.startsWith("response.web_search_preview_call.")))return!0;if(_(Y.item)&&typeof Y.item.type==="string")return Y.item.type==="web_search_call"||Y.item.type==="web_search_preview_call";return!1}function rL(Y,X){if(Y.type!=="response.output_item.done")return;if(!_(Y.item))return;EG(Y.item,X)}function sL(Y,X){let J=Y.response;if(!_(J)||!Array.isArray(J.output))return;for(let Q of J.output)if(_(Q))EG(Q,X)}function EG(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 aL(Y,X){if(Y?.type!=="error")return;let J=Y.status??Y.status_code;if(typeof J!=="number"||J>=200&&J<300)return;return{status:J,headers:_(Y.headers)?Object.fromEntries(Object.entries(Y.headers).flatMap(([Q,$])=>typeof $==="string"||typeof $==="number"||typeof $==="boolean"?[[Q,String($)]]:[])):void 0,body:X,message:_(Y.error)&&typeof Y.error.message==="string"?Y.error.message:`${J}`}}function $Y(Y){if(typeof Y==="string")try{return $Y(JSON.parse(Y))}catch{return}if(!_(Y))return;let X=$Y(Y.cause);if(X)return X;let J=$Y(Y.body);if(J)return J;let Q=_(Y.error)?Y.error:Y,$=typeof Q.type==="string"?Q.type:void 0,G=Y.status??Y.status_code;if($!=="usage_limit_reached"&&G!==429)return;let{resets_at:W,resets_in_seconds:K}=Q,H=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:H}}function tL(Y){if(I9(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function _9(Y){let X=Y?.reason;if(I9(X))return X;if(eL(X))return X;return new DOMException(X instanceof Error?X.message:"Aborted","AbortError")}function eL(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function MG(Y,X,J){let Q=[`code ${X}`];if(X===1009)Q.push("message too big");if(J.length>0)Q.push(J.toString());return`${Y} (${Q.join(": ")})`}var k9="x-opencode-title",aY="x-openai-auth-quota-account",S9=new Set([k9,r0,aY,"x-opencode-session"]),XN=15000,JN=300000,QN=3300000,AG="websocket_connection_limit_reached";function $N(Y){let X=typeof Y.authorization==="string"&&Y.authorization.startsWith("Bearer ")?Y.authorization.slice(7):"",J=typeof Y["chatgpt-account-id"]==="string"?Y["chatgpt-account-id"]:"";return YN("sha256").update(`${X}:${J}`).digest("hex").slice(0,12)}function GN(Y){let X=Y?.httpFetch??globalThis.fetch,J=new Map,Q=Y?.connectTimeout??XN,$=Y?.idleTimeout??JN,G=Y?.maxConnectionAge??QN,W=Y?.streamRetries??5,K=Y?.firstEventGraceMs??250,H=Y?.rawWebSocket??!1,U=Y?.onQuota,N=Y?.onRateLimitReached,O=setInterval(()=>Z(),Math.min($,60000));if(typeof O==="object"&&"unref"in O&&typeof O.unref==="function")O.unref();async function B(P,k){let x=P instanceof URL?P.toString():typeof P==="string"?P:P.url,S=D0.normalizeHeaders(k?.headers),d=xG(k),m=wY(d);if(k?.method!=="POST"||!new URL(x).pathname.endsWith("/responses"))return X(P,m);let e=(()=>{try{if(typeof k?.body!=="string")return;let a=JSON.parse(k.body);return typeof a==="object"&&a!==null?a:void 0}catch{return}})();if(!e?.stream)return X(P,m);if(S[k9]==="true")return X(P,m);let y=S[r0]??S["x-session-affinity"]??S["session-id"],s=y;if(!y)return X(P,m);let j1=D0.normalizeHeaders(d?.headers),u=$N(j1),g0=`${y}:${u}:conversation`,x1=typeof S[aY]==="string"?S[aY]:void 0,D1=N?(a,z0)=>N(a,x1,z0):void 0,g=J.get(g0)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};if(J.set(g0,g),g.fallback)return X(P,m);if(g.busy)return X(P,m);g.busy=!0,g.lastUsedAt=Date.now();try{let a=ZN(e),z0=D0.normalizeHeaders(d?.headers),J8=typeof z0.authorization==="string"&&z0.authorization.startsWith("Bearer ")?z0.authorization.slice(7):"",Q8=typeof z0["chatgpt-account-id"]==="string"?z0["chatgpt-account-id"]:void 0,P1=U?(Q0)=>U(Q0,J8,x1,Q8):void 0,VY=!g.socket&&!g.continuation?BN(z0):z0;if(g.socket=await UN(g,Y?.url??x,VY,Q,G,H,k?.signal),jN(g,a))await HN(g,a,$,{signal:k?.signal??void 0,sessionID:s,url:Y?.url??x,headers:d?.headers,onRateLimitReached:D1});let y0=()=>{},G1=()=>{},n0=new Promise((Q0,k0)=>{y0=Q0,G1=k0}),W1=qN(g,a),v1=GY(SG(g,W1,a)),z1=typeof v1.previous_response_id==="string";await A1({sessionID:s,transport:"websocket",phase:"main",bodyText:JSON.stringify(v1),url:Y?.url??x,method:d?.method,headers:d?.headers});let B0=D0.streamResponsesWebSocket({socket:g.socket,body:v1,sessionID:s??void 0,idleTimeout:$,signal:k?.signal??void 0,onQuota:P1,onRateLimitReached:D1,onFirstEvent:(Q0)=>y0(Q0??!0),onComplete:(Q0,k0)=>{let K1=TG(Q0);c0({component:"ws-pool",event:"main_completed",sessionID:s,responseID:RG(Q0),usage:K1}),IG(g,a,Q0,k0,z1)},onTerminal:(Q0)=>{if(g.busy=!1,g.lastUsedAt=Date.now(),g.streamFailures=0,Q0.type!=="response.completed"&&Q0.type!=="response.done")g.continuation=void 0,i0(g)},onConnectionInvalid:()=>{if(g.busy=!1,g.lastUsedAt=Date.now(),!g.fallback)L(g);g.continuation=void 0,i0(g),y0(!1)},onAbort:(Q0)=>{g.busy=!1,g.lastUsedAt=Date.now(),g.streamFailures=0,g.continuation=void 0,i0(g),G1(Q0)},onRetryableTerminal:async(Q0)=>{let k0=WN(Q0);if(!k0)return;throw g.fallback=!0,k0}}),q0=await zN(n0,K);if(q0!==!1){if(q0===!0||q0.status<200||q0.status>599)return B0;return new Response(q0.body,{status:q0.status,headers:{"content-type":"application/json",...q0.headers}})}if(!g.fallback)return B0;return X(P,m)}catch(a){if(g.busy=!1,g.lastUsedAt=Date.now(),D0.isAbortError(a))throw g.streamFailures=0,g.continuation=void 0,i0(g),a;let z0=D0.parseRateLimitSignal(a);if(z0)D1?.(z0.window,z0.resetAt);if(D0.isUpgradeFailure(a)&&!H)g.fallback=!0;if(L(g),g.continuation=void 0,i0(g),g.fallback)return X(P,m);return KN(new R0(a instanceof Error?a.message:String(a),{cause:a}))}}function L(P){if(P.streamFailures++,P.streamFailures>W)P.fallback=!0}function Z(){let P=Date.now();for(let[k,x]of J){if(x.busy)continue;if(P-x.lastUsedAt<$)continue;i0(x),J.delete(k)}}function j(){clearInterval(O);for(let P of J.values())i0(P);J.clear()}function w(P){let k=`${P}:`;for(let[x,S]of J){if(!x.startsWith(k))continue;i0(S),J.delete(x)}}return Object.assign(B,{close:j,remove:w})}function WN(Y){if(Y.type!=="error"||!_(Y.error)||Y.error.code!==AG)return;return Error(typeof Y.error.message==="string"?Y.error.message:AG)}async function zN(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 KN(Y){return new Response(new ReadableStream({start(X){X.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function UN(Y,X,J,Q,$,G,W){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<$)return Y.socket;i0(Y);let K=await D0.connectResponsesWebSocket({url:D0.toWebSocketUrl(X),headers:J,timeout:Q,rawWebSocket:G,signal:W??void 0});return Y.connectedAt=Date.now(),K}function i0(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function HN(Y,X,J,Q){if(!Y.socket||!Array.isArray(X.input)||X.input.length===0)return;let $=NN(X);await A1({sessionID:Q.sessionID,transport:"websocket",phase:"prewarm",bodyText:JSON.stringify($),url:Q.url,method:"POST",headers:Q.headers});let G=D0.streamResponsesWebSocket({socket:Y.socket,body:$,sessionID:Q.sessionID,idleTimeout:J,signal:Q.signal,onRateLimitReached:Q.onRateLimitReached,onComplete:(W,K)=>{c0({component:"ws-pool",event:"prewarm_completed",sessionID:Q.sessionID,responseID:RG(W),usage:TG(W)}),IG(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}});await LN(G)}function RG(Y){let X=Y.response;if(!_(X))return;return typeof X.id==="string"?X.id:void 0}function TG(Y){let X=Y.response;if(!_(X))return;return _(X.usage)?X.usage:void 0}async function LN(Y){let X=Y.body?.getReader();if(!X)return;while(!0)if((await X.read()).done)return}function NN(Y){return GY({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:VN(Y.client_metadata)})}function CG(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 VN(Y){if(!_(Y))return Y;if(typeof Y["x-codex-turn-metadata"]!=="string")return Y;try{let X=JSON.parse(Y["x-codex-turn-metadata"]);if(!_(X))return Y;return{...Y,"x-codex-turn-metadata":CG(X),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function BN(Y){let X=Y["x-codex-turn-metadata"];if(!X)return Y;try{let J=JSON.parse(X);if(!_(J))return Y;return{...Y,"x-codex-turn-metadata":CG(J)}}catch{return Y}}var _G=["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 ZN(Y){let X={...Y};if(Array.isArray(Y.input))X.input=Y.input.map(ON);return X}function GY(Y){let X={};for(let J of _G)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 ON(Y){if(!_(Y))return Y;if(typeof Y.type==="string")return Y;if(typeof Y.role!=="string")return Y;if(!("content"in Y))return Y;return{...Y,type:"message"}}function IG(Y,X,J,Q,$){let G=J.response,W=_(G)&&typeof G.id==="string"?G.id:void 0;if(!W||!Array.isArray(X.input)){Y.continuation=void 0;return}let K=$?new Set(Y.continuation?.finalizedCallIds):new Set;for(let H of Q)K.add(H);Y.continuation={responseID:W,input:X.input,signature:b9(X),finalizedCallIds:K}}function SG(Y,X,J=X){let Q=Array.isArray(X.input)?X.input:[],$=Array.isArray(J.input)?J.input:Q,G=b9(J),W=Y.turnInput&&Y.turnSignature===G?FN(Y.turnInput,$):void 0,K=W===void 0?Q:$.slice(W);if(K.length>0&&K.some(kG)||!Y.turnID)Y.turnID=N1(),Y.turnStartedAt=Date.now();Y.turnInput=$.slice(),Y.turnSignature=G;let U=X.client_metadata;if(!_(U)||typeof U["x-codex-turn-metadata"]!=="string")return X;let N;try{N=JSON.parse(U["x-codex-turn-metadata"])}catch{return X}if(!_(N))return X;let O=JSON.stringify({session_id:N.session_id,thread_id:N.thread_id,thread_source:N.thread_source,turn_id:Y.turnID,sandbox:N.sandbox,turn_started_at_unix_ms:Y.turnStartedAt,request_kind:"turn",window_id:N.window_id});return{...X,client_metadata:{...U,"x-codex-turn-metadata":O}}}function FN(Y,X){if(Y.length>X.length)return;for(let J=0;J<Y.length;J++)if(u0(Y[J])!==u0(X[J]))return;return Y.length}function qN(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!J||!Y.continuation)return X;if(Y.continuation.signature!==b9(X))return Y.continuation=void 0,X;if(!bG(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),$=DN(Q,Y.continuation.finalizedCallIds);if($.length===0)return X;return{...X,previous_response_id:Y.continuation.responseID,input:$}}function jN(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!Y.continuation)return!0;if(!J)return!1;if(!bG(Y.continuation.input,J))return!0;return J.slice(Y.continuation.input.length).some(kG)}function kG(Y){if(!_(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function DN(Y,X){return Y.filter((J)=>{if(!_(J))return!0;if(typeof J.type==="string"&&J.type.endsWith("_output"))return!0;if(J.type==="function_call_output"||J.type==="custom_tool_call_output")return!0;if(J.type==="function_call"||J.type==="custom_tool_call"){let Q=typeof J.call_id==="string"?J.call_id:typeof J.id==="string"?J.id:void 0;return Q?!X.has(Q):!0}if(J.type==="message")return J.role!=="assistant";if(typeof J.role==="string")return J.role!=="assistant";return!1})}function b9(Y){return u0(PN(Object.fromEntries(Object.entries(Y).filter(([X])=>X!=="input"&&X!=="stream"&&X!=="background"&&X!=="previous_response_id"&&X!=="generate"))))}function PN(Y){if(!_(Y.client_metadata))return Y;let X=Object.fromEntries(Object.entries(Y.client_metadata).filter(([J])=>J!=="x-codex-turn-metadata"&&J!=="x-codex-ws-stream-request-start-ms"));return{...Y,client_metadata:X}}function bG(Y,X){if(Y.length>=X.length)return!1;for(let J=0;J<Y.length;J++)if(u0(Y[J])!==u0(X[J]))return!1;return!0}function xG(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let X=new Headers(Y.headers);for(let J of S9)X.delete(J);return{...Y,headers:X}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((X)=>!S9.has(X[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([X])=>!S9.has(X.toLowerCase())))}}var CN=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),_N=new Set(["gpt-5.6"]),IN=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),SN="opencode-oauth-dummy-key",kN="terminal_resize_reflow",g9="0.144.0",bN=`codex_exec/${g9} (Debian 12.0.0; aarch64) unknown (codex_exec; ${g9})`,xN="seccomp",vN="main-refresh",hN=120000,gN=90000,yN=4000,vG=50,hG=3,fN=25,mN=60000,cN="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",gG=!1,yG=L0("models"),fG=!1,mG=!1;class f9 extends Error{code="OPENAI_AUTH_PERSIST_FAILED";constructor(Y){super("OpenAI OAuth token refreshed but could not be persisted; re-login required",{cause:Y});this.name="AuthPersistError"}}function v9(Y){return Y instanceof f9}function cG(){throw Error(cN)}function uN(Y){return Math.floor(Math.random()*Y)}function pN(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 lN(Y,X,J){let Q=Y.get(X);if(Q)return Q;let $=N1(),G={threadID:$,turnID:N1(),windowID:`${$}:0`};return Y.set(X,G),J?.(),G}function PW(){return TN(jY(),"openai-auth-sessions.json")}function dN(){let Y=new Map;try{let X=JSON.parse(EN(PW(),"utf8"));if(!_(X.sessions))return Y;for(let[J,Q]of Object.entries(X.sessions)){if(!_(Q)||typeof Q.threadID!=="string")continue;Y.set(J,{threadID:Q.threadID,turnID:N1(),windowID:`${Q.threadID}:0`})}}catch{}return Y}function iN(Y){let X=PW(),J=`${X}.tmp-${process.pid}`;try{wN(jY(),{recursive:!0});let Q={version:1,sessions:Object.fromEntries([...Y.entries()].map(([$,G])=>[$,{threadID:G.threadID}]))};RN(J,`${JSON.stringify(Q,null,2)}
168
- `,"utf8"),MN(J,X)}catch{}}function uG(Y,X){return _(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===X}function nN(Y,X){if(Y.length>X.length)return!1;for(let J=0;J<Y.length;J++)if(u0(Y[J])!==u0(X[J]))return!1;return!0}function oN(Y,X){if(!Y.input)return X.length>0;if(!nN(Y.input,X))return!0;return X.slice(Y.input.length).some((Q)=>uG(Q,"user")||uG(Q,"developer"))}function rN(Y,X){let J=Array.isArray(X?.input)?X.input:void 0;if(J&&(oN(Y,J)||!Y.turnID))Y.turnID=N1(),Y.turnStartedAt=Date.now();else if(!Y.turnStartedAt)Y.turnStartedAt=Date.now();if(J)Y.input=J}function sN(Y){if(!Y.metadata)return{init:Y.init};let X=pN(Y.init?.body);if(!Y.websocket)rN(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:xN,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",kN),Y.headers.set("x-codex-turn-metadata",J),Y.headers.set("user-agent",bN),Y.headers.set("version",g9),Y.dumpSessionID)Y.headers.set(r0,Y.dumpSessionID);let Q=X;if(!Q)return{init:Y.init};let $=Y.responsesLite&&typeof Q.model==="string"&&IN.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(QV);if(XV(Q),JV(Q),SX(Q),eN(Q),$)YV(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(GY(Q))}}}function aN(Y,X){return Y.find((J)=>J.enabled!==!1&&q1(J)&&(J.id===X||J.accountId===X))}function pG(Y,X){if(Y.resetCreditsAvailable!==void 0||X?.resetCreditsAvailable===void 0)return Y;return{...Y,resetCreditsAvailable:X.resetCreditsAvailable}}function tY(Y,X){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:X}}function wW(Y,X,J=Date.now(),Q=X.mainAccountId){let $=Y.getMain(),G=$?.quota;return{main:{quota:G?{...G,checkedAt:$.checkedAt,primary:tY(G.primary,$.checkedAt),secondary:tY(G.secondary,$.checkedAt)}:null,...typeof Q==="string"?{mainAccountId:Q}:{},killed:!1,...G?.resetCreditsAvailable!==void 0?{resetCredits:G.resetCreditsAvailable}:{}},fallbacks:X.accounts.filter((W)=>W.enabled).map((W)=>{let K=Y.getFallback(W.id),H=K?.quota;return{id:W.id,label:W.label,accountId:K?.accountId??W.accountId,quota:H?{...H,checkedAt:K.checkedAt,primary:tY(H.primary,K.checkedAt),secondary:tY(H.secondary,K.checkedAt)}:null,killed:!1,enabled:!0,...H?.resetCreditsAvailable!==void 0?{resetCredits:H.resetCreditsAvailable}:{}}}),route:X.routing?.mode??"main-first",lastUpdated:J}}function H4(Y,X,J,Q=Date.now()){return{...wW(Y,X,Q),activeId:J}}function lG(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 tN(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 dG(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}function eN(Y){if(!w0().webSearch)return;if(!Array.isArray(Y.tools)||Y.tools.length===0)return;if(Y.tools.some((X)=>_(X)&&X.type==="web_search"))return;Y.tools=[...Y.tools,{type:"web_search",external_web_access:!1,search_content_types:["text","image"]}]}function y9(Y){if(Array.isArray(Y)){for(let X of Y)y9(X);return}if(!_(Y))return;if(Y.type==="input_image")delete Y.detail;for(let X of Object.values(Y))y9(X)}function YV(Y){let X=_(Y.reasoning)?{...Y.reasoning}:{};X.context="all_turns",Y.reasoning=X,Y.parallel_tool_calls=!1;let J=Array.isArray(Y.input)?Y.input:[];y9(J);let $=[{type:"additional_tools",role:"developer",tools:Array.isArray(Y.tools)?Y.tools.filter((G)=>!(_(G)&&G.type==="web_search")):[]}];if(typeof Y.instructions==="string"&&Y.instructions.length>0)$.push({type:"message",role:"developer",content:[{type:"input_text",text:Y.instructions}]});Y.input=[...$,...J],delete Y.tools,delete Y.instructions}function XV(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(_(X)&&X.type==="function"&&X.name==="web_search"))}function JV(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(_(X)&&X.type==="function"&&X.name==="websearch_web_search_exa"))}function QV(Y){if(!_(Y))return Y;if(Y.type!=="function")return Y;let X=_(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:H,...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 $V(Y,X={}){let J=X.codexApiEndpoint??w0().codexApiEndpoint,Q=crypto.randomUUID(),$=dN(),G=()=>iN($),W=!1,K=[],H=null,U=null,N,O=new Z8;async function B(L,Z){let j=Y.client.session;if(typeof j?.promptAsync==="function"){let w=await fX(Y.client,L),P={noReply:!0,parts:[{type:"text",text:Z,ignored:!0}]};if(w?.agent)P.agent=w.agent;if(w?.model)P.model=w.model;if(w?.variant)P.variant=w.variant;await j.promptAsync({path:{id:L},body:P});return}}return{async dispose(){O.stop();for(let L of K)L.close();if(K.length=0,U){await U.stop().catch(()=>{});let L=globalThis;if(L.__openaiAuthRpcServer===U)L.__openaiAuthRpcServer=void 0;U=null}},async event(L){if(L.event.type!=="session.deleted")return;let Z=L.event.properties.info,j=$.get(Z.id);if(j)H?.cacheKeepManager?.remove(j.threadID);if($.delete(Z.id))G();if(N){let w=(await A0(U0()))?.accounts;await FW(Z.id,w,N)}for(let w of K)w.remove(Z.id)},provider:{id:"openai",async models(L,Z){if(Z.auth?.type!=="oauth")return L.models;let j=await A0(U0()),w=!j||zW(j),P=w?null:await vX();if(!w&&P&&!fG)fG=!0,yG.debug("restoring OAuth model costs from models.dev catalog");if(!w&&!P&&!mG)mG=!0,yG.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(L.models).filter(([,k])=>{if(k.options.reasoningMode==="pro")return!1;if(CN.has(k.api.id))return!0;if(_N.has(k.api.id))return!1;let S=k.api.id.match(/^gpt-(\d+\.\d+)/)?.[1];return S?parseFloat(S)>5.4:!1}).map(([k,x])=>[k,{...x,cost:w?{input:0,output:0,cache:{read:0,write:0}}:P?.[x.api.id]??P?.[k]??x.cost,limit:x.id.includes("gpt-5.5")?{context:400000,input:272000,output:128000}:x.id.includes("gpt-5.6")?{context:372000,input:244000,output:128000}:x.limit}]))}},tool:{web_search:_X},auth:{provider:"openai",async loader(L){let Z=await L();if(Z.type!=="oauth")return{};await UW({type:"oauth",access:Z.access??"",refresh:Z.refresh??"",expires:Z.expires??0},U0());let j=await A0(U0()).catch((V)=>{let F=U0();throw Error(`OpenAI auth store at ${F} is corrupt or unreadable: ${V instanceof Error?V.message:String(V)}. Fix or remove it to continue.`,{cause:V})}),w;async function P(){let V=U0();try{let F=AN(V);if(w?.path===V&&w.mtimeMs===F.mtimeMs&&w.size===F.size)return w.storage;let D=await A0(V);return w={path:V,mtimeMs:F.mtimeMs,size:F.size,storage:D},D}catch{return w=void 0,A0(V)}}function k(){w=void 0}if(j&&Z.access){let V=eY({id_token:"",access_token:Z.access,refresh_token:Z.refresh??""});if(V&&V!==j.mainAccountId)await X0((F)=>{return F.mainAccountId=V,F},U0()),j.mainAccountId=V,k()}let x=j?.logging?.level;if(x&&typeof x==="string")DY(x);let S=L0("transport"),d=L0("quota"),m=L0("refresh"),e=L0("accounts");S.info("codex auth loader ready",{codexApiEndpoint:J,transport:w0().rawWebSocket?"raw-websocket":w0().webSockets?"websocket":"http",webSearch:w0().webSearch});let y=new WW({storage:j,fetchQuotaFn:void 0}),s,j1=0,u=new HW({refreshFn:(V)=>b1({refreshToken:V.refreshToken,fetchImpl:V.fetchImpl,now:V.now}),quotaManager:y,onFallbackStorageChanged:k});if(j&&j.accounts.length>0)u.startBackgroundRefresh();let g0=L0("cachekeep"),x1=j?.cachekeep?.enabled===!0,D1=j?.cachekeep?.subagents===!0,g=j?.cachekeep?.sustain===!0,a=BX(j),z0;async function J8(V){await new Promise((F)=>setTimeout(F,V))}async function Q8(V){let F;for(let D=1;D<=hG;D++)try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:V.refresh,access:V.access,expires:V.expires}});return}catch(R){if(F=R,D<hG)await J8(fN*D)}throw new f9(F)}async function P1(V){await X0((F)=>{return F.refresh=F.refresh??{},V(F),F},U0()),k()}async function VY(V){let F=Date.now()+yN;while(Date.now()<F){await new Promise((I)=>setTimeout(I,vG+uN(vG)));let D=await L();if(D.type!=="oauth"||!D.access)continue;if((D.access!==V.access||D.refresh!==V.refresh||(D.expires??0)>(V.expires??0)+60000)&&(!D.expires||D.expires>Date.now()))return m.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:D.expires?D.expires-Date.now():void 0}),{access:D.access,refresh:D.refresh??V.refresh??"",expires:D.expires??0}}return null}async function y0(){if(!z0)z0=(async()=>{let V=await L();if(V.type!=="oauth")throw Error("not oauth");if(!V.refresh)throw Error("Token refresh failed: missing refresh token");let F=iG(V.refresh),D=await A0(U0()),R=D?.refresh?.mainLastRefreshError;if(R&&oG(R,V.refresh,Date.now()))throw Error(rG(R,Date.now()));if(D?.refresh?.mainRefreshLeaseUntil&&D.refresh.mainRefreshLeaseUntil>Date.now()&&D.refresh.mainRefreshLeaseTokenHash===F){let M=await VY(V);if(M)return M;throw Error("Codex OAuth refresh is already in progress")}let I=await PY({name:vN,ttlMs:hN,path:U0(),renew:!0});if(!I){let M=await VY(V);if(M)return M;throw Error("Codex OAuth refresh is already in progress")}let T=crypto.randomUUID(),C=F;try{await P1((h)=>{h.refresh=h.refresh??{},h.refresh.mainRefreshLeaseId=T,h.refresh.mainRefreshLeaseUntil=Date.now()+gN,h.refresh.mainRefreshLeaseTokenHash=F});let M=await A0(U0());if(M?.refresh?.mainRefreshLeaseId!==T||M.refresh.mainRefreshLeaseTokenHash!==F)throw Error("Codex OAuth refresh is already in progress");let E=await b1({refreshToken:V.refresh,fetchImpl:fetch,now:Date.now});return await Q8(E),await P1((h)=>{if(h.refresh=h.refresh??{},h.refresh.mainLastRefreshError=void 0,h.refresh.mainRefreshLeaseId===T)h.refresh.mainRefreshLeaseId=void 0,h.refresh.mainRefreshLeaseUntil=void 0,h.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),C=void 0,E}catch(M){if(V.refresh&&!v9(M))await P1((E)=>{E.refresh=E.refresh??{},E.refresh.mainLastRefreshError=nG({error:M,now:Date.now(),refreshToken:V.refresh??"",previous:E.refresh.mainLastRefreshError})}).catch(()=>{});throw M}finally{if(C)await P1((M)=>{if(M.refresh?.mainRefreshLeaseId===T&&M.refresh.mainRefreshLeaseTokenHash===C)M.refresh.mainRefreshLeaseId=void 0,M.refresh.mainRefreshLeaseUntil=void 0,M.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await I.release().catch(()=>{})}})().finally(()=>{z0=void 0});return z0}let G1=globalThis;G1.__openaiAuthCacheKeepManager?.stop();let n0=new D8({fetchImpl:fetch,getMainToken:async()=>{let V=await L();if(V.type!=="oauth")throw Error("not oauth");if(!V.access||(V.expires??0)<Date.now())try{return(await y0()).access}catch(F){if(v9(F))throw F;if(V.access)return V.access;throw Error("main token refresh failed")}return V.access},refreshFallback:async(V)=>{let F=await P(),D=F?aN(F.accounts,V):void 0;if(!D)throw Error(`fallback account ${V} not found`);let R=await u.refreshAccount(D,F??{version:1,accounts:[D]});if(!R.access)throw Error(`no access token for ${V}`);return R.access},codexResponsesUrl:J,logger:g0,now:Date.now,getWindow:()=>a,getSustain:()=>g});G1.__openaiAuthCacheKeepManager=n0;async function W1(V,F,D,R,I=!1){if(Object.keys(V).length===0&&!I)return;let T=Date.now(),C=V,M={quota:C,refreshAfter:T+300000,checkedAt:T},E;if(D&&D!=="main"){let b=F?LY(F):null,Y0=b?NY(b):void 0,Z0=y.peekFallbackForPolicy(D)?.quota,b0=pG(C,Z0);M={...M,quota:b0},y.setFallback(D,M,F,I,Y0)}else{if(E=R,!E&&F){let Z0=LY(F);E=Z0?NY(Z0):void 0}if(E&&s&&E!==s){d.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:E,currentMainIdentity:s});return}let b=y.peekMainForPolicy(E)?.quota,Y0=pG(C,b);M={...M,quota:Y0},y.setMain(F,M,E,I)}d.debug("quota pushed",{pid:process.pid,accountId:D??"main",snapshot:M.quota});let h=await P();await q0(y,h,D&&D!=="main"?h?.mainAccountId:E)}function v1(V,F,D){let R=V==="main"?y.peekMainForPolicy()?.quota:y.peekFallbackForPolicy(V)?.quota;return GW(R,F,Date.now(),mN,D)}let z1=X.experimentalWebSockets?$1.createWebSocketFetch({httpFetch:fetch,rawWebSocket:w0().rawWebSocket,onQuota:(V,F,D,R)=>{W1(V,F,D,!D||D==="main"?R:void 0,!0)},onRateLimitReached:(V,F,D)=>{if(!F)d.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:V});let R=F??"main",I=v1(R,V,D);y.markRateLimited(R,I),d.debug("mid-stream rate limit mark",{pid:process.pid,accountId:R,window:V})}}):void 0;if(z1)K.push(z1),W=!0;let B0=LW();N=B0;async function q0(V,F,D=F?.mainAccountId){if(!F)return;await ZW(wW(V,F,Date.now(),D),B0)}async function Q0(V,F,D,R,I){let T={activeId:D,route:R,updatedAt:Date.now()};if(V){if(await X8({sessionId:V,...T},I,B0),F&&F!==V){if(R==="sticky-balanced"){let C=(await L1(B0)).stickyAssignments?.[HY(F)]?.accountId,M=I===void 0||C==="main"||I.some((E)=>E.enabled!==!1&&E.id===C);if(!C||!M)return;await X8({sessionId:F,activeId:C,route:R,updatedAt:Date.now()},I,B0);return}await X8({sessionId:F,...T},I,B0)}return}await OW(T,B0)}H={accountStoragePath:U0(),quotaManager:y,loadAccounts:A0,client:Y.client,cacheKeepManager:n0,setCacheKeepEnabled:(V)=>{x1=V},setCacheKeepSubagents:(V)=>{D1=V},setCacheKeepSustain:(V)=>{g=V},setCacheKeepWindow:(V)=>{a=V},clearStickyRouting:(V)=>jW(V,B0),getStickyRouting:async(V)=>BW(await L1(B0),V),refreshSidebar:async()=>{let V=await A0(U0());await q0(y,V)},refreshAllQuota:async()=>y1({getAuth:L,codexRefreshFn:b1,refreshMainWithLease:y0,fallbackManager:u,quotaManager:y,loadAccounts:A0,writeSidebarState:q0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:U0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:q1,whamFn:Y8})};let k0=null;if(Y.directory){let V=await DW(Y.directory),F=globalThis;if(F.__openaiAuthRpcServer)await F.__openaiAuthRpcServer.stop().catch(()=>{}),F.__openaiAuthRpcServer=void 0;try{k0=await iX({dir:V.dir,secureDir:V.secureDir,sweepRoot:V.sweepRoot,drain:cX,apply:async(D)=>{let R={...H,sessionId:D.sessionId},I=await B8(D.command,D.arguments,R);return{text:I.text,knobs:I.knobs}}}),F.__openaiAuthRpcServer=k0,U=k0}catch{}}async function K1(V,F,D,R,I="main"){let T=lG(V,F);if(T.delete("x-api-key"),T.delete("api-key"),T.set("authorization",`Bearer ${D}`),R)T.set("ChatGPT-Account-Id",R);T.set($1.QUOTA_ACCOUNT_HEADER,I);let C=dG(T),M=C?lN($,C,G):void 0,E=V instanceof URL?V:new URL(typeof V==="string"?V:V.url),h=E.pathname.includes("/v1/responses")||E.pathname.includes("/chat/completions")?new URL(J):E,Y0=sN({init:{...F,headers:T},headers:T,metadata:M,installationID:Q,websocket:Boolean(z1&&E.pathname.endsWith("/responses")),responsesLite:X.responsesLite??!1,dumpSessionID:C}).init,Z0=x1,b0=new Headers(Y0?.headers),$0=VX({enabled:Z0,includeSubagents:D1,headers:b0,body:Y0?.body});if(Z0)g0.trace("cachekeep headers",{pid:process.pid,hasParent:b0.has("x-parent-session-id"),sessionKey:$0?.sessionKey,captured:Boolean($0),affinity:b0.get("x-session-affinity"),opencodeSession:b0.get("x-opencode-session"),sessionId:b0.get("session-id")});if(z1&&E.pathname.endsWith("/responses")){if(S.debug("WS transport",{pid:process.pid,pathname:E.pathname,accountId:I}),$0)n0.track($0.sessionKey,$0.bodyText,I,R,$0.replayHeaders,$0.isSubagent);return z1(h,Y0)}let V0=$1.withoutInternalHeaders(Y0);if(typeof V0?.body!=="string")return fetch(h,V0);if($0)n0.track($0.sessionKey,$0.bodyText,I,R,$0.replayHeaders,$0.isSubagent);S.debug("HTTP transport",{pid:process.pid,pathname:E.pathname,accountId:I});try{let T0=await fetch(h,V0);return await A1({sessionID:C,transport:"http",phase:"http",bodyText:V0.body,accountId:I,url:h.toString(),method:V0.method,headers:V0.headers,status:T0.status}),IX(T0)}catch(T0){throw await A1({sessionID:C,transport:"http",phase:"http",bodyText:V0.body,accountId:I,url:h.toString(),method:V0.method,headers:V0.headers,error:T0 instanceof Error?T0.message:String(T0)}),T0}}function BY(V,F){if((F?.method??(V instanceof Request?V.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof F?.body!=="string")return!1;try{let R=V instanceof URL?V.toString():typeof V==="string"?V:V.url;return new URL(R).pathname.endsWith("/responses")}catch{return!1}}function EW(V){return y.peekMainForPolicy(V)?.quota}function m9(V,F){for(let D of[V?.primary?.checkedAt,V?.secondary?.checkedAt,V?.checkedAt,F])if(typeof D==="number"&&Number.isFinite(D))return D;return}function h1(V,F,D,R,I){let T=m9(V,F),C=m9(D),M=R===I&&D!=null&&(V===void 0||C!==void 0&&(T===void 0||C>T));return{quota:M?D:V,quotaCheckedAt:M?C:T,source:M?"file":"memory"}}function c9(V,F,D,R,I){let T=V?.quota,C=h1(T,V?.checkedAt,F,R,I),M=C.source,E=C.quota;if(!VW(E,D))return{exhausted:!1};let h=NW(E,D);if(!h)return{exhausted:!1};return{exhausted:!0,source:M,...h}}function u9(V,F){d.debug("admission skip: exhausted account",{accountId:V,source:F.source,resetsAt:F.resetsAt})}function MW(V,F="killswitch",D){let R=Date.now(),I=y.getMain()?.quota,T=(V?.accounts??[]).filter((b)=>b.enabled!==!1&&q1(b)).map((b)=>({accountId:b.id,quota:y.getFallback(b.id)?.quota})),C=KW(I,T,R,V);if(F==="quota-exhausted"&&D!==void 0)C=Math.max(1,Math.ceil((D-R)/1000));else if(F==="mid-stream-rate-limit"&&D!==void 0){let b=Math.max(1,Math.ceil((D-R)/1000));C=Math.min(C,b)}let M=Math.floor(C/60),E=C%60,h=F==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${M}m ${E}s.`:F==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${M}m ${E}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${M}m ${E}s.`;return new Response(JSON.stringify({error:{message:h,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(C)}})}function p9(V){let F=V?.resetCreditsAvailable;return typeof F==="number"&&Number.isFinite(F)?F:void 0}async function AW(V){let F=KY(V.storage),D=Date.now(),R=y.peekMainForPolicy(V.mainAccountIdentity),I=h1(R?.quota,R?.checkedAt,V.sidebarState.main.quota,V.sidebarState.main.mainAccountId,V.mainAccountIdentity),T=F?UY(R?.quota,V.storage,void 0,D):void 0,C=[{accountId:"main",wireAccountId:V.mainAccountIdentity,access:V.primaryAccess,keepwarmAccountKey:"main",quota:I.quota,quotaCheckedAt:I.quotaCheckedAt,reservePercent:h9(V.storage),configuredOrder:0,resetCreditsApplicable:p9(I.quota),killswitchPasses:T}],M=await u.getUsableFallbackAccounts(V.storage);for(let E of M){if(!E.access)continue;let h=V.sidebarState.fallbacks.find((b0)=>b0.id===E.id),b=y.peekFallbackForPolicy(E.id,E.accountId),Y0=h1(b?.quota,b?.checkedAt,h?.quota,h?.accountId,E.accountId),Z0=F?UY(b?.quota,V.storage,E.id,D):void 0;C.push({accountId:E.id,wireAccountId:E.accountId,access:E.access,keepwarmAccountKey:E.id,fallback:E,quota:Y0.quota,quotaCheckedAt:Y0.quotaCheckedAt,reservePercent:h9(V.storage,E.id),configuredOrder:C.length,resetCreditsApplicable:p9(Y0.quota),killswitchPasses:Z0})}return C}function l9(V,F,D,R,I){let T=KY(I)?V.killswitchPasses:void 0;if(V.accountId==="main"){let h=y.peekMainForPolicy(V.wireAccountId),b=h1(h?.quota,h?.checkedAt,F.main.quota,F.main.mainAccountId,V.wireAccountId);return E8({quota:b.quota,quotaCheckedAt:b.quotaCheckedAt,status:D,now:R,killswitchPasses:T})}let C=F.fallbacks.find((h)=>h.id===V.accountId),M=y.peekFallbackForPolicy(V.accountId,V.wireAccountId),E=h1(M?.quota,M?.checkedAt,C?.quota,C?.accountId,V.wireAccountId);return E8({quota:E.quota,quotaCheckedAt:E.quotaCheckedAt,status:D,now:R,killswitchPasses:T})}function RW(V){return V.accountId==="main"?"main":V.keepwarmAccountKey}function d9(V){return y.isRateLimited(RW(V))}async function $8(V){let F=V.candidates.filter((M)=>!d9(M)),D=new Map(F.map((M)=>[M.accountId,M])),R=Object.fromEntries(F.map((M)=>[M.accountId,M.quotaCheckedAt])),I=new Set(V.excludeAccountIds),T,C=await qW({sessionId:V.sessionId,requestBytes:V.requestBytes,now:V.now,validPinnedAccountIds:[...D.keys()],excludeAccountIds:V.excludeAccountIds,quotaCheckedAtByAccount:R,choose:(M)=>{let E=F.filter((b)=>!I.has(b.accountId));if(E.length===0)return;let h=PX({candidates:E,pendingBytes:M,requestBytes:V.requestBytes,now:V.now,onEmptyWeightedSet:()=>{e.debug("sticky routing: no fresh weighted candidates; using configured order")}});if(!h)return;return T={accountId:h.accountId,source:h.source,pendingBytes:M.get(h.accountId)??0},h}},B0);if(T&&C?.accountId===T.accountId)e.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:HY(V.sessionId),accountId:T.accountId,source:T.source,requestBytes:V.requestBytes,pendingBytes:T.pendingBytes});return C?D.get(C.accountId):void 0}async function TW(V,F){let D=await u.getUsableFallbackAccounts(V),R=[];for(let b of D)if(b.access)R.push({access:b.access,accountId:b.accountId,keepwarmAccountKey:b.id,quotaAccountId:b.id,fallback:b});let I=R.filter((b)=>!y.isRateLimited(b.quotaAccountId)),T=KY(V)?I.filter((b)=>UY(y.peekFallbackForPolicy(b.quotaAccountId,b.accountId)?.quota,V,b.quotaAccountId,Date.now())):I,C=new Map(F.fallbacks.map((b)=>[b.id,{quota:b.quota,accountId:b.accountId}])),M=[],E=[],h=Date.now();for(let b of T){let Y0=C.get(b.quotaAccountId),Z0=c9(y.peekFallbackForPolicy(b.quotaAccountId,b.accountId),Y0?.quota,h,Y0?.accountId,b.accountId);if(Z0.exhausted)E.push({candidate:b,decision:Z0});else M.push(b)}return{current:T,retained:M,skipped:E}}function i9(V,F){if(V.retained.length===0&&!F)return V.current;for(let{candidate:D,decision:R}of V.skipped)u9(D.quotaAccountId,R);return V.retained}async function n9(V,F){try{let D=E1(V.headers);await W1(D,F.access,F.quotaAccountId,void 0,WY(V.headers))}catch{}}async function CW(V,F,D,R){for(let I of R){let T;try{T=await K1(V,F,I.access,I.accountId,I.keepwarmAccountKey)}catch(C){if(C instanceof DOMException&&C.name==="AbortError")throw C;if(F?.signal?.aborted)throw C;throw e.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:I.quotaAccountId}),C}if(!zY(T.status,D))return await u.markUsed(I.fallback),{response:T,accessToken:I.access,quotaAccountId:I.quotaAccountId,activeId:I.keepwarmAccountKey};await n9(T,I),T.body?.cancel().catch(()=>{})}return}async function _W(V,F,D,R,I){if(!BY(V,F))return{response:D};if(!I.length)return{response:D};let T=D,C;for(let M of I){let E;try{E=await K1(V,F,M.access,M.accountId,M.keepwarmAccountKey)}catch(h){if(h instanceof DOMException&&h.name==="AbortError")throw h;if(F?.signal?.aborted)throw h;return e.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:M.quotaAccountId}),{response:T,...C}}if(T.body?.cancel().catch(()=>{}),T=E,C={accessToken:M.access,accountId:M.quotaAccountId},!zY(E.status,R))return await u.markUsed(M.fallback),{response:E,...C};await n9(E,M)}return{response:T,...C}}if(!gG){if(gG=!0,j){let V=[];for(let F of j.accounts)if(q1(F))V.push(F);y.seedFallbacksFromAccounts(V)}q0(y,j).catch(()=>{}),y1({getAuth:L,codexRefreshFn:b1,refreshMainWithLease:y0,fallbackManager:u,quotaManager:y,loadAccounts:A0,writeSidebarState:q0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:U0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:q1,whamFn:Y8,respectBackoff:!0}).catch((V)=>d.warn("boot quota seed failed",{pid:process.pid,error:o0(V)}))}return O.start(async()=>{let F=(await KX({getAuth:L,codexRefreshFn:b1,refreshMainWithLease:y0,fallbackManager:u,quotaManager:y,loadAccounts:A0,writeSidebarState:(D,R)=>O.isStopped()?Promise.resolve():q0(D,R),client:Y.client,fetchImpl:fetch,now:Date.now,configPath:U0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:q1,whamFn:Y8,readSidebarState:()=>L1(B0)})).filter((D)=>!D.ok);if(F.length>0)d.warn("background quota refresh completed with failures",{pid:process.pid,failures:F})},(V)=>{d.warn("background quota refresh failed",{pid:process.pid,error:V instanceof Error?V.message:String(V)})}),{apiKey:SN,async fetch(V,F){let D=lG(V,F),R=dG(D),I=D.get("x-parent-session-id")?.trim()||void 0,T=await P(),C=await L(),M=++j1;if(C.type!=="oauth")return fetch(V,F);F=await tN(V,F);let E=C.access??"";if(!C.access||(C.expires??0)<Date.now()){m.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(C.access),expiresInMs:C.expires?C.expires-Date.now():void 0});try{let t=await y0();C.access=t.access,C.refresh=t.refresh,C.expires=t.expires}catch(t){if(v9(t))throw t}}E=C.access??"";let b=C.accountId??(E?NY(LY(E)??{}):void 0);if(M===j1)s=b;let Y0=T?.routing?.mode??"main-first",Z0,$0=await(()=>{return Z0??=L1(B0),Z0})();if(Y0==="sticky-balanced"&&R&&BY(V,F)&&typeof F?.body==="string"){let t=Buffer.byteLength(F.body,"utf8"),H0=await AW({storage:T,sidebarState:$0,primaryAccess:E,mainAccountIdentity:b}),K0=await $8({sessionId:R,requestBytes:t,candidates:H0,now:Date.now()});if(K0){let YX=d9(K0)?{action:"migrate",reason:"exhausted"}:l9(K0,$0,void 0,Date.now(),T);if(YX.action==="migrate"){let P0=await $8({sessionId:R,requestBytes:t,candidates:H0,excludeAccountIds:[K0.accountId],now:Date.now()});if(P0)e.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:HY(R),fromAccountId:K0.accountId,toAccountId:P0.accountId,reason:YX.reason}),K0=P0}let x0=await K1(V,F,K0.access,K0.wireAccountId,K0.keepwarmAccountKey),XX=async(P0,U1)=>{try{let IW=E1(P0.headers);await W1(IW,U1.access,U1.accountId==="main"?void 0:U1.accountId,U1.accountId==="main"?U1.wireAccountId:void 0,WY(P0.headers))}catch{}};await XX(x0,K0);let JX=l9(K0,$0,x0.status,Date.now(),T);if((x0.status===401||x0.status===403||x0.status===429)&&JX.action==="migrate"){let P0=await $8({sessionId:R,requestBytes:t,candidates:H0,excludeAccountIds:[K0.accountId],now:Date.now()});if(P0){e.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:HY(R),fromAccountId:K0.accountId,toAccountId:P0.accountId,reason:JX.reason});let U1=x0;x0=await K1(V,F,P0.access,P0.wireAccountId,P0.keepwarmAccountKey),U1.body?.cancel().catch(()=>{}),K0=P0,await XX(x0,K0)}}if(K0.fallback&&!zY(x0.status,T))await u.markUsed(K0.fallback);return await Q0(R,I,K0.accountId,Y0,T?.accounts).catch(()=>{}),x0}}let V0=c9(y.peekMainForPolicy(b),$0.main.quota,Date.now(),$0.main.mainAccountId,b),T0=KY(T)&&!UY(EW(b),T,void 0,Date.now()),ZY=y.isRateLimited("main"),o9,G8=()=>{return o9??=TW(T,$0),o9},f0,w1,r9=!1,OY;if(Y0==="fallback-first"&&BY(V,F)){r9=!0;let t=await G8();OY=i9(t,!T0&&!ZY&&!V0.exhausted);let H0=await CW(V,F,T,OY);if(H0)f0=H0.response,w1={accessToken:H0.accessToken,accountId:H0.quotaAccountId,activeId:H0.activeId}}if(!f0){let t=V0.exhausted&&BY(V,F)&&(await G8()).retained.length>0;if(T0||ZY||t){let H0=T0?"killswitch":ZY?"mid-stream-rate-limit":"quota-exhausted";if(H0==="quota-exhausted"&&V0.exhausted)u9("main",V0);e.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:H0}),f0=MW(T,H0,H0==="quota-exhausted"&&V0.exhausted?V0.resetAtMs:ZY?y.rateLimitedUntil("main"):void 0)}else f0=await K1(V,F,E,b,"main")}let s9=Boolean(w1),g1=f0,a9=w1?.accessToken??E,t9=w1?.accountId,e9=w1?.activeId??"main";if(!w1&&!r9&&zY(f0.status,T)){e.debug("reactive fallback triggered",{pid:process.pid,status:f0.status}),OY??=i9(await G8(),!1);let t=await _W(V,F,f0,T,OY),H0=t.response;if(H0!==f0){if(s9=!0,g1=H0,a9=t.accessToken??E,t9=t.accountId,t.accountId)e9=t.accountId}}try{let t=E1(g1.headers);if(s9)await W1(t,a9,t9,void 0,WY(g1.headers));else await W1(t,E,void 0,b,WY(g1.headers))}catch{}return await Q0(R,I,e9,Y0,T?.accounts).catch(()=>{}),g1},async dispose(){if(O.stop(),n0.stop(),G1.__openaiAuthCacheKeepManager===n0)G1.__openaiAuthCacheKeepManager=void 0;if(u.stopBackgroundRefresh(),U){await U.stop().catch(()=>{});let V=globalThis;if(V.__openaiAuthRpcServer===U)V.__openaiAuthRpcServer=void 0;U=null}}}},methods:[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:async()=>{let{redirectUri:L}=await XW(),Z=await tG(),j=aG(crypto.getRandomValues(new Uint8Array(32)).buffer),w=eG(L,Z,j),P=JW(Z,j);return{url:w,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let k=await P,x=eY(k);return{type:"success",refresh:k.refresh_token,access:k.access_token,expires:Date.now()+(k.expires_in??3600)*1000,accountId:x}}finally{YW(j)}}}}},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:async()=>{let{deviceData:L,url:Z,instructions:j}=await QW();return{url:Z,instructions:j,method:"auto",async callback(){try{let w=await $W(L);return{type:"success",refresh:w.refresh_token,access:w.access_token,expires:Date.now()+(w.expires_in??3600)*1000,accountId:eY(w)}}catch{return{type:"failed"}}}}}},{label:"Manually enter API Key",type:"api"}]},"chat.headers":async(L,Z)=>{if(L.model.providerID!=="openai")return;if(Z.headers.originator="opencode",Z.headers["User-Agent"]=`${sG} (${x9.platform()} ${x9.release()}; ${x9.arch()})`,Z.headers["session-id"]=L.sessionID,W&&L.agent==="title")Z.headers[$1.TITLE_HEADER]="true"},"chat.params":async(L,Z)=>{if(L.model.providerID!=="openai")return;Z.maxOutputTokens=void 0},config:async(L)=>{L.command={...L.command??{},[z8]:{template:z8,description:"Show current OpenAI Codex OAuth quota usage for all accounts."},[K8]:{template:K8,description:"Manage OpenAI accounts — add, switch, remove, or reorder."},[U8]:{template:U8,description:"Show or change OpenAI account routing between main-first, fallback-first, and sticky-balanced."},[H8]:{template:H8,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."},[L8]:{template:L8,description:"Show or toggle OpenAI Codex request dump capture for debugging."},[N8]:{template:N8,description:"Show or change the plugin log level (error, warn, info, debug, trace)."},[V8]:{template:V8,description:"Keep Codex prompt cache alive during idle by shadow-replaying the last request."}}},"command.execute.before":async(L)=>{if(!zX.includes(L.command))return;if(!H)await B(L.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),cG();let Z=L.command,j={...H,sessionId:L.sessionID,notify:(P)=>{b8(P,L.sessionID)}},w=await B8(Z,L.arguments,j);if(uX(L.sessionID))b8(w,L.sessionID);else await B(L.sessionID,w.text);cG()}}}var GV=async(Y)=>{let X=w0();return $V(Y,{codexApiEndpoint:X.codexApiEndpoint,experimentalWebSockets:X.webSockets,responsesLite:X.responsesLite})},L4={id:"cortexkit-openai-auth",server:GV};export{dG as resolveSidebarSessionId,LY as parseJwtClaims,pG as mergePushedQuotaMetadata,aN as findCachekeepFallbackAccount,NY as extractAccountIdFromClaims,L4 as default,H4 as buildSidebarState,wW as buildSidebarMachineState,GV as OpenAIAuthPlugin,hN as MAIN_REFRESH_LOCK_TTL_MS,gN as MAIN_REFRESH_LEASE_TTL_MS,$V as CodexAuthPlugin,f9 as AuthPersistError};
167
+ `)),W=!0,L("idle timeout waiting for websocket"),!e)return;if(e.type==="response.completed"||e.type==="response.done"){G=!0,YN(e,U),Y.onComplete?.(e,U),Y.onTerminal?.(e),O();return}if(e.type==="response.failed"||e.type==="response.incomplete"||e.type==="error")G=!0,Y.onTerminal?.(e),O()}function j(_){B(new R0(a0(_),{cause:_}))}function P(_){if(G)return;B(new R0(AG("WebSocket closed before response.completed",_.code,_.reason)))}function S(){let _=_9(Y.signal);if(G)return;G=!0,H(),N(),Y.onAbort?.(_),Q?.error(_)}function E(_){if(G)return;G=!0,H(),N(),Y.onAbort?.(JN(_))}function b(_){$(),J=_,J.addEventListener("message",Z),J.addEventListener("error",j,{once:!0}),J.addEventListener("close",P,{once:!0}),$=()=>{J.removeEventListener("message",Z),J.removeEventListener("error",j),J.removeEventListener("close",P)};let{background:u,...m}=Y.body;L("idle timeout sending websocket request");try{J.send(JSON.stringify({type:"response.create",...m})),L("idle timeout waiting for websocket")}catch(d){if(G)return;B(new R0(d instanceof Error?d.message:String(d),{cause:d}))}}return new Response(new ReadableStream({start(_){if(Q=_,Y.signal?.addEventListener("abort",S,{once:!0}),Y.signal?.aborted){S();return}b(J)},cancel(_){E(_)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function aL(Y,X){if(!tL(Y))return;await p0({component:"ws",event:"provider_native_web_search_event",sessionID:X,serverEventType:Y.type,itemType:I(Y.item)?Y.item.type:void 0,serverEvent:Y})}function tL(Y){if(typeof Y.type==="string"&&(Y.type.startsWith("response.web_search_call.")||Y.type.startsWith("response.web_search_preview_call.")))return!0;if(I(Y.item)&&typeof Y.item.type==="string")return Y.item.type==="web_search_call"||Y.item.type==="web_search_preview_call";return!1}function eL(Y,X){if(Y.type!=="response.output_item.done")return;if(!I(Y.item))return;MG(Y.item,X)}function YN(Y,X){let J=Y.response;if(!I(J)||!Array.isArray(J.output))return;for(let Q of J.output)if(I(Q))MG(Q,X)}function MG(Y,X){if(Y.type!=="function_call"&&Y.type!=="custom_tool_call")return;let J=typeof Y.call_id==="string"?Y.call_id:typeof Y.id==="string"?Y.id:void 0;if(J)X.add(J)}function XN(Y,X){if(Y?.type!=="error")return;let J=Y.status??Y.status_code;if(typeof J!=="number"||J>=200&&J<300)return;return{status:J,headers:I(Y.headers)?Object.fromEntries(Object.entries(Y.headers).flatMap(([Q,$])=>typeof $==="string"||typeof $==="number"||typeof $==="boolean"?[[Q,String($)]]:[])):void 0,body:X,message:I(Y.error)&&typeof Y.error.message==="string"?Y.error.message:`${J}`}}function GY(Y){if(typeof Y==="string")try{return GY(JSON.parse(Y))}catch{return}if(!I(Y))return;let X=GY(Y.cause);if(X)return X;let J=GY(Y.body);if(J)return J;let Q=I(Y.error)?Y.error:Y,$=typeof Q.type==="string"?Q.type:void 0,G=Y.status??Y.status_code;if($!=="usage_limit_reached"&&G!==429)return;let{resets_at:W,resets_in_seconds:K}=Q,U=typeof W==="number"&&Number.isFinite(W)&&W>0?W*1000:typeof K==="number"&&Number.isFinite(K)&&K>0?Date.now()+K*1000:void 0;return{window:$??"primary",resetAt:U}}function JN(Y){if(I9(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function _9(Y){let X=Y?.reason;if(I9(X))return X;if(QN(X))return X;return new DOMException(X instanceof Error?X.message:"Aborted","AbortError")}function QN(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function AG(Y,X,J){let Q=[`code ${X}`];if(X===1009)Q.push("message too big");if(J.length>0)Q.push(J.toString());return`${Y} (${Q.join(": ")})`}var k9="x-opencode-title",aY="x-openai-auth-quota-account",S9=new Set([k9,t0,aY,"x-opencode-session"]),GN=15000,WN=300000,zN=3300000,RG="websocket_connection_limit_reached";function KN(Y){let X=typeof Y["chatgpt-account-id"]==="string"?Y["chatgpt-account-id"]:"",J=typeof Y.authorization==="string"&&Y.authorization.startsWith("Bearer ")?Y.authorization.slice(7):"",Q=X?`acct:${X}`:`tok:${J}`;return $N("sha256").update(Q).digest("hex").slice(0,12)}function UN(Y){let X=Y?.httpFetch??globalThis.fetch,J=new Map,Q=Y?.connectTimeout??GN,$=Y?.idleTimeout??WN,G=Y?.maxConnectionAge??zN,W=Y?.streamRetries??5,K=Y?.firstEventGraceMs??250,U=Y?.rawWebSocket??!1,H=Y?.onQuota,N=Y?.onRateLimitReached,O=setInterval(()=>j(),Math.min($,60000));if(typeof O==="object"&&"unref"in O&&typeof O.unref==="function")O.unref();function B(E,b,_){if(!b||!_)return _;b9(E,TG(b));let u=new Headers(_.headers),m=u.get("x-codex-turn-metadata");if(!m)return _;let d=vG(m,E.turnID,E.turnStartedAt);if(!d)return _;return u.set("x-codex-turn-metadata",d),{..._,headers:u}}async function L(E,b){let _=E instanceof URL?E.toString():typeof E==="string"?E:E.url,u=j0.normalizeHeaders(b?.headers),m=yG(b),d=wY(m);if(b?.method!=="POST"||!new URL(_).pathname.endsWith("/responses"))return X(E,d);let y=(()=>{try{if(typeof b?.body!=="string")return;let o=JSON.parse(b.body);return typeof o==="object"&&o!==null?o:void 0}catch{return}})();if(!y?.stream)return X(E,d);if(u[k9]==="true")return X(E,d);let e=u[t0]??u["x-session-affinity"]??u["session-id"],g0=e;if(!e)return X(E,d);let p=j0.normalizeHeaders(m?.headers),r0=KN(p),v1=`${e}:${r0}:conversation`,h1=typeof u[aY]==="string"?u[aY]:void 0,D1=N?(o,V0)=>N(o,h1,V0):void 0,h=J.get(v1)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};if(J.set(v1,h),h.fallback)return X(E,B(h,y,d));if(h.busy)return X(E,B(h,y,d));h.busy=!0,h.lastUsedAt=Date.now();try{let o=TG(y),V0=j0.normalizeHeaders(m?.headers),J8=typeof V0.authorization==="string"&&V0.authorization.startsWith("Bearer ")?V0.authorization.slice(7):"",P1=typeof V0["chatgpt-account-id"]==="string"?V0["chatgpt-account-id"]:void 0,BY=H?(Y0)=>H(Y0,J8,h1,P1):void 0,K1=!h.socket&&!h.continuation?FN(V0):V0;if(h.socket=await NN(h,Y?.url??_,K1,Q,G,U,b?.signal),PN(h,o))await VN(h,o,$,{signal:b?.signal??void 0,sessionID:g0,url:Y?.url??_,headers:m?.headers,onRateLimitReached:D1});let s0=()=>{},y0=()=>{},U1=new Promise((Y0,A0)=>{s0=Y0,y0=A0}),Q8=DN(h,o),f0=WY(xG(h,Q8,o)),F0=typeof f0.previous_response_id==="string";await R1({sessionID:g0,transport:"websocket",phase:"main",bodyText:JSON.stringify(f0),url:Y?.url??_,method:m?.method,headers:m?.headers});let m0=j0.streamResponsesWebSocket({socket:h.socket,body:f0,sessionID:g0??void 0,idleTimeout:$,signal:b?.signal??void 0,onQuota:BY,onRateLimitReached:D1,onFirstEvent:(Y0)=>s0(Y0??!0),onComplete:(Y0,A0)=>{let w1=IG(Y0);p0({component:"ws-pool",event:"main_completed",sessionID:g0,responseID:_G(Y0),usage:w1}),bG(h,o,Y0,A0,F0)},onTerminal:(Y0)=>{if(h.busy=!1,h.lastUsedAt=Date.now(),h.streamFailures=0,Y0.type!=="response.completed"&&Y0.type!=="response.done")h.continuation=void 0,o0(h)},onConnectionInvalid:()=>{if(h.busy=!1,h.lastUsedAt=Date.now(),!h.fallback)Z(h);h.continuation=void 0,o0(h),s0(!1)},onAbort:(Y0)=>{h.busy=!1,h.lastUsedAt=Date.now(),h.streamFailures=0,h.continuation=void 0,o0(h),y0(Y0)},onRetryableTerminal:async(Y0)=>{let A0=CG(Y0);if(!A0)return;throw h.fallback=!0,A0}}),k0=await HN(U1,K);if(k0!==!1){if(k0===!0||k0.status<200||k0.status>599)return m0;return new Response(k0.body,{status:k0.status,headers:{"content-type":"application/json",...k0.headers}})}if(!h.fallback)return m0;return X(E,B(h,y,d))}catch(o){if(h.busy=!1,h.lastUsedAt=Date.now(),j0.isAbortError(o))throw h.streamFailures=0,h.continuation=void 0,o0(h),o;let V0=j0.parseRateLimitSignal(o);if(V0)D1?.(V0.window,V0.resetAt);if(j0.isUpgradeFailure(o)&&!U)h.fallback=!0;if(Z(h),h.continuation=void 0,o0(h),h.fallback)return X(E,B(h,y,d));return LN(new R0(o instanceof Error?o.message:String(o),{cause:o}))}}function Z(E){if(E.streamFailures++,E.streamFailures>W)E.fallback=!0}function j(){let E=Date.now();for(let[b,_]of J){if(_.busy)continue;if(E-_.lastUsedAt<$)continue;o0(_),J.delete(b)}}function P(){clearInterval(O);for(let E of J.values())o0(E);J.clear()}function S(E){let b=`${E}:`;for(let[_,u]of J){if(!_.startsWith(b))continue;o0(u),J.delete(_)}}return Object.assign(L,{close:P,remove:S})}function CG(Y){if(Y.type!=="error"||!I(Y.error)||Y.error.code!==RG)return;return Error(typeof Y.error.message==="string"?Y.error.message:RG)}async function HN(Y,X){if(X<=0)return!1;return new Promise((J,Q)=>{let $=setTimeout(()=>J(!1),X);Y.then((G)=>{clearTimeout($),J(G)},(G)=>{clearTimeout($),Q(G)})})}function LN(Y){return new Response(new ReadableStream({start(X){X.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function NN(Y,X,J,Q,$,G,W){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<$)return Y.socket;o0(Y);let K=await j0.connectResponsesWebSocket({url:j0.toWebSocketUrl(X),headers:J,timeout:Q,rawWebSocket:G,signal:W??void 0});return Y.connectedAt=Date.now(),K}function o0(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function VN(Y,X,J,Q){if(!Y.socket||!Array.isArray(X.input)||X.input.length===0)return;let $=ZN(X);await R1({sessionID:Q.sessionID,transport:"websocket",phase:"prewarm",bodyText:JSON.stringify($),url:Q.url,method:"POST",headers:Q.headers});let G=j0.streamResponsesWebSocket({socket:Y.socket,body:$,sessionID:Q.sessionID,idleTimeout:J,signal:Q.signal,onRateLimitReached:Q.onRateLimitReached,onComplete:(W,K)=>{p0({component:"ws-pool",event:"prewarm_completed",sessionID:Q.sessionID,responseID:_G(W),usage:IG(W)}),bG(Y,$,W,K,!1)},onTerminal:(W)=>{if(W.type!=="response.completed"&&W.type!=="response.done")Y.continuation=void 0},onConnectionInvalid:()=>{Y.continuation=void 0},onAbort:()=>{Y.continuation=void 0},onRetryableTerminal:async(W)=>{let K=CG(W);if(!K)return;throw Y.fallback=!0,K}});await BN(G)}function _G(Y){let X=Y.response;if(!I(X))return;return typeof X.id==="string"?X.id:void 0}function IG(Y){let X=Y.response;if(!I(X))return;return I(X.usage)?X.usage:void 0}async function BN(Y){let X=Y.body?.getReader();if(!X)return;while(!0)if((await X.read()).done)return}function ZN(Y){return WY({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:ON(Y.client_metadata)})}function SG(Y){return JSON.stringify({session_id:Y.session_id,thread_id:Y.thread_id,thread_source:Y.thread_source,turn_id:"",sandbox:Y.sandbox,request_kind:"prewarm",window_id:Y.window_id})}function ON(Y){if(!I(Y))return Y;if(typeof Y["x-codex-turn-metadata"]!=="string")return Y;try{let X=JSON.parse(Y["x-codex-turn-metadata"]);if(!I(X))return Y;return{...Y,"x-codex-turn-metadata":SG(X),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function FN(Y){let X=Y["x-codex-turn-metadata"];if(!X)return Y;try{let J=JSON.parse(X);if(!I(J))return Y;return{...Y,"x-codex-turn-metadata":SG(J)}}catch{return Y}}var kG=["type","model","instructions","previous_response_id","input","tools","tool_choice","parallel_tool_calls","reasoning","store","stream","include","prompt_cache_key","text","generate","client_metadata"];function TG(Y){let X={...Y};if(Array.isArray(Y.input))X.input=Y.input.map(qN);return X}function WY(Y){let X={};for(let J of kG)if(J in Y)X[J]=Y[J];for(let J of Object.keys(Y))if(!(J in X))X[J]=Y[J];return X}function qN(Y){if(!I(Y))return Y;if(typeof Y.type==="string")return Y;if(typeof Y.role!=="string")return Y;if(!("content"in Y))return Y;return{...Y,type:"message"}}function bG(Y,X,J,Q,$){let G=J.response,W=I(G)&&typeof G.id==="string"?G.id:void 0;if(!W||!Array.isArray(X.input)){Y.continuation=void 0;return}let K=$?new Set(Y.continuation?.finalizedCallIds):new Set;for(let U of Q)K.add(U);Y.continuation={responseID:W,input:X.input,signature:x9(X),finalizedCallIds:K}}function b9(Y,X,J=X){let Q=Array.isArray(X.input)?X.input:[],$=Array.isArray(J.input)?J.input:Q,G=x9(J),W=Y.turnInput&&Y.turnSignature===G?jN(Y.turnInput,$):void 0,K=W===void 0?Q:$.slice(W);if(K.length>0&&K.some(hG)||!Y.turnID)Y.turnID=V1(),Y.turnStartedAt=Date.now();Y.turnInput=$.slice(),Y.turnSignature=G}function xG(Y,X,J=X){b9(Y,X,J);let Q=X.client_metadata;if(!I(Q)||typeof Q["x-codex-turn-metadata"]!=="string")return X;let $=vG(Q["x-codex-turn-metadata"],Y.turnID,Y.turnStartedAt);if(!$)return X;return{...X,client_metadata:{...Q,"x-codex-turn-metadata":$}}}function vG(Y,X,J){let Q;try{Q=JSON.parse(Y)}catch{return}if(!I(Q))return;return JSON.stringify({session_id:Q.session_id,thread_id:Q.thread_id,thread_source:Q.thread_source,turn_id:X,sandbox:Q.sandbox,turn_started_at_unix_ms:J,request_kind:"turn",window_id:Q.window_id})}function jN(Y,X){if(Y.length>X.length)return;for(let J=0;J<Y.length;J++)if(l0(Y[J])!==l0(X[J]))return;return Y.length}function DN(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!J||!Y.continuation)return X;if(Y.continuation.signature!==x9(X))return Y.continuation=void 0,X;if(!gG(Y.continuation.input,J))return Y.continuation=void 0,X;if(Y.continuation.input.length===0)return{...X,previous_response_id:Y.continuation.responseID};let Q=J.slice(Y.continuation.input.length),$=wN(Q,Y.continuation.finalizedCallIds);if($.length===0)return X;return{...X,previous_response_id:Y.continuation.responseID,input:$}}function PN(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!Y.continuation)return!0;if(!J)return!1;if(!gG(Y.continuation.input,J))return!0;return J.slice(Y.continuation.input.length).some(hG)}function hG(Y){if(!I(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function wN(Y,X){return Y.filter((J)=>{if(!I(J))return!0;if(typeof J.type==="string"&&J.type.endsWith("_output"))return!0;if(J.type==="function_call_output"||J.type==="custom_tool_call_output")return!0;if(J.type==="function_call"||J.type==="custom_tool_call"){let Q=typeof J.call_id==="string"?J.call_id:typeof J.id==="string"?J.id:void 0;return Q?!X.has(Q):!0}if(J.type==="message")return J.role!=="assistant";if(typeof J.role==="string")return J.role!=="assistant";return!1})}function x9(Y){return l0(EN(Object.fromEntries(Object.entries(Y).filter(([X])=>X!=="input"&&X!=="stream"&&X!=="background"&&X!=="previous_response_id"&&X!=="generate"))))}function EN(Y){if(!I(Y.client_metadata))return Y;let X=Object.fromEntries(Object.entries(Y.client_metadata).filter(([J])=>J!=="x-codex-turn-metadata"&&J!=="x-codex-ws-stream-request-start-ms"));return{...Y,client_metadata:X}}function gG(Y,X){if(Y.length>=X.length)return!1;for(let J=0;J<Y.length;J++)if(l0(Y[J])!==l0(X[J]))return!1;return!0}function yG(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let X=new Headers(Y.headers);for(let J of S9)X.delete(J);return{...Y,headers:X}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((X)=>!S9.has(X[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([X])=>!S9.has(X.toLowerCase())))}}var IN=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),SN=new Set(["gpt-5.6"]),kN=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),bN="opencode-oauth-dummy-key",xN="terminal_resize_reflow",y9="0.144.0",vN=`codex_exec/${y9} (Debian 12.0.0; aarch64) unknown (codex_exec; ${y9})`,hN="seccomp",gN="main-refresh",yN=120000,fN=90000,mN=4000,fG=50,mG=3,cN=25,uN=60000,pN="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",cG=!1,uG=H0("models"),pG=!1,lG=!1;class m9 extends Error{code="OPENAI_AUTH_PERSIST_FAILED";constructor(Y){super("OpenAI OAuth token refreshed but could not be persisted; re-login required",{cause:Y});this.name="AuthPersistError"}}function h9(Y){return Y instanceof m9}function dG(){throw Error(pN)}function lN(Y){return Math.floor(Math.random()*Y)}function dN(Y){if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return typeof X==="object"&&X!==null&&!Array.isArray(X)?X:void 0}catch{return}}function iN(Y,X,J){let Q=Y.get(X);if(Q)return Q;let $=V1(),G={threadID:$,turnID:V1(),windowID:`${$}:0`};return Y.set(X,G),J?.(),G}function AW(){return _N(jY(),"openai-auth-sessions.json")}function nN(){let Y=new Map;try{let X=JSON.parse(AN(AW(),"utf8"));if(!I(X.sessions))return Y;for(let[J,Q]of Object.entries(X.sessions)){if(!I(Q)||typeof Q.threadID!=="string")continue;Y.set(J,{threadID:Q.threadID,turnID:V1(),windowID:`${Q.threadID}:0`})}}catch{}return Y}function oN(Y){let X=AW(),J=`${X}.tmp-${process.pid}`;try{MN(jY(),{recursive:!0});let Q={version:1,sessions:Object.fromEntries([...Y.entries()].map(([$,G])=>[$,{threadID:G.threadID}]))};CN(J,`${JSON.stringify(Q,null,2)}
168
+ `,"utf8"),RN(J,X)}catch{}}function iG(Y,X){return I(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===X}function rN(Y,X){if(Y.length>X.length)return!1;for(let J=0;J<Y.length;J++)if(l0(Y[J])!==l0(X[J]))return!1;return!0}function sN(Y,X){if(!Y.input)return X.length>0;if(!rN(Y.input,X))return!0;return X.slice(Y.input.length).some((Q)=>iG(Q,"user")||iG(Q,"developer"))}function aN(Y,X){let J=Array.isArray(X?.input)?X.input:void 0;if(J&&(sN(Y,J)||!Y.turnID))Y.turnID=V1(),Y.turnStartedAt=Date.now();else if(!Y.turnStartedAt)Y.turnStartedAt=Date.now();if(J)Y.input=J}function tN(Y){if(!Y.metadata)return{init:Y.init};let X=dN(Y.init?.body);if(!Y.websocket)aN(Y.metadata,X);else if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Date.now();if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Date.now();let J=JSON.stringify({session_id:Y.metadata.threadID,thread_id:Y.metadata.threadID,thread_source:"user",turn_id:Y.metadata.turnID,sandbox:hN,turn_started_at_unix_ms:Y.metadata.turnStartedAt,request_kind:"turn",window_id:Y.metadata.windowID});if(Y.headers.set("originator","codex_exec"),Y.websocket)Y.headers.delete("accept"),Y.headers.delete("content-type");else Y.headers.set("accept","text/event-stream");if(Y.headers.set("session-id",Y.metadata.threadID),Y.headers.delete("x-session-id"),Y.headers.delete("x-session-affinity"),Y.headers.set("thread-id",Y.metadata.threadID),Y.headers.set("x-codex-window-id",Y.metadata.windowID),Y.headers.set("x-client-request-id",Y.metadata.threadID),Y.headers.set("x-codex-beta-features",xN),Y.headers.set("x-codex-turn-metadata",J),Y.headers.set("user-agent",vN),Y.headers.set("version",y9),Y.dumpSessionID)Y.headers.set(t0,Y.dumpSessionID);let Q=X;if(!Q)return{init:Y.init};let $=Y.responsesLite&&typeof Q.model==="string"&&kN.has(Q.model);if($&&!Y.websocket)Y.headers.set("x-openai-internal-codex-responses-lite","true");if(Q.prompt_cache_key=Y.metadata.threadID,Q.parallel_tool_calls??=!0,Array.isArray(Q.tools))Q.tools=Q.tools.map(GV);if(QV(Q),$V(Q),kX(Q),XV(Q),$)JV(Q);let G={...typeof Q.client_metadata==="object"&&Q.client_metadata!==null?Q.client_metadata:{},"x-codex-installation-id":Y.installationID,"x-codex-window-id":Y.metadata.windowID};if(Y.websocket){if(G["x-codex-turn-metadata"]=J,G["x-codex-ws-stream-request-start-ms"]=String(Date.now()),$)G.ws_request_header_x_openai_internal_codex_responses_lite="true"}return Q.client_metadata=G,Y.headers.delete("content-length"),Y.headers.delete("Content-Length"),{init:{...Y.init,body:JSON.stringify(WY(Q))}}}function eN(Y,X){return Y.find((J)=>J.enabled!==!1&&j1(J)&&(J.id===X||J.accountId===X))}function nG(Y,X){if(Y.resetCreditsAvailable!==void 0||X?.resetCreditsAvailable===void 0)return Y;return{...Y,resetCreditsAvailable:X.resetCreditsAvailable}}function tY(Y,X){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:X}}function RW(Y,X,J=Date.now(),Q=X.mainAccountId){let $=Y.getMain(),G=$?.quota;return{main:{quota:G?{...G,checkedAt:$.checkedAt,primary:tY(G.primary,$.checkedAt),secondary:tY(G.secondary,$.checkedAt)}:null,...typeof Q==="string"?{mainAccountId:Q}:{},killed:!1,...G?.resetCreditsAvailable!==void 0?{resetCredits:G.resetCreditsAvailable}:{}},fallbacks:X.accounts.filter((W)=>W.enabled).map((W)=>{let K=Y.getFallback(W.id),U=K?.quota;return{id:W.id,label:W.label,accountId:K?.accountId??W.accountId,quota:U?{...U,checkedAt:K.checkedAt,primary:tY(U.primary,K.checkedAt),secondary:tY(U.secondary,K.checkedAt)}:null,killed:!1,enabled:!0,...U?.resetCreditsAvailable!==void 0?{resetCredits:U.resetCreditsAvailable}:{}}}),route:X.routing?.mode??"main-first",lastUpdated:J}}function N4(Y,X,J,Q=Date.now()){return{...RW(Y,X,Q),activeId:J}}function oG(Y,X){if(X?.headers!==void 0)return new Headers(X.headers);if(Y instanceof Request)return new Headers(Y.headers);return new Headers}async function YV(Y,X){if(!(Y instanceof Request))return X;let J=new Request(Y,X),Q=J.method.toUpperCase(),$=Q==="GET"||Q==="HEAD"||J.body===null?void 0:await J.text();return{method:J.method,headers:new Headers(J.headers),body:$,signal:J.signal,cache:J.cache,credentials:J.credentials,integrity:J.integrity,keepalive:J.keepalive,mode:J.mode,redirect:J.redirect,referrer:J.referrer,referrerPolicy:J.referrerPolicy}}function rG(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}function XV(Y){if(!P0().webSearch)return;if(!Array.isArray(Y.tools)||Y.tools.length===0)return;if(Y.tools.some((X)=>I(X)&&X.type==="web_search"))return;Y.tools=[...Y.tools,{type:"web_search",external_web_access:!1,search_content_types:["text","image"]}]}function f9(Y){if(Array.isArray(Y)){for(let X of Y)f9(X);return}if(!I(Y))return;if(Y.type==="input_image")delete Y.detail;for(let X of Object.values(Y))f9(X)}function JV(Y){let X=I(Y.reasoning)?{...Y.reasoning}:{};X.context="all_turns",Y.reasoning=X,Y.parallel_tool_calls=!1;let J=Array.isArray(Y.input)?Y.input:[];f9(J);let $=[{type:"additional_tools",role:"developer",tools:Array.isArray(Y.tools)?Y.tools.filter((G)=>!(I(G)&&G.type==="web_search")):[]}];if(typeof Y.instructions==="string"&&Y.instructions.length>0)$.push({type:"message",role:"developer",content:[{type:"input_text",text:Y.instructions}]});Y.input=[...$,...J],delete Y.tools,delete Y.instructions}function QV(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(I(X)&&X.type==="function"&&X.name==="web_search"))}function $V(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(I(X)&&X.type==="function"&&X.name==="websearch_web_search_exa"))}function GV(Y){if(!I(Y))return Y;if(Y.type!=="function")return Y;let X=I(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:U,...H}=Y.parameters;return H})():Y.parameters,{type:J,name:Q,description:$,strict:G,parameters:W,...K}=Y;return{type:J,name:Q,description:$,strict:G??!1,parameters:X,...K}}async function WV(Y,X={}){let J=X.codexApiEndpoint??P0().codexApiEndpoint,Q=crypto.randomUUID(),$=nN(),G=()=>oN($),W=!1,K=[],U=null,H=null,N,O=new Z8;async function B(L,Z){let j=Y.client.session;if(typeof j?.promptAsync==="function"){let P=await mX(Y.client,L),S={noReply:!0,parts:[{type:"text",text:Z,ignored:!0}]};if(P?.agent)S.agent=P.agent;if(P?.model)S.model=P.model;if(P?.variant)S.variant=P.variant;await j.promptAsync({path:{id:L},body:S});return}}return{async dispose(){O.stop();for(let L of K)L.close();if(K.length=0,H){await H.stop().catch(()=>{});let L=globalThis;if(L.__openaiAuthRpcServer===H)L.__openaiAuthRpcServer=void 0;H=null}},async event(L){if(L.event.type!=="session.deleted")return;let Z=L.event.properties.info,j=$.get(Z.id);if(j)U?.cacheKeepManager?.remove(j.threadID);if($.delete(Z.id))G();if(N){let P=(await M0(K0()))?.accounts;await PW(Z.id,P,N)}for(let P of K)P.remove(Z.id)},provider:{id:"openai",async models(L,Z){if(Z.auth?.type!=="oauth")return L.models;let j=await M0(K0()),P=!j||LW(j),S=P?null:await hX();if(!P&&S&&!pG)pG=!0,uG.debug("restoring OAuth model costs from models.dev catalog");if(!P&&!S&&!lG)lG=!0,uG.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(L.models).filter(([,E])=>{if(E.options.reasoningMode==="pro")return!1;if(IN.has(E.api.id))return!0;if(SN.has(E.api.id))return!1;let _=E.api.id.match(/^gpt-(\d+\.\d+)/)?.[1];return _?parseFloat(_)>5.4:!1}).map(([E,b])=>[E,{...b,cost:P?{input:0,output:0,cache:{read:0,write:0}}:S?.[b.api.id]??S?.[E]??b.cost,limit:b.id.includes("gpt-5.5")?{context:400000,input:272000,output:128000}:b.id.includes("gpt-5.6")?{context:372000,input:244000,output:128000}:b.limit}]))}},tool:{web_search:IX},auth:{provider:"openai",async loader(L){let Z=await L();if(Z.type!=="oauth")return{};await VW({type:"oauth",access:Z.access??"",refresh:Z.refresh??"",expires:Z.expires??0},K0());let j=await M0(K0()).catch((V)=>{let F=K0();throw Error(`OpenAI auth store at ${F} is corrupt or unreadable: ${V instanceof Error?V.message:String(V)}. Fix or remove it to continue.`,{cause:V})}),P;async function S(){let V=K0();try{let F=TN(V);if(P?.path===V&&P.mtimeMs===F.mtimeMs&&P.size===F.size)return P.storage;let D=await M0(V);return P={path:V,mtimeMs:F.mtimeMs,size:F.size,storage:D},D}catch{return P=void 0,M0(V)}}function E(){P=void 0}if(j&&Z.access){let V=eY({id_token:"",access_token:Z.access,refresh_token:Z.refresh??""});if(V&&V!==j.mainAccountId)await J0((F)=>{return F.mainAccountId=V,F},K0()),j.mainAccountId=V,E()}let b=j?.logging?.level;if(b&&typeof b==="string")DY(b);let _=H0("transport"),u=H0("quota"),m=H0("refresh"),d=H0("accounts");_.info("codex auth loader ready",{codexApiEndpoint:J,transport:P0().rawWebSocket?"raw-websocket":P0().webSockets?"websocket":"http",webSearch:P0().webSearch});let y=new HW({storage:j,fetchQuotaFn:void 0}),e,g0=0,p=new BW({refreshFn:(V)=>x1({refreshToken:V.refreshToken,fetchImpl:V.fetchImpl,now:V.now}),quotaManager:y,onFallbackStorageChanged:E});if(j&&j.accounts.length>0)p.startBackgroundRefresh();let r0=H0("cachekeep"),v1=j?.cachekeep?.enabled===!0,h1=j?.cachekeep?.subagents===!0,D1=j?.cachekeep?.sustain===!0,h=ZX(j),o;async function V0(V){await new Promise((F)=>setTimeout(F,V))}async function J8(V){let F;for(let D=1;D<=mG;D++)try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:V.refresh,access:V.access,expires:V.expires}});return}catch(R){if(F=R,D<mG)await V0(cN*D)}throw new m9(F)}async function P1(V){await J0((F)=>{return F.refresh=F.refresh??{},V(F),F},K0()),E()}async function BY(V){let F=Date.now()+mN;while(Date.now()<F){await new Promise((k)=>setTimeout(k,fG+lN(fG)));let D=await L();if(D.type!=="oauth"||!D.access)continue;if((D.access!==V.access||D.refresh!==V.refresh||(D.expires??0)>(V.expires??0)+60000)&&(!D.expires||D.expires>Date.now()))return m.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:D.expires?D.expires-Date.now():void 0}),{access:D.access,refresh:D.refresh??V.refresh??"",expires:D.expires??0}}return null}async function K1(){if(!o)o=(async()=>{let V=await L();if(V.type!=="oauth")throw Error("not oauth");if(!V.refresh)throw Error("Token refresh failed: missing refresh token");let F=sG(V.refresh),D=await M0(K0()),R=D?.refresh?.mainLastRefreshError;if(R&&tG(R,V.refresh,Date.now()))throw Error(eG(R,Date.now()));if(D?.refresh?.mainRefreshLeaseUntil&&D.refresh.mainRefreshLeaseUntil>Date.now()&&D.refresh.mainRefreshLeaseTokenHash===F){let M=await BY(V);if(M)return M;throw Error("Codex OAuth refresh is already in progress")}let k=await PY({name:gN,ttlMs:yN,path:K0(),renew:!0});if(!k){let M=await BY(V);if(M)return M;throw Error("Codex OAuth refresh is already in progress")}let T=crypto.randomUUID(),C=F;try{await P1((g)=>{g.refresh=g.refresh??{},g.refresh.mainRefreshLeaseId=T,g.refresh.mainRefreshLeaseUntil=Date.now()+fN,g.refresh.mainRefreshLeaseTokenHash=F});let M=await M0(K0());if(M?.refresh?.mainRefreshLeaseId!==T||M.refresh.mainRefreshLeaseTokenHash!==F)throw Error("Codex OAuth refresh is already in progress");let w=await x1({refreshToken:V.refresh,fetchImpl:fetch,now:Date.now});return await J8(w),await P1((g)=>{if(g.refresh=g.refresh??{},g.refresh.mainLastRefreshError=void 0,g.refresh.mainRefreshLeaseId===T)g.refresh.mainRefreshLeaseId=void 0,g.refresh.mainRefreshLeaseUntil=void 0,g.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),C=void 0,w}catch(M){if(V.refresh&&!h9(M))await P1((w)=>{w.refresh=w.refresh??{},w.refresh.mainLastRefreshError=aG({error:M,now:Date.now(),refreshToken:V.refresh??"",previous:w.refresh.mainLastRefreshError})}).catch(()=>{});throw M}finally{if(C)await P1((M)=>{if(M.refresh?.mainRefreshLeaseId===T&&M.refresh.mainRefreshLeaseTokenHash===C)M.refresh.mainRefreshLeaseId=void 0,M.refresh.mainRefreshLeaseUntil=void 0,M.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await k.release().catch(()=>{})}})().finally(()=>{o=void 0});return o}let s0=globalThis;s0.__openaiAuthCacheKeepManager?.stop();let y0=new D8({fetchImpl:fetch,getMainToken:async()=>{let V=await L();if(V.type!=="oauth")throw Error("not oauth");if(!V.access||(V.expires??0)<Date.now())try{return(await K1()).access}catch(F){if(h9(F))throw F;if(V.access)return V.access;throw Error("main token refresh failed")}return V.access},refreshFallback:async(V)=>{let F=await S(),D=F?eN(F.accounts,V):void 0;if(!D)throw Error(`fallback account ${V} not found`);let R=await p.refreshAccount(D,F??{version:1,accounts:[D]});if(!R.access)throw Error(`no access token for ${V}`);return R.access},codexResponsesUrl:J,logger:r0,now:Date.now,getWindow:()=>h,getSustain:()=>D1});s0.__openaiAuthCacheKeepManager=y0;async function U1(V,F,D,R,k=!1){if(Object.keys(V).length===0&&!k)return;let T=Date.now(),C=V,M={quota:C,refreshAfter:T+300000,checkedAt:T},w;if(D&&D!=="main"){let x=F?NY(F):null,X0=x?VY(x):void 0,B0=y.peekFallbackForPolicy(D)?.quota,b0=nG(C,B0);M={...M,quota:b0},y.setFallback(D,M,F,k,X0)}else{if(w=R,!w&&F){let B0=NY(F);w=B0?VY(B0):void 0}if(w&&e&&w!==e){u.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:w,currentMainIdentity:e});return}let x=y.peekMainForPolicy(w)?.quota,X0=nG(C,x);M={...M,quota:X0},y.setMain(F,M,w,k)}u.debug("quota pushed",{pid:process.pid,accountId:D??"main",snapshot:M.quota});let g=await S();await m0(y,g,D&&D!=="main"?g?.mainAccountId:w)}function Q8(V,F,D){let R=V==="main"?y.peekMainForPolicy()?.quota:y.peekFallbackForPolicy(V)?.quota;return UW(R,F,Date.now(),uN,D)}let f0=X.experimentalWebSockets?z1.createWebSocketFetch({httpFetch:fetch,rawWebSocket:P0().rawWebSocket,onQuota:(V,F,D,R)=>{U1(V,F,D,!D||D==="main"?R:void 0,!0)},onRateLimitReached:(V,F,D)=>{if(!F)u.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:V});let R=F??"main",k=Q8(R,V,D);y.markRateLimited(R,k),u.debug("mid-stream rate limit mark",{pid:process.pid,accountId:R,window:V})}}):void 0;if(f0)K.push(f0),W=!0;let F0=ZW();N=F0;async function m0(V,F,D=F?.mainAccountId){if(!F)return;await jW(RW(V,F,Date.now(),D),F0)}async function k0(V,F,D,R,k){let T={activeId:D,route:R,updatedAt:Date.now()};if(V){if(await X8({sessionId:V,...T},k,F0),F&&F!==V){if(R==="sticky-balanced"){let C=(await N1(F0)).stickyAssignments?.[LY(F)]?.accountId,M=k===void 0||C==="main"||k.some((w)=>w.enabled!==!1&&w.id===C);if(!C||!M)return;await X8({sessionId:F,activeId:C,route:R,updatedAt:Date.now()},k,F0);return}await X8({sessionId:F,...T},k,F0)}return}await DW(T,F0)}U={accountStoragePath:K0(),quotaManager:y,loadAccounts:M0,client:Y.client,cacheKeepManager:y0,setCacheKeepEnabled:(V)=>{v1=V},setCacheKeepSubagents:(V)=>{h1=V},setCacheKeepSustain:(V)=>{D1=V},setCacheKeepWindow:(V)=>{h=V},clearStickyRouting:(V)=>EW(V,F0),getStickyRouting:async(V)=>qW(await N1(F0),V),refreshSidebar:async()=>{let V=await M0(K0());await m0(y,V)},refreshAllQuota:async()=>f1({getAuth:L,codexRefreshFn:x1,refreshMainWithLease:K1,fallbackManager:p,quotaManager:y,loadAccounts:M0,writeSidebarState:m0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:K0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:j1,whamFn:Y8})};let Y0=null;if(Y.directory){let V=await MW(Y.directory),F=globalThis;if(F.__openaiAuthRpcServer)await F.__openaiAuthRpcServer.stop().catch(()=>{}),F.__openaiAuthRpcServer=void 0;try{Y0=await nX({dir:V.dir,secureDir:V.secureDir,sweepRoot:V.sweepRoot,drain:uX,apply:async(D)=>{let R={...U,sessionId:D.sessionId},k=await B8(D.command,D.arguments,R);return{text:k.text,knobs:k.knobs}}}),F.__openaiAuthRpcServer=Y0,H=Y0}catch{}}async function A0(V,F,D,R,k="main"){let T=oG(V,F);if(T.delete("x-api-key"),T.delete("api-key"),T.set("authorization",`Bearer ${D}`),R)T.set("ChatGPT-Account-Id",R);T.set(z1.QUOTA_ACCOUNT_HEADER,k);let C=rG(T),M=C?iN($,C,G):void 0,w=V instanceof URL?V:new URL(typeof V==="string"?V:V.url),g=w.pathname.includes("/v1/responses")||w.pathname.includes("/chat/completions")?new URL(J):w,X0=tN({init:{...F,headers:T},headers:T,metadata:M,installationID:Q,websocket:Boolean(f0&&w.pathname.endsWith("/responses")),responsesLite:X.responsesLite??!1,dumpSessionID:C}).init,B0=v1,b0=new Headers(X0?.headers),$0=BX({enabled:B0,includeSubagents:h1,headers:b0,body:X0?.body});if(B0)r0.trace("cachekeep headers",{pid:process.pid,hasParent:b0.has("x-parent-session-id"),sessionKey:$0?.sessionKey,captured:Boolean($0),affinity:b0.get("x-session-affinity"),opencodeSession:b0.get("x-opencode-session"),sessionId:b0.get("session-id")});if(f0&&w.pathname.endsWith("/responses")){if(_.debug("WS transport",{pid:process.pid,pathname:w.pathname,accountId:k}),$0)y0.track($0.sessionKey,$0.bodyText,k,R,$0.replayHeaders,$0.isSubagent);return f0(g,X0)}let N0=z1.withoutInternalHeaders(X0);if(typeof N0?.body!=="string")return fetch(g,N0);if($0)y0.track($0.sessionKey,$0.bodyText,k,R,$0.replayHeaders,$0.isSubagent);_.debug("HTTP transport",{pid:process.pid,pathname:w.pathname,accountId:k});try{let T0=await fetch(g,N0);return await R1({sessionID:C,transport:"http",phase:"http",bodyText:N0.body,accountId:k,url:g.toString(),method:N0.method,headers:N0.headers,status:T0.status}),SX(T0)}catch(T0){throw await R1({sessionID:C,transport:"http",phase:"http",bodyText:N0.body,accountId:k,url:g.toString(),method:N0.method,headers:N0.headers,error:T0 instanceof Error?T0.message:String(T0)}),T0}}function w1(V,F){if((F?.method??(V instanceof Request?V.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof F?.body!=="string")return!1;try{let R=V instanceof URL?V.toString():typeof V==="string"?V:V.url;return new URL(R).pathname.endsWith("/responses")}catch{return!1}}function TW(V){return y.peekMainForPolicy(V)?.quota}function c9(V,F){for(let D of[V?.primary?.checkedAt,V?.secondary?.checkedAt,V?.checkedAt,F])if(typeof D==="number"&&Number.isFinite(D))return D;return}function g1(V,F,D,R,k){let T=c9(V,F),C=c9(D),M=R===k&&D!=null&&(V===void 0||C!==void 0&&(T===void 0||C>T));return{quota:M?D:V,quotaCheckedAt:M?C:T,source:M?"file":"memory"}}function u9(V,F,D,R,k){let T=V?.quota,C=g1(T,V?.checkedAt,F,R,k),M=C.source,w=C.quota;if(!FW(w,D))return{exhausted:!1};let g=OW(w,D);if(!g)return{exhausted:!1};return{exhausted:!0,source:M,...g}}function p9(V,F){u.debug("admission skip: exhausted account",{accountId:V,source:F.source,resetsAt:F.resetsAt})}function CW(V,F="killswitch",D){let R=Date.now(),k=y.getMain()?.quota,T=(V?.accounts??[]).filter((x)=>x.enabled!==!1&&j1(x)).map((x)=>({accountId:x.id,quota:y.getFallback(x.id)?.quota})),C=NW(k,T,R,V);if(F==="quota-exhausted"&&D!==void 0)C=Math.max(1,Math.ceil((D-R)/1000));else if(F==="mid-stream-rate-limit"&&D!==void 0){let x=Math.max(1,Math.ceil((D-R)/1000));C=Math.min(C,x)}let M=Math.floor(C/60),w=C%60,g=F==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${M}m ${w}s.`:F==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${M}m ${w}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${M}m ${w}s.`;return new Response(JSON.stringify({error:{message:g,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(C)}})}function l9(V){let F=V?.resetCreditsAvailable;return typeof F==="number"&&Number.isFinite(F)?F:void 0}async function _W(V){let F=UY(V.storage),D=Date.now(),R=y.peekMainForPolicy(V.mainAccountIdentity),k=g1(R?.quota,R?.checkedAt,V.sidebarState.main.quota,V.sidebarState.main.mainAccountId,V.mainAccountIdentity),T=F?HY(R?.quota,V.storage,void 0,D):void 0,C=[{accountId:"main",wireAccountId:V.mainAccountIdentity,access:V.primaryAccess,keepwarmAccountKey:"main",quota:k.quota,quotaCheckedAt:k.quotaCheckedAt,reservePercent:g9(V.storage),configuredOrder:0,resetCreditsApplicable:l9(k.quota),killswitchPasses:T}],M=await p.getUsableFallbackAccounts(V.storage);for(let w of M){if(!w.access)continue;let g=V.sidebarState.fallbacks.find((b0)=>b0.id===w.id),x=y.peekFallbackForPolicy(w.id,w.accountId),X0=g1(x?.quota,x?.checkedAt,g?.quota,g?.accountId,w.accountId),B0=F?HY(x?.quota,V.storage,w.id,D):void 0;C.push({accountId:w.id,wireAccountId:w.accountId,access:w.access,keepwarmAccountKey:w.id,fallback:w,quota:X0.quota,quotaCheckedAt:X0.quotaCheckedAt,reservePercent:g9(V.storage,w.id),configuredOrder:C.length,resetCreditsApplicable:l9(X0.quota),killswitchPasses:B0})}return C}function d9(V,F,D,R,k){let T=UY(k)?V.killswitchPasses:void 0;if(V.accountId==="main"){let g=y.peekMainForPolicy(V.wireAccountId),x=g1(g?.quota,g?.checkedAt,F.main.quota,F.main.mainAccountId,V.wireAccountId);return E8({quota:x.quota,quotaCheckedAt:x.quotaCheckedAt,status:D,now:R,killswitchPasses:T})}let C=F.fallbacks.find((g)=>g.id===V.accountId),M=y.peekFallbackForPolicy(V.accountId,V.wireAccountId),w=g1(M?.quota,M?.checkedAt,C?.quota,C?.accountId,V.wireAccountId);return E8({quota:w.quota,quotaCheckedAt:w.quotaCheckedAt,status:D,now:R,killswitchPasses:T})}function IW(V){return V.accountId==="main"?"main":V.keepwarmAccountKey}function i9(V){return y.isRateLimited(IW(V))}async function $8(V){let F=V.candidates.filter((M)=>!i9(M)),D=new Map(F.map((M)=>[M.accountId,M])),R=Object.fromEntries(F.map((M)=>[M.accountId,M.quotaCheckedAt])),k=new Set(V.excludeAccountIds),T,C=await wW({sessionId:V.sessionId,requestBytes:V.requestBytes,now:V.now,validPinnedAccountIds:[...D.keys()],excludeAccountIds:V.excludeAccountIds,quotaCheckedAtByAccount:R,choose:(M)=>{let w=F.filter((x)=>!k.has(x.accountId));if(w.length===0)return;let g=wX({candidates:w,pendingBytes:M,requestBytes:V.requestBytes,now:V.now,onEmptyWeightedSet:()=>{d.debug("sticky routing: no fresh weighted candidates; using configured order")}});if(!g)return;return T={accountId:g.accountId,source:g.source,pendingBytes:M.get(g.accountId)??0},g}},F0);if(T&&C?.accountId===T.accountId)d.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:LY(V.sessionId),accountId:T.accountId,source:T.source,requestBytes:V.requestBytes,pendingBytes:T.pendingBytes});return C?D.get(C.accountId):void 0}async function SW(V,F){let D=await p.getUsableFallbackAccounts(V),R=[];for(let x of D)if(x.access)R.push({access:x.access,accountId:x.accountId,keepwarmAccountKey:x.id,quotaAccountId:x.id,fallback:x});let k=R.filter((x)=>!y.isRateLimited(x.quotaAccountId)),T=UY(V)?k.filter((x)=>HY(y.peekFallbackForPolicy(x.quotaAccountId,x.accountId)?.quota,V,x.quotaAccountId,Date.now())):k,C=new Map(F.fallbacks.map((x)=>[x.id,{quota:x.quota,accountId:x.accountId}])),M=[],w=[],g=Date.now();for(let x of T){let X0=C.get(x.quotaAccountId),B0=u9(y.peekFallbackForPolicy(x.quotaAccountId,x.accountId),X0?.quota,g,X0?.accountId,x.accountId);if(B0.exhausted)w.push({candidate:x,decision:B0});else M.push(x)}return{current:T,retained:M,skipped:w}}function n9(V,F){if(V.retained.length===0&&!F)return V.current;for(let{candidate:D,decision:R}of V.skipped)p9(D.quotaAccountId,R);return V.retained}async function o9(V,F){try{let D=M1(V.headers);await U1(D,F.access,F.quotaAccountId,void 0,zY(V.headers))}catch{}}async function kW(V,F,D,R){for(let k of R){let T;try{T=await A0(V,F,k.access,k.accountId,k.keepwarmAccountKey)}catch(C){if(C instanceof DOMException&&C.name==="AbortError")throw C;if(F?.signal?.aborted)throw C;throw d.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:k.quotaAccountId}),C}if(!KY(T.status,D))return await p.markUsed(k.fallback),{response:T,accessToken:k.access,quotaAccountId:k.quotaAccountId,activeId:k.keepwarmAccountKey};await o9(T,k),T.body?.cancel().catch(()=>{})}return}async function bW(V,F,D,R,k){if(!w1(V,F))return{response:D};if(!k.length)return{response:D};let T=D,C;for(let M of k){let w;try{w=await A0(V,F,M.access,M.accountId,M.keepwarmAccountKey)}catch(g){if(g instanceof DOMException&&g.name==="AbortError")throw g;if(F?.signal?.aborted)throw g;return d.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:M.quotaAccountId}),{response:T,...C}}if(T.body?.cancel().catch(()=>{}),T=w,C={accessToken:M.access,accountId:M.quotaAccountId},!KY(w.status,R))return await p.markUsed(M.fallback),{response:w,...C};await o9(w,M)}return{response:T,...C}}if(!cG){if(cG=!0,j){let V=[];for(let F of j.accounts)if(j1(F))V.push(F);y.seedFallbacksFromAccounts(V)}m0(y,j).catch(()=>{}),f1({getAuth:L,codexRefreshFn:x1,refreshMainWithLease:K1,fallbackManager:p,quotaManager:y,loadAccounts:M0,writeSidebarState:m0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:K0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:j1,whamFn:Y8,respectBackoff:!0}).catch((V)=>u.warn("boot quota seed failed",{pid:process.pid,error:a0(V)}))}return O.start(async()=>{let F=(await UX({getAuth:L,codexRefreshFn:x1,refreshMainWithLease:K1,fallbackManager:p,quotaManager:y,loadAccounts:M0,writeSidebarState:(D,R)=>O.isStopped()?Promise.resolve():m0(D,R),client:Y.client,fetchImpl:fetch,now:Date.now,configPath:K0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:j1,whamFn:Y8,readSidebarState:()=>N1(F0)})).filter((D)=>!D.ok);if(F.length>0)u.warn("background quota refresh completed with failures",{pid:process.pid,failures:F})},(V)=>{u.warn("background quota refresh failed",{pid:process.pid,error:V instanceof Error?V.message:String(V)})}),{apiKey:bN,async fetch(V,F){let D=oG(V,F),R=rG(D),k=D.get("x-parent-session-id")?.trim()||void 0,T=await S(),C=await L(),M=++g0;if(C.type!=="oauth")return fetch(V,F);F=await YV(V,F);let w=C.access??"";if(!C.access||(C.expires??0)<Date.now()){m.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(C.access),expiresInMs:C.expires?C.expires-Date.now():void 0});try{let t=await K1();C.access=t.access,C.refresh=t.refresh,C.expires=t.expires}catch(t){if(h9(t))throw t}}w=C.access??"";let x=C.accountId??(w?VY(NY(w)??{}):void 0);if(M===g0)e=x;let X0=T?.routing?.mode??"main-first",B0,$0=await(()=>{return B0??=N1(F0),B0})();if(X0==="sticky-balanced"&&R&&w1(V,F)&&typeof F?.body==="string"){let t=Buffer.byteLength(F.body,"utf8"),U0=await _W({storage:T,sidebarState:$0,primaryAccess:w,mainAccountIdentity:x}),z0=await $8({sessionId:R,requestBytes:t,candidates:U0,now:Date.now()});if(z0){let XX=i9(z0)?{action:"migrate",reason:"exhausted"}:d9(z0,$0,void 0,Date.now(),T);if(XX.action==="migrate"){let D0=await $8({sessionId:R,requestBytes:t,candidates:U0,excludeAccountIds:[z0.accountId],now:Date.now()});if(D0)d.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:LY(R),fromAccountId:z0.accountId,toAccountId:D0.accountId,reason:XX.reason}),z0=D0}let x0=await A0(V,F,z0.access,z0.wireAccountId,z0.keepwarmAccountKey),JX=async(D0,H1)=>{try{let xW=M1(D0.headers);await U1(xW,H1.access,H1.accountId==="main"?void 0:H1.accountId,H1.accountId==="main"?H1.wireAccountId:void 0,zY(D0.headers))}catch{}};await JX(x0,z0);let QX=d9(z0,$0,x0.status,Date.now(),T);if((x0.status===401||x0.status===403||x0.status===429)&&QX.action==="migrate"){let D0=await $8({sessionId:R,requestBytes:t,candidates:U0,excludeAccountIds:[z0.accountId],now:Date.now()});if(D0){d.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:LY(R),fromAccountId:z0.accountId,toAccountId:D0.accountId,reason:QX.reason});let H1=x0;x0=await A0(V,F,D0.access,D0.wireAccountId,D0.keepwarmAccountKey),H1.body?.cancel().catch(()=>{}),z0=D0,await JX(x0,z0)}}if(z0.fallback&&!KY(x0.status,T))await p.markUsed(z0.fallback);return await k0(R,k,z0.accountId,X0,T?.accounts).catch(()=>{}),x0}}let N0=u9(y.peekMainForPolicy(x),$0.main.quota,Date.now(),$0.main.mainAccountId,x),T0=UY(T)&&!HY(TW(x),T,void 0,Date.now()),ZY=y.isRateLimited("main"),r9,G8=()=>{return r9??=SW(T,$0),r9},c0,E1,s9=!1,OY;if(X0==="fallback-first"&&w1(V,F)){s9=!0;let t=await G8();OY=n9(t,!T0&&!ZY&&!N0.exhausted);let U0=await kW(V,F,T,OY);if(U0)c0=U0.response,E1={accessToken:U0.accessToken,accountId:U0.quotaAccountId,activeId:U0.activeId}}if(!c0){let t=N0.exhausted&&w1(V,F)&&(await G8()).retained.length>0;if(T0||ZY||t){let U0=T0?"killswitch":ZY?"mid-stream-rate-limit":"quota-exhausted";if(U0==="quota-exhausted"&&N0.exhausted)p9("main",N0);d.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:U0}),c0=CW(T,U0,U0==="quota-exhausted"&&N0.exhausted?N0.resetAtMs:ZY?y.rateLimitedUntil("main"):void 0)}else c0=await A0(V,F,w,x,"main")}let a9=Boolean(E1),y1=c0,t9=E1?.accessToken??w,e9=E1?.accountId,YX=E1?.activeId??"main";if(!E1&&!s9&&KY(c0.status,T)){d.debug("reactive fallback triggered",{pid:process.pid,status:c0.status}),OY??=n9(await G8(),!1);let t=await bW(V,F,c0,T,OY),U0=t.response;if(U0!==c0){if(a9=!0,y1=U0,t9=t.accessToken??w,e9=t.accountId,t.accountId)YX=t.accountId}}try{let t=M1(y1.headers);if(a9)await U1(t,t9,e9,void 0,zY(y1.headers));else await U1(t,w,void 0,x,zY(y1.headers))}catch{}return await k0(R,k,YX,X0,T?.accounts).catch(()=>{}),y1},async dispose(){if(O.stop(),y0.stop(),s0.__openaiAuthCacheKeepManager===y0)s0.__openaiAuthCacheKeepManager=void 0;if(p.stopBackgroundRefresh(),H){await H.stop().catch(()=>{});let V=globalThis;if(V.__openaiAuthRpcServer===H)V.__openaiAuthRpcServer=void 0;H=null}}}},methods:[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:async()=>{let{redirectUri:L}=await GW(),Z=await JW(),j=XW(crypto.getRandomValues(new Uint8Array(32)).buffer),P=QW(L,Z,j),S=WW(Z,j);return{url:P,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let E=await S,b=eY(E);return{type:"success",refresh:E.refresh_token,access:E.access_token,expires:Date.now()+(E.expires_in??3600)*1000,accountId:b}}finally{$W(j)}}}}},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:async()=>{let{deviceData:L,url:Z,instructions:j}=await zW();return{url:Z,instructions:j,method:"auto",async callback(){try{let P=await KW(L);return{type:"success",refresh:P.refresh_token,access:P.access_token,expires:Date.now()+(P.expires_in??3600)*1000,accountId:eY(P)}}catch{return{type:"failed"}}}}}},{label:"Manually enter API Key",type:"api"}]},"chat.headers":async(L,Z)=>{if(L.model.providerID!=="openai")return;if(Z.headers.originator="opencode",Z.headers["User-Agent"]=`${YW} (${v9.platform()} ${v9.release()}; ${v9.arch()})`,Z.headers["session-id"]=L.sessionID,W&&L.agent==="title")Z.headers[z1.TITLE_HEADER]="true"},"chat.params":async(L,Z)=>{if(L.model.providerID!=="openai")return;Z.maxOutputTokens=void 0},config:async(L)=>{L.command={...L.command??{},[z8]:{template:z8,description:"Show current OpenAI Codex OAuth quota usage for all accounts."},[K8]:{template:K8,description:"Manage OpenAI accounts — add, switch, remove, or reorder."},[U8]:{template:U8,description:"Show or change OpenAI account routing between main-first, fallback-first, and sticky-balanced."},[H8]:{template:H8,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."},[L8]:{template:L8,description:"Show or toggle OpenAI Codex request dump capture for debugging."},[N8]:{template:N8,description:"Show or change the plugin log level (error, warn, info, debug, trace)."},[V8]:{template:V8,description:"Keep Codex prompt cache alive during idle by shadow-replaying the last request."}}},"command.execute.before":async(L)=>{if(!KX.includes(L.command))return;if(!U)await B(L.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),dG();let Z=L.command,j={...U,sessionId:L.sessionID,notify:(S)=>{b8(S,L.sessionID)}},P=await B8(Z,L.arguments,j);if(pX(L.sessionID))b8(P,L.sessionID);else await B(L.sessionID,P.text);dG()}}}var zV=async(Y)=>{let X=P0();return WV(Y,{codexApiEndpoint:X.codexApiEndpoint,experimentalWebSockets:X.webSockets,responsesLite:X.responsesLite})},V4={id:"cortexkit-openai-auth",server:zV};export{rG as resolveSidebarSessionId,NY as parseJwtClaims,nG as mergePushedQuotaMetadata,eN as findCachekeepFallbackAccount,VY as extractAccountIdFromClaims,V4 as default,N4 as buildSidebarState,RW as buildSidebarMachineState,zV as OpenAIAuthPlugin,yN as MAIN_REFRESH_LOCK_TTL_MS,fN as MAIN_REFRESH_LEASE_TTL_MS,WV as CodexAuthPlugin,m9 as AuthPersistError};